$(function () {
// IE6 Warning----------------------------------------------------------------------------------------------------------
	if ( $('#rootIE6').length ) {						
		$('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"); 
	}

// IE select width fix--------------------------------------------------------------------------------------------------
	function ieSelectWidthFix() {
		if ( $('#rootIE').length ) {
			$('select').each(function () { $(this).data("originalWidth", parseInt($(this).css('width'))-70); });
			
			$('select').mouseenter(function () {
				$(this).css('width', "auto");
				$(this).data("resizedWidth", $(this).attr('offsetWidth'));
			
				if ( parseInt($(this).data("resizedWidth")) < parseInt($(this).data("originalWidth")) ) { 
					$(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 () {
						if ( !($(this).attr('offsetWidth') > $(this).data("originalWidth")) ) {
							$(this).css('width', $(this).data("originalWidth"));
							$(this).removeClass('expanded');
						}
					});
				}
			});
		}
	}

// 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';

// 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;
	}
	
	// validate a checkbox?

// Form validation---------------------------------------------------------------------------------------------------------
	function removeError() {
		if ( !$(this).data('errorMessage') ) return;
	
		$(this).removeClass('errorMessage');	
		$(this).parent().find('label.errorMessage').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
				
				// Setup checkbox 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+'">'+message+'</label>');
		
		$(formField).data('errorMessage', message);
	}

// Page setup-------------------------------------------------------------------------------------------------------------	
	$('.expandable').hide();
	$('#content h3').css({cursor: "pointer"}).append('<img src="_presentation/images/expand.gif" />').click(function () {
		var checkElement = $(this).next();
		
		if ( checkElement.is(':visible') ) { 
			$("img", this).attr('src', '_presentation/images/expand.gif');
			checkElement.slideUp();
		} else { 
			$("img", this).attr('src', '_presentation/images/collapse.gif');
			checkElement.slideDown();
		}
	});
	
	if ($.url.param("selection")) {
		var selection = $.url.param("selection");
			
		$('#'+selection).trigger('click');
	}

	
// Form setup-------------------------------------------------------------------------------------------------------------	
	$('#education_level_code').change(function () {
		switch ( $(this).val() ) {
			case "GED":
			case "HS":
			case "SOME":
			case "ASSOC":
				$('#program_code').attr('validation', 'required').removeAttr('disabled');
				$('#program_code').empty();
				$('#program_code').append('<option value="BATCP">BA/Teacher Certification Program</option>');
			break;
			
			case "BACH":
			case "MAST":
			case "DOCT":
				$('#program_code').attr('validation', 'required').removeAttr('disabled');
				$('#program_code').empty();
				$('#program_code').append('<option value="">-- Select --</option>');
				$('#program_code').append('<option value="MA/Education">MA/Education</option>');
				$('#program_code').append('<option value="MATLT">MA/Teaching and Learning with Technology</option>');
			break;
			
			default:
				$('#program_code').removeAttr('validation').attr('disabled', 'disabled');
				$('#program_code').empty();
				$('#program_code').append('<option value="">-- Select your education level --</option>');
			break;
		}
	});
	
	$('.military_affiliation').hide();
	$('#military_affiliation').val('I am not affiliated with the military');
	$('#military').change(function () {
		switch ( $(this).val() ) {
			case "yes":
				$('#military_affiliation').val('');
				$('.military_affiliation').slideDown();
			break;
						
			case "no":
				$('#military_affiliation').val('I am not affiliated with the military');
				$('.military_affiliation').slideUp();
			break;
			
			default:
				$('#military_affiliation').val('I am not affiliated with the military');
				$('.military_affiliation').slideUp();
			break;
		}
	});
	
	if ( !$('#rootIE6').length ) {		
		$('#requestForm').submit(function () { return false; });
		
		$('#program_code').removeAttr('validation').attr('disabled', 'disabled');
		$('#program_code option:first').text('-- Select your education level --');
		
		$('#address_block').before('<input id="btn_Back" type="image" src="_presentation/images/btn_Back.gif" alt="Back" height="19" width="128" />');
		$('#stepTwo, #disclaimer_kansas').hide();
		
		$('#btn_Submit').replaceWith('<img id="btn_Submit" src="_presentation/images/btn_Submit.gif" alt="Submit" height="19" width="128" />');
		
		$('#stepOne').append('<img id="btn_Next" src="_presentation/images/btn_Next.gif" alt="Next" height="19" width="128" />');
		$('#stepOne label').css({
			color: "#6a2d91",
			fontWeight: "bold"
		});
		
		$('#btn_Next').click(function () {
			var validStepOne = validate('stepOne');
		
			if ( validStepOne ) {
				$('#stepOne').hide();
				$('#stepTwo, #disclaimer_kansas').show();
			}
		});
		
		$('#btn_Back').click(function () {
			$('#stepOne').show();
			$('#stepTwo, #disclaimer_kansas').hide();
		});
		
		$('#btn_Submit').click(function () {
			var validForm = validate();
		
			if ( validForm ) { $('#requestForm').unbind('submit').submit(); }								 
		});
	}
	
	/* Basic form setup 
		use if ( !$('#rootIE6').length ) {} to only do extra form behavior if not IE6
			Leave campus >> program narrowing in before turning everything else off
		
		$('#requestForm').submit(function () { return false; }); // Stop enter key submission
		
		Replace <input id="btn_Submit" type="image" src="" alt="" /> w/ appropriate image
		If two-step: hide step two, add next button, add back button
		
		Setup buttons:
			
			
			$('#btn_Back').click(function () {
				// Show step one
				// Hide step two
			});
			
			
	*/
	
	/*  Example: Narrow programs by campus selection
		$('#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').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');
				});							   
			}
		});
	*/
		
	/* Example: Country and State/Province interaction
		$('#postal_code').attr('disabled', 'disabled');
	
		$('#state').change(function () {
			var country = $('#state :selected').attr('class');
	
			$('#country').val(country).attr("selected", "selected");
			$('#country').removeClass('errorMessage');	
			$('#country').next().remove();
			$('#country').removeData('errorMessage');
	
			$('#postal_code').removeAttr('disabled');
		});
	
		$('#country').change(function () {
			$('#postal_code').removeAttr('disabled');
	
			$('#state option:first').attr("selected", "selected");								   
	
			switch ( $(this).val() ) {
				case "Canada":				
					$('#state option:first').text("Select a province");
					$('#usStates').hide();
					$('#canadaProvinces').show();
				break;
	
				case "USA":
					$('#state option:first').text("Select a state");
					$('#canadaProvinces').hide();
					$('#usStates').show();
				break;
	
				default:
					$('#postal_code').attr('disabled', 'disabled');
					$('#state option:first').text("Select One");
					$('#canadaProvinces').show();
					$('#usStates').show();
				break;
			}
	
			$('#state').removeClass('errorMessage');	
			$('#state').next().remove();
			$('#state').removeData('errorMessage');
		});
	*/

	ieSelectWidthFix();
});