

/*	=================================================================================
	page 1 Submit style validation 
	- no validation note nor graphic on startup, only after the first submit 
	================================================================================= */

	function manageRadios(whoCalled) {
		var theQuestionsID  = $(whoCalled).parent('div').attr('id');
		var whatToCheck 	= '#' + theQuestionsID + 'Feedback';
		var whatToHide 	    = '#' + theQuestionsID + 'ValidationNote';
		$(whatToCheck)		.fadeOut(600);
		$(whatToHide)		.fadeOut(600);
	}
	
	
	function manageZip(whoCalled) {
		var currentZipCode = $(whoCalled).val();
		if ( currentZipCode.length > 4 ) {
			var theQuestionsID	= $(whoCalled).parent('div').attr('id');
			var whatToCheck 	= '#' + theQuestionsID + 'Feedback';
			var whatToHide 	    = '#' + theQuestionsID + 'ValidationNote';
			$(whatToCheck)		.fadeOut(300);
			$(whatToHide)		.fadeOut(300);
			return false;		// we are checking to see if the zip is NOT valid so return false. It IS valid
		} else {
			var theQuestionsID	= $(whoCalled).parent('div').attr('id');
			var whatToCheck 	= '#' + theQuestionsID + 'Feedback';
			var whatToShow 	    = '#' + theQuestionsID + 'ValidationNote';
			$(whatToCheck)		.attr("src","resources/validation-dot-arrow.gif")
								.attr("title","Please answer this question. It is required")
								.fadeIn(600);
			$(whatToShow)		.fadeIn(600);
			return true;		// we are checking to see if the zip is NOT valid so return true. It IS NOT valid
		}
	}
	
	
	function validateTheFormSubmitStyle() {
	
		// test radio button questions
		var radioButtonsAreIncomplete		= false;
		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);
				radioButtonsAreIncomplete 	= true;
			} else {
				// do not show the check mark on valid fields - show feedback only on incomplete fields 
			}
		});
		
		// test zip
		var currentZipCode	= $('#txtZipCode');
		var zipIsNotValid	= manageZip(currentZipCode) ;
	
		// take necessary actions
		if (zipIsNotValid || radioButtonsAreIncomplete) {
			// something doesn't validate so turn on the inline validation
			$('div.formatradiobuttons :radio')	.bind('click', function(event) { manageRadios(this)	});
			$('#txtZipCode')					.bind('keyup', function(event) { manageZip(this) 	});
			if ( zipIsNotValid  &&  radioButtonsAreIncomplete ) { alert('Please be sure that you have answered all the required questions including ZIP code.') }
			if ( zipIsNotValid  && !radioButtonsAreIncomplete ) { alert('Please enter your ZIP code.');$('#txtZipCode').focus(); }
			if (!zipIsNotValid  &&  radioButtonsAreIncomplete ) { alert('Please be sure that you have answered all the required questions.') }
			return false;
		} else {
			// all questions and fields validate
			return true;
		}
	}
	
	function setupPage1SubmitStyleValidation() {
		// nothing needs to be done on startup. It all is setup after the first submit
		// this function is provided only to make the coding parallel between the two styles
	}





/*	=================================================================================
	page 1 Inline style validation
	- show validation graphic on startup and manage it inline
	================================================================================= */

	function validateTheFormInlineStyle() {
		var validationSuccess = true;
		$('img.ValidationFeedback').each( function(){ 
			var currentImgSource = $(this).attr('src');
			if (currentImgSource.indexOf('arrow') != -1 ) {
				var whichQuestion = $(this).parents('div').attr('id');
				var whichNote     = 'div#' + whichQuestion + ' span.ValidationNote';
				$(whichNote).show();
				validationSuccess = false;
			}
		});
		if (!validationSuccess) {
			alert('Please be sure that you have answered all the required questions including ZIP code.');
			return false;
		} else {
			return true;
		}
	}


	function setupPage1InlineStyleValidation() {
		$('div.formatradiobuttons :radio').bind('click', function(event) { 
			var theQuestionsID  = $(this).parent('div').attr('id');
			var whatToCheck 	= '#' + theQuestionsID + 'Feedback';
			var whatToHide 	    = '#' + theQuestionsID + 'ValidationNote';
			$(whatToCheck).attr("src","resources/validation-check.gif").attr("title","This question is complete");
			$(whatToHide).fadeOut(600);
		});
	
		$('#txtZipCode').bind('keyup', function(event) { 
			var currentZipCode = $('#txtZipCode').val();
			if ( currentZipCode.length > 4 ) {
				var theQuestionsID = $(this).parent('div').attr('id');
				var whatToCheck 	= '#' + theQuestionsID + 'Feedback';
				var whatToHide 	    = '#' + theQuestionsID + 'ValidationNote';
				$(whatToCheck).attr("src","resources/validation-check.gif").attr("title","This question is complete");
				$(whatToHide).fadeOut(300);
			} else {
				var theQuestionsID = $(this).parent('div').attr('id');
				var whatToCheck 	= '#' + theQuestionsID + 'Feedback';
				var whatToHide 	    = '#' + theQuestionsID + 'ValidationNote';
				$(whatToCheck).attr("src","resources/validation-dot-arrow.gif").attr("title","Please answer this question. It is required");
				$(whatToHide).fadeIn(600);
			}
		});
	
		// if the page happens to load with already selected checkboxes, hide the dot
			$(':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 ( startupZipCode.length > 4 ) {
				var whatToCheck = $('#txtZipCode').parent('div').attr('id');
				whatToCheck 	= '#' + whatToCheck + 'Feedback';
				$(whatToCheck).attr("src","resources/validation-check.gif");
			}
	}





/*	=================================================================================
	page 2 only uses Submit style validation
	================================================================================= */

	// page 2 validation globals, the page validity is known globally.
		var gFirstName				= false ;
		var gLastName				= false ;
		var CompanyNameIsRequired	= $('CompanyName').id ;
		if (!CompanyNameIsRequired) { 
				var gCompanyName	= true  ; 
				// set to true when companyname is not required so it always tests as valid 
				// and the code can handle pages with and without company names.
		} else {
				var gCompanyName	= false ;
		}
		var gAddress1				= false ;
		var gCity					= false ;
		var gEmailAddress			= false ;
		var gPhoneNumber			= false ;
		var gState					= false ;
		var gZIP					= false ;
		var gNormalColor			= '#fff';
		var gAlertColor				= '#f7ca73';
		var gEmailExpression		= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var gZipExpression			= /(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/;
		var gNumbersOnly 			= /^[0-9]+$/;

	
	// page 2 validation functions
	
	// validate any field that just needs to be not empty
	function validateNotEmpty(whichField) {
		var theInputToManage = '#' + whichField.id;
		var theHintToManage  = '#' + whichField.id + 'ValidationHint';
		var currentValidity  = false;
		(whichField.value == "") ? (currentValidity = false) : (currentValidity = true) ; 
		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 that validates page 2 of the survey...');
		}
		checkAllFields();
	}

	// validate the email
	function validateEmail(whichField) {
		var theInputToManage = '#' + whichField.id;
		var theHintToManage  = '#' + whichField.id + 'ValidationHint';
		(gEmailExpression.test(whichField.value) == false) ? (gEmailAddress = false) : (gEmailAddress = true) ;
		if (gEmailAddress) { 
			$(theHintToManage).fadeOut(600);
			$(theInputToManage).css({ backgroundColor: gNormalColor }); 
		};
		checkAllFields();
	}

	// validate the 3 phone number fields as one component
	function validatePhoneNumber() {
		var theHintToManage     			= '#PhoneNumberValidationHint';

		var AreaCodeIsCorrectLength 		= $('#areacode').val().length == 3;
		var AreaCodeIsNumbersOnly			= gNumbersOnly.test( $('#areacode').val() );
		var PrefixIsCorrectLength 			= $('#prefix').val().length == 3;
		var PrefixIsNumbersOnly				= gNumbersOnly.test( $('#prefix').val() );
		var PhoneNumberIsIsCorrectLength	= $('#PhoneNumber').val().length == 4;
		var PhoneNumberIsNumbersOnly		= gNumbersOnly.test( $('#PhoneNumber').val() );

		if ( AreaCodeIsCorrectLength && AreaCodeIsNumbersOnly && PrefixIsCorrectLength  && PrefixIsNumbersOnly && PhoneNumberIsNumbersOnly && PhoneNumberIsIsCorrectLength) {
			gPhoneNumber = true;
		} else {
			gPhoneNumber = false;
		}

		if (AreaCodeIsCorrectLength 	 && AreaCodeIsNumbersOnly)		{ $('#areacode')   	.css({ backgroundColor: gNormalColor }) };
		if (PrefixIsCorrectLength 		 && PrefixIsNumbersOnly)		{ $('#prefix')		.css({ backgroundColor: gNormalColor }) };
		if (PhoneNumberIsIsCorrectLength && PhoneNumberIsNumbersOnly)	{ $('#PhoneNumber')	.css({ backgroundColor: gNormalColor }) };
		if (gPhoneNumber) { $(theHintToManage).fadeOut(600) };

		checkAllFields();
	}

	// validate the zip code
	function validateZip(whichField) {
		var theInputToManage = '#' + whichField.id;
		var theHintToManage  = '#' + whichField.id + 'ValidationHint';
		(gZipExpression.test(whichField.value) == false) ? (gZIP = false) : (gZIP = true) ;
		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() {
		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 are ready to get quotes.")
									.show();
		} else {
			$('#ValidationMark')	.attr("src","resources/validation-dot-arrow.gif")	
									.attr("title","Please provide us with your contact information.")
									.hide();
		}
	}


	// when the user clicks the submit button...

	function validateAfterSubmitPage2() {

		// the overall strategy here is to have the validity of every field stored in a global as the user manipulates the field.
		// this function just looks at that global data.
		// discovered a problem with auto-fill. It does not fire any events so flow of control could get here with the globals being inaccurate.
		// simulate all the necessary events to be sure the globals in synch with the actual 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 {
			// else show all the attention getting effects and show them a dialog.
			
			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();
				var AreaCodeIsCorrectLength 		= $('#areacode').val().length == 3;
				var AreaCodeIsNumbersOnly			= gNumbersOnly.test( $('#areacode').val() );
				var PrefixIsCorrectLength 			= $('#prefix').val().length == 3;
				var PrefixIsNumbersOnly				= gNumbersOnly.test( $('#prefix').val() );
				var PhoneNumberIsIsCorrectLength	= $('#PhoneNumber').val().length == 4;
				var PhoneNumberIsNumbersOnly		= gNumbersOnly.test( $('#PhoneNumber').val() );
				if (!(AreaCodeIsCorrectLength      && AreaCodeIsNumbersOnly))		{ $('#areacode')	.css({ backgroundColor: gAlertColor }) };
				if (!(PrefixIsCorrectLength        && PrefixIsNumbersOnly))			{ $('#prefix')		.css({ backgroundColor: gAlertColor }) };
				if (!(PhoneNumberIsIsCorrectLength && PhoneNumberIsNumbersOnly))	{ $('#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\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 for testing not on live sites!
	function showSuccess() {
			document.location.href='validation-page3.html'
	}


	// setup page 2 when the page loads

	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();

		$('#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);    });

		$('#areacode')			.bind('blur',   function(event) { validatePhoneNumber();  });
		$('#prefix')			.bind('blur',   function(event) { validatePhoneNumber();  });
		$('#PhoneNumber')		.bind('blur',   function(event) { validatePhoneNumber();  });

		$('#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) { validateZip(this);      });

		// the page might load with some existing data so set the validation status accordingly
		if ( $('#FirstName')    .val() != "")      { gFirstName     = true ; };
		if ( $('#LastName')     .val() != "")      { gLastName      = true ; };
		if ( $('#CompanyName')  .val() != "")      { gCompanyName   = true ; };
		if ( $('#Address1')     .val() != "")      { gAddress1      = true ; };
		if ( $('#City')         .val() != "")      { gCity          = true ; };
		if ( $('#StateId')      .val() != -1)      { gState         = true ; };
		if ( $('#zip')          .val().length > 4) { gZIP           = true ; };
		if ( ($('#areacode').val().length > 2)  &&  ( $('#prefix').val().length > 2)  &&  ($('#PhoneNumber').val().length > 3) ) { gPhoneNumber   = true ; };
		if   ( ($('#EmailAddress').val() == "") || (gEmailExpression.test( $('#EmailAddress').val() ) == false)) { 
			gEmailAddress  = false; 
		} else {
			gEmailAddress  = true; 
		}
	}
