﻿
// **********************************
// * Setup of the config data object


// Calculates some values for the webcxData object based on other values
function webcx_expandData(webcxData) {
    // Modify the object to suit our needs.
    webcxData.debugString = webcxData.debug ? "debug=1&" : "";
    if (webcxData.afterLogin == "Redirect" && webcxData.redirectURL != "" && webcxData.redirectURL != null)
        webcxData.redirectURLString = "&redirectURL=" + encodeURIComponent(webcxData.redirectURL);
    else
        webcxData.redirectURLString = "";

    // Finally, return the modified object
    return webcxData;
}

function bustCache() {
    var myDate = new Date();
    return "cacheBuster=" + myDate.getTime() + "&";
}


// *************************************************************************************************
// * ASP.NET Webcx Client
// *
// * The parameter clientOptions must be JSON with the following structure:
// *    lastJSON - a string with the last value JSON received from the remote loginstatus or login
// *        For the asp.net client, this should be returned from server-side storage

function webcx_initializeClient_AspNet(clientOptions) {

    // Point the remoteFrame
    jQuery("#webcx_remoteFrame").attr("src", webcxData.protocol + webcxData.remoteHost + webcxData.remotePath + "?" + bustCache() + webcxData.debugString + "parentFrameURL=" + encodeURIComponent(location.href));
    // Possibly show the webcx page connector objects
    if (webcxData.debug)
        jQuery("#webcx_pageconnector").show();
    // Create a JS place holder for the JSON string
    var sJSON = "";
    // Hook up the message receive so we can receive messages from the remoteFrame
    jQuery.receiveMessage(
        function (e) {

            // Begin by closing a LOGIN box that might be up (in case this is from a LOGIN popup)
            closePopups();

            sJSON = e.data;

            // Which "message" are we getting?
            switch (sJSON) {
                case "redirectNonMember=1":
                    // Process this redirect by using the callback passed in the setup of the control
                    try {
                        eval(webcxData.redirectNonMemberCallback);
                    } catch (Error) {
                        // Just ignore it
                    }
                    break;
                default:
                    // Process all the other messages
                    processMessage_Authenticate_AspNet(clientOptions, sJSON);
                    break;
            }

        },
        webcxData.protocol + webcxData.remoteHost
    );
    jQuery("#webcx_remoteMessage").text("listening.");

}

function processMessage_Authenticate_AspNet(clientOptions, sJSON) {
    // Put the JSON Query String back into true JSON format and in a var that is page level
    parseJSONqueryString(sJSON);

    // Handle the "Background Login" (in the asp.net client, with postback, this needs to be done
    // very early in the page so that the frames have time to load.)
    if (webcxData.enableBackgroundNetForumLogin) {
        // Direct a hidden frame to the NetForum login or logoff page, but only if we've had a "state change"
        // as directed by the server side code logic.
        // Check if we are SETTING (login) or CLEARING (logoff or not logged in)
        if (clientOptions.execBackground == "logoff") {
            // We are clearing (or not logged in)
            jQuery("#webcx_netforumFrame").attr("src", webcxData.httpNetForumLogoff + "&" + bustCache());
            //jQuery("#webcx_netforumFrame").attr("src", "http://www.google.com/");
        }
        else if (clientOptions.execBackground == "login") {
            // We are setting (back from a login)
            // Check to make sure we have an ssoToken (otherwise, this is useless, so we skip it)
            if (typeof (userObjectJSON.ssoToken) != "undefined" && userObjectJSON.ssoToken != "" && userObjectJSON.ssoToken != null )
            {
                jQuery("#webcx_netforumFrame").attr("src", webcxData.httpNetForumLogin + "&" + bustCache() + "&ssoToken=" + userObjectJSON.ssoToken);
            }
            //jQuery("#webcx_netforumFrame").attr("src", "http://www.google.com/");
            //alert("made it");
        }
    }

    // Call a function after the message for further implementation customization
    afterMessageCallback();

    // If the caller has the property set, this will also call another function
    // which must be declared on the page that contains the webcx object
    try {
        eval(webcxData.afterMessageClientCallbackString);
    } catch (Error) {
        // Ignore any errors in the callback for the page
    }
    // End user control callback (if any)                                    

    if (webcxData.debug)
        jQuery("#webcx_remoteMessage").text(sJSON);

    // Save the JSON to an INPUT that we pass to the server for PostBack
    jQuery("#txtUserObjectKeyValueList").val(sJSON);

    if (!webcxData.disablePostBackOnMessage) {

        // This is the ASP.NET client, so we let the server side code store
        // the incoming JSON for later comparison.

        // See if the current client JSON (in sJSON) matches the last server side JSON
        if (clientOptions.lastJSON != sJSON) {
            // Force a postBack to resolve a discrepancy
            __doPostBack('LAST_JSON_DIFF', '');
            // alert(sJSON);
        }
    }
}


// *************************************************************************************
// * Raw JS Client
// *
// * The parameter clientOptions must be JSON with the following structure:
// *    Presently, none are required for the RawJS client, so the function should be 
// *    called with null for the parameter.

function webcx_initializeClient_RawJS(clientOptions) {
    // Point the remoteFrame
    jQuery("#webcx_remoteFrame").attr("src", webcxData.protocol + webcxData.remoteHost + webcxData.remotePath + "?" + bustCache() + "&" + webcxData.debugString + "parentFrameURL=" + encodeURIComponent(location.href));
    // Possibly show the webcx page connector objects
    if (webcxData.debug)
        jQuery("#webcx_pageconnector").show();
    // Create a JS place holder for the JSON string
    var sJSON = "";
    // Hook up the message receive so we can receive messages from the remoteFrame
    jQuery.receiveMessage(
        function (e) {

            // Begin by closing a LOGIN box that might be up (in case this is from a LOGIN popup)
            closePopups();

            sJSON = e.data;

            // Which "message" are we getting?
            switch (sJSON) {
                case "redirectNonMember=1":
                    // Process this redirect by using the callback passed in the setup of the JS Client
                    try {
                        eval(webcxData.redirectNonMemberCallback);
                    } catch (Error) {
                        // Just ignore it
                    }
                default:
                    // Process all the other messages
                    processMessage_Authenticate_RawJS(clientOptions, sJSON);
                    break;
            }
        },
        webcxData.protocol + webcxData.remoteHost
    );
    jQuery("#webcx_remoteMessage").text("listening.");

}

function processMessage_Authenticate_RawJS(clientOptions, sJSON) {
    // Put the JSON Query String back into true JSON format and in a var that is page level
    parseJSONqueryString(sJSON);

    // Call a function after the message for further implementation customization
    afterMessageCallback();

    // If the caller has the property set, this will also call another function
    // which must be declared on the page that contains the webcx object
    try {
        eval(webcxData.afterMessageClientCallbackString);
    }
    catch (err) {
        // Just ignore any errors in the callback
    }
    // End user control callback (if any)                                    

    if (webcxData.debug)
        jQuery("#webcx_remoteMessage").text(sJSON);

    // Save the JSON to an INPUT that we can pass to the server on SUBMIT
    jQuery("#txtUserObjectKeyValueList").val(sJSON);

    // This is the RAW JS client, so we compare the JSON to a previous
    // value (in a cookie). If it's the same, we don't do anything.
    // If it is not, we call a client function (to be defined
    // on the page using this library.

    // Read the JSON from a cookie, if it exists
    var lastJSON = jQuery.cookie("webcx_lastJSON");
    // Check to see if the cookie is set at all
    if (lastJSON==null)
    {
        // It is not, so, let's set it to EMPTY to simplify the later logic
        // Essentially a NULL cookie means "Empty=1" (logged out)
        lastJSON="Empty=1"
        // And set it already also to faciliate later processing
        jQuery.cookie("webcx_lastJSON", "Empty=1", { path: "/" });
    }

    // Detect if we've had a change in state
    // Posible conditions: 
    // JSON is different so we have a "change in state"
    //    
    var flagStateChanged = false;
    // alert(lastJSON);
    if (lastJSON != sJSON) {
        // First, store the new one for later comparison
        jQuery.cookie("webcx_lastJSON", sJSON, { path: "/" });
        // Now, set the flag
        flagStateChanged = true;
    }

    // Handle the "Background Login"
    if (webcxData.enableBackgroundNetForumLogin) {
        // Direct a hidden frame to the NetForum login page, but only if we've had a "state change"
        if (flagStateChanged) {

            // Check if we are SETTING (login) or CLEARING (logoff or not logged in)
            if (sJSON == "Empty=1") {
                // We are clearing (or not logged in)
                jQuery("#webcx_netforumFrame").attr("src", webcxData.httpNetForumLogoff + "&" + bustCache());
            }
            else {
                // We are setting (back from a login)
                // Check to make sure we have an ssoToken (otherwise, this is useless, so we skip it)
                if (typeof (userObjectJSON.ssoToken) != "undefined" && userObjectJSON.ssoToken != "" && userObjectJSON.ssoToken != null)
                    jQuery("#webcx_netforumFrame").attr("src", webcxData.httpNetForumLogin + "&" + bustCache() + "&ssoToken=" + userObjectJSON.ssoToken);
            }
        }
    }

    // Handle the PostBackOnMessage
    if (!webcxData.disablePostBackOnMessage) {
        // Prepare for the postback but only if we've had a "state change"
        if (flagStateChanged) {
            // Figure out which items we postBack (from the webcxData config)
            // webcxData.postBackItems += "," // in case it's only 1 item, add a second so the array will be created
            var postBackItems = webcxData.postBackItems.split(",");

            // Hold the page's query string as a jQuery.query object!!
            var oNewQueryString = jQuery.query;

            // Check if we are SETTING (login) or CLEARING (logoff or not logged in)
            if (sJSON == "Empty=1") {
                // We are clearing (or not logged in)
                // Clear the query string of the webcx objects
                // adding or modifying items is handled by the jQuery.query library
                for (i = 0; i <= postBackItems.length - 1; i++) {
                    oNewQueryString = oNewQueryString.remove(postBackItems[i]);
                }
                // Finally, add a redirect to LOGOUT (for the NetForum Website)
                oNewQueryString = oNewQueryString.set("webcx_redir", "logout");
            }
            else {
                // We are setting (back from a login)

                // Create the desired query string
                // adding or modifying items is handled by the jQuery.query library
                for (i = 0; i <= postBackItems.length - 1; i++) {
                    var sNodeData = eval("userObjectJSON." + postBackItems[i]);
                    if (sNodeData != "" && sNodeData != null) {
                        oNewQueryString = oNewQueryString.set(postBackItems[i], sNodeData);
                    }
                }

                // Avectra keeps a "logoff" query string even after the user is logged off, so
                // we remove it so that the "login ssoToken" is accepted without the user being
                // immediately logged out.
                oNewQueryString = oNewQueryString.remove("Logoff");

            }

            // ASSERT: the page's query string is modified with new items (or removed items) as defined in webcxData

            // PostBack to the same page and pass the desired QueryString - IF we have one at all
            var sNewString = oNewQueryString.toString();
            if (sNewString.length > 0) {
                // We have a new Query string, so we post back to it
                location.href = location.href.split("?")[0] + sNewString;
            }
            else {
                // The new query string is empty, so we post back to an empty URL to force clearing a previous 
                // Query String.
                location.href = location.href.split("?")[0]
            }

            //alert("json is different");
        }
    }
}

// ********************************************************************************
// * Supporting functions needed for both the asp.net client and the pure js client

function parseJSONqueryString(sStringWithStuff) {
    // The receiveMessage function brings over the "message" using a QUERY STRING syntax
    // userName=fakeUser&userDisplayName=Fake+User+From+Class&userToken=2790c03a-6a8f-422a-9805-d90aa80d6a4e
    // This function parses that back into a JSON object available at globally on the DOM called userObjectJSON

    var jsonBody = "";
    // Split the JSON Query String by "&"
    var vars = sStringWithStuff.split("&");
    for (var i = 0; i < vars.length; i++) {
        // Split each pair using the "="
        var pair = vars[i].split("=");
        // Store each "side" in JSON syntax "left":"right"
        // But urlDecode AND replace "+" with spaces

        // Add a comma separator if not the first JSON item
        if (jsonBody != "")
            jsonBody += " , ";

        jsonBody += '"' + decodeURI(pair[0]).split('+').join(' ') + '" : "' + decodeURI(pair[1]).split('+').join(' ') + '"';
    }
    // Wrap the body by the JSON "{ bodyHere }"
    jsonBody = "{" + jsonBody + "}";
    // alert(jsonBody);
    // Parse into a JSON object. Note, this might not work on older browsers unless json2.js 
    // is loaded on the page. See http://www.json.org/js.html
    userObjectJSON = JSON.parse(jsonBody);
}

// This function will be called after a message is received
// Add any client side custmization here.
// NOTE, some objects WILL exist when this function is called. See the notes below.
function afterMessageCallback() {
    // The jSON Query String is currently in 
    // jQuery("#txtUserObjectKeyValueList").val();
    // page dom variable "userObjectJSON", which contains the following nodes:
    //      userObjectJSON.userName
    //      userObjectJSON.userDisplayName
    //      userObjectJSON.userToken

    // Process any MACROS on the page
    if (typeof (userObjectJSON.userDisplayName) == 'undefined') {
        jQuery(".webcx_macro_userDisplayNameWithLink").html("<span class='webcx_class_userString'>You are not logged in. <a href='javascript:showLogin();'>Login now</a></span>");
        jQuery(".webcx_macro_autoLink, .webcx_macro_autoLink_Login:not(img)").html("<span class='webcx_class_userString'><a href='javascript:showLogin();'>Login now</a></span>");
        jQuery("img.webcx_macro_autoLink_Login").wrap("<span class='webcx_class_button'><a href='javascript:showLogin();'></a></span>").show();
        jQuery(".webcx_macro_userDisplayName").html("");
        jQuery("img.webcx_macro_autoLink_Logout").hide();
        jQuery(".webcx_macro_userDisplayNameWithLink_Logout").html("");
        jQuery(".webcx_netForumLink_myAccount").attr("href", "#").hide();
        jQuery(".webcx_netForumLink_myTransactions").attr("href", "#").hide();
    }
    else {
        jQuery(".webcx_macro_userDisplayNameWithLink").html("<span class='webcx_class_userString'>Welcome Back, <a href='" + webcxData.httpNetForumAccountURL + "' class='webcx_class_userName'>" + userObjectJSON.userDisplayName + "</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='javascript:showDashboard();'>MY SUBSCRIPTIONS</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='javascript:signOut();'>Log Out</a></span>");
        jQuery(".webcx_macro_autoLink, .webcx_macro_autoLink_Logout:not(img)").html("<span class='webcx_class_userString'><a href='javascript:signOut();'>Log Out</a></span>");
        jQuery("img.webcx_macro_autoLink_Logout").wrap("<span class='webcx_class_button'><a href='javascript:signOut();'></a></span>").show();
        jQuery(".webcx_macro_userDisplayName").html("<span class='webcx_class_userString'>Welcome Back, <a href='" + webcxData.httpNetForumAccountURL + "'>" + userObjectJSON.userDisplayName + "</a></span>");
        jQuery("img.webcx_macro_autoLink_Login").hide();
        jQuery(".webcx_macro_userDisplayNameWithLink_Logout").html("<span class='webcx_class_userString'>Welcome Back, <a href='" + webcxData.httpNetForumAccountURL + "' class='userName'>" + userObjectJSON.userDisplayName + "</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='javascript:showDashboard();'>MY SUBSCRIPTIONS</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='javascript:signOut();'>Log Out</a></span>");
        jQuery(".webcx_netForumLink_myAccount").attr("href", webcxData.httpNetForumURL + "&webcx_redir=myaccount");
        jQuery(".webcx_netForumLink_myTransactions").attr("href", webcxData.httpNetForumURL + "&webcx_redir=mytransactions");
    }

    // "State Agnostic" macros
    jQuery(".webcx_netForumLink_onlineStore").attr("href", webcxData.httpNetForumURL + "&webcx_redir=onlinestore");
    jQuery(".webcx_netForumLink").attr("href", webcxData.httpNetForumURL);

};

function closePopups() {
    jQuery(document).ready(function () {
        jQuery(document).trigger('close.facebox');
    });
}

function signOut() {
    // Point the remoteFrame
    jQuery("#webcx_remoteFrame").attr("src", webcxData.protocol + webcxData.remoteHost + webcxData.remotePathSignout + "?parentFrameURL=" + encodeURIComponent(location.href) + "&" + bustCache() + webcxData.debugString);
}

function showLogin() {
    var loginURL = webcxData.protocol + webcxData.remoteHost + webcxData.remotePathLogin + "?parentFrameURL=" + encodeURIComponent(location.href) + "&" + webcxData.debugString + webcxData.redirectURLString + "&" + bustCache();
    var skinPath = webcxData.SkinPath;
    jQuery.facebox.settings.loadingImage = skinPath + "facebox/loading.gif";
    jQuery.facebox.settings.closeImage = skinPath + "facebox/closelabel.png";
    jQuery.facebox("<iframe style='width:428px; height:280px' frameborder='0' src='" + loginURL + "'></iframe>");
    // These two classes require css_browser_selector on the host page to be effective
    jQuery(".ie7 #facebox .content").css("width", "428px").css("border", "1px solid grey");
    jQuery(".ie #facebox .content").css("border", "4px solid #8C8C8C");
}

function showDashboard() {
    if (webcxData.httpUserDashboardURL != "" && webcxData.httpUserDashboardURL != null)
        location.href = webcxData.httpUserDashboardURL;
}
