/* This is a collection of generic non validation functions used in the sites forms
* Methods:
* submitForm()
* focusOnField()
* addBookmark()
* togglePosition(idname)
* toggleVisibility(targetId)
* togglePrice(extcovoption, stdtotal, exttotal)
* addClearCookies()
* clearCookies()
* clearFormValues(theform)
* checkBeneficiary()
* checkSFForm()
* checkEmailDelivery()
* clearFormField(id)
*/





/* MXS
 * Constructor - Detect Browser and set var accordingly
 * from: http://www.quirksmode.org/js/detect.html
 */
com.csatp.form.BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
            string: navigator.userAgent,
            subString: "iPhone",
            identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
com.csatp.form.BrowserDetect.init();

//document.write("[ Browser: " + com.csatp.form.BrowserDetect.browser + " ]<br />");
//document.write("[ Version: " + com.csatp.form.BrowserDetect.version + " ]<br />");
//document.write("[ OS: " + com.csatp.form.BrowserDetect.OS + " ]<br />");






/************************************************************
* Start of Functions
************************************************************/


/* MXS
 * checks the passed in checkbox id, should be used when page loads
 */
com.csatp.form.checkCheckbox = function(checkboxid) {
	if (document.getElementById){
		if (document.getElementById(checkboxid)){
			document.getElementById(checkboxid).checked=true;
		}
	}
	else if (document.all){
		if (document.all(checkboxid)){
			document.all(checkboxid).checked="true";
		}
	}
};


/* MXS
 * Check all checkboxes if the parent checkbox is checked
 */
com.csatp.form.checkAll = function(selector,field)
{
    var len = field.length;
    var isChecked = selector.checked;

    if (typeof len == 'undefined')
    {
        // do nothing
    }
    else
    {
        for (var i = 0; i < len; i++)
            field[i].checked = isChecked;
    }
};


/* MXS
 * Change text of submit buttons to show form has been submitted
 * Reduces chance of submitting forms multiple times
 */
function submitForm(form) {
  form.submit.disabled = true;
  form.submit.value="Please Wait..."; 
  return true;
}


/* MXS
 * Focus on the passed in fields
 */
com.csatp.form.focusOnField = function(formname, fieldname){
    document.forms[formname].elements[fieldname].focus();
};


/* MXS
 * Call in the template to prevent back button from being used
 */
com.csatp.form.disableBackButton = function(){
    window.history.forward(1);
};


/* MXS
 * This is a function to output instructions on how to add a bookmark
 */
com.csatp.form.addBookmark = function(){
    if ((com.csatp.form.BrowserDetect.browser == "Explorer") &&
        (com.csatp.form.BrowserDetect.version >= 4 && com.csatp.form.BrowserDetect.version <= 6)){
        //IE 4-6 allow you to call window.external.AddFavorite() to save bookmark
        var mainurl = document.location;
        if (mainurl.toString().indexOf('.do') > 0){
	        document.write("<a style='cursor: hand;' onclick='window.external.AddFavorite(\"" + mainurl.toString().substring(0,mainurl.toString().indexOf('.do') + 3) + "\",document.title);' title='Click here to bookmark this page.  (Only works with IE 4+)'>Bookmark this page &raquo;</a>");
        }
    }else
        //All other browsers support Crtl-D for saving bookmark
        document.write("Press Crtl-D to bookmark this page.");
};


/* MXS
 * Change the id's position opposite of what it is when passed in.
 * idname is the document object that you wish to hide
 */
com.csatp.form.togglePosition = function(idname){
    if (document.getElementById(idname).style.position=='absolute'){
        document.getElementById(idname).style.position='relative';
    }
    else if (document.getElementById(idname).style.position=='relative'){
        document.getElementById(idname).style.position='absolute';
    }
};


/* MXS
 * Show or hide the object name thats passed in based on what it currently is
 * targetId is the document object that you wish to hide
 */
function toggleVisibility(targetId){
    if (document.getElementById){
    	var target=document.getElementById(targetId);
		if (target.style.display == "none"){
			target.style.display = "";
		} else {
			target.style.display = "none";
		}
    }
}


/* MXS
 * toggle visibility of an element based on another elements value and an expected value
 */
com.csatp.toggleVisibilityWithValue = function(blockIdToToggle, idToCompare, valueToCompareWith){
    if (document.getElementById(idToCompare).value==valueToCompareWith)
        document.getElementById(blockIdToToggle).style.display='block';
    else
        document.getElementById(blockIdToToggle).style.display='none';
};


/* MXS
 * Toggle quote price that is displayed, used on QuoteOptions_xx page
 * extcovoption is the checkbox fieldname
 * stdtotal and exttotal are the id's of the Hx tag used to display the quote
 */
com.csatp.form.togglePrice = function(extcovoption, stdtotal, exttotal){
    if (document.getElementById){
    	// Create objects
    	var extcovoptionobj=document.getElementById(extcovoption);
    	var stdtotalobj=document.getElementById(stdtotal);
    	var exttotalobj=document.getElementById(exttotal);

		// Toggle visibility
		if (eval(extcovoptionobj) && eval(stdtotalobj) && eval(exttotalobj)) {
			if (extcovoptionobj.checked)
			{
			stdtotalobj.style.display = "none";
			exttotalobj.style.display = "";
			} else {
			stdtotalobj.style.display = "";
			exttotalobj.style.display = "none";
			}
		}		
	}
};


/* MXS
 * Manually Clear Cookies
 * Used on the clearcookies.do page
 **/
com.csatp.form.addClearCookies = function(){
	if (jsbrowsertype == "IE"){
		document.write("<a href='#' style='cursor: hand;' onclick='clearCookies();'>Clear CSA Cookies &raquo;</a>");
	}
};
com.csatp.form.clearCookies = function(){
	if (confirm("Are you sure you wish to delete your CSA cookies?")){
		var expDate = new Date();
		expDate.setTime(903314994000);													// time in ms
		var thecookies = document.cookie.split("; ");
		//alert(thecookies);
	
		for(var name in thecookies){
			if (thecookies[name].indexOf("Z=") < 0){
				//alert("Current Cookie:" + thecookies[name]);
				//alert("Before clearing them out, the cookies are: " + document.cookie.substring(0));
				//alert(thestring);
				document.cookie=thecookies[name] + "; expires=" + expDate.toGMTString();	// delete the cookie;
				//alert("Remaining cookies: " + document.cookie.substring(0));
			}
		}
		alert("Your CSA cookies are now cleared. You will need to restart all open browsers.");
		//window.close();
	}
};


/* MXS
 * Clear all form fields
 * Reset button usage: onClick="resetFormValues(this.form)"
 * Available types are: checkbox, radio, hidden, select-one, select-multiple, text, submit, button, reset, textarea
 **/
function clearFormValues(theform) {
    for (var i=0, j=theform.elements.length; i<j; i++) {
        fieldType = theform.elements[i].type;
        fieldName = theform.elements[i].name;
        if (fieldType!='button' && fieldType!='submit' && fieldType!='reset' && fieldType!='hidden' && fieldType!='checkbox' && fieldType!='radio' && fieldName!='producer'){
			theform.elements[i].value = "";
		}
    }
}





/************************************************************
* PURCHASE FUNCTIONS
************************************************************/


/* MXS
 * Detect if agent email is the same as insured email on the purchase page
 */
function detectDuplicateEmails(formdata){
	//alert('>>>' + formdata.emailaddress.value + ' - ' + formdata.agentemail.value + '<<<');
	var rtnval = true;
	if (formdata.emailaddress && formdata.agentemail){
		if (formdata.printpolconfltr[0].checked){
			if (formdata.emailaddress.value==formdata.agentemail.value){
				if (formdata.emailaddress.value=='' && formdata.agentemail.value==''){}
				else{rtnval = confirm('ATTENTION: We detected that the e-mail address ' + 
				'you entered for the traveler is the same as the agent e-mail address. ' + 
				'To ensure that your client is e-mailed a copy of the policy purchased, ' +
				'please enter the client\'s e-mail address. If you have any additional ' +
				'questions, please call CSA at 800-873-9855.\n\nAre you sure you wish ' +
				'to continue using identical e-mails?');}
			}
		}
	}
	return rtnval;
}


/**
 *
 * @param fieldId
 */
com.csatp.form.disablePasteOnFieldWithId = function(fieldId) {
   if(typeof(com.csatp.chainEvent) == "undefined") {
      throw ("Unable to disable paste on field id('" + fieldId + "'.  " +
      "Please load a javascript file containing function chainEvent()");
   }

   var field = document.getElementById(fieldId);
   if(field) {
      com.csatp.chainEvent(field, "onpaste", function() {
         return false;
      });
   }
   else {
      throw("Cannot disable paste on field " + fieldId +": feild not found");
   }
 };


/*
* Take the baseline quote and addon price, strip off the dollar sign, and add
* together.  Then add dollar sign back to the total and update the innerHTML
* of the custom field.
* */
com.csatp.form.updateCustomQuote = function(baseline,addon,id)
{
    // strip off the $
    var x = parseFloat(baseline.replace("$",""));
    var y = parseFloat(addon.replace("$",""));

    // add amounts together
    var custom = x + y;
    alert(custom);
    alert(x);
    alert(y);

    // update form fields innerHTML
    document.getElementById(id).innerHTML = "$" + custom.toString();

    return false;
};


/*
*  RXA
*  Adding asterisks to the fields in Beneficiary information IF the firstName or lastName is NOT blank
*  Refer to bug WEB-592
*/
com.csatp.form.checkBeneficiary = function()
{
    var firstName = document.getElementById('beneficiaryfirstnamelabel').innerHTML;
    var lastName = document.getElementById('beneficiarylastnamelabel').innerHTML;

    var firstNameText =  document.getElementById('beneficiaryfirstname').value;
    var lastNameText =  document.getElementById('beneficiarylastname').value;

    if (    ( document.getElementById('beneficiaryfirstname').value != "" ||
            document.getElementById('beneficiarylastname').value != "" ) &&
            firstName.charAt(0) != '*' &&
            lastName.charAt(0) != '*' )
    {

        com.csatp.form.addAsteriskInFront('beneficiaryfirstnamelabel');
        com.csatp.form.addAsteriskInFront('beneficiarylastnamelabel');
        com.csatp.form.addAsteriskInFront('beneficiaryrelationshiplabel');
    }
    else if (   document.getElementById('beneficiaryfirstname').value == "" &&
                document.getElementById('beneficiarylastname').value == "" &&
                ( firstName.charAt(0) == '*' || lastName.charAt(0) == '*' ) )
    {
        com.csatp.form.deleteAsteriskInFront('beneficiaryfirstnamelabel');
        com.csatp.form.deleteAsteriskInFront('beneficiarylastnamelabel');
        com.csatp.form.deleteAsteriskInFront('beneficiaryrelationshiplabel');
    }
};


/**
 *
 * @param fieldName
 */
com.csatp.form.addAsteriskInFront = function(fieldName)
{
    var temp = document.getElementById(fieldName).innerHTML;
    document.getElementById(fieldName).innerHTML = '* ' + temp;
};


/**
 *
 * @param fieldName
 */
com.csatp.form.deleteAsteriskInFront = function(fieldName)
{
    var temp = document.getElementById(fieldName).innerHTML;
    document.getElementById(fieldName).innerHTML =  temp.substring(2);
};


/*
*  AXB
*  Re-index tab order on form fields
*    This function should be called by page onLoad() trigger on all pages with forms
*/
com.csatp.form.tabReIndex = function()
{
    var formElement;

    for (var i=0; i<document.forms.length; i++)
    {
        if (document.forms[i].length != 1)
        {
            formElement = new Array(document.forms[i].length);

            // create 2D array
            for (var k=0; k<formElement.length; k++)
            {
                formElement[k] = new Array(2);
            }

            // copy the original name and tabIndex
            for (j=0; j<document.forms[i].length; j++)
            {
                    formElement[j][0] = document.forms[i][j];
                    formElement[j][1] = document.forms[i][j].tabIndex;
            }

            // sort the 2D array by tabIndex value (using BubbleSort)
            var n = formElement.length;
            var swapped = true;
            var tempNode;
            var tempIndex;

            while (swapped)
            {
                swapped = false;
                n = n - 1;
                for (var x=0; x<n; x++)
                {

                    if (formElement[x][1] > formElement[x+1][1])
                    {
                        // do a swap
                        tempNode = formElement[x][0];
                        tempIndex = formElement[x][1];

                        formElement[x][0] = formElement[x+1][0];
                        formElement[x][1] = formElement[x+1][1];

                        formElement[x+1][0] = tempNode;
                        formElement[x+1][1] = tempIndex;

                        swapped = true;
                    }
                }
            }

            // set the new tabIndex values
            for (var j=0; j<document.forms[i].length; j++)
            {
                formElement[j][0].tabIndex = Number((i*1000)+j+1);
            }
        }
    }
};


/*
 * RXA
 * Moved agentsignupsf.jsp js into here
 */
com.csatp.form.checkSFForm = function(form)
{
    var errormsg = "";

    if (form.first_name == null || form.first_name.value == "")
        errormsg += "First Name is Required\n";
    if (form.last_name == null || form.last_name.value=="")
        errormsg += "Last Name is Required\n";
    if (form.company == null || form.company.value=="")
        errormsg += "Agency Name is Required\n";
    if (form.email == null || form.email.value=="")
        errormsg += "Email is Required\n";
    if (form.phone == null || form.phone.value=="")
        errormsg += "Phone is Required\n";
    if (form.street == null || form.street.value=="")
        errormsg += "Address is Required\n";
    if (form.city == null || form.city.value=="")
        errormsg += "City is Required\n";
    if (form.state == null || form.state.value=="")
        errormsg += "State is Required\n";
    if (form.zip == null || form.zip.value=="")
        errormsg += "Zip Code is Required\n";
    if (document.getElementById('00N30000001RHui') == null || document.getElementById('00N30000001RHui').value=="")
			errormsg += "# Agents in your office is Required\n";
    if (document.getElementById('00N30000001RHtb') == null || document.getElementById('00N30000001RHtb').value=="")
			errormsg += "# Agents offsite is Required\n";
    if (document.getElementById('revenue') == null || document.getElementById('revenue').value=="")
			errormsg += "Annual Sales Revenue is Required\n";

    if (errormsg.length != 0){
        alert(errormsg);
        return false;
    }
    else{
        return true;
    }
};


/*
*  AXB 11/21/08
*  Adding asterisks to the Email field IF the E-Mail Delivery radio button is
*  selected.
*  Refer to WEB-1162
*/
com.csatp.form.checkEmailDelivery = function()
{
    var emailAddressLabel = document.getElementById('emailaddresslabel').innerHTML;

    if (document.getElementById("delemail").checked && (emailAddressLabel.charAt(0) != "*")) {
        // Make sure E-Mail is marked as required if E-Mail delivery is selected
        com.csatp.form.addAsteriskInFront('emailaddresslabel');
    }
    else if (document.getElementById("delps").checked && (emailAddressLabel.charAt(0) == '*')) {
        // Make sure E-Mail is not marked as required if Postal delivery is selected
        com.csatp.form.deleteAsteriskInFront('emailaddresslabel');
    }
};


/**
 * MXS
 * Clear a single form field
 * @param id the id of the element to set to ""
 */
com.csatp.form.clearFormField = function(id){
    if (document.getElementById(id))
        document.getElementById(id).value = "";
};

/**
 * AXB
 * Toggle an element's disabled property by a checkbox.  If the checkbox is checked,
 * the lookup element is enabled; otherwise, it is disabled.
 * @param elementId The DOM ID for the lookup element.
 * @param checkboxId The DOM ID for the checkbox.
 */
com.csatp.form.toggleDisabledByCheckbox = function(elementId, checkboxId) {
    var element = document.getElementById(elementId);
    var checkbox = document.getElementById(checkboxId);
    element.disabled = !checkbox.checked;
};

//com.csatp.form.toggleFutureQuoteDate = function(isFutureQuoteCheckboxId, appDateId, theForm) {
com.csatp.form.toggleFutureQuoteDate = function(isFutureQuoteCheckboxId, appDateId, serverdate) {
    var futureQuoteCheckbox = document.getElementById(isFutureQuoteCheckboxId);
    var appDateField = document.getElementById(appDateId);

    if (futureQuoteCheckbox.checked) {
        appDateField.disabled = false;
    }
    else {
        appDateField.disabled = true;
        appDateField.value = serverdate.value;
    }
};

/**
 *
 * @param days
 */
com.csatp.form.logGAEvent = function(category, action, label, value){
    if (typeof _gaq != 'undefined')
        _gaq.push(['_trackEvent', category, action, label, value]);
};

/* SELENIUM Methods */
// This is a method for selenium to get a date in the future, days from today
com.csatp.form.seleniumGetFutureDate = function(days){
    var date = new Date();
    date.setDate(date.getDate()+days);

    var month = date.getMonth() + 1;
    if(month < 10){month = '0' + month;}

    var day = date.getDate();
    if(day < 10){day = '0' + day;}

    var year = date.getYear() - 100;
    if(year < 10){year = '0' + year;}

    var displaytime = month + '/' + day + '/' + year;
    return displaytime;
};
