shared = {
    webBaseUrl: '',
    init: function(event) {
        if(typeof uploadErrorMsg != 'undefined') {
            this.errorPopup(uploadErrorMsg);
        }
    },    
    trimLeft: function(value) {
      var re = /\s*((\S+\s*)*)/;
      return value.replace(re, "$1");
    },
    trimRight: function(value) {
        var re = /((\s*\S+)*)\s*/;
        return value.replace(re, "$1");
    },
	trim:function(value) {
        return this.trimLeft(this.trimRight(value));
    },
    displayPopup: function(popupId, url, ajaxParams) {
        var body = $$('body')[0];
        if(!$(popupId)) {
            var popup = document.createElement('div');
            popup.id = popupId;
            popup.style.display = 'none';
            popup.className = 'popupDialogWrapper';
            
            body.appendChild(popup);
            new Ajax.Updater(popupId, url, ajaxParams);
            
            var scrollOffsets = document.viewport.getScrollOffsets();
            popup.style.top = (scrollOffsets.top + 80) +  'px';
            
            if($('modalDiv')) {
                var divHeight = Math.max($('mainContainer').getHeight(), document.viewport.getHeight());
                $('modalDiv').style.height = divHeight + 'px';
                $('modalDiv').show();
            }
            var userAgent = navigator.userAgent.toLowerCase();
            if(userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
                new Effect.Appear(popupId, {duration: 0.5, to: 1.1}); // NOTE: set to 1.1 to deal with mac ff flash opacity issue
            }
            else {
                new Effect.Appear(popupId, {duration: 0.5});
            }
        }
    },
    closePopup: function(popupId) {
        if($(popupId)) {
            new Effect.Fade(popupId, {queue: 'end', duration: .50 });
            var popups = $$('.popupDialogWrapper');
            if(popups != null && popups.length == 1) {
                if($('modalDiv')) {
                    new Effect.Fade('modalDiv', {queue: 'end', duration: .50 });
                }
            }
            setTimeout("$$('body')[0].removeChild($('" + popupId + "'));", 1000);
        } 
    },
    errorPopup: function(msg) {
        this.displayPopup('errorPopup', 'popup_error.htm?msg=' + encodeURIComponent(msg), '');
    },
    errorPopupClose: function() {
        this.closePopup('errorPopup');
    },
    alertPopup: function(msg) {
        this.displayPopup('alertPopup', 'popup_alert.htm?msg=' + encodeURIComponent(msg), '');
    },
    alertPopupClose: function() {
        this.closePopup('alertPopup');    
    },
    apiPopup: function() {
        this.displayPopup('apiPopup', 'popup_api.htm', '');
    },
    apiPopupSubmit: function() {
        var url = 'ws/apiFeedback.json';
        var params = {
            method: 'POST',
            postBody: 'name=' + $F('apiPopupName') + '&email=' + encodeURIComponent($F('apiPopupEmail')) + '&company=' + encodeURIComponent($F('apiPopupCompany')) + '&appName=' + encodeURIComponent($F('apiPopupAppName'))  + '&url=' + encodeURIComponent($F('apiPopupURL'))  + '&notes=' + encodeURIComponent($F('apiPopupNotes')),
            onSuccess: function(resp) {
                alert('Thanks! Your request has been submitted.')
                window.location.reload();
            },
            onFailure: function(resp) {
                shared.errorPopup('All fields are required.');
            }
        };
        new Ajax.Request(url, params);
    },
    apiPopupClose: function() {
        this.closePopup('apiPopup');
    },
    loginPopup: function() {
        this.displayPopup('loginPopup', 'popup_login.htm', '');
    },
    betaLoginPopup: function() {
        this.displayPopup('loginPopup', 'popup_login.htm?betaLogin=true', '');
    },
    basicAuthPopup: function() {
        this.displayPopup('loginPopup', 'popup_basic_auth.htm?betaLogin=false', '');
    },
    loginPopupSubmit: function(betaLogin) {
        var url = 'ws/login.json';
        if(betaLogin) {
            url = 'ws/betalogin.json';
        }
        var params = {
            method: 'POST',
            postBody: 'username=' + $F('loginPopupUsername') + '&password=' + encodeURIComponent($F('loginPopupPassword')),
            onSuccess: function(resp) {
                window.location.reload();
            },
            onFailure: function(resp) {
                var jsonResponse = resp.responseJSON;
                var errorMsg = shared.getLoginErrorMsg(jsonResponse.error);
                shared.errorPopup(errorMsg);
            }
        };
        new Ajax.Request(url, params);
    },
    loginBasicAuthSubmit: function() {
        var url = 'ws/basicAuth.json';
        var params = {
            method: 'POST',
            postBody: 'username=' + $F('loginPopupUsername') + '&password=' + encodeURIComponent($F('loginPopupPassword')),
            onSuccess: function(resp) {
                window.location.reload();
            },
            onFailure: function(resp) {
                var jsonResponse = resp.responseJSON;
                var errorMsg = shared.getBasicAuthErrorMsg(jsonResponse.error);
                shared.errorPopup(errorMsg);
            }
        };
        new Ajax.Request(url, params);
    },
    loginPopupClose: function() {
        this.closePopup('loginPopup');
    },
    getLoginErrorMsg: function(errorType) {
        var errorMsg = 'Sorry, there was a problem logging you in.  Please try again.';
        if(errorType == 'emptyUsername') {
            errorMsg = 'Please enter your email address.';
        } else if(errorType == 'emptyPassword') {
            errorMsg = 'Please enter your password.';
        } else if(errorType == 'invalidCredentialsError') {
            errorMsg = 'Incorrect email/password combination. Please try again.';
        } else if(errorType == 'authenticationDownError') {
            errorMsg = 'We are unable to connect to Twitter at this time (maybe Twitter is down?). Please try again later.';
        } else if(errorType == 'authenticationError') {
            errorMsg = 'There was an error during login. Please try again.';
        } else if(errorType == 'invalidBetaUserError') {
            errorMsg = 'Sorry, you must have a beta code to log into the tap11 site. If you have a beta code, please register below.';
        } else if(errorType == 'accountExists') {
            errorMsg = 'That email address is already registered';
        } else if(errorType == 'invalidEmail') {
            errorMsg = 'Please enter a valid email address';
        } else if(errorType == 'invalidPassword') {
            errorMsg = 'Please enter a valid password';
        } else {
            errorMsg = 'Sorry, there was an unknown error during login. Please try again.';
        }
        return errorMsg;
    },
    getBasicAuthErrorMsg: function(errorType) {
        var errorMsg = 'Sorry, there was a problem logging you in. Please try again.';
        if(errorType == 'invalidCredentials') {
            errorMsg = 'Incorrect username/password combination. Please try again';
        } else if(errorType == 'authenticationDown') {
            errorMsg = 'Sorry, twitter is down. Please try again';
        }
        return errorMsg;
    },
    logout: function() {
        var url = 'ws/logout.json';
        var params = {
            onComplete: function() {
                window.location.href= shared.webBaseUrl;
            }
        };
        new Ajax.Request(url, params);
    },
    limitTextArea: function(obj, max) {
        if(obj.value.length > max) {
            obj.value = obj.value.substring(0,max);
        }
    },
    focusTextBox: function(textBox, defaultClassName, activeClassName) {
        textBox = Element.extend(textBox);
        if(textBox.hasClassName(defaultClassName)) {
            textBox.clear();
            textBox.removeClassName(defaultClassName);
            textBox.addClassName(activeClassName);    
        }
    },
    getUploadStatus: function(percentId, statusIntervalId) {
        var uploadStatusUrl = 'ws/uploadStatus.json';
        var params = {
            method: 'get',
            onSuccess: function(resp) {
                var jsonResponse = resp.responseJSON;
                var currentStatus = jsonResponse.uploadStatus.currentStatus;
                var percentage = jsonResponse.uploadStatus.percentage;
                if(currentStatus == 'UPLOADING') {
                    $(percentId).innerHTML = percentage + '%';
                } else if(currentStatus == 'DONE') {
                    $(percentId).innerHTML = 'finishing...';
                    clearInterval(statusIntervalId);
                } else if(currentStatus == 'MAX_SIZE_EXCEEDED') {
                    $(percentId).innerHTML = 'max upload size exceeded...';
                    clearInterval(statusIntervalId);
                }
            }
        };
        new Ajax.Request(this.uploadStatusUrl, params);
    },
    facebookSwitch: function(facebookActive, successFunction) {
        var url = "ws/facebookConnect.json";
        var params = {
            method: 'POST',
            postBody: 'facebookActive=' + facebookActive,
            onSuccess: successFunction,
            onFailure: function(resp) {
                var errorMsg = resp.responseJSON.error;
                shared.errorPopup(errorMsg);
            }
        };
        new Ajax.Request(url, params);
    },
    myspaceSwitch: function(myspaceActive, successFunction) {
        var url = "ws/mySpaceConnect.json";
        var params = {
            method: 'POST',
            postBody: 'myspaceActive=' + myspaceActive,
            onSuccess: successFunction,
            onFailure: function(resp) {
                var errorMsg = resp.responseJSON.error;
                shared.errorPopup(errorMsg);
            }
        };
        new Ajax.Request(url, params);
    },
    youTubeSwitch: function(youTubeActive, successFunction) {
        var url = "ws/youTubeConnect.json";
        var params = {
            method: 'POST',
            postBody: 'youTubeActive=' + youTubeActive,
            onSuccess: successFunction,
            onFailure: function(resp) {
                var errorMsg = resp.responseJSON.error;
                shared.errorPopup(errorMsg);
            }
        };
        new Ajax.Request(url, params);
    },
    flickrSwitch: function(flickrActive, successFunction) {
        var url = "ws/flickrSwitch.json";
        var params = {
            method: 'POST',
            postBody: 'flickrActive=' + flickrActive,
            onSuccess: successFunction,
            onFailure: function(resp) {
                var errorMsg = resp.responseJSON.error;
                shared.errorPopup(errorMsg);
            }
        };
        new Ajax.Request(url, params);
    }
};
document.observe("dom:loaded", shared.init.bindAsEventListener(shared));