﻿var STS = {

    // **** Member variables *****
    settings: {
        serverName: "",
        passiveEndpoint: "login",
        accountProfileUrl: "https://account.cancer.org/account/profile",
        liveidAppId: "",
        facebookAppId: "",
        enableProfileAutoExt: true
    },

    config: {
        "https://atlnhoiddvapxy1.nho.acs.cancer.org/account/signin/":
        {
            serverName: "dev.cancer.org",
            passiveEndpoint: "account/login",
            accountProfileUrl: "https://dev.cancer.org/account/profile",
            liveidAppId: "000000004C024105",
            facebookAppId: "ea3a01eb136659b41a2e91f38e6844d2",
            enableProfileAutoExt: true
        },

        "https://atlnhoidqvapxy1.nho.acs.cancer.org/account/signin/":
        {
            serverName: "qa.cancer.org",
            passiveEndpoint: "account/login",
            accountProfileUrl: "https://qa.cancer.org/account/profile",
            liveidAppId: "000000004002ED31",
            facebookAppId: "88907a6ef101d4cda62c84aad41ac2e9",
            enableProfileAutoExt: true
        },

        "https://contrib.cancer.org/":
        {
            serverName: "contrib.cancer.org",
            passiveEndpoint: "account/login",
            accountProfileUrl: "https://contrib.cancer.org/account/profile",
            liveidAppId: "000000004C02F5BF",
            facebookAppId: "b236031d4e03031ecc28ffc0b3ec9493",
            enableProfileAutoExt: true
        },

        "https://account.cancer.org/":
        {
            serverName: "account.cancer.org",
            passiveEndpoint: "login",
            accountProfileUrl: "https://account.cancer.org/profile",
            liveidAppId: "0000000048038164",
            facebookAppId: "9eee97a1a46b6f8712c801d4a75baeff",
            enableProfileAutoExt: false
        },

        "https://www.cancer.org/":
        {
            serverName: "account.cancer.org",
            passiveEndpoint: "login",
            accountProfileUrl: "https://account.cancer.org/profile",
            liveidAppId: "0000000048038164",
            facebookAppId: "9eee97a1a46b6f8712c801d4a75baeff",
            enableProfileAutoExt: false
        }
    },

    // ***************************

    loginToOpenIdProvider: function(realm, identifier) {
        identifier = encodeURIComponent(identifier);
        var uri = this.getPassiveEndpointUri("http") + "/OpenIDProvider.aspx?identifier=" + identifier + "&" + this.getLoginParams(realm);

        window.open(uri, "openid", "width=650,height=500,scrollbars=yes");
        return false;
    },

    login: function(realm) {
        // Get URI for login
        var loginUri = this.getLoginUri(realm);

        //
        // Redirect to STS
        document.location = loginUri;
    },

    signInWithOpenId: function(identifier) {
        var signInUri = this.getLoginUri(this.rpRealm) + "&lm=openid&loginid=" + identifier;
        document.location = signInUri;
    },

    logout: function() {
        var ru = encodeURIComponent(document.location.href);
        ru = this.trimUrl(ru);

        // Build logout URI based on passive sign-on profile:
        // http://msdn.microsoft.com/en-us/library/bb608217.aspx
        var uri = this.getPassiveEndpointUri() +
                  "/?wa=wsignout1.0" +      /* wa=wsignout1.0: Required action parameter */
                  "&wreply=" + ru +         /* wreply: Return URL */
                  "&wtrealm=" + encodeURIComponent(this.rpRealm);
        document.location = uri;
    },

    editProfile: function(returnUrl) {
        document.location = this.getProfileUrl("EditProfile", returnUrl);
    },

    viewProfile: function(returnUrl) {
        document.location = this.getProfileUrl("ViewProfile", returnUrl);
    },

    register: function(returnUrl) {
        document.location = this.getProfileUrl("Register", returnUrl);
    },

    getProfileUrl: function(basePage, returnUrl) {
        var url = this.settings.accountProfileUrl + "/" + basePage + (this.settings.enableProfileAutoExt ? "" : ".aspx") + "?realm=" + encodeURIComponent(this.rpRealm);

        if (returnUrl != null && returnUrl != undefined) {
            url += "&returnUrl=" + encodeURIComponent(returnUrl);
        }
        else {
            url += "&returnUrl=" + encodeURIComponent(document.location.href);
        }

        return url;
    },

    getPassiveEndpointUri: function(protocol) {
        if (protocol == undefined) {
            protocol = "https";
        }
        return protocol + "://" + STS.settings.serverName + "/" + STS.settings.passiveEndpoint;
    },

    // ############## Login methods ######################
    showLoginArea: function(a, c) {
        $('#login-selector-list li').not(a).removeClass();
        $(a).addClass('active');
        var b = a.attr('id');
        b = b.split("-link");
        var d = "#" + b[0] + '-icon-wrap';
        //console.log(d);
        b = '#' + b[0];
        $('.account-icon-wrap').not(d).hide();
        $(d).show();
        $('.login-area').not(b).hide();
        c = c.split(" Account");
        $("#loginProvider").text(c[0]);
        $(b).show();
    },

    rpRealm: "",
    rpName: "",
    returnUrl: "",
    loginUri: "",
    isPassivePage: false,
    isRendered: false,
    isInitialized: false,
    isFacebookInitialized: false,

    getLoginUri: function(realm) {
        var uri = this.getPassiveEndpointUri() + "/?" + this.getLoginParams(realm);
        return uri;
    },

    trimUrl: function(url) {
        if (url.charAt(url.length - 1) == '#') {
            // Remove extraneous "#" at end of URL
            url = url.substring(0, url.length - 1);
        }

        return url;
    },

    getLoginParams: function(realm) {
        // Get current URL for return
        var ru = this.returnUrl;
        ru = this.trimUrl(ru);

        // Build login URI based on passive sign-on profile:
        // http://msdn.microsoft.com/en-us/library/bb608217.aspx
        var wctx = "";

        if (this.isPassivePage) {
            wctx = this.getParameterByName("wctx");
        }
        else {
            wctx = encodeURIComponent("rm=0&id=passive&ru=" + ru);
        }

        realm = encodeURIComponent(realm);

        // Current date in UTC format
        var dt = new Date();
        var wct = dt.getUTCFullYear() + "-" + dt.getUTCMonth() + dt.getUTCDate() + "T" +
                  dt.getUTCHours() + ":" + dt.getUTCMinutes() + ":" + dt.getUTCSeconds() + "Z";

        var loginParams = "wa=wsignin1.0" +         /* wa=wsignin1.0: Required action parameter */
                          "&wtrealm=" + realm +     /* wtrealm: Relying party URI */
                          "&wctx=" + wctx +         /* wctx: Optional return information */
                          "&wct=" + wct;            /* wct: Optional current time */

        return loginParams;
    },

    getParameterByName: function(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return results[1];
    },

    createCookie: function(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    configureEvents: function() {
        // Enable submission when pressing enter
        /*
        $("#acsAccountForm :input").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        STS.loginToACSAccount();
        return false;
        } else {
        return true;
        }
        });
        */

        $('#login-selector-list li a').click(function(e) {
            var a = $(this).parent();
            var c = $(this).text();
            if ($(a).hasClass('active')) {
                return false;
            } else {
                STS.showLoginArea(a, c);
            }
            e.preventDefault();
        });
    },

    readCookie: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    },

    eraseCookie: function(name) {
        createCookie(name, "", -1);
    },

    getUserNameFromCookie: function() {
        return this.readCookie("ACS_ACCOUNT_USERNAME");
    },

    getRememberMeFromCookie: function() {
        return this.readCookie("ACS_ACCOUNT_REMEMBER_LOGIN");
    },

    init: function(realm, name, ru) {
        if (!this.isInitialized) {
            this.initSettings(realm);

            if (realm == "" || realm == undefined) {
                this.rpRealm = decodeURIComponent(this.getParameterByName("wtrealm"));
            }
            else {
                this.rpRealm = realm;
            }

            this.initFacebook();

            this.isInitialized = true;
        }

        if (ru == "" || ru == undefined) {
            this.returnUrl = document.location.href;
        }
        else {
            this.returnUrl = ru;
        }

        this.rpName = name; // Application name
        this.loginUri = this.getLoginUri(this.rpRealm);

        var fbScript = "<script type=\"text/\javascript\" src=\"";

        if (document.location.protocol == "https:") {
            fbScript += "https:\/\/ssl.connect.facebook.com\/js\/api_lib\/v0.4\/FeatureLoader.js.php";
        }
        else {
            fbScript += "http:\/\/static.ak.connect.facebook.com\/js\/api_lib\/v0.4\/FeatureLoader.js.php";
        }

        fbScript += "\"><\/script>";

        $("body").append(fbScript);
    },

    initSettings: function(realm) {
        if (this.config[realm] != null && this.config[realm] != undefined) {
            this.settings = this.config[realm];
        }
    },

    initPassive: function() {
        this.isPassivePage = true;
        this.rpRealm = decodeURIComponent(this.getParameterByName("wtrealm"));
        this.initSettings(this.rpRealm);
        this.isInitialized = true;
    },

    initFacebook: function() {
        if (!this.isFacebookInitialized && typeof (FB) !== "undefined") {
            if (!this.isInitialized) {
                this.initSettings(this.rpRealm);
            }

            var receiver = "";

            if (document.location.protocol == "https:") {
                receiver = "xd_receiver_ssl.htm";
            }
            else {
                receiver = "xd_receiver.htm";
            }

            FB.init(this.settings.facebookAppId, "/" + this.settings.passiveEndpoint + "/facebook/" + receiver);
            this.isFacebookInitialized = true;
        }
    },

    loginToACSAccountWithUser: function(userName, password, rememberMe) {
        $("#username").val(userName);
        $("#password").val(password);
        $("#remember").val(rememberMe);

        this.loginToACSAccount();
    },

    loginToACSAccount: function() {
        this.rememberProvider("acs");
        $("#acsAccountForm").submit();
    },

    loginToAOL: function(screenName) {
        this.rememberProvider("aol");
        if (screenName == null || screenName == undefined) {
            screenName = $("#aolScreenName").val();
        }

        if (screenName == null || screenName == undefined || screenName == "") {
            alert("Please enter an AOL screen name");
        }
        else {
            this.loginToOpenIdProvider(this.rpRealm, 'openid.aol.com/' + screenName);
        }
        return false;
    },

    loginToGoogle: function() {
        this.rememberProvider("google");
        this.loginToOpenIdProvider(this.rpRealm, "https://www.google.com/accounts/o8/id");
        return false;
    },

    loginToLive: function() {
        this.rememberProvider("liveid");
        document.location = "http://login.live.com/wlogin.srf?appid=" + this.settings.liveidAppId + "&appctx=" + encodeURIComponent(this.getLoginUri(this.rpRealm));
    },

    loginToOpenId: function(url) {
        this.rememberProvider("openid");
        if (url == null || url == undefined) {
            url = $("#openIdUrl").val();
        }
        if (url == null || url == undefined || url == "") {
            alert("Please enter a valid OpenID identifier");
        }
        else {
            this.loginToOpenIdProvider(this.rpRealm, url);
        }
        return false;
    },

    loginToYahoo: function() {
        this.rememberProvider("yahoo");
        this.loginToOpenIdProvider(this.rpRealm, "https://me.yahoo.com");
        return false;
    },

    loginWithFacebook: function() {
        this.rememberProvider("facebook");
        var fbLoginUri = this.getLoginUri(this.rpRealm) + "&lm=facebook";
        document.location = fbLoginUri;
        return false;
    },

    rememberProvider: function(providerName) {
        this.createCookie("ACS_ACCOUNT_PROVIDER_SELECTION", providerName);
    },

    renderSelector: function(selectedProvider, providerName, providerDesc) {
        var active = "";
        if (selectedProvider == providerName) {
            active = "class=\"active\"";
        }
        var selector = "<li " + active + " id=\"" + providerName + "-login-link\">";
        selector += "<a href=\"#\"><span>" + providerDesc + "<\/span><\/a><\/li>";

        return selector;
    },

    renderLogin: function(root, showHeader) {
        if (root != null && !this.isRendered) {
            if (root.tagName === undefined) {
                root = $("#" + root)[0];
            }
            this.isRendered = true;

            this.initFacebook();

            var userName = this.getUserNameFromCookie();
            if (userName == null) userName = "";

            if (showHeader == undefined) {
                showHeader = true;
            }

            var loginContent = "";
            loginContent += "<div id=\"signin-wrapper\">";
            if (showHeader) {
                loginContent += "  <div id=\"signin-header\">";
                loginContent += "    <h2>Sign in to " + this.rpName + "<\/h2>";
                loginContent += "    <p><a title=\"close\" id=\"close-button\" class=\"signin-close\" href=\"#\">Close<\/a><\/p>";
                loginContent += "  <\/div>";
            }
            loginContent += "  <div id=\"signin-content\"> <span style=\"color:red;\" id=\"error\"><\/span>";
            loginContent += "    <div id=\"signin-left\">";
            loginContent += "      <p>Sign in using<br \/>";
            loginContent += "        your account with:<\/p>";
            loginContent += "      <ul id=\"login-selector-list\">";
            loginContent += "        <li id=\"acs-login-link\" class=\"active\"><a href=\"#\" id=\"acs-link\"><span>ACS Account<\/span><\/a><\/li>";
            loginContent += "        <li id=\"google-login-link\"><a href=\"#\" id=\"google-link\"><span>Google<\/span><\/a><\/li>";
            loginContent += "        <li id=\"yahoo-login-link\"><a href=\"#\" id=\"yahoo-link\"><span>Yahoo<\/span><\/a><\/li>";
            loginContent += "        <li id=\"facebook-login-link\"><a href=\"#\" id=\"facebook-link\"><span>Facebook<\/span><\/a><\/li>";
            loginContent += "        <li id=\"liveid-login-link\"><a href=\"#\" id=\"liveid-link\"><span>Windows Live ID<\/span><\/a><\/li>";
            loginContent += "        <li id=\"aol-login-link\"><a href=\"#\" id=\"aol-link\"><span>AOL<\/span><\/a><\/li>";
            loginContent += "        <li id=\"openid-login-link\"><a href=\"#\" id=\"openid-link\"><span>OpenID<\/span><\/a><\/li>";
            loginContent += "      <\/ul>";
            loginContent += "    <\/div>";
            loginContent += "    <!-- \/signin-header -->";
            loginContent += "    <div id=\"signin-right\">";
            loginContent += "      <div id=\"signin-right-content\">";
            loginContent += "        <h3>Sign In With Your <span id=\"loginProvider\">ACS<\/span> Account<\/h3>";
            loginContent += "        <p id=\"account-icon-wraps\"><img src=\"\/acs\/fragments\/acs_css_files\/images\/global\/acs-account-icon-wrap.png\" alt=\"\" class=\"account-icon-wrap\" id=\"acs-login-icon-wrap\" \/> <img src=\"\/acs\/fragments\/acs_css_files\/images\/global\/google-account-icon-wrap.png\" alt=\"\" class=\"account-icon-wrap\" id=\"google-login-icon-wrap\" \/> <img src=\"\/acs\/fragments\/acs_css_files\/images\/global\/yahoo-account-icon-wrap.png\" alt=\"\" class=\"account-icon-wrap\" id=\"yahoo-login-icon-wrap\" \/> <img src=\"\/acs\/fragments\/acs_css_files\/images\/global\/facebook-account-icon-wrap.png\" alt=\"\" class=\"account-icon-wrap\" id=\"facebook-login-icon-wrap\" \/> <img src=\"\/acs\/fragments\/acs_css_files\/images\/global\/liveid-account-icon-wrap.png\" alt=\"\" class=\"account-icon-wrap\" id=\"liveid-login-icon-wrap\" \/> <img src=\"\/acs\/fragments\/acs_css_files\/images\/global\/aol-account-icon-wrap.png\" alt=\"\" class=\"account-icon-wrap\" id=\"aol-login-icon-wrap\" \/> <img src=\"\/acs\/fragments\/acs_css_files\/images\/global\/openid-account-icon-wrap.png\" alt=\"\" class=\"account-icon-wrap\" id=\"openid-login-icon-wrap\" \/><\/p>";
            loginContent += "        <p>Registering and signing in allows you to interact with your American Cancer Society the way you want to.   Automatically receive the cancer information you're interested in, connect with events and resources in your area, and customize your site to save relevant articles.  You can even use an ID you may already have - including Facebook, Google, Yahoo, and more.<\/p>";
            loginContent += "      <\/div>";
            loginContent += "      <!-- \/signin-right-content -->";
            loginContent += "      <div class=\"login-area\" id=\"acs-login\">";
            loginContent += "        <form action=\"" + this.loginUri + "\" method=\"post\" id=\"acsAccountForm\" onsubmit=\"STS.rememberProvider('acs')\">";
            loginContent += "          <fieldset>";
            loginContent += "          <p>";
            loginContent += "            <label class=\"block\" for=\"username\">Email Address:<\/label>";
            loginContent += "            <input type=\"text\" name=\"username\" id=\"username\" tabindex=\"1\" value=\"" + userName + "\" class=\"textfield\" \/>";
            loginContent += "            <input type=\"submit\" class=\"signin-button\" tabindex=\"3\" \/>";
            loginContent += "            <input type=\"checkbox\" value=\"yes\" tabindex=\"4\" name=\"remember\" id=\"remember\" " + (userName != "" ? "checked" : "") + " \/>";
            loginContent += "            <label for=\"remember\">Remember me<\/label>";
            loginContent += "          <\/p>";
            loginContent += "          <p>";
            loginContent += "            <label class=\"block\" for=\"password\">Password:<\/label>";
            loginContent += "            <input type=\"password\" name=\"password\" id=\"password\" tabindex=\"2\" class=\"textfield\" \/>";
            loginContent += "            <a  class=\"block\" href=\"" + this.getProfileUrl("ForgotPassword") + "\">Forgot your password?<\/a> <\/p>";
            loginContent += "          <\/fieldset>";
            loginContent += "        <\/form>";
            loginContent += "        <p id=\"register-blurb\">Don't have an ACS Account? <span>Create an account now!<\/span> <a href=\"" + this.getProfileUrl("Register") + "\" id=\"register-button\">Register<\/a><\/p>";
            loginContent += "      <\/div>";
            loginContent += "      <div class=\"login-area\" id=\"google-login\">";
            loginContent += "        <p>";
            loginContent += "          <button type=\"submit\" onclick=\"STS.loginToGoogle();return false;\" id=\"btnSignInGoogle\" class=\"signin-button\">Sign In<\/button>";
            loginContent += "        <\/p>";
            loginContent += "      <\/div>";
            loginContent += "      <div class=\"login-area\" id=\"yahoo-login\">";
            loginContent += "        <p>";
            loginContent += "          <button type=\"submit\" onclick=\"STS.loginToYahoo();return false;\" id=\"btnSignInYahoo\" class=\"signin-button\">Sign In<\/button>";
            loginContent += "        <\/p>";
            loginContent += "      <\/div>";
            loginContent += "      <div class=\"login-area\" id=\"liveid-login\">";
            loginContent += "        <p><a onclick=\"STS.loginToLive();return false;\" href=\"#\"><img alt=\"Windows Live Login\" style=\"border-style: none;\" src=\"https:\/\/www.passportimages.com\/1033\/signin.gif\" \/><\/a><\/p>";
            loginContent += "      <\/div>";
            loginContent += "      <div class=\"login-area\" id=\"aol-login\">";
            loginContent += "        <fieldset>";
            loginContent += "        <p>";
            loginContent += "          <label for=\"aolScreenName\">Screen Name:<\/label>";
            loginContent += "          <input type=\"text\" name=\"aolScreenName\" id=\"aolScreenName\" class=\"textfield\" \/>";
            loginContent += "          <button onclick=\"STS.loginToAOL();return false;\" id=\"btnSignInAOL\" class=\"signin-button\">Sign In<\/button>";
            loginContent += "        <\/p>";
            loginContent += "        <\/fieldset>";
            loginContent += "      <\/div>";
            loginContent += "      <div class=\"login-area\" id=\"facebook-login\" >";
            loginContent += "        <div style=\"position: absolute; top: -10000px; width: 0px; height: 0px;\" id=\"FB_HiddenContainer\"><\/div>";
            //loginContent += "        <fb:login-button v=\"2\" size=\"large\" onlogin=\"STS.loginWithFacebook()\">Login with Facebook<\/fb:login-button>";
            loginContent += "          <a href=\"#\" onclick=\"FB.Connect.requireSession(function() { STS.loginWithFacebook(); }); return false;\" class=\"fbconnect_login_button FBConnectButton FBConnectButton_Large\">";
            loginContent += "             <span id=\"RES_ID_fb_login_text\" class=\"FBConnectButton_Text\">Login with Facebook<\/span>";
            loginContent += "          <\/a>";
            loginContent += "      <\/div>";
            loginContent += "      <div class=\"login-area\" id=\"openid-login\">";
            loginContent += "        <fieldset>";
            loginContent += "        <p>";
            loginContent += "          <label for=\"openIdUrl\">OpenID URL:<\/label>";
            loginContent += "          <input type=\"text\" style=\"width: 300px;\" name=\"openIdUrl\" id=\"openIdUrl\" class=\"textfield\" \/>";
            loginContent += "          <button type=\"submit\" onclick=\"STS.loginToOpenId();return false;\" id=\"btnSignInOpenId\" class=\"signin-button\">Sign In<\/button>";
            loginContent += "        <\/p>";
            loginContent += "        <\/fieldset>";
            loginContent += "      <\/div>";
            loginContent += "    <\/div>";
            loginContent += "  <\/div>";
            loginContent += "  <div id=\"signin-footer\">";
            loginContent += "    <h3>The American Cancer Society - The Official Sponsor of Birthdays&reg;<\/h3>";
            loginContent += "  <\/div>";
            loginContent += "<\/div>";

            $(root).append(loginContent);

            var selectedProvider = this.readCookie("ACS_ACCOUNT_PROVIDER_SELECTION");
            if (selectedProvider == null || selectedProvider == "") selectedProvider = "acs";
            var selectItem = $("#" + selectedProvider + "-login-link");
            var selectText = $("#" + selectedProvider + "-link").text();
            this.showLoginArea(selectItem, selectText);

            this.configureEvents();
        }
    }
}