///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// File: LandingpageFunctions.js
//
// Description: JavaScript file containing common Landingpage functions.
//
// Public Functions:
//     LandingpageFunctions.navigateUrlWithParams - Takes in a URL and an array hash containing parameter names and 
//                                                  corresponding in-page <input> element IDs that contain the 
//                                                  values for those parameters. Also takes in an options array 
//                                                  hash and a validation array hash containing options for how the 
//                                                  navigation should occur as well as any items that should go 
//                                                  through validation prior to navigation. Function redirects to 
//                                                  the specified URL and passes along the in-page query parameters 
//                                                  as well as any query parameters that were sent intially to the 
//                                                  page as long as all validations are passed. Passed in query 
//                                                  parameters will take precedence over in-page parameters. Also, 
//                                                  since JavaScript hash arrays are case sensitive, there may be 
//                                                  duplicate entries if the same query parameter name is passed in
//                                                  and in-page, but with different casing.
//     LandingpageFunctions.saveQueryParams       - Saves incoming query string parameters to a private global 
//                                                  variable.
//
// Author: Darren Bock
//
// Created: 2010-07-20
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Change History
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Date       Who Description
// ---------- --- ------------------------------------------------------------------------------------------------
// 2010-07-20 DAB Initial Creation.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define Public Global Variables.
//     LandingpageFunctions - Landingpage functions object used to interact with Landingpage functions.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var LandingpageFunctions = new Object();


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define Private Global Variables.
//     LandingpageFunctions._incomingQueryParams - Hash array used for storing passed in query parameters.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LandingpageFunctions._incomingQueryParams = new Array();

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Begin Public Functions.
//     LandingpageFunctions.navigateUrlWithParams
//     LandingpageFunctions.saveQueryParams
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: LandingpageFunctions.navigateUrlWithParams
// Description: Takes in a URL and an array hash containing parameter names and corresponding in-page <input> 
//              element IDs that contain the values for those parameters. Also takes in an options array hash and a 
//              validation array hash containing options for how the navigation should occur as well as any items 
//              that should go through validation prior to navigation. Function redirects to the specified URL 
//              and passes along the in-page query parameters as well as any query parameters that were sent 
//              intially to the page as long as all validations are passed. Passed in query parameters will take 
//              precedence over in-page parameters. Also, since JavaScript hash arrays are case sensitive, there 
//              may be duplicate entries if the same query parameter name is passed in and in-page, but with 
//              different casing.
// Parameters:
//     [queryParamHash] - Array hash of parameter names and correspoding in-page <input> element IDs.
//                        Example:
//                            queryParamHash['TFN'] = 'TFNElementId', where document.getElementById('TFNId').value
//                            will yield the value for the query string parameter 'TFN'.
//     [optionsHash]    - Array hash of options for how the navigation should occur. Only current option is new or
//                        same window.
//                        Example:
//                            optionsHash['windowType'] = 'new' (or 'same').                        
//     [validationHash] - Array hash of in page element ids that require validation and the associated in page
//                        validation function for each element id where document.getElementById('elementId').value
//                        will yield the value to validate.
//                        Example:
//                            validationHash['elementId'] 'functionName'.
//     urlToNavigate    - URL to navigate to.
// Return value:
//     none.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LandingpageFunctions.navigateUrlWithParams = function(queryParamHash, optionsHash, validationHash, urlToNavigate)
{
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Declare local variables.
    //     queryParamString - Fully created query parameter string based upon based in parameter hash.
    //     validationResult - Variable containing results of all item validations.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    var queryParamString = '';
    var validationResult = true;

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Execute all validation functions before attempting to navigate.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    for (var validationElementId in validationHash)
    {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Ensure the document element exists before extracting a value. Call the passed in validation function on
        // the value to validate.
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        if(document.getElementById(validationElementId))
        {
            var validationFunctionCall = validationHash[validationElementId] + "('" + validationElementId + "');";
            var validationReturn = eval(validationFunctionCall);
            if(!validationReturn)
            {
                validationResult = false;
            }
        }        
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // If any of the validations fail, do not allow the navigation to occur.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if(!validationResult)
    {
        return false;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Extract the key value pairs for each query string parameter by getting the in-page HTML element value.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    for (var paramName in queryParamHash)
    {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Ensure the document element exists before extracting a value. If it doesnt exist, then set the value
        // for that hash key to be 'DNE' so we can ignore it later. An easier meathod is to use the delete function
        // but it is not supported in all versions of JavaScript.
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        if(document.getElementById(queryParamHash[paramName]))
        {
            queryParamHash[paramName] = document.getElementById(queryParamHash[paramName]).value;
        }
        else
        {
            queryParamHash[paramName] = 'DNE';
            ///////////////////////////////////////////////////////////////////////////////////////////////////////
            // Debugging alert. Uncomment the following lines to debug this function.
            ///////////////////////////////////////////////////////////////////////////////////////////////////////
            //alert("Failed to find document element id: " + queryParamHash[paramName]);
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Add any query parameters that were originally passed into the page. If any in-page parameter names match
    // any of the passed in parameter names, the passed in parameter names will take precedence. Also, since
    // JavaScript hash arrays are case sensitive, there maybe "duplicate" entries.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    for (var paramName in LandingpageFunctions._incomingQueryParams)
    {
        queryParamHash[paramName] = LandingpageFunctions._incomingQueryParams[paramName];
    }
        
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Create the query string variable.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    for (var paramName in queryParamHash)
    {
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        // Ensure the parameter has a value before adding it to the query string.
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        if(queryParamHash[paramName] != 'DNE')
        {
            if (queryParamString == '')
            {
                queryParamString += '?' + paramName + '=' + queryParamHash[paramName];
            }
            else
            {
                queryParamString += '&' + paramName + '=' + queryParamHash[paramName];
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Construct the full URL to navigate to redirect the page.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    urlToNavigate += queryParamString;
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Debugging alert. Uncomment the following lines to debug this function.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //alert(urlToNavigate);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Check the passed in options for window type (new/same) and redirect to the passed in URL.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if(optionsHash['windowType'] == 'new')
    {
        window.open(urlToNavigate);
    }
    else
    {
        window.location.href = urlToNavigate;
    }
}//LandingpageFunctions.navigateUrlWithParams()

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: LandingpageFunctions.saveQueryParams
// Description: Saves incoming query string parameters to a private global variable.
// Parameters:
//     none.
// Return value:
//     none.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LandingpageFunctions.saveQueryParams = function()
{
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Declare local variables
    //     queryString - Query string portion of the current page URL.
    //     urlString   - Current page URL.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    var queryString = window.location.search.substring(1);
    var urlString   = window.location.href;

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Populate the global hash array with the passed in query parameters and values. Do not do any processing if
    // there is no query string. Note, must check the .length property returned by 
    // window.location.search to see if it is null. You cannot compare the queryString variable itself to an empty
    // string;
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (window.location.search.length > 1)
    {
        var queryParamSections = queryString.split("&");
        for (var sectionIndex = 0; sectionIndex < queryParamSections.length; sectionIndex++)
        {
            var queryParamPair  = queryParamSections[sectionIndex].split("=");
            LandingpageFunctions._incomingQueryParams[queryParamPair[0]] = queryParamPair[1];
        }
    }    
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Debugging alert. Uncomment the following lines to debug this function.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //var myMessage = "Parameters:\n"
    //for (var paramName in LandingpageFunctions._incomingQueryParams)
    //{
    //    myMessage += paramName + " = " + LandingpageFunctions._incomingQueryParams[paramName] + "\n";
    //}
    //alert(myMessage);
    
}//LandingpageFunctions.saveQueryParams()

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// End Public Functions.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Begin Private Functions.
//     LandingpageFunctions.initialize
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: LandingpageFunctions.initialize
// Description: Initializes the LandingpageFunctions object.
// Parameters:
//     none.
// Return value:
//     none.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LandingpageFunctions.initialize = function()
{
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Declare local variables
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Save any passed into query string parameters into the LandingpageFunctions object.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    LandingpageFunctions.saveQueryParams();
    
}//LandingpageFunctions.initialize()

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// End Private Functions.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Initialize the LandingpageFunctions object.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LandingpageFunctions.initialize();
