// This causes jQuery to release its binding of the $ operator
jQuery.noConflict();

Array.prototype.contains = function(obj) {
	var i = this.length - 1;
	
    // Looping backwards in javascript is usually faster than forwards.
	while (i >= 0) {
		if (this[i] === obj) {
		    return true;
		}
		i--;
	}
    return false;
}


var topNavMouseOverDelay = 250;
var topNavMouseOutDelay  = 750;

var selectedMenu       = null;
var selectTabTimeoutId = null;
function SwitchTab(menuIdName) {
    selectedMenu       = jQuery('#' + menuIdName);
    CancelTabTimeout();
    selectTabTimeoutId = setTimeout('ActualSwitchTab();',topNavMouseOverDelay);
}
function CancelTab() {
    selectedMenu       = null;
    CancelTabTimeout();
    selectTabTimeoutId = setTimeout('ActualSwitchTab();',topNavMouseOutDelay);
}
function CancelTabTimeout() {
    if (selectTabTimeoutId != null) { clearTimeout(selectTabTimeoutId); }
}
function ActualSwitchTab() {
    jQuery('#siteTopNav .menu').slideUp();
    if (selectedMenu != null) {
        selectedMenu.slideDown();
    }
}


function clearFieldValue(obj,fieldValue){
	if(fieldValue=='search'){
		fieldValue="Enter Search Term";
	}
	if(obj.value==fieldValue){
		obj.value='';
	}
}
function setFieldValue(obj,defaultValue){
	if(defaultValue=='search'){
		defaultValue="Enter Search Term";
	}
	if(obj.value==''){
		obj.value=defaultValue;
	}
}

function toggle_div(lnkId) {

	if(lnkId=='locate') {
		document.getElementById('locate_btm').style.display="block";
		document.getElementById('lnk_Locate').className="active";
		document.getElementById('search_btm').style.display="none";
		document.getElementById('lnk_Search').className="inactive";

	} else {
		//document.getElementById('locate_btm').style.display="none";
		//document.getElementById('lnk_Locate').className="inactive";
		document.getElementById('search_btm').style.display="block";
		document.getElementById('lnk_Search').className="active";

	}
}

function showOverlayImage(){
   document.getElementById('overlayConnectComingSoon').style.display="block";
}

function openQHMarketplace() {
    window.open("http://marketplace.qualityhealth.com/index.jsp?partnerID=20001", "QHMarketplace", "menubar=0,resizable=0,scrollbars=1,width=940,height=700");
}

function selectOnChangeJumpToUrl(elemSelect) {
    if (!elemSelect) { return; }
    if (elemSelect.nodeName != 'SELECT') { return; }
    
    var selectedValue = elemSelect.value;
    if (selectedValue == '') { return; }
    document.location.href = selectedValue;
}

// Never do any session keep alive from popunder traffic.
if(isPopUnderTraffic != true) {
	// Keeps the session alive by performing an Ajax call periodically until stopped.
	var keepAliveIntervalId = setInterval(
	    function sessionKeepAlive() {
	        new Ajax.Request('/sessionKeepAlive.jsp');
	    },
	    2 * 60 * 1000 // 2 minutes
	);
}

// This function prevents double form submits.
function preventDoubleSubmission(form) {
	
    // If form hidden field not present, alert the developer.
    if (form.formHasBeenSubmitted === undefined) {
    	alert("formHasBeenSubmitted hidden field is missing in " + form.name + " form");
    	return true;
    }
	
	var submitButtonSelector = "form[id='" + form.id + "'] input[type='image'], form[id='" + form.id + "'] input[type='submit']";
	
    // Make sure this hasn't been submitted multiple times
    if (form.formHasBeenSubmitted.value === true) {
        return false;
    }
    else {
        form.formHasBeenSubmitted.value = true;
        
        // Look for the button to disable.
        jQuery(document).find(submitButtonSelector).each(function() { 
        	jQuery(this).attr("disabled", "true");
        });
        
        return true;
    }
}

function navigateToHealthCenter() {
    var selectedIndex, contentURL;
    if (document.healthCentersForm && document.healthCentersForm.healthCentersList) {
        selectedIndex = document.healthCentersForm.healthCentersList.selectedIndex;
        contentURL = document.healthCentersForm.healthCentersList.options[selectedIndex].value;
        window.location.href = contentURL;
    }
}

var captcha = {};
// Dynamically inserts a CAPTCHA challenge on pages that require it, based on ref code and publisher id. 
captcha.insert = function() {

	// Declare local variables
	var regexpResult, pid, random, path, index, image, longkey;
	
	// If there is no "images" array to choose from, or there is no array of low-quality "pids", stop processing.
	if (!captcha.pids || !captcha.images) {
        return;
    }
	
	// Look up the *PID param to see if it needs captcha for this ref code.
	
	// Example PID parameter name-value pair: anythingGoesHerePID=1234
	// Regex is a question mark or ampersand followed by the *PID param name. 
	// The param name is zero or more characters that are not amps or question marks followed by PID.
	// An equals sign separates name and value. 
	// Value is as many characters as possible before reaching an ampersand or hash mark
	regexpResult = /[?&]([^?&]*?PID)=([^&#]*)/.exec(window.location.href);
	if (regexpResult) {
		pid = regexpResult[1] + ':' + unescape(regexpResult[2]);
	}
	// If there is no *PID param, then use the special case of a null pid.
	else {
		pid = null;
	}
	// If the pids array does not contain the pid we're looking for, don't use captcha.
	if (!captcha.pids.contains(pid)) {
        return;
    }
	
	// A function to get a random number below the specified upper limit.
	random = function(upperLimit) {
        return Math.floor(Math.random() * upperLimit);
    };
    
    // Choose a random image
	index = random(captcha.images.length);
	image = captcha.images[index];
	
    // Add random 3-digit numbers to both sides of key
	longkey = '' + (random(900) + 100) + image.key + (random(900) + 100);
	
	// Add the image, the prompt, the text input, and the hidden input
	// to the form if the captcha placeholder exists.
	jQuery('#captchaContainer'
	).append(
	    jQuery('<input type="hidden" name="captchaImageKey"/>').attr('value', longkey)
	).append(
	    jQuery('<img/>').attr('src', image.src)
	).append(
	    jQuery('<div>Type the word shown above:</div>')
	).append(
	    jQuery('<div><input type="text" name="captchaResponse" class="captchaResponse"/></div>')
	);
};

jQuery(document).ready(captcha.insert);


/**
 * This function will take the parameters from the query string and populate the form with the values.
 */
function setFormWithURLParameters(){

    var insertElementsToPopulateIntoArray, setFormValues, parsePhoneNumber, parseDate, stripLeadingZero, parameterNameToElementName;
    var arrayOfParams = [];
	var forms;
	var arrayOfElementDescriptors = [];
    var paramPair, parameterName, parameterValue;
    var dateOfBirthParsed, phoneNumberParsed;
    var i;
	
    // Look for any of these form types. For each form, populate the form elements from the query string values. The 
    // zipAuthForm is not included since we don't want that form to be populated.
    forms = jQuery("form[name='campaignResponseForm'], form[name='prospectForm'], form[name='registrationForm']");
    
    if (!forms.length) {
        return;
    }

    // FUNCTION: This function will take the name of a parameter from the URL, get its equivalent form element 
	// name and add it, its value and its form type to an array.
    addToElementDescriptorArray = function(name, value, elementType){
		var elementDescriptor;
        // Get the corresponding element name from the parameter name to element name mapping object
        var elementName = parameterNameToElementName[name];
        value = jQuery.trim(value);
        elementName = jQuery.trim(elementName);
        
        // Verify that no value pairs are empty since it is possible that parameters may be added to the query 
		// string that do not exist in the form or empty values may have been passed in, in which case form 
		// manipulation should not occur.
        if (value && elementName) {
            elementDescriptor = {
                elementName : elementName,
                elementValue : value,
                elementType : elementType
            };
            arrayOfElementDescriptors.push(elementDescriptor);
        }
    };
    
    // FUNCTION: This function will get the name of the element that needs to be populated. If it exists and the 
	// value is empty, sets it.
    setFormValues = function(elementDescriptor, form){
        var elementName = elementDescriptor.elementName;
        var elementValue = elementDescriptor.elementValue;
        // jQuery takes time to navigate through the DOM every time a find is done. The elements variable is used to 
        // minimize the number of navigations.
        var elements;
        
        if (elementDescriptor.elementType === "text") {
            // If the text input is empty, populate it with the value
            elements = jQuery(form).find('input[name="'+ elementName + '"]');
            if (!elements.val()) {
                elements.val(elementValue);
            }
        }
        else if (elementDescriptor.elementType === "select") {
            // If nothing is selected, then select the option with the desired value
            elements = jQuery(form).find('select[name="' + elementName + '"]');
            if (!elements.val()) {
                elements.find('option[value="' + elementValue + '"]').attr("selected", "selected");
            }
        }
        else if (elementDescriptor.elementType === "radio") {
            // If no radio buttons in the radio group are checked, then check the one with the correct value
            elements = jQuery(form).find('input[name="' + elementName + '"]');
            if (!elements.is(":checked")) {
                elements.filter('[value="' + elementValue + '"]').attr("checked", "checked");
            }
        }
    };
    
    // FUNCTION: This function will take a string and strip out the "0" if it is the first character in the string. 
    // "05" will become "5". "11" will remain "11".
    stripLeadingZero = function(string){
        if (string.charAt(0) === "0") {
            string = string.substr(1);
        }
        return string;
    };
    
    // FUNCTION: This function will take a date in the form of MM-DD-YYYY and parse out the day month and year 
    // values into an object.
    parseDate = function(value){
        var dateParsed, date;
        if (value.match("[0-9]{2}-[0-9]{2}-[0-9]{4}")) {
            dateParsed = value.split("-");
            date = {
                monthOfBirth: stripLeadingZero(dateParsed[0]),
                dayOfBirth: stripLeadingZero(dateParsed[1]),
                yearOfBirth: dateParsed[2]
			}
        }
        return date;
    };
    
    // FUNCTION: This function will take a phone number in the form of XXX-XXX-XXXX and parse out the area code, 
	// first 3 digits and last 4 digits into an object.
    parsePhoneNumber = function(value){
        var phoneNumberParsed, phoneNumber;
        // Format XXX-XXX-XXXX
        if (value.match("[0-9]{3}-[0-9]{3}-[0-9]{4}")) {
            phoneNumberParsed = value.split("-");
            phoneNumber = {
				areaCode: phoneNumberParsed[0],
				firstThree: phoneNumberParsed[1],
				lastFour: phoneNumberParsed[2]
			}
        }
        return phoneNumber;
    };
    
    // The map of query string parameter names to form element names. Different names were used to avoid struts 
    // populating form elements with the same name as the query string parameter on its own.
    parameterNameToElementName = {
        qhfirstname: "firstName",
        qhlastname: "lastName",
        qhemail: "email",
        qhaddress: "address1",
        qhcity: "city",
        qhstate: "stateProvince",
        qhzipcode: "zipPostalCode",
        qhphoneareacode: "phoneNumberAreaCode",
        qhphonefirstthree: "phoneNumberFirstThree",
        qhphonelastfour: "phoneNumberLastFour",
        qhdayofbirth: "dayOfBirth",
        qhmonthofbirth: "monthOfBirth",
        qhyearofbirth: "yearOfBirth",
        qhgender: "gender"
        // The following shouldn't be added because they are special cases: 
        // qhphone -> will be parsed into qhphoneareacode qhphonefirstthree and qhphonelastfour
        // qhdateofbirth -> will be parsed into qhdayofbirth qhmonthofbirth qhyearofbirth
    };
     		
    // PARSE THE URL
    arrayOfParams = parseQueryString();
    
    // HANDLE SPECIAL CASES AND INSERT ELEMENT NAME AND VALUE INTO AN ARRAY OF ELEMENTS TO POPULATE THE FORM.
    for (i = 0; i < arrayOfParams.length; i++) {
        paramPair = arrayOfParams[i];
        parameterName = paramPair.paramName;
        parameterValue = paramPair.paramValue;
        switch (parameterName) {
			// Parse the parameter qhdateofbirth which is in the format MM-DD-YYYY
			case "qhdateofbirth":
				dateOfBirthParsed = parseDate(parameterValue);
				if (dateOfBirthParsed) {
					addToElementDescriptorArray("qhmonthofbirth", dateOfBirthParsed.monthOfBirth, "select");
					addToElementDescriptorArray("qhdayofbirth", dateOfBirthParsed.dayOfBirth, "select");
					addToElementDescriptorArray("qhyearofbirth", dateOfBirthParsed.yearOfBirth, "select");
				}
				break;
			// Parse the parameter qhphone which is in the format xxx-xxx-xxxx
			case "qhphone":
				phoneNumberParsed = parsePhoneNumber(parameterValue);
				if (phoneNumberParsed) {
					addToElementDescriptorArray("qhphoneareacode", phoneNumberParsed.areaCode, "text");
					addToElementDescriptorArray("qhphonefirstthree", phoneNumberParsed.firstThree, "text");
					addToElementDescriptorArray("qhphonelastfour", phoneNumberParsed.lastFour, "text");
			    }
                break;
            case "qhstate":
                addToElementDescriptorArray(parameterName, parameterValue.toUpperCase(), "select");
                break;
            case "qhgender":
                addToElementDescriptorArray(parameterName, parameterValue.toUpperCase(), "radio");
                break;
            // For the rest, insert the name value pair into the array of elements to populate
            default:
                addToElementDescriptorArray(parameterName, parameterValue, "text");
                break;
        }
    }
    
    // FOR EACH FORM, ITERATE THROUGH THE ARRAY OF ELEMENTS TO POPULATE THE FORM
    forms.each(function(){
        for (i = 0; i < arrayOfElementDescriptors.length; i++) {
            setFormValues(arrayOfElementDescriptors[i], this);
        }
    });
}

/**
 * Extract parameter names and values from the query string and add them to an array.
 * 
 * @return array of name-value pair objects
 */
function parseQueryString() {
    var i, parameter, parameterName, parameterValue, indexOfEquals;
    var paramNameValueArray = [];
    var indexOfQuestionMark = window.location.href.indexOf('?');
    
    // Get the query string from the URL
    var requestParameters = indexOfQuestionMark > -1 ? window.location.href.substr(indexOfQuestionMark + 1) : '';
    var parameters = requestParameters.split('&');
    
    // For each parameter name value pair in the query string
    for (i = 0; i < parameters.length; i++) {
        parameter = parameters[i];
        
        // Skip entries that have no size or start with =
        if (parameter.empty() || parameter.startsWith('=')) {
            continue;
        }
        
        // Extract the parameter name and the parameter value from the parameter
        parameterName = parameter.include('=') ? parameter.substr(0, parameter.indexOf('=')) : parameter;
        parameterValue = parameter.include('=') ? decodePlus(parameter.substr(parameter.indexOf('=') + 1)) : '';
        
        paramNameValueArray.push({
            paramValue : parameterValue,
            paramName : parameterName
        });
    }
    return paramNameValueArray;
}

/**
 * Decode the url encoded value. Also replaces '+' with ' ' since the javascript decoding functions don't handle that.
 * Ex. 10+Exchange%20Place becomes 10 Exchange Place
 */ 
function decodePlus( str ) { 
    return decodeURIComponent( str ).replace( /\+/g, ' ' ); 
} 

// This function will execute each time the page loads.
jQuery(document).ready(setFormWithURLParameters);

