﻿/*********************************************************
'Filename:      LoginControl.js
'Website:       etherstudios.com
'Created By:    Michael England
'Created Date:

Modified        By              Description
----------------------------------------------------------

*********************************************************/

try {
    if (!EtherStudios.IsInitialized)
        document.write(unescape("%3Cscript type='text/javascript' src='/Common/Scripts/EtherStudios.js'%3E%3C/script%3E"));
} catch (err) {
    document.write(unescape("%3Cscript type='text/javascript' src='/Common/Scripts/EtherStudios.js'%3E%3C/script%3E"));
}

var LoginControl = new LoginControl()


function LoginControl()
{
    this.HasErrors = null;
    this.FacebookConnect_Enabled = false;
    this.FacebookConnect_ApplicationKey = null
    this.Twitter_Enabled = false;
    this.Twitter_OAuthPath = null;

    this.Init = function (hasErrors, facebookConnect_ApplicationKey, twitter_OAuthPath) {
        this.HasErrors = hasErrors;
        this.FacebookConnect_ApplicationKey = facebookConnect_ApplicationKey;
        this.Twitter_OAuthPath = twitter_OAuthPath;

        if (document.getElementById("linkLoginControl") == undefined) {
            var linkLoginControl = document.createElement("link");
            linkLoginControl.setAttribute("id", "linkLoginControl");
            linkLoginControl.setAttribute("type", "text/css");
            linkLoginControl.setAttribute("rel", "stylesheet");
            linkLoginControl.setAttribute("href", "/Common/Stylesheets/LoginControl.css");

            var head = document.getElementsByTagName("head")[0];
            head.appendChild(linkLoginControl);
        }


        if (facebookConnect_ApplicationKey != null) {
            this.FacebookConnect_Enabled = true;
            this.FacebookConnect_ApplicationKey = facebookConnect_ApplicationKey

            if (document.getElementById("jsFacebookConnectInclude") == undefined) {
                var jsFacebookConnectInclude = document.createElement("script");
                jsFacebookConnectInclude.setAttribute("id", "jsFacebookConnectInclude");
                jsFacebookConnectInclude.setAttribute("type", "text/javascript");
                jsFacebookConnectInclude.setAttribute("src", "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US");

                if (jsFacebookConnectInclude.readyState) {  //IE
                    jsFacebookConnectInclude.onreadystatechange = function () {
                        if (jsFacebookConnectInclude.readyState == "loaded" || jsFacebookConnectInclude.readyState == "complete") {
                            jsFacebookConnectInclude.onreadystatechange = null;
                            EtherStudios.RegisterLoadFunction("FB.init(LoginControl.FacebookConnect_ApplicationKey, 'xd_receiver.htm')");
                        }
                    };
                } else {  //Others
                    jsFacebookConnectInclude.onload = function () {
                        EtherStudios.RegisterLoadFunction("FB.init(LoginControl.FacebookConnect_ApplicationKey, 'xd_receiver.htm')");
                    };
                }

                var body = document.getElementsByTagName("body")[0];
                body.insertBefore(jsFacebookConnectInclude, document.body.firstChild);
            }
        }

        if (twitter_OAuthPath != null) {
            this.Twitter_Enabled = true;
        }

        if (this.HasErrors) {
            this.ShowLogin();
        }
    }

    this.Logout = function () {

        if (document.getElementById("divLogout") == undefined) {
            var html = '';
            html += '<form action="' + document.location + '" method="post" enctype="multipart/form-data" name="Logout">';
            html += '    <input type="hidden" name="Action" value="Logout" />';
            html += '</form>';

            var divLogout = document.createElement("div");
            divLogout.className = "Logout";
            divLogout.setAttribute("id", "divLogout");
            divLogout.style.display = "none";
            divLogout.innerHTML = html;

            var body = document.getElementsByTagName("body")[0];
            body.appendChild(divLogout);
        }
            
        if (this.FacebookConnect_Enabled) {
            FB.Connect.logout(function () {
                document.Logout.submit();
            });
        } else {
            document.Logout.submit();
        }
        
        return false;
    }

    this.ShowLogin = function () {
        if (document.getElementById("divLogin") == undefined) {
            var html = '';
            html += '<div class="LoginWrapper">';
            html += '    <div class="LoginLightBox"></div>';
            html += '    <div class="LoginForm">';
            html += '        <h2>Login</h2>';
            html += '        <form action="' + document.location + '" method="post" enctype="multipart/form-data" name="Login">';

            if (this.HasErrors)
                html += '<div class="Validator">Email Address or Password was incorrect</div>';

            if (this.FacebookConnect_Enabled || this.Twitter_Enabled)
                html += '<div class="LoginServices">';

            if (this.FacebookConnect_Enabled)
                html += '<fb:login-button size="medium" v="2" onlogin="window.location.reload(true);" class="Facebook"><span>Login with Facebook</span></fb:login-button>';

            if (this.Twitter_Enabled)
                html += '<a href="' + this.Twitter_OAuthPath + '" class="Twitter">Login with Twitter</a>';

            if (this.FacebookConnect_Enabled || this.Twitter_Enabled)
                html += '</div>';
                
            html += '            <div><span class="Label">Email Address</span><input type="text" name="txtEmailAddress" class="TextBox" /></div>';
            html += '            <div><span class="Label">Password</span><input type="password" name="txtPassword" class="TextBox" /></div>';
            html += '            <div class="CheckBox"><input type="checkbox" name="cbRememberMe" value="true" />Remember Me</div>';
            html += '            <div><input type="submit" class="Button LoginButton" value="Login" /> <a href="javascript:///" onclick="LoginControl.HideLogin();">Cancel</a></div>';
            html += '            <input type="hidden" name="Action" value="Login" />';
            html += '        </form>';
            html += '    </div>';
            html += '</div>';

            var divLogin = document.createElement("div");
            divLogin.className = "Login";
            divLogin.setAttribute("id", "divLogin");
            divLogin.style.display = "none";
            divLogin.innerHTML = html;
            var body = document.getElementsByTagName("body")[0];
            body.appendChild(divLogin);

        }

        if (this.FacebookConnect_Enabled)
            FB.XFBML.Host.parseDomTree();

        document.getElementById("divLogin").style.display = "block";
        return false;
    }

    this.HideLogin = function () {
        document.getElementById("divLogin").style.display = "none";
    }

    this.ShowFacebook = function (hasCreateUserErrors, hasLinkedUserErrors, validationSummary) {
        EtherStudios.RegisterLoadFunction("LoginControl.ShowFacebook_Load(" + hasCreateUserErrors + ", " + hasLinkedUserErrors + ", '" + validationSummary + "')");
    }

    this.ShowFacebook_Load = function (hasCreateUserErrors, hasLinkedUserErrors, validationSummary) {

        if (document.getElementById("divFacebook") == undefined) {
            var html = '';
            html += '<div class="LoginWrapper">';
            html += '    <div class="LoginLightBox"></div>';
            html += '    <div class="LoginForm">';
            html += '        <h2>Create an Account</h2>';
            html += '        <form action="' + document.location + '" method="post" enctype="multipart/form-data" name="CreateUser">';

            if (hasCreateUserErrors)
                html += 'div class="Validator">' + validationSummary + '</div>';

            html += '            <div><span class="Label">Your Facebook Account</span>';
            html += '                <fb:profile-pic uid="loggedinuser" size="thumb" facebook-logo="true"></fb:profile-pic>';
            html += '                <fb:name uid="loggedinuser" useyou="false" linked="false"></fb:name>';
            html += '            </div>';
            html += '            <div><span class="Label">Email Address</span><input type="text" name="txtEmailAddress" class="TextBox" /></div>';
            html += '            <div><input type="submit" class="Button CreateAccountButton" value="Create Account" /></div>';
            html += '            <input type="hidden" name="Action" value="FacebookConnect_CreateUser" />';
            html += '        </form>';
            html += '        <form action="" + HttpContext.Current.Request.RawUrl + @"" method="post" enctype="multipart/form-data" name="LinkeUser">';
            html += '            <div>Or, link your existing account to Facebook</div>';

            if (hasLinkedUserErrors)
                html += 'div class="Validator">Email Address or Password was incorrect</div>';

            html += '            <div><span class="Label">Email Address</span><input type="text" name="txtEmailAddress" class="TextBox" /></div>';
            html += '            <div><span class="Label">Password</span><input type="password" name="txtPassword" class="TextBox" /></div>';
            html += '            <div><input type="submit" class="Button LoginButton" value="Login" /> <a href="javascript:///" onclick="FB.Connect.logout(LoginControl.HideFacebook())">Cancel</a></div>';
            html += '            <input type="hidden" name="Action" value="FacebookConnect_LinkedUser" />';
            html += '        </form>';
            html += '    </div>';
            html += '</div>';

            var divFacebook = document.createElement("div");
            divFacebook.className = "Login";
            divFacebook.setAttribute("id", "divFacebook");
            divFacebook.style.display = "none";
            divFacebook.innerHTML = html;

            var body = document.getElementsByTagName("body")[0];
            body.appendChild(divFacebook);
        }

        //FB.XFBML.Host.parseDomTree();
        document.getElementById("divFacebook").style.display = "block";
        
        return false;
    }

    this.HideFacebook = function () {
        document.getElementById("divFacebook").style.display = "none";
    }

    this.ShowTwitter = function (hasCreateUserErrors, hasLinkedUserErrors, validationSummary, name, thumbnail) {
        EtherStudios.RegisterLoadFunction("LoginControl.ShowTwitter_Load(" + hasCreateUserErrors + ", " + hasLinkedUserErrors + ", '" + validationSummary + "','" + name + "','" + thumbnail + "')");
    }

    this.ShowTwitter_Load = function (hasCreateUserErrors, hasLinkedUserErrors, validationSummary, name, thumbnail) {

        if (document.getElementById("divTwitter") == undefined) {
            var html = '';
            html += '<div class="LoginWrapper">';
            html += '    <div class="LoginLightBox"></div>';
            html += '    <div class="LoginForm">';
            html += '        <h2>Create an Account</h2>';
            html += '        <form action="' + document.location + '" method="post" enctype="multipart/form-data" name="CreateUser">';

            if (hasCreateUserErrors)
                html += 'div class="Validator">' + validationSummary + '</div>';

            html += '            <div><span class="Label">Your Twitter Account</span>';
            html += '                <img src="' + string.decode(thumbnail) + '" alt="' + string.decode(name) + '" />';
            html += '                <span class="Name">' + string.decode(name) + '</span>';
            html += '            </div>';
            html += '            <div><span class="Label">Email Address</span><input type="text" name="txtEmailAddress" class="TextBox" /></div>';
            html += '            <div><input type="submit" class="Button CreateAccountButton" value="Create Account" /></div>';
            html += '            <input type="hidden" name="Action" value="Twitter_CreateUser" />';
            html += '        </form>';
            html += '        <form action="" + HttpContext.Current.Request.RawUrl + @"" method="post" enctype="multipart/form-data" name="LinkeUser">';
            html += '            <div>Or, link your existing account to Twitter</div>';

            if (hasLinkedUserErrors)
                html += 'div class="Validator">Email Address or Password was incorrect</div>';

            html += '            <div><span class="Label">Email Address</span><input type="text" name="txtEmailAddress" class="TextBox" /></div>';
            html += '            <div><span class="Label">Password</span><input type="password" name="txtPassword" class="TextBox" /></div>';
            html += '            <div><input type="submit" class="Button LoginButton" value="Login" /> <a href="javascript:///" onclick="FB.Connect.logout(LoginControl.HideTwitter())">Cancel</a></div>';
            html += '            <input type="hidden" name="Action" value="Twitter_LinkedUser" />';
            html += '        </form>';
            html += '    </div>';
            html += '</div>';

            var divFacebook = document.createElement("div");
            divFacebook.className = "Login";
            divFacebook.setAttribute("id", "divTwitter");
            divFacebook.style.display = "none";
            divFacebook.innerHTML = html;

            var body = document.getElementsByTagName("body")[0];
            body.appendChild(divFacebook);
        }

        //FB.XFBML.Host.parseDomTree();
        document.getElementById("divTwitter").style.display = "block";

        return false;
    }

    this.HideTwitter = function () {
        var expires = new Date();
        expires.setUTCFullYear(expires.getUTCFullYear() - 1);
        document.cookie = 'Twitter=; expires=' + expires.toUTCString() + '; path=/';
    
        document.getElementById("divTwitter").style.display = "none";
    }

    var string = {

        // public method for url encoding
        encode: function (string) {
            return escape(this._utf8_encode(string));
        },

        // public method for url decoding
        decode: function (string) {
            return this._utf8_decode(unescape(string.replace(/\+/g, " ")));
        },

        // private method for UTF-8 encoding
        _utf8_encode: function (string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";

            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
            }
            return utftext;
        },

        // private method for UTF-8 decoding
        _utf8_decode: function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;

            while (i < utftext.length) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    }
}
