$(function () {
	// IE6 Warning-------------------------------------------------------------------------------
		if ($('#rootIE6').html() != null) {						
			$('body').append('<div id="IEwarning"><p>You are using an outdated browser. For the best experience using this site, please upgrade to a modern web browser.</p></div>');
			
			$('#IEwarning').css({
				border: "1px solid #f7941d",
				borderTop: "none",
				background: "#feefda",
				textAlign: "center",
				position: "absolute",
				top: 0,
				left: 0,
				zIndex: 100,
				display: "none",
				font: "bold 12px arial, sans-serif",
				padding: "3px",
				width: $('body').width()
			}).slideDown("slow");
		}
	// END IE6 Warning---------------------------------------------------------------------------
	
	
	
	
	// 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 postal code';
	// END Error messages used in form validation---------------------------------------------------------------------------
	
	
	
	
	// 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');
						});
					}
				});
			}
		}
	// END IE select width fix----------------------------------------------------------------------------------------------
	
	
	
	
	// 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}$"); }
		
		function radioCheck(groupName) {
			var isChecked = false;
			
			for (var i=0; i<document.lead_data [groupName].length; i++) {
				if (document.lead_data [groupName][i].checked) {
					isChecked = true;
				}
			}
			
			return isChecked;
		}
	// END Validation checks----------------------------------------------------------------------------------------------------
	
	
	
	
	// Form validation---------------------------------------------------------------------------------------------------------
		function removeError() {
			if ( !$(this).data('errorMessage') ) return;
			
			$(this).removeClass('errorMessage');	
			//$(this).parent().find('label.errorMessage').remove();
			$(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 ) { 
							if ( $('#country').length ) {
								switch ( $('#country').val() ) {
									case "Canada":
										OK = isValidPostalCode(formFields[i]);
									break;
									
									case "USA":
										OK = isValidZip(formFields[i]);
									break;
								}
							} else {
								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;
					
					// Setup radio button cases here
						
					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');
			
			$(formField).addClass('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-----------------------------------------------------------------------------------------------------
	
	
	
	
	// Form setup-------------------------------------------------------------------------------------------------------------
		$('#campus_code').removeAttr("validation").attr({disabled: "disabled"})
		$('#campus_code option:first').text('-- Enter your zip code first --');
		
		$('#program_code').removeAttr("validation").attr({disabled: "disabled"})
		$('#program_code option:first').text('-- Enter your zip code first --');
		
		$('#requestForm').css({paddingBottom: 300});
		$('#indicatesRequired').css({
			bottom: 175,
			right: 84
		});
		
		$('#stepOne').append('<img id="btn_Next" src="_presentation/images/btn_Next.png" alt="Next" title="" />');
		
		$('#btn_Submit').replaceWith('<img id="btn_Submit" src="_presentation/images/btn_Submit.png" alt="Finish" title="" />');
		$('#stepTwo').append($('#btn_Submit'));
		$('#btn_Submit').css({
			bottom: -75,
			right: 84			   
		});
		$('#stepTwo').append('<p id="btn_Back">&laquo; Back</p>');
		$('#stepTwo').hide();
		
		$('#postal_code').keyup(function () {
			if ($('#postal_code').val().length > 4) {
				$('#campus_code').removeAttr('disabled').focus();
				$('#campus_code').attr({validation: "required"});
												
				$('#campus_code, #program_code').val("");
				
				$('#campus_code option:first').text('-- Choose a Campus --');
				$('#program_code option:first').text('-- Choose a Campus First --');
				
				$.getJSON('/global/cdm-server.php?path=http://ulm.datamark.com/cdm/clients/NAT0052/campuses?zip='+$('#postal_code').val(), function (json) {
					if (json.body != "") {
						var campus_code = json.body[0].CustNum;	
						
						$('#campus_code').find('option').remove().end();
						
						$.getJSON('/global/cdm-server.php?path=http://ulm.datamark.com/cdm/clients/NAT0052/campuses', function (json) {
							for (var i=0; i<json.body.length; i++) {
								if ( json.body[i].CustNum == campus_code ) {
									if ( $('#campus_code option[value='+json.body[i].CustNum+']').length == 0 ) {
										$('#campus_code').append('<option value="'+json.body[i].CustNum+'">'+json.body[i].Name+'</option>');
									}
								}
							}
							
							$('#campus_code').trigger('change');
						});					
					} else {
						$.getJSON('/global/cdm-server.php?path=http://ulm.datamark.com/cdm/clients/NAT0052/campuses', function (json) {
							for (var i=0; i<json.body.length; i++) {
								if ( $('#campus_code option[value='+json.body[i].CustNum+']').length == 0 ) {
									$('#campus_code').append('<option value="'+json.body[i].CustNum+'">'+json.body[i].Name+'</option>');
								}
							}
						});
					}
				});
			}
		});
		
		$('#campus_code').change(function () {
			if ( $(this).val() == "") {
				$('#program_code').attr({disabled: 'disabled'});
				$('#program_code option:first').text('-- Choose a Campus First --');
				$('#program_code').val("");
			} else {
				$('#program_code').removeClass('errorMessage');	
				$('#program_code').next().remove();
				$('#program_code').removeData('errorMessage');
				
				$.getJSON('/global/cdm-server.php?path=http://ulm.datamark.com/cdm/campuses/'+$(this).val()+'/programs?order_asc=ProgramName', function (json) { 
					$('#program_code').find('optgroup').remove().end();
					$('#program_code').find('option').remove().end();
					
					
						for (var i=0; i<json.body.length; i++) {
								var categoryName = json.body[i].CategoryName.replace(/'s/, "s");
								
								if ( $('#'+categoryName).html() != "" ) {									
									switch (categoryName) {
										case "Diploma":
											$('#program_code').prepend('<optgroup id="'+categoryName+'" label="'+json.body[i].CategoryName+'"></optgroup>');
										break;
										
										case "Associates":
											$('#program_code').append('<optgroup id="'+categoryName+'" label="'+json.body[i].CategoryName+'"></optgroup>');
										break;
										
										case "Bachelors":
											if ( $('#Associates').html() != "" ) {
												$('#Associates').after('<optgroup id="'+categoryName+'" label="'+json.body[i].CategoryName+'"></optgroup>');
											} else {
												$('#program_code').append('<optgroup id="'+categoryName+'" label="'+json.body[i].CategoryName+'"></optgroup>');	
											}
										break;
										
										case "Masters":
											if ( $('#Bachelors').html() != "" ) {
												$('#Bachelors').after('<optgroup id="'+categoryName+'" label="'+json.body[i].CategoryName+'"></optgroup>');
											} else {
												$('#program_code').append('<optgroup id="'+categoryName+'" label="'+json.body[i].CategoryName+'"></optgroup>');	
											}
										break;
									}
								}
																	
								$('#program_code').append('<option class="'+categoryName+'" value="'+json.body[i].ProgramCode+'">'+json.body[i].Name+'</option>');	
						}
					
					$('optgroup').each(function () {
						var optionSelector = '.'+$(this).attr('id');
						var optGroupSelector = '#'+$(this).attr('id');
						
						$(optionSelector).each(function () {
							$(optGroupSelector).append($(this));								 
						});
					});

					$('#program_code').prepend('<option value="">-- Choose a Program --</option>');
					$('#program_code').removeAttr('disabled');
					$('#program_code').attr({validation: "required"});
					$('#program_code option:first').attr('selected', 'selected');
				});
			}
		});
		
		
		$('#btn_Next').click(function () {
			var validStepOne = validate('stepOne');
			
			if ( validStepOne ) {
				$('#stepOne').hide();
				$('#stepTwo').show();
				
				$('#requestForm').css({paddingBottom: 175});
				$('#indicatesRequired').css({
					bottom: 50,
					right: 84
				});
			}
		});
		
		$('#btn_Back').click(function () {
			$('#stepOne').show();
			$('#stepTwo').hide();
			
			$('#requestForm').css({paddingBottom: 300});
			$('#indicatesRequired').css({
				bottom: 175,
				right: 84
			});
		});
		
		$('#btn_Submit').click(function () {
			var validForm = validate();
			
			if ( validForm ) {
				$('#requestForm').submit();
			}								 
		});
		
		/*  Example: Narrow programs by campus selection
			$('#program_code').attr('disabled', 'disabled');
			
			$('#campus_code').change(function () {
				if ( $(this).val() == "" ) {
					$('#program_code').attr('disabled', 'disabled');
					$('#program_code option:first').text('-- Select a campus first --');
				} else {
					$('#program_code').removeClass('errorMessage');	
					$('#program_code').next().remove();
					$('#program_code').removeData('errorMessage');
					
					$.getJSON('/global/cdm-server.php?path=http://ulm.datamark.com/cdm/campuses/' + $(this).val() + '/programs?order=ACS', function (json) {
						$('#program_code').find('option').remove().end();
						$('#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');
					});							   
				}
			});
		*/
		
		ieSelectWidthFix();	
	// END Form setup---------------------------------------------------------------------------------------------------------
});