
// =====================================================================================================================================
//	Theme system 
// =====================================================================================================================================

/*

	Allows OC to change the keyword displayed on survey pages by using a query string.
	showTheTheme() must be called from the page's setup handler.
	
	Examples of urls;
		somePage.html?TheTheme=columbian%20coffee
		somePage.html ( this would show the test that is in the html page itself )
		
	remember to use %20 instead of spaces:
		somePage.html?TheTheme=columbian%20coffee   NOT somePage.html?kw=columbian coffee 
	
	RL

*/


	function GetTheURLparms( name ) {
	// used by the location system

		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 unescape(results[1]); 
		}
		
	}


	function showTheTheme() {
	// any page can call this from its setup function
		var TheTheme = "";
		var TheTheme = GetTheURLparms('TheTheme');
		if (TheTheme != "") { $('span.TheTheme').html(TheTheme) }
	}



// =====================================================================================================================================
//	Validation 
// =====================================================================================================================================

/*

	Every element that requires validation is active (has some kind of event handler attached). They all call functions 
	whenever the user manipulates them.  And they provide validation feedback accordingly as the user fills out the form.
	
	Note that the page 1 and 2 setup functions are named setupCoffeStep1() and setupCoffeStep2() but they are used by 
	all categories, not just coffee.
	
	RL

*/

// =====================================================================================================================================
//	Validation utilities (page 1 and page 2)
// =====================================================================================================================================

	//  regex expressions used to validate input
	var gNonBlank 		 		= /\w/																					; // must contain at least 1 word character
	var gThreeDigits	 		= /^[0-9][0-9][0-9]$/																	; // used for phone number validation
	var gFourDigits		 		= /^[0-9][0-9][0-9][0-9]$/																; // used for phone number validation
	var gEmail 					= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/							; // used for email
	var gSingleUSZip 			= /^[\d]{5}$/																			; // 5 digits and 5 digits only
	var gSingleCanPostalCode 	= /^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$/	; // CharDigitChar DigitCharDigit separated by one optional space ex: T3M 2K7. Validator assumes that the field has been UPPERCASE'd


	function uppercaseTheZip(whichField) {
	// called by both page 1 and page 2
	// uppercase the zip code (required by Canadian postal codes). Call this only from a blur handler.
	// if you call it on a keyup handler it will move the insertion point to the end of the text in the field 
	// whenever it is called. That will bug the user so don't do it. Blur handler, only.
		whichField.value = whichField.value.toUpperCase();	
	}


	function cleanupTheUsersString(theStringToClean) {
		// called by page 1
		// expects a string, returns a cleaned string.
		var cleanedString	= theStringToClean;
		// this is a very specific, step by step process...
		cleanedString			= jQuery.trim(cleanedString);				// get rid of leading and trailing whitespace
		cleanedString			= cleanedString.replace(/, +/g,  "," );		// get rid of spaces after commas
		cleanedString			= cleanedString.replace(/ +,/g,  "," );		// get rid of spaces before commas 
		cleanedString			= cleanedString.replace(/^,+/,   ""  );		// get rid of any number of leading commas
		cleanedString			= cleanedString.replace(/ +$/,   ""  );		// retrim trailing whitespace!
		cleanedString			= cleanedString.replace(/,+$/,   ""  );		// get rid of any number of trailing commas
		cleanedString			= cleanedString.replace(/,+/g,   "," );		// get rid of multiple commas
		return cleanedString ;							// return the cleaned string to the caller
	}


	function cleanupTheUsersEntry(theFieldToClean) {
	// called by 2
		// expects a reference to an input element, modifies the value of that element.
		var cleanedField		= theFieldToClean.value;
		
		// this is a very specific, step by step process...
		cleanedField			= jQuery.trim(cleanedField);				// get rid of leading and trailing whitespace
		cleanedField			= cleanedField.replace(/, +/g,  "," );		// get rid of spaces after commas
		cleanedField			= cleanedField.replace(/ +,/g,  "," );		// get rid of spaces before commas 
		cleanedField			= cleanedField.replace(/^,+/,   ""  );		// get rid of any number of leading commas
		cleanedField			= cleanedField.replace(/ +$/,   ""  );		// retrim trailing whitespace!
		cleanedField			= cleanedField.replace(/,+$/,   ""  );		// get rid of any number of trailing commas
		cleanedField			= cleanedField.replace(/,+/g,   "," );		// get rid of multiple commas
		theFieldToClean.value	= cleanedField ;							// put the cleaned entry back into the input
	}


	function validateMultipleUSOrCanCodes(whoCalled) {
		// called by page 1
		// validates a field for multiple 5 digit US zip codes or 7 character Canadian postal codes separated with commas
		// expects a reference to an text input element.
		// returns true if all the codes in the passed in field are valid, false if not.

			var cleanedUsersInput			= cleanupTheUsersString(whoCalled.value);
			var individualCodesArray		= cleanedUsersInput.toUpperCase().split(",");
			var zipCodeFieldIsValid 		= false
			var numberOfValidCodes 			= 0;

			jQuery.each(individualCodesArray, function() { 
				var isCurrentArrayElementValid = (gSingleUSZip.test(this) || gSingleCanPostalCode.test(this));
				numberOfValidCodes = numberOfValidCodes + isCurrentArrayElementValid ;
			} );

			// if all the zip codes we extracted into the array are valid then the zip field is valid.
			zipCodeFieldIsValid 			= (numberOfValidCodes == individualCodesArray.length);
			
			if (zipCodeFieldIsValid) {
				var previousPwithFinger 	=  $(whoCalled).prev('p.questionText');
				$(previousPwithFinger)		.find(' img.validationArrow').fadeOut('fast');
			} else {
				var previousPwithFinger 	=  $(whoCalled).prev('p.questionText');
				$(previousPwithFinger)		.find(' img.validationArrow').fadeIn('fast');
			}

			return zipCodeFieldIsValid;
	}


	function setupAFinger(whichRadioButton) {
		// page 1 might load with checked radio buttons (browser Back button)
		// so every time the page loads check all the radio groups and hide/show the finger 
		// if any of the radios are checked.

		var theRadioButtonsID			= '#' + whichRadioButton.id ;
		var previousPwithFinger			= $(theRadioButtonsID).parents('ul').prev('p.questionText') ;
		var theRadioButtonGroupsName	= $(theRadioButtonsID).attr('name');

		if ( $('[name=' + theRadioButtonGroupsName + ']:checked').length == 1) {
			$(previousPwithFinger).find(' img.validationArrow').fadeOut('fast');
		} else {
			$(previousPwithFinger).find(' img.validationArrow').fadeIn( 'fast');
		}
	}


	function giveThemTheFinger(whichRadioButton) {
		// called by page 1
		var theRadioButtonsID = '#' + whichRadioButton.id ;
		var previousPwithFinger = $(theRadioButtonsID).parents('ul').prev('p.questionText') ;
		$(previousPwithFinger).find(' img.validationArrow').fadeOut('fast');
	}


	function validateNonBlank(whichField) {
		// called by page 2
		var IDofTheInputToManage	= '#' + whichField.id;
		var currentFieldsIsValid	= false;
		
		( gNonBlank.test(whichField.value) == true ) ? (currentFieldsIsValid = true) : (currentFieldsIsValid = false) ;
		
		manageAValidationHint(IDofTheInputToManage, currentFieldsIsValid) ;
		return currentFieldsIsValid
	}


	function validateEmail(whichField) {
		// called by page 2
		var IDofTheInputToManage	= '#' + whichField.id;
		var currentFieldsIsValid	= false;
		( gEmail.test(whichField.value) == true ) ? (currentFieldsIsValid = true) : (currentFieldsIsValid = false) ;
		manageAValidationHint(IDofTheInputToManage, currentFieldsIsValid) ;
		return currentFieldsIsValid
	}


	function validateStateSelect(whichField) {
		// called by page 2
		var IDofTheSelectToManage 	= '#' + whichField.id;
		var currentSelectsIsValid	= false;
		
		(whichField.value == -1) ? (currentSelectsIsValid = false) : (currentSelectsIsValid = true) ;
		manageAValidationHint(IDofTheSelectToManage, currentSelectsIsValid) ;
		return currentSelectsIsValid

	}


	function validatePhoneNumber() {
		// called by page 2
		// validate the 3 phone number fields as one component
		var completePhoneNumberIsValid	= false;

		var AreaCodeIsValid		= gThreeDigits.test($('#Areacode')   .val());
		var PrefixIsValid		= gThreeDigits.test($('#PhonePrefix').val());
		var PhoneNumberIsValid	= gFourDigits.test( $('#PhoneNumber').val());
		
		(AreaCodeIsValid && PrefixIsValid && PhoneNumberIsValid ) ?  (completePhoneNumberIsValid = true) : (completePhoneNumberIsValid = false);
		
		if (AreaCodeIsValid) {
			$('#Areacode').css({backgroundColor : 'rgb(255,255,255)'});
		} else {
			$('#Areacode').css({backgroundColor : 'rgb(255,220,220)'});
		}
		if (PrefixIsValid) {
			$('#PhonePrefix').css({backgroundColor : 'rgb(255,255,255)'});
		} else {
			$('#PhonePrefix').css({backgroundColor : 'rgb(255,220,220)'});
		}
		if (PhoneNumberIsValid) {
			$('#PhoneNumber').css({backgroundColor : 'rgb(255,255,255)'});
		} else {
			$('#PhoneNumber').css({backgroundColor : 'rgb(255,220,220)'});
		}

		if (completePhoneNumberIsValid) {
			$('#Areacode').siblings().filter('.validationHint').fadeOut('fast');
		} else {
			$('#Areacode').siblings().filter('.validationHint').fadeIn('fast');
		}

		return completePhoneNumberIsValid

	}


	function autoAdvancePhoneNumberFields(whichField) {
		// called by page 2
		if (whichField.id == 'Areacode'    && whichField.value.length == 3) { $('#PhonePrefix')	.focus(); $('#Areacode')   .blur(); }
		if (whichField.id == 'PhonePrefix' && whichField.value.length == 3) { $('#PhoneNumber')	.focus(); $('#PhonePrefix').blur(); }
		if (whichField.id == 'PhoneNumber' && whichField.value.length == 4) { $('#Extension')	.focus(); $('#PhoneNumber').blur(); }
	}


	function validateOneUSOrCanZipCode(whichField) {
		// called by page 2
		var IDofTheInputToManage	= '#' + whichField.id;
		var currentFieldsIsValid	= false;
		var whatTheUserEntered		= whichField.value;
			whatTheUserEntered		= whatTheUserEntered.toUpperCase();

		( gSingleUSZip.test(whatTheUserEntered) || gSingleCanPostalCode.test(whatTheUserEntered)  == true ) ? (currentFieldsIsValid = true) : (currentFieldsIsValid = false) ;
		manageAValidationHint(IDofTheInputToManage, currentFieldsIsValid) ;
		return currentFieldsIsValid

	}


	function manageAValidationHint(IDofTheInputToManage, currentFieldsIsValid) {
		// called by page 2
		// a validation hint is the div with text that appears to the right of the inputs on page 2
		if (currentFieldsIsValid) {
			$(IDofTheInputToManage).css({backgroundColor : 'rgb(255,255,255)'}).siblings().filter('.validationHint').fadeOut('fast');
		} else {
			$(IDofTheInputToManage).css({backgroundColor : 'rgb(255,220,220)'}).siblings().filter('.validationHint').fadeIn('fast');
		}
	}


	function countDownTo1000(whoCalled) {
	
		var whatWasEntered				= whoCalled.value 		 ;
		var howManyCharsWereEntered		= whoCalled.value.length ;
		
		if (howManyCharsWereEntered > 999 ) {
			whatWasEntered  = whatWasEntered.substring(0,999);
			whoCalled.value = whatWasEntered;
		}

		$('#numberOfCharsRemaining').html(1000 - whoCalled.value.length);
	}




// =====================================================================================================================================
//	Main validation functions
// =====================================================================================================================================

	function validateStep1() {
		
		var numberOfRequiredResponses	= $('img.validationArrow').length ;
		var numberOfValidResponses		= $('img.validationArrow:hidden').length ; 
		var ZipIsValid					= validateMultipleUSOrCanCodes( $('#txtZipCode').get(0) ) ;
		
		if (numberOfValidResponses == numberOfRequiredResponses) {
			//alert('The form is valid so we will call George\'s code and it will move to page 2.');
			return true;
		} else {
			var theMessage = 'We need more information in order to get you free quotes.\n\n' +
							 '- Please answer all the questions that are marked \nwith a pointing red hand' ;
			if (!ZipIsValid) { theMessage += ' including Zip/postal code.\n\n'}
			alert(theMessage);
			return false;
		}
	}


	function validateStep2() {
		
		var CompanyName		= validateNonBlank($('#CompanyName')	.get(0)) ;	// the get(0) gets a DOM reference to the element. It is like
		var FirstName		= validateNonBlank($('#FirstName')		.get(0)) ;	// the 'this' function context of the event binding code below.
		var LastName		= validateNonBlank($('#LastName')		.get(0)) ;
		var EmailAddress	= validateEmail($('#EmailAddress')		.get(0)) ;
		var PhoneNumber		= validatePhoneNumber() 						 ;
		var Address1		= validateNonBlank($('#Address1')		.get(0)) ;
		var City			= validateNonBlank($('#City')			.get(0)) ;
		var State			= validateStateSelect($('#StateId')		.get(0)) ;
		var Zip				= validateOneUSOrCanZipCode($('#Zip')	.get(0)) ;
	
		numberOfValidElements = CompanyName+FirstName+LastName+EmailAddress+PhoneNumber+Address1+City+State+Zip ;

		if (numberOfValidElements == 9) {
			// the form is valid, send it to George
			return true;
		} else {
			// the form is not valid, alert the user
			var theMessasge		= 'Your contact information is not complete. \nWe need the following in order to send you your free quotes.\n\n' 
			var fieldToFocus	= false;
	
			if (!CompanyName) {
				theMessasge += 'Company Name\n'
				if (!fieldToFocus) { fieldToFocus	= '#CompanyName'}
			}
			if (!FirstName) {
				theMessasge += 'First Name\n'
				if (!fieldToFocus) { fieldToFocus	= '#FirstName'}
			}
			if (!LastName) {
				theMessasge += 'Last Name\n'
				if (!fieldToFocus) { fieldToFocus	= '#LastName'}
			}
			if (!EmailAddress) {
				theMessasge += 'Email Address\n'
				if (!fieldToFocus) { fieldToFocus	= '#EmailAddress'}
			}
			if (!PhoneNumber) {
				theMessasge += 'Phone Number\n'
				if (!fieldToFocus && !gThreeDigits.test($('#Areacode')   .val())) { fieldToFocus	= '#Areacode'   }
				if (!fieldToFocus && !gThreeDigits.test($('#PhonePrefix').val())) { fieldToFocus	= '#PhonePrefix'}
				if (!fieldToFocus && !gFourDigits.test( $('#PhoneNumber').val())) { fieldToFocus	= '#PhoneNumber'}
			}
			if (!Address1) {
				theMessasge += 'Street Address\n'
				if (!fieldToFocus) { fieldToFocus	= '#Address1'}
			}
			if (!City) {
				theMessasge += 'City\n'
				if (!fieldToFocus) { fieldToFocus	= '#City'}
			}
			if (!State) {
				theMessasge += 'State\n'
				if (!fieldToFocus) { fieldToFocus	= '#StateId'}
			}
			if (!Zip) {
				theMessasge += 'Zip or Postal code\n'
				if (!fieldToFocus) { fieldToFocus	= '#Zip'}
			}
	
		if (fieldToFocus) { $(fieldToFocus).focus() }
			alert(theMessasge);	
			return false;
		}
	}




// =====================================================================================================================================
//	Page setup functions
// =====================================================================================================================================

	function setupCoffeStep1() {
 		$('input[name^=rbAnswer]')	.bind('click',		function(){ giveThemTheFinger(this)				});
 		$('#txtZipCode')			.bind('keyup',		function(){ validateMultipleUSOrCanCodes(this);	});
 		$('#txtZipCode')			.bind('blur',		function(){ uppercaseTheZip(this) 				});
 		$('#txtAdditionalComments')	.bind('keydown',	function(){ countDownTo1000(this) 				});
 		$('input[name^=rbAnswer]')	.each(				function(){ setupAFinger(this)});
 		$('#txtZipCode')			.keyup();
 		showTheTheme();
	}


	function setupCoffeStep2() {
	
		$('#CompanyName')	.focus();
	
		$('#CompanyName')	.bind('keyup',  function() { validateNonBlank(this)					});
		$('#CompanyName')	.bind('blur',   function() { validateNonBlank(this)					});
		$('#FirstName')		.bind('keyup',  function() { validateNonBlank(this)					});
		$('#LastName')		.bind('keyup',  function() { validateNonBlank(this)					});
		$('#Address1')		.bind('keyup',  function() { validateNonBlank(this)					});
		$('#City')			.bind('keyup',  function() { validateNonBlank(this)					});
		$('#StateId')		.bind('change', function() { validateStateSelect(this)				});
		$('#EmailAddress')	.bind('keyup',  function() { validateEmail(this)					});
		$('#EmailAddress')	.bind('blur',   function() { $('#EmailAddress').keyup()				});		// easy to run into autofill here
			
		$('#Areacode')		.bind('keyup',  function() { validatePhoneNumber()					});
		$('#PhonePrefix')	.bind('keyup',  function() { validatePhoneNumber()					});
		$('#PhoneNumber')	.bind('keyup',  function() { validatePhoneNumber()					});
		$('#Areacode')		.bind('blur',   function() { validatePhoneNumber()					});
		$('#PhonePrefix')	.bind('blur',   function() { validatePhoneNumber()					});
		$('#PhoneNumber')	.bind('blur',   function() { validatePhoneNumber()					});
		
		$('#Zip') 			.bind('keyup',  function() { validateOneUSOrCanZipCode(this)		});
		$('#Zip')			.bind('blur',   function() { uppercaseTheZip(this)					});
		
		$('#CompanyName,#FirstName,#LastName,#Address1,#Address2,#City,#Zip')	.bind('blur', function() { cleanupTheUsersEntry(this) });
		$('#CompanyName,#FirstName,#EmailAddress,#LastName')					.keyup();
		$('#Areacode,#PhonePrefix,#PhoneNumber,#Address1,#City,#Zip')			.keyup();
		$('#Areacode,#PhonePrefix,#PhoneNumber')								.blur();
		$('#StateId')															.change();
 		showTheTheme();

	}


// =====================================================================================================================================
//	End of validation
// =====================================================================================================================================







// Historical functions from Dreamweaver

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


// Commented out by G.Rios - conflicts with page-level code.

/*
var pm_tagname = "universalTag.txt";
var pm_tagversion = "1.4";
var pm_accountid = "1T7GJ9M2CUA7EM2B78CVG78KJ4";
var pm_scripthost = "srv.perf.overture.com";
var pm_customargs = "";
var pm_querystr = "?" + "ver=" + pm_tagversion + "&aid=" + pm_accountid + pm_customargs;
var pm_tag = "<SCR" + "IPT LANGUAGE='JavaScript' " + "SRC=//" +
pm_scripthost + "/collweb/ScriptServlet" + pm_querystr + "></SCR" + "IPT>";

document.write(pm_tag);


document.write("<scr" + "ipt src=\"http://www.google-analytics.com/urchin.js\" type=\"test/javascript\"></scr" + "ipt>");
document.write("<scr" + "ipt type=\"text/javascript\">");
document.write("_uacct=\"UA-306708-1\";");
document.write("urchinTracker();");
document.write("</scr" + "ipt>");
*/