﻿var STS = {
    config: {
        dev: {
            serverName: "dev.cancer.org",
            passiveEndpoint: "/account/login/",
            accountProfileUrl: "https://dev.cancer.org/account/profile/",
            dialogHtmlSrcUrl: "http://dev.cancer.org/account/login/scripts/acsAcct.htm",
            dialogHtml: "",
            cssUrl: "https://dev.cancer.org/account/login/scripts/acsAcct.css",
            liveidAppId: "000000004C024105",
            facebookAppId: "303181704029",
            registrationMessage: "This is the Development Authentication Environment",
            registrationAlternateURL: null
        },

        qa: {
            serverName: "qa.cancer.org",
            passiveEndpoint: "/account/login/",
            accountProfileUrl: "https://qa.cancer.org/account/profile/",
            dialogHtmlSrcUrl: "http://qa.cancer.org/account/login/scripts/acsAcct.htm",
            dialogHtml: "",
            cssUrl: "https://qa.cancer.org/account/login/scripts/acsAcct.css",
            liveidAppId: "000000004002ED31",
            facebookAppId: "497747250520",
            registrationMessage: "This is the QA Authentication Environment",
            registrationAlternateURL: null
        },

        prod: {
            serverName: "account.cancer.org",
            passiveEndpoint: "/login/",
            accountProfileUrl: "https://account.cancer.org/profile/",
            dialogHtmlSrcUrl: "http://account.cancer.org/login/scripts/acsAcct.htm",
            dialogHtml: "",
            cssUrl: "https://account.cancer.org/login/scripts/acsAcct.css",
            liveidAppId: "0000000048038164",
            facebookAppId: "122253584464232",
            registrationMessage: "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.",
            registrationAlternateURL: null
        }
    },

    settings: {},

    // ***************************

    realm: "",
    modalTitle: "",
    returnUrl: "",
    isPassivePage: false,
    isRendered: false,
    isInitialized: false,
    isFacebookInitialized: false,

    logout: function(returnURL) {
        // Build logout URI based on passive sign-on profile:
        // http://msdn.microsoft.com/en-us/library/bb608217.aspx
        var uri = STS.getPassiveEndpointUri() +
                  "?wa=wsignout1.0" +      /* wa=wsignout1.0: Required action parameter */
                  "&wreply=" + encodeURIComponent(STS.getReturnURL(returnURL)) +         /* wreply: Return URL */
                  "&wtrealm=" + encodeURIComponent(STS.realm);

        window.location = uri;
    },

    editProfile: function(returnUrl) {
        window.location = STS.getEditProfileURL(returnUrl);
    },

    viewProfile: function(returnUrl) {
        window.location = STS.getViewProfileURL(returnUrl);
    },

    register: function(returnUrl) {
        window.location = STS.getProfileUrl("Register", returnUrl);
    },

    forgotPassword: function(returnUrl) {
        window.location = STS.getForgotPasswordURL(returnUrl);
    },

    getReturnURL: function(returnURL) {
        var ru = returnURL;

        if (!ru) {
            if (!STS.returnUrl)
                ru = window.location.href;
            else
                ru = STS.returnUrl;
        }

        // Remove extraneous "#" at end of URL
        if (ru.charAt(ru.length - 1) == '#')
            ru = ru.substring(0, ru.length - 1);

        return ru;
    },

    getEditProfileURL: function(returnURL) {
        return STS.getProfileUrl("EditProfile", returnURL);
    },

    getViewProfileURL: function(returnURL) {
        return STS.getProfileUrl("ViewProfile", returnURL);
    },

    getRegisterProfileURL: function(returnURL) {
        if (STS.settings.registrationAlternateURL)
            return STS.settings.registrationAlternateURL;
        else
            return STS.getProfileUrl("Register", returnURL);
    },

    getForgotPasswordURL: function(returnURL) {
        return STS.getProfileUrl("ForgotPassword", returnURL);
    },

    getProfileUrl: function(basePage, returnURL) {
        var url = STS.settings.accountProfileUrl
                   + basePage
                   + ".aspx?realm=" + encodeURIComponent(STS.realm)
                   + "&returnUrl=" + encodeURIComponent(STS.getReturnURL(returnURL));

        return url;
    },

    getPassiveEndpointUri: function(protocol) {
        if (protocol == undefined)
            protocol = "https";

        return protocol + "://" + STS.settings.serverName + STS.settings.passiveEndpoint;
    },

    // ############## Login methods ######################
    showLoginArea: function(provider, label) {
        //Get the base for all DOM elements we're going to alter.
        var providerId = '#' + $(provider).attr('id').split("-link")[0];

        // Highlight only the menu item selected
        $('#login-selector li').removeClass();
        $(provider).parent().addClass('active');

        // Show only the login for for the selected menu item
        $('.login-area').hide();
        $(providerId).show();

        // Show only the icon for the menu item selected
        $('#account-icon-wraps img').hide();
        $(providerId + '-icon-wrap').show();

        // Alter the form title with the name of the item clicked.
        if (label)
            $("#loginProvider").text(label.split(" Account")[0]);
    },

    getLoginUri: function() {
        return STS.getPassiveEndpointUri() + "?" + STS.getLoginParams();
    },


    getLoginParams: function() {
        // Get current URL for return
        var returnURL = STS.getReturnURL();

        // Build login URI based on passive sign-on profile:
        // http://msdn.microsoft.com/en-us/library/bb608217.aspx
        var wctx = "";

        if (STS.isPassivePage)
            wctx = STS.getParameterByName("wctx");
        else
            wctx = encodeURIComponent("rm=0&id=passive&ru=" + encodeURIComponent(returnURL));
        //        wctx = encodeURIComponent("rm=0&id=passive&ru=" + returnURL);

        // 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=" + encodeURIComponent(STS.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() {
        $('#login-selector li a').click(function(e) {
            var li = $(this).parent();
            var label = $(this).text();
            if ($(li).hasClass('active')) {
                return false;
            } else {
                STS.showLoginArea(this, label);
            }
            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;
    },

    getUserNameFromCookie: function() {
        return STS.readCookie("ACS_ACCOUNT_USERNAME");
    },

    loadCSS: function() {
        //Add ACS Account CSS
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('type', 'text/css');
        link.setAttribute('href', STS.settings.cssUrl);
        head.appendChild(link);
    },

    loadHtmlTemplating: function() {
        //Same Origin bug prevents this!
        //Dynamically load HTML
        //$.get(STS.settings.dialogHtmlSrcUrl, function(html) { STS.settings.dialogHtml = html; });
        //        $.ajax({
        //            url: STS.settings.dialogHtmlSrcUrl,
        //            success: function(html) { STS.settings.dialogHtml = html; },
        //            async: false
        //        });
        STS.settings.dialogHtml = '<div id="modal-ACSAcontainer"> <div class="modal-header"> <div class="modal-title"> Sign in to <span id="realmTitle"></span> </div> <div class="modal-close"> <a href="#" class="signin-close" id="close-button" title="close">Close</a></div> </div> <div class="modal-content"> <div id="login-selector"> <div class="login-selector-label"> Sign in using<br> your account with:</div> <ul> <li class="active"><a id="acs-login-link" href="#"><span>ACS Account</span></a></li> <li><a id="google-login-link" href="#"><span>Google</span></a></li> <li><a id="yahoo-login-link" href="#"><span>Yahoo</span></a></li> <li><a id="facebook-login-link" href="#"><span>Facebook</span></a></li> <li><a id="liveid-login-link" href="#"><span>Windows Live ID</span></a></li> <li><a id="aol-login-link" href="#"><span>AOL</span></a></li> <li><a id="openid-login-link" href="#"><span>OpenID</span></a></li> </ul> </div> <div id="signin"> <div id="signin-content"> <div id="account-icon-wraps"> <img id="acs-login-icon-wrap" alt="" src="https://www.cancer.org/acs/fragments/acs_css_files/images/global/acs-account-icon-wrap.png" style="display: inline;"> <img id="google-login-icon-wrap" alt="" src="https://www.cancer.org/acs/fragments/acs_css_files/images/global/google-account-icon-wrap.png" style="display: none;"> <img id="yahoo-login-icon-wrap" alt="" src="https://www.cancer.org/acs/fragments/acs_css_files/images/global/yahoo-account-icon-wrap.png" style="display: none;"> <img id="facebook-login-icon-wrap" alt="" src="https://www.cancer.org/acs/fragments/acs_css_files/images/global/facebook-account-icon-wrap.png" style="display: none;"> <img id="liveid-login-icon-wrap" alt="" src="https://www.cancer.org/acs/fragments/acs_css_files/images/global/liveid-account-icon-wrap.png" style="display: none;"> <img id="aol-login-icon-wrap" alt="" src="https://www.cancer.org/acs/fragments/acs_css_files/images/global/aol-account-icon-wrap.png" style="display: none;"> <img id="openid-login-icon-wrap" alt="" src="https://www.cancer.org/acs/fragments/acs_css_files/images/global/openid-account-icon-wrap.png" style="display: none;"> </div> <div id="error"> </div> <div class="signin-headline"> Sign In With Your <span id="loginProvider">ACS</span> Account</div> <div class="signin-paragraph"> </div> </div> <div id="acs-login" class="login-area"> <form id="acsAccountForm" method="post" action="[-CHANGE-THIS-ACTION-URL-]"> <fieldset> <div class="width50"> <label for="username" class="block">Email Address:</label> <input type="text" class="textfield" value="" tabindex="1" id="username" name="username"> <input type="checkbox" id="remember" name="remember" tabindex="4" value="yes"> <label for="remember" class="remember">Remember me</label> </div> <div class="width50"> <label for="password" class="block">Password:</label> <input type="password" class="textfield" tabindex="2" id="password" name="password"> <a href="#" class="forgot-password">Forgot your password?</a> <input type="submit" tabindex="3" class="signin-button"> </div> </fieldset> </form> <div class="register-blurb"> Don\'t have an ACS Account? Create an account now! <a id="register-button" href="#">Register</a> </div> </div> <div id="google-login" class="login-area" style="display: none;"> <button class="signin-button" id="btnSignInGoogle" type="submit"> Sign In</button> </div> <div id="yahoo-login" class="login-area" style="display: none;"> <button class="signin-button" id="btnSignInYahoo" type="submit"> Sign In</button> </div> <div id="liveid-login" class="login-area" style="display: none;"> <a href="#"> <img src="https://www.passportimages.com/1033/signin.gif" style="border-style: none;" alt="Windows Live Login"></a> </div> <div id="aol-login" class="login-area" style="display: none;"> <fieldset> <label for="aolScreenName"> Screen Name:</label> <input type="text" class="textfield" id="aolScreenName" name="aolScreenName"> <button class="signin-button" id="btnSignInAOL"> Sign In</button> </fieldset> </div> <div id="facebook-login" class="login-area" style="display: none;"><a class="fb_button fb_button_medium" onclick="ConnectLogin.login(null, \'\'); return false;"><span class="fb_button_text">Login with Facebook</span></a></div> <div id="openid-login" class="login-area" style="display: none;"> <fieldset> <label for="openIdUrl"> OpenID URL:</label> <input type="text" class="textfield" id="openIdUrl" name="openIdUrl" style="width: 300px;"> <button class="signin-button" id="btnSignInOpenId" type="submit"> Sign In</button> </fieldset> </div> </div> </div> <div class="modal-footer"> <div class="acsLogo-wTag"> The American Cancer Society - The Official Sponsor of Birthdays&reg;</div> </div> </div>';
    },

    init: function(realm, modalTitle, returnURL) {

        if (!STS.isInitialized) {
            STS.realm = (realm) ? realm : decodeURIComponent(STS.getParameterByName("wtrealm"));
            STS.initFacebook();
            STS.loadCSS();
            STS.isInitialized = true;
        }

        STS.returnUrl = STS.getReturnURL(returnURL);
        STS.modalTitle = modalTitle; // Application name
    },

    initSettings: function(realm) {
        STS.realm = (realm) ? realm : decodeURIComponent(STS.getParameterByName("wtrealm"));
    },

    initPassive: function() {
        STS.isPassivePage = true;
        STS.loadCSS();
        STS.realm = decodeURIComponent(STS.getParameterByName("wtrealm"));
        STS.initSettings(STS.realm);
        STS.isInitialized = true;
        STS.returnUrl = STS.parseReturnUrl();
    },

    parseReturnUrl: function() {
        var ru = "";

        var wctx = decodeURIComponent(STS.getParameterByName("wctx"));

        if (wctx != "" && wctx != null) {
            var ruix = wctx.indexOf("ru=");
            var endru = wctx.indexOf("&", ruix + 1);
            ru = (endru == -1 ? wctx.substring(ruix + 3) : wctx.substring(ruix + 3, endru));
            ru = decodeURIComponent(ru);
        }
        else {
            ru = decodeURIComponent(STS.getParameterByName("wreply"));
        }
        return ru;
    },

    initFacebook: function() {
        if (!STS.isFacebookInitialized) {
            if (!STS.isInitialized)
                STS.initSettings(STS.realm);

            $("body").append("<div id=\"fb-root\"></div>");

            window.fbAsyncInit = function() {
                FB.init({
                    appId: STS.settings.facebookAppId,
                    status: true,
                    cookie: true,
                    xfbml: true,
                    channelURL: STS.getPassiveEndpointUri() + "facebook/channel.html",
                    oauth: true
                });

                STS.isFacebookInitialized = true;
            };

            // Load the SDK Asynchronously
            (function(d) {
                var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
                js = d.createElement('script'); js.id = id; js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                d.getElementsByTagName('head')[0].appendChild(js);
            } (document));
        }
    },

    rememberProvider: function(providerName) {
        STS.createCookie("ACS_ACCOUNT_PROVIDER_SELECTION", providerName);
    },

    renderLogin: function(targetElement, showHeader) {
        if (targetElement && !STS.isRendered) {

            STS.loadHtmlTemplating();

            if (!targetElement.tagName)
                targetElement = $("#" + targetElement)[0];

            STS.initFacebook();

            var userName = STS.getUserNameFromCookie();
            if (!userName)
                userName = "";

            var dialog = $(STS.settings.dialogHtml);

            // Customize Modal UI
            dialog
                .find("#realmTitle")
                    .text(STS.modalTitle)
                    .end()
                .find("div.signin-paragraph")
                .text(STS.settings.registrationMessage)

            if (showHeader == false)
                dialog.find(".modal-header").remove();

            dialog
            // Prefill form
                .find("#username")
                    .val(userName)
                    .end()
                .find("#remember")
                    .attr('checked', !!userName)
                    .end()

                .find("#register-button")
                    .attr('href', STS.getRegisterProfileURL())
                    .end()
                .find("a.forgot-password")
                    .attr("href", STS.getForgotPasswordURL())
                    .end()

            // Bind Events
                .find("#acsAccountForm")
                    .attr("action", STS.getLoginUri())
                    .submit(function() { STS.rememberProvider("acs") })
                    .end()
                .find("#btnSignInGoogle")
                    .click(function() { STS.loginToGoogle(); return false; })
                    .end()
                .find("#btnSignInYahoo")
                    .click(function() { STS.loginToYahoo(); return false; })
                    .end()
                .find("#liveid-login a")
                    .click(function() { STS.loginToLive(); return false; })
                    .end()
                .find("#btnSignInAOL")
                    .click(function() { STS.loginToAOL(); return false; })
                    .end()
                .find("#facebook-login a")
                    .click(function() { STS.loginWithFacebook(); return false; })
            /*
            .attr("href", STS.getPassiveEndpointUri() +
            "/facebook/auth_request_receiver.htm?realm=" + STS.realm +
            "&name=" + STS.modalTitle +
            "&ru=" + encodeURIComponent(window.location.pathname + window.location.search)
            )
            */
                    .end()
                .find("#btnSignInOpenId")
                    .click(STS.loginToOpenId)
                    .end();

            // Render Modal
            $(targetElement).append(dialog);

            var selectedProvider = STS.readCookie("ACS_ACCOUNT_PROVIDER_SELECTION");
            if (!selectedProvider)
                selectedProvider = "acs";

            var selectItem = $("#" + selectedProvider + "-login-link")
                , selectText = $("#" + selectedProvider + "-link").text();

            STS.showLoginArea(selectItem, selectText);
            STS.configureEvents();

            STS.isRendered = true;
        };
    },


    loginToOpenIdProvider: function(identifier) {
        var uri = STS.getPassiveEndpointUri("https")
                + "OpenIDProvider.aspx?identifier="
                + encodeURIComponent(identifier)
                + "&" + STS.getLoginParams();

        window.open(uri, "openid", "width=650,height=500,scrollbars=yes");

        return false;
    },


    loginToACSAccountWithUser: function(userName, password, rememberMe) {
        $("#username").val(userName);
        $("#password").val(password);
        $("#remember").val(rememberMe);

        STS.loginToACSAccount();

        return false;
    },

    loginToACSAccount: function() {
        STS.rememberProvider("acs");

        $("#acsAccountForm").submit();

        return false;
    },

    loginToAOL: function(screenName) {
        STS.rememberProvider("aol");

        if (!screenName)
            screenName = $("#aolScreenName").val();

        if (!screenName)
            alert("Please enter an AOL screen name");
        else
            STS.loginToOpenIdProvider('openid.aol.com/' + screenName);

        return false;
    },

    loginToGoogle: function() {
        STS.rememberProvider("google");

        STS.loginToOpenIdProvider("https://www.google.com/accounts/o8/id");

        return false;
    },

    loginToLive: function() {
        STS.rememberProvider("liveid");

        window.location = "https://login.live.com/wlogin.srf?appid=" + STS.settings.liveidAppId +
                            "&appctx=" + encodeURIComponent(STS.getLoginUri());

        return false;
    },

    loginToOpenId: function(URL) {
        STS.rememberProvider("openid");

        if (!URL)
            URL = $("#openIdUrl").val();

        if (!URL)
            alert("Please enter a valid OpenID identifier");
        else
            STS.loginToOpenIdProvider(URL);

        return false;
    },

    loginToYahoo: function() {
        STS.rememberProvider("yahoo");

        STS.loginToOpenIdProvider("https://me.yahoo.com");

        return false;
    },

    loginWithFacebook: function() {
        STS.rememberProvider("facebook");

        var fbLoginURI = STS.getPassiveEndpointUri() +
                          "facebook/auth_request_receiver.htm?realm=" + STS.realm +
                          "&name=" + STS.modalTitle +
                          "&ru=" + STS.getReturnURL();

        window.location = fbLoginURI;

        return false;
    }
};

STS.settings = STS.config.prod;
