$(function () {
	//--Error messages used in form validation-------------------------------------------------------------------------------
		var validationErrorMessage = {};
			validationErrorMessage['email'] = 'Invalid email address';	
			validationErrorMessage['phone'] = 'XXX-XXX-XXXX';
			validationErrorMessage['phone2'] = 'XXX-XXX-XXXX';
			validationErrorMessage['postal_code'] = 'Invalid zip';
	
	
	
	//--IE select width fix--------------------------------------------------------------------------------------------------
		function ieSelectWidthFix() {
			if (jQuery.browser.msie) {
				$('select').each(function () {
					$(this).data("originalWidth", $(this).css('width'));
				});
				
				$('select').mouseenter(function () {
					$(this).css('width', "auto");
					$(this).data("resizedWidth", $(this).attr('offsetWidth'));
					
					if (parseInt($(this).data("resizedWidth")) < parseInt($(this).data("originalWidth").replace(/px/, ""))) {
						$(this).css('width', $(this).data("originalWidth"));		
					} else {
						$(this).addClass('expanded');	
					}
				});
				
				$('select').change(function () {
					$(this).css('width', $(this).data("originalWidth"));
					$(this).removeClass('expanded');
				});
				
				$(':input').focus(function () {
					if ($(this).attr('class') != 'expanded') {
						$('.expanded').each(function () {
							$(this).css('width', $(this).data("originalWidth"));
							$(this).removeClass('expanded');
						});
					}
				});
			}
		}
	
	
	
	//--Validation checks--------------------------------------------------------------------------------------------------------  
		
		function isRequired(formField) {
			switch ($(formField).attr('type')) {
				case 'text':
				case 'textarea':
				case 'select-one':
					if ($(formField).val()) {
						return true;
					}
				return false;
			}
		}
		
		function isPattern(formField, pattern) {
			var regExp = new RegExp("^" + pattern + "$");
			
			var correct = regExp.test($(formField).val());
	
			return correct;
		}
		
		function isValidEmail(formField) { return isPattern(formField, "[a-zA-Z0-9._+%-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"); }
		
		function isValidPhone(formField) { return isPattern(formField, "^[0-9]{3}-[0-9]{3}-[0-9]{4}$"); }
		
		function isValidZip(formField) { return isPattern(formField, "^[0-9]{5}(-[0-9]{4})?$"); }
		
		function isValidPostalCode(formField) { return isPattern(formField, "^[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}[0-9]{1}[A-Za-z]{1} *[0-9]{1}[A-Za-z]{1}[0-9]{1}$"); }
	
	//-----------------------------------------------------------------------------------------------------END Validation checks



	//--Form validation---------------------------------------------------------------------------------------------------------
		
		function removeError() {
			if (!$(this).data('errorMessage')) return;
			
			$(this).removeClass('errorMessage');	
			$(this).next().remove();
			$(this).removeData('errorMessage');
		}
		
		function validate (step) {
			var validForm = true;
			
			if (step == "stepOne") {
				var formFields = $('#stepOne :input');
			} else {
				var formFields = $(':input');	
			}
			
			for (var i = 0; i < formFields.length; i++) {
				var validation = $(formFields[i]).attr('validation');
				var fieldID = $(formFields[i]).attr('id');
				var OK, requiredFirst = true;
				
				if (!validation) {
					switch (fieldID) {
						case "phone":
						case "phone2":
						case "email":
							if ($(formFields[i]).val() == "") {
								continue;
							}
						break;
						
						default:
							continue;
						break;
					}
				}
				
				switch (fieldID) {
					case "postal_code":
						OK = isRequired(formFields[i]);
						
						if (OK) { 
							OK = isValidZip(formFields[i]);
							requiredFirst = false;						
						}
						break;
						
					case "email":
						OK = isRequired(formFields[i]);
						if (OK) { 
							OK = isValidEmail(formFields[i]);
							requiredFirst = false;
						}
						break;
						
					case "phone":
					case "phone2":
						OK = isRequired(formFields[i]);
						if (OK) { 
							OK = isValidPhone(formFields[i]);
							requiredFirst = false;
						}
						break;
						
					default:
						OK = isRequired(formFields[i]);
						break;
				};
				
				if (!OK) {
					var errorMessage = "Required"; 
					
					if (!requiredFirst) {
						errorMessage =  validationErrorMessage[fieldID] || "";
					}
					
					writeError(formFields[i], errorMessage);
					
					validForm = false;
				}
				
			}
			
			return validForm;
		}
		
		function writeError(formField, message) {
			var fieldID = $(formField).attr('id');
			var fieldWidth = $(formField).attr('offsetWidth');
			var fieldHeight = $(formField).attr('offsetHeight');
			
			if ( typeof(_gaq) != 'undefined' ) { _gaq.push(['_trackEvent', 'Forms', 'error-'+fieldID]); }
			
			$(formField).attr('class', 'errorMessage');
							
			$(formField).focus(removeError);
			
			if ($(formField).data('errorMessage')) return;
					
			$(formField).parent().append('<label style="width:'+fieldWidth+'px; height: '+fieldHeight+'px;" class="errorMessage" for="'+fieldID+'" htmlFor="'+fieldID+'">'+message+'</label>');
			
			$(formField).data('errorMessage', message);
		}
	
	//-------------------------------------------------------------------------------------------------------END Form validation
	
	
	
	//--Page initialization----------------------------------------------------------------------------------------------------
		
		$(".conditional_field").hide();
		$("#prereq_message").hide();
		$("#relocate_message").hide();
		
		$("#campus_code").change(function() {
			$(".conditional_field").hide();
			$("#relocate_message, #prereq_message").hide();
		});
		
		$("#program_code").change(function(){
			if($("#program_code").val() != "DH") {
				$("#relocation").removeAttr("validation");
				$("#prerequisites").removeAttr("validation");
			}
			
			if($("#program_code").val() == "DH") {
				$('.conditional_field').show();
			} else if ($("#program_code").val() != "DH") {
				$(".conditional_field").hide();
				$("#relocate_message, #prereq_message").hide();
			}
			
			if($("#campus_code").val() == "SAN0009") {
				var campusName = "Rancho Cucamonga";
				$("#campus_name").text(campusName + ' ');
			} else if ($("#campus_code").val() == "SAN0010") {
				var campusName = "Visalia";
				$("#campus_name").text(campusName + ' ');
			}
		});
		
		$("#relocation").change(function() {
			$("#relocate_message, #prereq_message").hide();
			
			var prerequisites = $("#prerequisites").val();
			var relocation = $("#relocation").val();
		
			if(prerequisites == "Yes" && relocation == "No") {
				$("#relocate_message").show();
				$("#btn_Next").hide();
			}
			
			if(prerequisites == "No" && relocation == "Yes") {
				$("#prereq_message").show();
				$("#btn_Next").show();
			}
			
			if(prerequisites == "No" && relocation == "No") {
				$("#relocate_message").show();
				$("#btn_Next").hide();
			}
			
			if(prerequisites == "Yes" && relocation == "Yes") {
				$("#relocate_message, #prereq_message").hide();
				$("#btn_Next").show();
			}
		});
		
		$("#prerequisites").change(function() {
			
			var prerequisites = $("#prerequisites").val();
			var relocation = $("#relocation").val();
			
			if(prerequisites == "Yes" && relocation == "Yes") {
				$("#relocate_message, #prereq_message").hide();
				$("#btn_Next").show();
			}
		});
		
		
		$('.moreInfo').hide();
		
		$('h2').each(function () {
			var currentHeader = $(this).children('img').attr('alt').toLowerCase();
			var initialIndex = currentHeader.indexOf(" ");	
				while (initialIndex != -1) {
					currentHeader = currentHeader.replace(/ /, '');	
					
					initialIndex = currentHeader.indexOf(" ");
				}
			
			if (currentHeader == "heating,ventilation,airconditioningandrefrigeration") {
				currentHeader = "hvacr";
			}
			
			$(this).attr('id', currentHeader);
		});
		
		$('li').each(function () {
			$(this).wrapInner('<a></a>');
						
			var pageSelection;
			var programSelection = $(this).text();
			var initialIndex = programSelection.indexOf(" ");	
				while (initialIndex != -1) {
					programSelection = programSelection.replace(/ /, '');	
					
					initialIndex = programSelection.indexOf(" ");
				}
			
			if ( programSelection == "Heating,Ventilation,AirConditioningandRefrigeration" ) 
			{ programSelection = "HVACR"; } 
			
			if ( programSelection == "SJVCOnline" )
			{ $(this).children('a').attr('href', "online.php"); }
			else
			{
				switch ($(this).attr('class')) {
					case "business":
						pageSelection = "business";
					break;
					
					case "medical":
						pageSelection = "medical";
					break;
					
					case "technical":
						pageSelection = "technical";
					break;
					
					default:
						pageSelection = "campus"
					break;
				}
				
				$(this).children('a').attr('href', pageSelection+".php?selection="+programSelection);
			}
		});
		
		$('h2').click(function () {
			$('.moreInfo:visible').each(function () {
				$(this).slideUp('normal');
				
				$(this).prev('h2').css({
					backgroundPosition: "0 0"
				});
				
				$(this).prev().children('img').attr('src', $(this).prev().children('img').attr('src').replace(/-Selected\.gif/, ".gif"));
			});
			
			var checkElement = $(this).next();
			
			var newHeader = $(this).children('img').attr('alt');
			var initialIndex = newHeader.indexOf(" ");	
				while (initialIndex != -1) {
					newHeader = newHeader.replace(/ /, '');	
					
					initialIndex = newHeader.indexOf(" ");
				}
			
			if (newHeader == "Heating,Ventilation,AirConditioningandRefrigeration") {
				newHeader = "HVACR";
			}
									
			if (checkElement.is(':visible')) {
				checkElement.slideUp('normal');
				
				$(this).children('img').attr('src', $(this).children('img').attr('src').replace(/-Selected\.gif/, ".gif"));
				
				$(this).css({
					backgroundPosition: "0 0"
				});
				
				if (newHeader != "SJVCOnline") {
					$('#campusAddress').fadeOut();
					$('#headerImage').fadeOut(function () {
						$('#headerImage').attr('src', '_Presentation/Images/headerImages/headerImage_default.jpg');
						$('#headerImage').fadeIn();								
					});
				}
			} else {
				checkElement.slideDown('normal');
				
				$(this).children('img').attr('src', $(this).children('img').attr('src').replace(/\.gif/, "-Selected.gif"));
				
				$(this).css({
					backgroundPosition: "0 -63px"
				});
												
				if (newHeader != "SJVCOnline") {
					var newHeaderImage = 'headerImage_'+newHeader+'.jpg';
						
					$('#campusAddress').fadeOut();
					$('#headerImage').fadeOut(function () {
						$('#headerImage').attr('src', '_Presentation/Images/headerImages/'+newHeaderImage);
						
						switch (newHeader) {
							case "Bakersfield":
							case "Fresno":
							case "Hanford":
							case "Hesperia":
							case "Modesto":
							case "RanchoCordova":
							case "RanchoCucamonga":
							case "Temecula":
							case "Visalia":
								$('#campusAddress').attr('src', '_Presentation/Images/address_'+newHeader+'.gif');
							break;
						}
						
						$('#headerImage').fadeIn();
						$('#campusAddress').fadeIn();
					});	
				}
			}
		});
		
		if ($.url.param("selection")) {
			var selection = "#"+$.url.param("selection");
				selection = selection.toLowerCase()
			$(selection).trigger("click");
		}
		
		if ( typeof(url_selection) != "undefined") {
			var selection = "#"+url_selection;
				selection = selection.toLowerCase();
			$(selection).trigger("click");							  
		}
		
		$('#headerImage').fadeIn();
		
		$('#hygiene_show').hide();
		
		$('#hygiene_learn').click(function() {
			$('#hygiene_hide').hide();
			$('#hygiene_show').show();
		});
		
	//--------------------------------------------------------------------------------------------------END Page initialization
	
	
	
	//--Form setup----------------------------------------------------------------------------------------------------
	
		if ($('#thanks').html() == null) {			
			if ( $('#campus_code').val() == "" ) {
				$('#program_code').removeAttr('validation').attr('disabled', 'disabled');
				$('#program_code option:first').text('-- Select a campus first --');
			}
			
			$('#campus_code').change(function () {
				if ( $(this).val() == "" ) {
					$('#program_code').removeAttr('validation').attr('disabled', 'disabled'); 
					$('#program_code option:first').text('-- Select a campus first --');
				} else {
					$('#program_code option:first').text('Loading. . .');
					
					$('#program_code').removeClass('errorMessage');	
					$('#program_code').next('label').remove();
					$('#program_code').removeData('errorMessage');
			
					$('#program_code').attr('validation', 'required'); 
					
					$.getJSON('/global/cdm-server.php?path=http://ulm.datamark.com/cdm/campuses/' + $(this).val() + '/programs?order_asc=ProgramName', function (json) {
						$('#program_code').empty();
						$('#program_code').append('<option value="">-- Select a program --</option>');
			
						for (var i=0; i<json.body.length; i++) { $('#program_code').append('<option value="'+json.body[i].ProgramCode+'">'+json.body[i].DefaultName+'</option>'); }
			
						$('#program_code').removeAttr('disabled');
					});							   
				}
			});
			
			$('#formArea').append('<img id="stepIndicator" src="_Presentation/Images/step1of2.gif" alt="Step 1 of 2" title="" />');
			$('#stepTwo').hide();
			$('#btn_Submit').replaceWith('<img id="btn_Next" src="_Presentation/Images/btn_Next.gif" alt="Go to Step 2" title="" />');
			
			$('#btn_Next').click(function () {
				var validStepOne = validate('stepOne');
								
				if ( typeof(_gaq) != 'undefined' ) { _gaq.push(['_trackEvent', 'Forms', 'next']); }
				
				if (validStepOne) {
					if ( typeof(_gaq) != 'undefined' ) { _gaq.push(['_trackPageview','/form/continue']); }
					
					$('#prereq_message').hide();
					$('#stepTwo').show();
	
					$('#btn_Next').replaceWith('<img id="btn_Submit" src="_Presentation/Images/btn_Submit.gif" alt="Submit" title="" />');
					
					$('#btn_Submit').click(function () {
						var validForm = validate();
						
						if (validForm) {
							$('#requestForm').submit();
						}								 
					});
					
					$('#stepIndicator').attr({
						src: "_Presentation/Images/step2of2.gif",
						alt: "Step 2 of 2"
					});
				}
			});
			
			$(':input').change(function () {
				$('#setVar').load('_Includes/setVar.php', {'setVar': $(this).attr('id'), 'varValue': $(this).val()})							 
			});
			
			$('#stepTwo :input').each(function () {
				if ($(this).val() != "") {
					$('#stepTwo').show();
					
					$('#btn_Next').replaceWith('<img id="btn_Submit" src="_Presentation/Images/btn_Submit.gif" alt="Submit" title="" />');
					
					$('#btn_Submit').click(function () {
						var validForm = validate();
						
						if ( typeof(_gaq) != 'undefined' ) { _gaq.push(['_trackEvent', 'Forms', 'submit']); }
						
						if (validForm) {
							if ( typeof(_gaq) != 'undefined' ) { _gaq.push(['_trackPageview','/form/filled']); }
							
							$('#requestForm').submit();
						}								 
					});
					
					$('#stepIndicator').attr({
						src: "_Presentation/Images/step2of2.gif",
						alt: "Step 2 of 2"
					});
				}
			});
		}
		
		ieSelectWidthFix();
		
	//--------------------------------------------------------------------------------------------------END Form setup
});
