// Utilities  used by the site

// This file has modifications to support the steel building numeric fields.

// regex globals used for validation on any page

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 gNumbersOnly		 	= /^[0-9]+$/																			; // any number of numbers only
var gSingleUSZip 			= /^[\d]{5}$/																			; // US ZipCode, 5 digits and 5 digits only
var gSingleCanPostalCode 	= /^[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]$/	; // Can postal code: CharDigitChar DigitCharDigit separated by one optional space ex: T3M 2K7. Validator assumes that the field has been UPPERCASE'd
var gOneFieldPhoneNumber	= /^\(?[\d]{3}\)?[ .\/_\-]?[\d]{3}[ .\/_\-]?[\d]{4}/									; // 3 part phone number in one field.
var gEmailExpression 		= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/							; // used for email

// field background colors
var gNormalColor     = '#fff';
var gAlertColor      = '#f7ca73';




/*	====================================================================================================================================
	Just makes the steel building images set/unset their radio buttons in IE. 
	Sure would be nice if IE would support this natively like all the other browsers.
	==================================================================================================================================== */

	function setupSteelBuildingWithImagesSurvey() {
		$('img.iconNextToQuestion').bind('click', function(){ toggleARadioButton(this) });
	}

		function toggleARadioButton(whichImage) {
			var idOfTheRadioToToggle 	= '#' + $(whichImage).parent().attr('for');
			$(idOfTheRadioToToggle)		.attr('checked', 'true');
		}


/*	====================================================================================================================================
	the Theme system
	allows 360 to change the text displayed as the category on survey page 1.
	==================================================================================================================================== */

	function GetTheURLparms( name ) {
	// used by the theme 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('theme');
		if (TheTheme != "") { $('span.TheTheme').html(TheTheme) }
	}




/*	====================================================================================================================================
	City/State pages. These are created by 360 staff from Dreamweaver templates.
	==================================================================================================================================== */

	function setupCityStatePage() {
		$('#getQuotesBtnInTheContent').hover(
			function(){$(this).attr({src : 'resources/btn_getquotes_large_rollover.jpg'				})},
			function(){$(this).attr({src : 'resources/btn_getquotes_large.jpg'						})}		);
		$('#getQuotesBtnInTheSidebar').hover(
			function(){$(this).attr({src : 'resources/btn_getquotes_large_blueback_rollover.jpg'	})},
			function(){$(this).attr({src : 'resources/btn_getquotes_large_blueback.jpg'				})}		);
	}


	function goToTheURL () {
	// Go to a url from a select element.
	// Called by a select element on City/State pages to change the page.
	// The value of the option must be the url of the page to go to. RL
		document.location.href = document.ListOfURLs.contentSelector.value;
	}




/*	====================================================================================================================================
	Article pages. Both articles and Supplier articles.
	These are created by 360 from Dreamweaver templates.
	==================================================================================================================================== */

	function setupArticlePage() {
	// there will be the usual DW template path issues...
		$('#getFreeQuotesBtn').hover(
			function(){$(this).attr({src : 'resources/btn_getquotes_large_blueback_rollover.gif'	})},
			function(){$(this).attr({src : 'resources/btn_getquotes_large_blueback.gif'				})}		);
	}

	function setupSupplierArticlePage() {
	// there will be the usual DW template path issues...
		$('#signUpNowBtn').hover(
			function(){$(this).attr({src : 'resources/btn_signupnow_rollover.gif'	})},
			function(){$(this).attr({src : 'resources/btn_signupnow.gif'			})}		);
	}





/*	====================================================================================================================================
	the Supplier page
	==================================================================================================================================== */


	function manageASignUpInput(whichField) {

		var theInputToManage = '#' + whichField.id;
		var currentValidity  = false;
			currentValidity  = gNonBlank.test(whichField.value) ;
		if ( currentValidity ) {
			$(theInputToManage).removeClass('notValid');
			$("label[for=" + whichField.id +"]").removeClass('notValid');
		} else {
			$(theInputToManage).addClass('notValid');
			$("label[for=" + whichField.id +"]").addClass('notValid');
		}

	}


	function manageASignUpEmail(whichField) {

		var theInputToManage = '#' + whichField.id;
		var currentValidity  = false;
			currentValidity  = gEmailExpression.test(whichField.value) ;
		if ( currentValidity ) {
			$(theInputToManage).removeClass('notValid');
			$("label[for=" + whichField.id +"]").removeClass('notValid');
		} else {
			$(theInputToManage).addClass('notValid');
			$("label[for=" + whichField.id +"]").addClass('notValid');
		}

	}


	function manageASignUpPhoneNumber(event, whichField) {

		var theInputToManage 	= '#' + whichField.id;
		var requiredLength		= event.data
		var currentValidity  	= false;
		
		if (requiredLength == 3) {
			currentValidity  = gThreeDigits.test(whichField.value) ;
		} else if (requiredLength == 4) {
			currentValidity  = gFourDigits.test(whichField.value) ;
		}
		
		if ( currentValidity ) {
			$(theInputToManage)	.removeClass('notValid');
		} else {
			$(theInputToManage)	.addClass('notValid');
		}

		// manage the label feedback
		var AreaCodeValidity		= gThreeDigits			.test( $('#areacode')   	.val() );
		var PrefixValidity			= gThreeDigits			.test( $('#phonePrefix')	.val() );
		var PhoneNumberValidity		= gFourDigits			.test( $('#phoneNumber')	.val() );
		(AreaCodeValidity && PrefixValidity && PhoneNumberValidity ) ?  (PhoneNumberIsValid = true) : (PhoneNumberIsValid = false);

		if (PhoneNumberIsValid) {
			$('label#fullPhoneNumber').removeClass('notValid');
		} else {
			$('label#fullPhoneNumber').addClass('notValid');
		}

		// auto advance
		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) { $('#ext')			.focus(); $('#phoneNumber').blur(); }

	}


	function sendEmailForUniquenessTest() {
		var currentSessionKey	= '01234567890';
		var requestedEmail		= $('#EmailAddress').val();
		$.ajax( {
			url			: "http://sellers.officecoffee.com/ESM/svs/datavalidator.asmx/ValidateUser",
			type		: "GET",
			async		: false, 
			data		: { userNameToTest: requestedEmail, sessionKey : currentSessionKey },
			dataType	: "json",
			success		: function ( data ) { return respondToEmailUniquenessTest( data ) }
		});
	}

		gEmailIsUnique = false;			// not really keen about having to declare a global here...
		
		function respondToEmailUniquenessTest (data) {
			var emailIsUnique = data.response.valid;
			if (emailIsUnique == 'False') {
				gEmailIsUnique = false;
			} else {
				gEmailIsUnique = true;
			}
		}


	function validateTheSignUpForm() {
	//	validates the user entered data, 
	// 	checks for a unique email, 
	// 	shows appropriate feedback when necessary, 
	// 	returns true or false to manageARegistrationAttempt()

		var firstNameIsValid		= gNonBlank				.test( $('#FirstName')		.val() );
		var lastNameIsValid			= gNonBlank				.test( $('#LastName')		.val() );
		var companynameIsValid		= gNonBlank				.test( $('#CompanyName')	.val() );
		var emailAddressIsValid		= gEmailExpression		.test( $('#EmailAddress')	.val() );
		// set the gEmailIsUnique global. There must be a better way.
		sendEmailForUniquenessTest();
		// now the gEmailIsUnique global is set to true or false and we can use it.
		var PhoneNumberIsValid 		= false
		var AreaCodeValidity		= gThreeDigits			.test( $('#areacode')   	.val() );
		var PrefixValidity			= gThreeDigits			.test( $('#phonePrefix')	.val() );
		var PhoneNumberValidity		= gFourDigits			.test( $('#phoneNumber')	.val() );
			(AreaCodeValidity && PrefixValidity && PhoneNumberValidity ) ?  (PhoneNumberIsValid = true) : (PhoneNumberIsValid = false);

		// setup the display. Brute force but easy to read...
		
		if (firstNameIsValid) {
			$("#FirstName, label[for='FirstName']").removeClass('notValid');
		} else {
			$("#FirstName, label[for='FirstName']").addClass('notValid');
		}
		if (lastNameIsValid) {
			$("#LastName, label[for='LastName']").removeClass('notValid');
		} else {
			$("#LastName, label[for='LastName']").addClass('notValid');
		}
		if (companynameIsValid) {
			$("#CompanyName, label[for='CompanyName']").removeClass('notValid');
		} else {
			$("#CompanyName, label[for='CompanyName']").addClass('notValid');
		}
		if (emailAddressIsValid) {
			$("#EmailAddress, label[for='EmailAddress']").removeClass('notValid');
		} else {
			$("#EmailAddress, label[for='EmailAddress']").addClass('notValid');
		}
		if (AreaCodeValidity) {
			$("#areacode").removeClass('notValid');
		} else {
			$("#areacode").addClass('notValid');
		}
		if (PrefixValidity) {
			$("#phonePrefix").removeClass('notValid');
		} else {
			$("#phonePrefix").addClass('notValid');
		}
		if (PhoneNumberValidity) {
			$("#phoneNumber").removeClass('notValid');
		} else {
			$("#phoneNumber").addClass('notValid');
		}

		if (AreaCodeValidity && PrefixValidity && PhoneNumberValidity) {
			$('label#fullPhoneNumber').removeClass('notValid');
		} else {
			$('label#fullPhoneNumber').addClass('notValid');
		}

		// send the registration or do the user feedback
		
		var formIsValid = false;
		
		if ( firstNameIsValid && lastNameIsValid && companynameIsValid && emailAddressIsValid && gEmailIsUnique && PhoneNumberIsValid) {
			return true;

		} else {
			if ( (firstNameIsValid + lastNameIsValid + companynameIsValid + emailAddressIsValid + PhoneNumberIsValid) == 4 ) {
				var messageToTheVisitor = "We need more info in order to complete your registration.\nPlease complete the following field:\n\n"
			} else {
				var messageToTheVisitor = "We need more info in order to complete your registration.\nPlease complete the following fields:\n\n"
			}
			var fieldToFocus = ""
			if ( !firstNameIsValid )	{
				if (fieldToFocus == "") {fieldToFocus = '#FirstName'};
				messageToTheVisitor += "first name\n"}
			if ( !lastNameIsValid )		{
				if (fieldToFocus == "") {fieldToFocus = '#LastName'};
				messageToTheVisitor += "last name\n"}
			if ( !companynameIsValid )	{
				if (fieldToFocus == "") {fieldToFocus = '#CompanyName'};
				messageToTheVisitor += "company name\n"}
			if ( !emailAddressIsValid)	{
				if (fieldToFocus == "") {fieldToFocus = '#EmailAddress'};
				messageToTheVisitor += "email - valid email is required\n"}
			if ( !PhoneNumberIsValid )	{
				if (fieldToFocus == "") {
					if (!AreaCodeValidity) 		{fieldToFocus = '#areacode'		}
				};
				if (fieldToFocus == "") {
					if (!PrefixValidity) 		{fieldToFocus = '#phonePrefix'	}
				};
				if (fieldToFocus == "") {
					if (!PhoneNumberValidity) 	{fieldToFocus = '#phoneNumber'	}
				};
				messageToTheVisitor += "phone number - ex: 123 123 1234 (extension is optional)\n"
			}

			// if we find a non-unique email we deal with it here.
			
			if ( emailAddressIsValid && !gEmailIsUnique) {
				if (fieldToFocus == "") {fieldToFocus = '#EmailAddress'};
				messageToTheVisitor = "The email you have entered is already in our system. Please use a different email address.\n\nIf you have problems or questions please contact customer service <need site 800 number here>"
			} else {
				messageToTheVisitor += "\nOnce you complete this form you will be taken to your Supplier portal welcome page and you can setup your leads."
			}

			alert						(messageToTheVisitor);
			$(fieldToFocus)				.focus();
			return						false;
		}

	}



	function registerANewSupplier() {

		$("#sessionKey")	.val('01234567890');
		var resultObject	= null;

		$.ajax( {
			url			: "http://sellers.officecoffee.com/ESM/svs/SupplierServices.asmx/SignUp",
			type		: "POST",
			async		: false, 
			data		: $("#theSignUpForm").serialize(),
			dataType	: "json",
			success		: function (data) { resultObject = data },
			error		: function (data) { resultObject = data }
		});
		
		return resultObject;
		
	}


	function manageARegistrationAttempt(event) {

		// make sure the event goes no farther than this handler
		event.preventDefault();
		event.stopPropagation();
		
		// check validation. Just return false if the user's data is invalid.
		var usersDataIsValid = validateTheSignUpForm();
		if (!usersDataIsValid) { return false; }
	
		// If the user's data is valid send the data for registration
		// currently this /always fails with an xhr status of 0 and a responseText of ""
		var ajaxRegistrationResult	= registerANewSupplier();

		var registrationWasSuccessful = false;
		if (ajaxRegistrationResult.message == "OK") { registrationWasSuccessful = true; }

		if (!registrationWasSuccessful) {
			alert("We were not able to register you. Please try again. If the problem continues please contact customer service at " +
			gSite800Number +
			" and we will take your registration over the phone.");
			return false;
		} else {
			var loginURL = "https://sellers.officecoffee.com/ESM/SignUp/signupSSO.aspx?" ;
			var loginParms = "id=" + ajaxRegistrationResult.sellerId + "&token=" + ajaxRegistrationResult.loginToken ;
			var SSOurl = loginURL + loginParms ;
			self.location = SSOurl ;
		}

		return false;	// just in case...
	}



	// setup the supplier page

	function setupSupplierPage() {

		$('div#moreDetails')		.hide();
		$('input#FirstName')		.focus();
		
		$('input#FirstName')	.bind('keyup', function(){manageASignUpInput(this)} 	);
		$('input#LastName')		.bind('keyup', function(){manageASignUpInput(this)} 	);
		$('input#CompanyName')	.bind('keyup', function(){manageASignUpInput(this)} 	);
		
		$('input#EmailAddress')	.bind('keyup', function(){manageASignUpEmail(this)} 	);
		$('input#EmailAddress')	.bind('blur',  function(){manageASignUpEmail(this)} 	);
		
		$('input#areacode')		.bind('keyup', [3], function(event){manageASignUpPhoneNumber(event, this)} );
		$('input#phonePrefix')	.bind('keyup', [3], function(event){manageASignUpPhoneNumber(event, this)} );
		$('input#phoneNumber')	.bind('keyup', [4], function(event){manageASignUpPhoneNumber(event, this)} );

		$('img#ViewSampleLead')	.hover(
			function(){ $(this).attr({src : 'resources/Supplier-view-sample-lead-hover.gif'}) 		},
			function(){ $(this).attr({src : 'resources/Supplier-view-sample-lead.gif'}) 			}	);

		$('img#ViewSampleLead')	.bind( 'click',  function(){  $('div#SampleLead').fadeIn ('slow')	});
		$('div#SampleLead')		.bind( 'click',  function(){  $('div#SampleLead').fadeOut('slow')	});

		$('input#JoinNowButton').bind( 'click', function(event){ manageARegistrationAttempt(event) 			});

		$('input#JoinNowButton').hover(
			function(){ $(this).attr({src : 'resources/Supplier-join-now-button-hover.gif'}) 		},
			function(){ $(this).attr({src : 'resources/Supplier-join-now-button.gif'}) 				}	);
		
		$('img.SupplierJoinNow').hover(
			function(){ $(this).attr({src : 'resources/Supplier-join-now-button2-hover.gif'	})		},
			function(){ $(this).attr({src : 'resources/Supplier-join-now-button2.gif'		})		}	);
		
		$('img.SupplierJoinNow, a#SignUpNowLink')	.bind( 'click',  function(){ 
			$('body')			.animate({scrollTop:0}, 'slow');
			$('input#FirstName').focus()	
		});

		$('h2#moreDetailsActuator')	.hover(
			function(){ $(this).addClass('hover') },
			function(){ $(this).removeClass('hover') }
		);
		$('#moreDetailsActuator')	.toggle(
			function() { $('div#moreDetails').slideDown('slow') },
			function() { $('div#moreDetails').slideUp('medium') }
		);
		
	}



/*	====================================================================================================================================
	The error page seems to need to call SurveyInit().
	==================================================================================================================================== */

	function setupErrorPage() {
		SurveyInit();
	}




/*	====================================================================================================================================
	Validation system. Pages 1 and 2
	==================================================================================================================================== */
		
	
	function uppercaseTheZip(whichField) {
	// 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.
		whichField.value = whichField.value.toUpperCase();	
	}


	function blurOneCanPostalCode6to7(whichField) {
	// changes a field with a valid 6 character code to a 7 character canadian postal code
	// expects a DOM reference to a text input.
		var currentZipValue 		= whichField.value.toUpperCase();
		var zipCodeFieldValidity 	= gSingleCanPostalCode.test(currentZipValue);
		if (zipCodeFieldValidity && whichField.value.length == 6) {
			whichField.value = whichField.value.substr(0,3) + ' ' + whichField.value.substr(3,5);	
		};			
	}



/*	====================================================================================================================================
	page 1 Inline style validation
	- show validation graphic on startup and manage it inline
	==================================================================================================================================== */

	// manage the radio button questions
	
	function manageTheRadioButtonQuestions (whichQuestion) { 
		var theQuestionsID  = $(whichQuestion).parent('div').attr('id');
		var whatToCheck 	= '#' + theQuestionsID + 'Feedback';		// the img check mark or >
		var whatToHide 	    = '#' + theQuestionsID + 'ValidationNote';	// the text note, currently: required
		$(whatToCheck).attr("src","resources/validation-check.gif").attr("title","This question is complete");
		$(whatToHide).fadeOut(600);
	}
	

	// manage the numeric fields
	
	function validateBuildingDimensions() {
	// validate the 3 building dimensions fields as one component
	
		var theBuildingDimensionsQuestionsID  	= $('#buildingDimensionsWidth').parent('div').attr('id');
		var theImageValidationFeedback 			= '#' + theBuildingDimensionsQuestionsID + 'Feedback';
		var theValidationNoteToManage 			= '#' + theBuildingDimensionsQuestionsID + 'ValidationNote';

		var theHintToManage				= '#BuildingDimensionsValidationHint';
		var buildingDimensionsAreValid	= false;

		var buildingDimensionsWidthValidity		= gNumbersOnly.test($('#buildingDimensionsWidth') .val()) && gNonBlank.test($('#buildingDimensionsWidth')  .val());
		var buildingDimensionsLengthValidity	= gNumbersOnly.test($('#buildingDimensionsLength').val()) && gNonBlank.test($('#buildingDimensionsLength') .val());
		var buildingDimensionsHeightValidity	= gNumbersOnly.test($('#buildingDimensionsHeight').val()) && gNonBlank.test($('#buildingDimensionsHeight') .val());
		
		(buildingDimensionsWidthValidity && buildingDimensionsLengthValidity && buildingDimensionsHeightValidity ) ?  (buildingDimensionsAreValid = true) : (buildingDimensionsAreValid = false);
		
		(buildingDimensionsWidthValidity  ) ? ($('#buildingDimensionsWidth') .css({ backgroundColor: gNormalColor })) : ($('#buildingDimensionsWidth') .css({ backgroundColor: gAlertColor })) ;
		(buildingDimensionsLengthValidity ) ? ($('#buildingDimensionsLength').css({ backgroundColor: gNormalColor })) : ($('#buildingDimensionsLength').css({ backgroundColor: gAlertColor })) ;
		(buildingDimensionsHeightValidity ) ? ($('#buildingDimensionsHeight').css({ backgroundColor: gNormalColor })) : ($('#buildingDimensionsHeight').css({ backgroundColor: gAlertColor })) ;
		(buildingDimensionsAreValid		  )	? ($(theHintToManage).removeClass('BuildingDimensionsAreNotValid')) 	  : ($(theHintToManage).addClass('BuildingDimensionsAreNotValid'));

		if (buildingDimensionsAreValid) {
			$(theImageValidationFeedback).attr("src","resources/validation-check.gif").attr("title","This question is complete");
			$(theValidationNoteToManage).fadeOut(300);
		} else {
			$(theImageValidationFeedback).attr("src","resources/validation-arrow.gif").attr("title","Please answer this question. It is required");
			$(theValidationNoteToManage).fadeIn(600);
		}
	}


	// manage the zip code

	function validateZipInline(whichField) {
		var theQuestionsID  			= $(whichField).parent('div').attr('id');
		var theImageValidationFeedback 	= '#' + theQuestionsID + 'Feedback';
		var theValidationNoteToManage 	= '#' + theQuestionsID + 'ValidationNote';
		var currentZipValue 			= whichField.value.toUpperCase();	// Canadian postal codes require uppercase. So does our validating regex.

		if ( gSingleUSZip.test(currentZipValue) || gSingleCanPostalCode.test(currentZipValue) ) { 
			$(theImageValidationFeedback).attr("src","resources/validation-check.gif").attr("title","This question is complete");
			$(theValidationNoteToManage).fadeOut(300);
		} else {
			// no valid zip
			$(theImageValidationFeedback).attr("src","resources/validation-arrow.gif").attr("title","Please answer this question. It is required");
			$(theValidationNoteToManage).fadeIn(600);
		}
	}


	function validateTheFormInlineStyle() {

		// validate radio button questions
		var radioButtonQuestionsAreComplete = true;
		
		var radioButtonQuestions				= $("div[id^='Answer']:has(:radio)");
		$(radioButtonQuestions)					.each(function(){ 
			var theCurrentAnswerDiv 			= this.id;
			var selectorWeNeed					= '#' + theCurrentAnswerDiv + ':has(:radio:checked)';
			if ($(selectorWeNeed)				.length == 0) {
				var arrowToShow					= '#' + theCurrentAnswerDiv + 'Feedback';
				var noteToShow 					= '#' + theCurrentAnswerDiv + 'ValidationNote';
				$(arrowToShow)					.fadeIn(600);
				$(noteToShow)					.fadeIn(600);
				radioButtonQuestionsAreComplete = false;
			} else {
				// valid fields 
			}
		});

		// validate the building dimensions
		if ($('#buildingDimensionsWidth').length != 0) {
			var theBuildingDimensionsQuestionsID  	= $('#buildingDimensionsWidth').parent('div').attr('id');
			var theImageValidationFeedback 			= '#' + theBuildingDimensionsQuestionsID + 'Feedback';
			var theValidationNoteToManage 			= '#' + theBuildingDimensionsQuestionsID + 'ValidationNote';
			
			var buildingDimensionsAreValid			= false;
			var buildingDimensionsWidthValidity		= gNumbersOnly.test($('#buildingDimensionsWidth') .val()) && gNonBlank.test($('#buildingDimensionsWidth')  .val());
			var buildingDimensionsLengthValidity	= gNumbersOnly.test($('#buildingDimensionsLength').val()) && gNonBlank.test($('#buildingDimensionsLength') .val());
			var buildingDimensionsHeightValidity	= gNumbersOnly.test($('#buildingDimensionsHeight').val()) && gNonBlank.test($('#buildingDimensionsHeight') .val());
			(buildingDimensionsWidthValidity && buildingDimensionsLengthValidity && buildingDimensionsHeightValidity ) ?  (buildingDimensionsAreValid = true) : (buildingDimensionsAreValid = false);
		
			if (buildingDimensionsAreValid) {
				$(theImageValidationFeedback).attr("src","resources/validation-check.gif").attr("title","This question is complete");
				$(theValidationNoteToManage).fadeOut(300);
			} else {
				$(theImageValidationFeedback).attr("src","resources/validation-arrow.gif").attr("title","Please answer this question. It is required");
				$(theValidationNoteToManage).fadeIn(600);
			}
		} else {
			var buildingDimensionsAreValid			= true;		// I.e. no building dimensions on the current page.
		}


		// validate the zip/postal code
		var ZipCodeQuestionsIsValid		= false;
		var currentZipValue				= $('#txtZipCode').val();
		currentZipValue					= currentZipValue.toUpperCase();
		var theQuestionsID  			= $('#txtZipCode').parent('div').attr('id');
		var theImageValidationFeedback 	= '#' + theQuestionsID + 'Feedback';
		var theValidationNoteToManage 	= '#' + theQuestionsID + 'ValidationNote';

		if ( gSingleUSZip.test(currentZipValue) || gSingleCanPostalCode.test(currentZipValue) ) { 
			$(theImageValidationFeedback).attr("src","resources/validation-check.gif").attr("title","This question is complete");
			$(theValidationNoteToManage).fadeOut(300);
			ZipCodeQuestionsIsValid = true;
		} else {
			// no valid zip
			$(theImageValidationFeedback).attr("src","resources/validation-arrow.gif").attr("title","Please answer this question. It is required");
			$(theValidationNoteToManage).fadeIn(600);
		}


		// return true or alert the user and return false
		if (radioButtonQuestionsAreComplete && buildingDimensionsAreValid && ZipCodeQuestionsIsValid) {
			return true;
		} else {
			var noteToShow = "We need more information in order to send you your free quotes.\r\r"
			if (!radioButtonQuestionsAreComplete) {
				noteToShow += "* Please complete all of the required questions.\r"
			}
			if (!buildingDimensionsAreValid) {
				noteToShow += "* Be sure to specify the width, length and height you need.\r"
			}
			if (!ZipCodeQuestionsIsValid) {
				noteToShow += "* Be sure to fill in your 5 digit US Zip code or 6 character Canadian Postal code."
			}
			alert(noteToShow);
			return false;
		}
	}


	// ====================================================================================================================================
	// setup page 1 for inline style validation
	// ====================================================================================================================================

	function setupSurveyPage1() {
		SurveyInit();
		showTheTheme();
		setupPage1InlineStyleValidation();
		Tooltip.init();
	}


	function setupPage1InlineStyleValidation() {

		$('div.formatradiobuttons :radio')	.bind('click',  function() 		{ manageTheRadioButtonQuestions(this)	});
		$('#buildingDimensionsWidth')		.bind('keyup',	function()		{ validateBuildingDimensions(this)		});

if ($('#buildingDimensionsWidth').length != 0) {
		$('#buildingDimensionsLength')		.bind('keyup',	function()		{ validateBuildingDimensions(this)		});
		$('#buildingDimensionsHeight')		.bind('keyup',	function()		{ validateBuildingDimensions(this)		});
}
		$('#txtZipCode')         			.bind('keyup',  function(event) { validateZipInline(this);			 	});
		$('#txtZipCode')       			  	.bind('blur',   function(event) { uppercaseTheZip(this);				});
		$('#txtZipCode')       			  	.bind('blur',   function(event) { blurOneCanPostalCode6to7(this);		});

		if ($('#txtMovingPostalCode').length != 0) {
			$('#txtMovingPostalCode')       .bind('keyup',  function(event) { validateZipInline(this);			 	});
			$('#txtMovingPostalCode')       .bind('blur',   function(event) { uppercaseTheZip(this);				});
			$('#txtMovingPostalCode')       .bind('blur',   function(event) { blurOneCanPostalCode6to7(this);		});
		}
		

		$('#goToStep2Btn').hover(
			function(){$(this).attr({src : 'resources/btn_gotostep2_rollover.jpg'	})},
			function(){$(this).attr({src : 'resources/btn_gotostep2.jpg'			})}		);
		
		// if the page happens to load with already selected checkboxes
			$(':radio:checked').each(function() {
					var whatToCheck = $(this).parent('div').attr('id');
					whatToCheck 	= '#' + whatToCheck + 'Feedback';
					$(whatToCheck)	.attr("src","resources/validation-check.gif");
				}
			);
			var startupZipCode = $('#txtZipCode').val();
			if ( gSingleUSZip.test(startupZipCode) || gSingleCanPostalCode.test(startupZipCode.toUpperCase()) ) {
				var whatToCheck = $('#txtZipCode').parent('div').attr('id');
				whatToCheck 	= '#' + whatToCheck + 'Feedback';
				$(whatToCheck).attr("src","resources/validation-check.gif");
			}
	}




/*	====================================================================================================================================
	Validate Survey page 2.
	- no validation note nor graphic on startup, only after the first submit.
	==================================================================================================================================== */

	// page 2 validation globals. The validity of each field is know and used globally.
		var gFirstName       = false ;
		var gLastName        = false ;
		var gEmailAddress    = false ;
		var gPhoneNumber     = false ;
		var CompanyNameIsRequired	= $('CompanyName').id ;
		if (!CompanyNameIsRequired) { 
			// If there is no Company name input the global is set to true so it always tests as valid 
			// and the validation code can handle pages with and without company name fields.
			var gCompanyName	= true  ; 
		} else {
			var gCompanyName	= false ;
		}
		var gAddress1        = false ;
		var gCity            = false ;
		var gState           = false ;
		var gZIP             = false ;

	
	// page 2 validation utility functions

	function validateNotEmpty(whichField) {
	// validate any field that just needs to be not empty. Empty in the sense that it must contain at least one word character.
	// expects a reference to a text input element.

		var theInputToManage = '#' + whichField.id;
		var theHintToManage  = '#' + whichField.id + 'ValidationHint';
		var currentValidity  = false;
		if ( gNonBlank.test(whichField.value) ) {
			currentValidity = true;
		} else {
			currentValidity = false;
		}

		// the following will only HIDE validation hints, not show them. Showing is only done by the submit handler.
		switch ( whichField.id ) {
			case 'FirstName':
				gFirstName     = currentValidity; 
				if (gFirstName) { 
					$(theHintToManage).fadeOut(600);
					$(theInputToManage).css({ backgroundColor: gNormalColor }); 
				};
				break;
			case 'LastName':
				gLastName      = currentValidity; 
				if (gLastName) { 
					$(theHintToManage).fadeOut(600);
					$(theInputToManage).css({ backgroundColor: gNormalColor }); 
				};
				break;
			case 'CompanyName':
				gCompanyName   = currentValidity; 
				if (gCompanyName) { 
					$(theHintToManage).fadeOut(600);
					$(theInputToManage).css({ backgroundColor: gNormalColor }); 
				};
				break;
			case 'Address1':
				gAddress1      = currentValidity; 
				if (gAddress1) { 
					$(theHintToManage).fadeOut(600);
					$(theInputToManage).css({ backgroundColor: gNormalColor }); 
				};
				break;
			case 'City':
				gCity          = currentValidity; 
				if (gCity) { 
					$(theHintToManage).fadeOut(600);
					$(theInputToManage).css({ backgroundColor: gNormalColor }); 
				};
				break;
			default:
				alert('problem with the case statement...');
		}
		checkAllFields();
	}


	// validate the email
	function validateEmail(whichField) {
		var theInputToManage = '#' + whichField.id;
		var theHintToManage  = '#' + whichField.id + 'ValidationHint';
		(gEmailExpression.test(whichField.value) == true) ? (gEmailAddress = true) : (gEmailAddress = false) ;
		if (gEmailAddress) { 
			$(theHintToManage).fadeOut(600);
			$(theInputToManage).css({ backgroundColor: gNormalColor }); 
		};
		checkAllFields();
	}


	function validatePhoneNumber() {
	// validate the 3 phone number fields as one component
	
		var theHintToManage     = '#PhoneNumberValidationHint';

		var AreaCodeValidity	= gThreeDigits.test($('#areacode')   .val());
		var PrefixValidity		= gThreeDigits.test($('#PhonePrefix').val());
		var PhoneNumberValidity	= gFourDigits.test( $('#PhoneNumber').val());
		
		(AreaCodeValidity && PrefixValidity && PhoneNumberValidity ) ?  (gPhoneNumber = true) : (gPhoneNumber = false);
		
		if (AreaCodeValidity   ) { $('#areacode')   .css({ backgroundColor: gNormalColor }) };
		if (PrefixValidity     ) { $('#PhonePrefix').css({ backgroundColor: gNormalColor }) };
		if (PhoneNumberValidity) { $('#PhoneNumber').css({ backgroundColor: gNormalColor }) };
		if (gPhoneNumber) { $(theHintToManage).fadeOut(600) };
		checkAllFields();
	}

	function autoAdvancePhoneNumberFields(whichField) {
		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) { $('#ext')			.focus(); $('#PhoneNumber').blur(); }
	}

	// validate the zip code
	function validateZip(whichField) {
		var theInputToManage = '#' + whichField.id;
		var theHintToManage  = '#' + whichField.id + 'ValidationHint';

		var currentZipValue  = whichField.value.toUpperCase();	// Canadian postal codes require uppercase. So does our validating regex.

		(gSingleUSZip.test(currentZipValue) || gSingleCanPostalCode.test(currentZipValue)) ? (gZIP = true) : (gZIP = false) ;
		if (gZIP) { 
			$(theHintToManage).fadeOut(600) 
			$(theInputToManage).css({ backgroundColor: gNormalColor }); 
		};
		checkAllFields();
	}


	// validate the state select
	function validateState(whichField) {
		var theSelectToManage = '#' + whichField.id;
		var theHintToManage   = '#' + whichField.id + 'ValidationHint';
		(whichField.value == -1) ? (gState = false) : (gState = true) ;
		if (gState) { 
			$(theHintToManage).fadeOut(600) 
			$(theSelectToManage).css({ backgroundColor: gNormalColor }); 
		};
		checkAllFields();
	}


	// test overall validity and manage the (1) validation mark
	function checkAllFields() {
		//alert(gFirstName + '  ' + gLastName + '  ' + gEmailAddress + '  ' + gPhoneNumber + '  ' + gCompanyName + '  ' + gAddress1 + '  ' + gCity + '  ' + gState + '  ' + gZIP );
		if ( gFirstName && gLastName && gEmailAddress && gPhoneNumber && gCompanyName && gAddress1 && gCity && gState && gZIP ) {
			$('#ValidationMark')	.attr("src","resources/validation-check.gif")	
									.attr("title","Your contact information is complete and you ready to get quotes.")
									.fadeIn('slow');	
		} else {
			$('#ValidationMark')	.hide();	
		}
	}


	function validateAfterSubmitPage2() {
	// when the user clicks the submit button...
	
		// auto-fill does not fire any events so we could get here with the globals being inaccurate.
		// fire all the necessary events just to get the globals in synch with the current field data.

			$('#FirstName')   .keyup();
			$('#LastName')    .keyup();
			$('#EmailAddress').keyup();
			
			$('#areacode')    .blur();
			$('#PhonePrefix') .blur();
			$('#PhoneNumber') .blur();
			
			$('#CompanyName') .keyup();
			$('#Address1')    .keyup();
			$('#City')        .keyup();
			$('#StateId')     .change();
			$('#zip')         .keyup();
	
		if ( gFirstName && gLastName && gEmailAddress && gPhoneNumber && gCompanyName && gAddress1 && gCity && gState && gZIP ) {
			// if all the fields are currently marked as valid, submit the form without comment.
			return true;
		} else {
			// not all the fields are valid so show the dialog and all the attention getting effects.
			
			var theMessage = 'Please be sure to complete all required fields.\r\n\r\nThe following still need to be completed:\r\n'
			
			if (!gFirstName) { 
				$('#FirstNameValidationHint').show();
				$('#FirstName').css({ backgroundColor: gAlertColor });
				theMessage += ' First Name\r\n'; } 
			else { 
				$('#FirstNameValidationHint').hide();
				$('#FirstName').css({ backgroundColor: gNormalColor }); }
			
			if (!gLastName) { 
				$('#LastNameValidationHint').show();
				$('#LastName').css({ backgroundColor: gAlertColor });
				theMessage += ' Last Name\r\n'; } 
			else { 
				$('#LastNameValidationHint').hide();
				$('#LastName').css({ backgroundColor: gNormalColor }); }
			
			if (!gEmailAddress) { 
				$('#EmailAddressValidationHint').show();
				$('#EmailAddress').css({ backgroundColor: gAlertColor });
				theMessage += ' Email\r\n'; } 
			else { 
				$('#EmailAddressValidationHint').hide();
				$('#EmailAddress').css({ backgroundColor: gNormalColor }); }
			
			if (!gPhoneNumber) {
				$('#PhoneNumberValidationHint').show();
				if ( !gThreeDigits.test($('#areacode')   .val()) ) { $('#areacode')   .css({ backgroundColor: gAlertColor }) };
				if ( !gThreeDigits.test($('#PhonePrefix').val()) ) { $('#PhonePrefix').css({ backgroundColor: gAlertColor }) };
				if ( !gFourDigits.test( $('#PhoneNumber').val()) ) { $('#PhoneNumber').css({ backgroundColor: gAlertColor }) };
				theMessage += ' Phone Number\r\n';
			} else {
				$('#PhoneNumberValidationHint').hide() ;
			}
			
			if (!gCompanyName) { 
				$('#CompanyNameValidationHint').show();
				$('#CompanyName').css({ backgroundColor: gAlertColor });
				theMessage += ' Company Name\r\n'; } 
			else { 
				$('#CompanyNameValidationHint').hide();
				$('#CompanyName').css({ backgroundColor: gNormalColor }); }
			
			if (!gAddress1) { 
				$('#Address1ValidationHint').show();
				$('#Address1').css({ backgroundColor: gAlertColor });
				theMessage += ' Street Address\r\n'; } 
			else { 
				$('#Address1ValidationHint').hide();
				$('#Address1').css({ backgroundColor: gNormalColor }); }
			
			if (!gCity) { 
				$('#CityValidationHint').show();
				$('#City').css({ backgroundColor: gAlertColor });
				theMessage += ' City\r\n'; } 
			else { 
				$('#CityValidationHint').hide();
				$('#City').css({ backgroundColor: gNormalColor }); }
			
			if (!gState) { 
				$('#StateIdValidationHint').show();
				$('#StateId').css({ backgroundColor: gAlertColor });
				theMessage += ' State\r\n'; } 
			else { 
				$('#StateIdValidationHint').hide();
				$('#StateId').css({ backgroundColor: gNormalColor }); }
			
			if (!gZIP) { 
				$('#zipValidationHint').show();
				$('#zip').css({ backgroundColor: gAlertColor });
				theMessage += ' ZIP or Postal code\r\n'; } 
			else { 
				$('#zipValidationHint').hide();
				$('#zip').css({ backgroundColor: gNormalColor }); }

			alert(theMessage);
			return false;
		}
	}


	// if we actually got a valid submission - this is only used in the generic site!
	function showSuccess() {
			document.location.href='validation-page3.html'
	}


	// =====================================================================================
	// setup page 2
	// =====================================================================================
	
	function setupSurveyPage2() {
		SurveyInit();
		setupPage2SubmitStyleValidation();
	}
	
	function setupPage2SubmitStyleValidation() {
	
		$('table#SurveyPage2table td:nth-child(2)').css({ width:'256px' });
		$('table#SurveyPage2table td:nth-child(3)').css({ paddingTop:'2px', textAlign:'left' });
		$('table#SurveyPage2table td#zipValidationHintTD').css({ paddingTop:'8px', textAlign:'left', verticalAlign:'top' });
		$('#FirstName').focus();
		$('#getQuotesNowBtn').hover(
			function(){$(this).attr({src : 'resources/btn_GetQuotesNow_rollover.gif'			})},
			function(){$(this).attr({src : 'resources/btn_GetQuotesNow.gif'						})}		);

		$('#FirstName')   .bind('keyup',  function(event) { validateNotEmpty(this); 			});
		$('#LastName')    .bind('keyup',  function(event) { validateNotEmpty(this); 			});
		$('#EmailAddress').bind('keyup',  function(event) { validateEmail(this);    			});
		$('#EmailAddress').bind('blur',   function(event) { validateEmail(this);    			});		// easy to run into autofill here

		$('#areacode')    .bind('blur',   function(event) { validatePhoneNumber();  			});
		$('#areacode')    .bind('keyup',  function(event) { autoAdvancePhoneNumberFields(this);	});
		$('#PhonePrefix') .bind('blur',   function(event) { validatePhoneNumber();				});
		$('#PhonePrefix') .bind('keyup',  function(event) { autoAdvancePhoneNumberFields(this);	});
		$('#PhoneNumber') .bind('blur',   function(event) { validatePhoneNumber();				});
		$('#PhoneNumber') .bind('keyup',  function(event) { autoAdvancePhoneNumberFields(this);	});

		$('#CompanyName') .bind('keyup',  function(event) { validateNotEmpty(this);				});
		$('#Address1')    .bind('keyup',  function(event) { validateNotEmpty(this);				});
		$('#City')        .bind('keyup',  function(event) { validateNotEmpty(this);				});
		$('#StateId')     .bind('change', function(event) { validateState(this);				});
		$('#zip')         .bind('keyup',  function(event) { validateZip(this);					});
		$('#zip')         .bind('blur',   function(event) { uppercaseTheZip(this);				});
		$('#zip')         .bind('blur',   function(event) { blurOneCanPostalCode6to7(this);		});

		// the page might load with some existing data so set the validation status accordingly
		if ( gNonBlank.test( $('#FirstName')		.val() ))		{ gFirstName     = true ; };		// all of these are set to false when the page loads.
		if ( gNonBlank.test( $('#LastName')			.val() ))		{ gLastName      = true ; };
		if ( gNonBlank.test( $('#CompanyName')		.val() ))		{ gCompanyName   = true ; };
		if ( gNonBlank.test( $('#Address1')			.val() ))		{ gAddress1      = true ; };
		if ( gNonBlank.test( $('#City')				.val() ))		{ gCity          = true ; };
		if ( $('#StateId')							.val() != -1)	{ gState         = true ; };
		(gEmailExpression.test(  $('#EmailAddress')	.val() ) == true) ? (gEmailAddress = true) : (gEmailAddress = false) ;
		validatePhoneNumber();										// this will set gPhoneNumber appropriately
		var currentZipValue  = $('#zip').val().toUpperCase();		// Canadian postal codes require uppercase. So does our validating regex.
		(gSingleUSZip.test(currentZipValue) || gSingleCanPostalCode.test(currentZipValue)) ? (gZIP = true) : (gZIP = false) ;

	}




/*	====================================================================================================================================
	End of utilities
	==================================================================================================================================== */

