var UniversalAuthentication = function() {        
    return {
        loadingImage : new Image(),
        storedSecret : 0.0,
        prematuredlyToggled : false,
        
        init: function() {
            //this.getDisplayName();           
            YAHOO.util.Event.addListener(YAHOO.util.Dom.get("authPopupTrigger"), "click", this.toggle, this, true);
            YAHOO.util.Event.addListener(YAHOO.util.Dom.get("loginclose").childNodes[0], "click", this.toggle, this, true);
            this.setup();
        },
        
        setup : function() {  
            this.iframe = YAHOO.util.Dom.get("authiframe");
            
            if (typeof(this.iframe) != "undefined")
            {
                this.firstOpen = true;
                this.overlay = document.getElementById("loginoverlay");
                
                if (!this.prematurelyToggled) { this.overlayVisible = false; }
                else { this.toggle(); }
                
                this.loadingImage.src = "https://secure.marketwatch.com/mw3/misc/ajax-loader.gif";
            }
        },
        
        toggle : function(e) {
            YAHOO.util.Event.stopEvent(e);
            
            if (typeof(this.iframe) == "undefined") { this.prematurelyToggled = true; }
            else
            {
                if (this.overlayVisible)
                {
                    this.overlay.style.display = "none"; this.overlayVisible = false;
                }
                else
                {
                    if (this.firstOpen)
                    {
                        // First, generate a stored secret that someone can check...
                        // Then populate the global variable and pass it on to the authentication page.
                        // The authentication page should append this number onto the URL of any frame
                        // which will communication back with this one...
                        UniversalAuthentication.storedSecret = Math.floor(Math.random()*100000001)
                        this.iframe.src = YAHOO.util.Dom.get("authiframesrc").value + "#vars=" + UniversalAuthentication.storedSecret + "&domain=" + window.location.host;
                        this.firstOpen = false;
                        
                        var me = this;
                        YAHOO.util.Event.addListener(this.iframe, "load", function() { me.overlay.style.display = "block"; } );
                    }
                    else { this.overlay.style.display = "block"; }
                    this.overlayVisible = true;
                }
            }
        },
        
        checkLoginKeyEvent : function(e) {
            if (e.keyCode == 13) this.attemptLogin();
	        return false;
        },
        
        ignoreLoginKeyEvent : function(e) {
            try { e.preventDefault(); e.stopPropagation(); }
            catch (exception) { }
        },
        
        // Dirty, dirty, dirty, dirty...
        getDisplayName : function() {
            try {
                var mktwport = /marketwatchportfolio=([^;]*)/i.exec(document.cookie)[1];
                var uname = /uname=([^&;]*)/i.exec(mktwport)[1];
                var dncheck = 0;
                var dncheckMatch = /dncheck=([^&;]*)/i.exec(mktwport);
                if (typeof(dncheckMatch) != "undefined" && dncheckMatch) { dncheck = dncheckMatch[1]; }
                var email = /email=([^&;]*)/i.exec(mktwport)[1];
                
                if (unescape(uname).indexOf("@") > 0 || uname.length > 20 || (email.toLowerCase().indexOf(uname.toLowerCase()) >= 0 && dncheck != "1"))
                {
                    var userid = /uid=([^&;]*)/i.exec(mktwport)[1];
                    var nameRequest = this.getRequestObject();
                    var params = "userid=" + unescape(userid);
                    
                    var uri = "https://secure3.marketwatch.com/registration/getdisplayname.aspx";
                    
                    nameRequest.open("POST", uri, true);
                    nameRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    nameRequest.setRequestHeader("Content-length", params.length);
                    nameRequest.setRequestHeader("Connection", "close");
                    
                    var me = this;
                    nameRequest.onreadystatechange = function()
                    {
                        if(nameRequest.readyState == 4)
                        {
                            me.getDisplayNameResponse(nameRequest.responseText);
                        }
                    };
                    nameRequest.send(params);
                }
            }
            catch (exception) { }
            
            return false;
        },
        
        // ...dirty, dirty, dirty, dirty...
        getDisplayNameResponse : function(response) {
            try {
                var displayName = /{\"displayname\":\"(.*)\"}/i.exec(response)[1];
                if (typeof(displayName) != "undefined" && displayName != "")
                {
                    var mktwport = unescape(/marketwatchportfolio=([^;]*)/i.exec(document.cookie)[0]);
                    mktwport = mktwport.replace(/(uname=)([^&;]*)/gi, "$1" + displayName);
                    var date = new Date();
                    date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000)); // Add 30 days to today
                    var rest = "; expires=" + date.toGMTString() + "; path=/; domain=.marketwatch.com";
                    if (mktwport.toLowerCase().indexOf("dncheck") < 0) rest = "&dncheck=1" + rest;
                    mktwport = mktwport + rest;
                    document.cookie = mktwport;
                }
            }
            catch (exception) { }
        },
        
        attemptLogin : function(loginUrl) {
            this.showSignInAnimation();
            
            var loginRequest = this.getRequestObject();
            var authId = document.getElementById("authenticationid").value;
            var password = document.getElementById("password").value;
            var params = "authenticationid=" + authId + "&password=" + password;

            // First, make sure a load event would trigger...
            document.getElementById("frameChild").src = "";

            loginRequest.open("POST", "authentication.aspx", true);
            
            loginRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            loginRequest.setRequestHeader("Content-length", params.length);
            loginRequest.setRequestHeader("Connection", "close");
            
            var me = this;
            loginRequest.onreadystatechange = function()
            {
                if(loginRequest.readyState == 4)
                {
                    me.loginComplete(loginRequest.responseText);
                }
            };
            loginRequest.send(params);
            
            return false;
        },
        
        loginComplete : function(response) {      
            var dsrlzd = JSON.deserializeNoValidate(response);
            if (!dsrlzd.ValidMember) { this.hideSignInAnimation(); }
            
            // Get the secret value we have stored...
            var box = document.getElementById("secret");
            var secret = box.value;
            
            var domain = "http://" + /[?|&]domain=([^&]*)/i.exec(window.location)[1];
            document.getElementById("frameChild").src = domain + "/AuthenticationReceiver.htm#secret=" + secret + "&var=" + response;
        },
        
        showSignInAnimation : function() {
            var loginButton = document.getElementById("loginbutton");
            var loginLoading = document.getElementById("loginloading");
            loginButton.style.display = "none";
            loginLoading.style.display = "block";
        },
        
        hideSignInAnimation : function() {
            var loginButton = document.getElementById("loginbutton");
            var loginLoading = document.getElementById("loginloading");
            loginLoading.style.display = "none";
            loginButton.style.display = "block";
        },
        
        storeHash : function() {
            var box = document.getElementById("secret");
            box.value = /[#|?|&]vars=([^&]*)/i.exec(window.location)[1];
        },
        
        getRequestObject : function() {
            var xmlHttp = false;
            try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } 
            catch (msxml2Exception) 
            {
                try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
                catch (microsoftException) { xmlHttp = false; }
            }
            if (!xmlHttp && typeof XMLHttpRequest != 'undefined')
                xmlHttp = new XMLHttpRequest();
            return xmlHttp;     
        },
        
        reloadPage : function() {
            window.location.reload();
        }
    };
}();