$(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 postal code';
		validationErrorMessage['opt_in'] = 'Required';
	
	
	
	//--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');
						});
					}
				});
			}
		}
		
	
	
	//--Ashford qualify check--------------------------------------------------------------------------------------------------
		function qualifyCheck () 
		{
			var eduLevelCheck;
			
			$('#category').find('option').remove().end();
			$('#category').append('<option value="">Loading&hellip;</option>').attr({disabled: 'disabled'});
			
			$('#program_code').find('option').remove().end();
			$('#program_code').append('<option value="">Choose a Program</option>');
			$('#program_code').attr({disabled: 'disabled'});
			
			switch ( education_level = $('#education_level_code').val() ) 
			{
				case "HSGED":
					eduLevelCheck = RegExp(/^(AA\/|BA\/)/);
				break;
				
				case "SC30":
					eduLevelCheck = RegExp(/^(AA\/|BA\/)/);
				break; 
				
				case "SC60":
					eduLevelCheck = RegExp(/^(AA\/|BA\/)/);
				break; 
				
				case "SCASSOC":
					eduLevelCheck = RegExp(/^(BA\/)/);
				break; 
				
				case "BACH":
					eduLevelCheck = RegExp(/^(MA\/|MBA|Master)/);
				break; 
				
				case "MAST":
				case "DOCT":
					eduLevelCheck = RegExp(/^(MA\/|MBA|Master)/);		
				break;
			}
			
			$.getJSON('/global/cdm-server.php?path=http://ulm.datamark.com/cdm/clients/BRI0006/programs?order_asc=ProgramName', function (json) {
					for (var i=0, ii = json.body.length; i<ii; i++) 
					{
						var currentProgram = json.body[i].Name;
					
						if ( currentProgram.search(eduLevelCheck) == 0 && ($('#category option[value='+currentProgram+']').length == 0) ) 
						{ $('#category').append('<option value="'+currentProgram+'">'+currentProgram+'</option>'); }
					}
					
					$('#category option:first').text('-- Select --');
					$('#category').removeAttr('disabled');
			});
			
			$('#category').change( function () {				
				if ($('#category').val() == "") 
				{
					$('#program_code').find('option').remove().end();
					$('#program_code').append('<option value="">Choose an Area of Interest</option>');
					$('#program_code').attr({disabled: 'disabled'});
				} 
				else 
				{
					$('#program_code').find('option').remove().end();
					$('#program_code').append('<option value="">Loading&hellip;</option>');
					$('#program_code').attr({disabled: 'disabled'});
				
					programCheck = RegExp($('#category').val());
				
					$.getJSON('/global/cdm-server.php?path=http://ulm.datamark.com/cdm/clients/BRI0006/programs?order_asc=Emphasis', function (json) {
						for (var i=0, ii=json.body.length ; i<ii; i++) 
						{
							var currentProgram = {
								'Name': json.body[i].Name,
								'ProgramCode': json.body[i].ProgramCode,
								'Emphasis': json.body[i].Emphasis
							};
				
							if ( (currentProgram['Name'].search(programCheck) == 0) && ($('#program_code option[value='+currentProgram['ProgramCode']+']').length == 0) ) 
							{
								if ( currentProgram['Emphasis'] ) 
								{ $('#program_code').append('<option value="'+currentProgram['ProgramCode']+'">'+currentProgram['Emphasis']+'</option>'); }	
								else 
								{ 
									var message = "";
									var programName = currentProgram['Name'];
									
									switch ( true )
									{
										case programName.search(/^AA\//) != -1:
										case programName.search(/^BA\//) != -1:
											message = "No Concentration";
										break;
										
										case programName.search(/^(MA\/|MBA|Master)/) != -1:
											message = "No Specialization";
										break;
									}
																																				
									$('#program_code').append('<option value="'+currentProgram['ProgramCode']+'" selected="selected">'+message+'</option>'); 
								}
				
								$('#program_code option:first').text('-- Select --');
								$('#program_code').removeAttr('disabled').attr({validation: 'required'});
							}
						}
					});
				}
			});
		}
			
					
		$('#category option:first').html('Choose an Education Level');
		$('#program_code option:first').html('Choose an Area of Interest');
		$('#category, #program_code').attr({disabled: 'disabled'});
		
		$('#education_level_code').change(function () { qualifyCheck(); });
		
		if ( $('#education_level_code').val() != "" ) { $('#education_level_code').trigger('change'); }
		
		$('#education_level_code').change(function () {
			$('#age, #category').val("");
			$('#category option:first').html('Indicate Your Education Level');
			$('#program_code option:first').html('Choose a Program');
			$('#category, #program_code').attr({disabled: 'disabled'});
		});
	
	//--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 isChecked(formField) {
		return $(formField).attr('checked');
	}
	
	//-----------------------------------------------------------------------------------------------------END Validation checks

		
		
	//--Form validation---------------------------------------------------------------------------------------------------------
		
		function removeError() {
			if ( !$(this).data('errorMessage') ) return;
		
			$(this).removeClass('errorMessage');	
			$(this).parent().find('label.errorMessage, span.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) { 
							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;
						
						case "opt_in":
							OK = isChecked(formFields[i]);
							
							requiredFirst = false;
						break;
						
					default:
						OK = isRequired(formFields[i]);
						break;
				};
				
				if (!OK) {
					var errorMessage = "Required Field"; 
					
					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');
			
			_gaq.push(['_trackEvent', 'Forms', 'error-'+fieldID]);
						
			if(fieldID == 'opt_in') {
				fieldWidth = '225';
				fieldHeight = '20';
				
				if ( $('span.errorMessage', $(formField).parent()).length == 0 )
				{
					$(formField).parent().prepend('<span style="width:'+fieldWidth+'px; height: '+fieldHeight+'px;" class="errorMessage">'+message+'</span>');
				}
				
				$(formField).attr('checked', 'unchecked');
				$(formField).attr('checked', false);
			}
			else
			{ $(formField).parent().append('<label style="width:'+fieldWidth+'px; height: '+fieldHeight+'px;" class="errorMessage" for="'+fieldID+'">'+message+'</label>'); }
			
			$(formField).addClass('errorMessage');
			
			$(formField).click(removeError);
			$(formField).focus(removeError);
			
			if ( $(formField).data('errorMessage') ) return;
			
			$(formField).data('errorMessage', message);
		}

		
		
	
	//-------------------------------------------------------------------------------------------------------END Form validation
	
	
	
	//--Page initialization----------------------------------------------------------------------------------------------------
		var bodyHeight = $('body').height();
		var contentArea2Height = $('#contentArea2').height();
		
		$('.expandable').each(function () {
			$(this).prev().css({cursor: "pointer"});
			
			$(this).prev().click(function () {
				var checkElement = $(this).next();
							
				$('.expandable:visible').slideUp('normal',function() {$('#contentArea2').css({height: contentArea2Height});$('body').css({height: bodyHeight});});
			
				if (checkElement.is(':visible')) {
					var elementHeight = $(checkElement).height();
					checkElement.slideUp('normal',function() {$('#contentArea2').css({height: contentArea2Height});$('body').css({height: bodyHeight});});
				} else {
					checkElement.slideDown('normal',function() {$('#contentArea2').css({height: $('#contentArea2').height() + $(checkElement).height()});$('body').css({height: $('body').height() + $(checkElement).height()});});
					
				}							   
			});
		});
		
		if (branch != "military") {
			$('#tuitionAssistance').trigger("click");
		}
		
		$('#btn_Submit').replaceWith('<img id="btn_Submit" src="_Presentation/Images/btn_Submit.png" alt="Submit &raquo;" title="" />');
				
		$('#btn_Submit').click(function () {
			var validForm = validate();
			
			_gaq.push(['_trackEvent', 'Forms', 'submit']);
			
			if (validForm) {
				_gaq.push(['_trackPageview','/form/filled']);
				$('#requestForm').submit();
			}								 
		});
		
		if ($('#stepOne').html() != null && $('#stepTwo').html() != null) {
			$('#stepTwo').hide();
			$('#requiredFields2').hide();
			
			$('#requestForm').append('<span id="stepIndicator">Step 1 of 2</span>');
			$('#requestForm').append('<img id="btn_Next" src="_Presentation/Images/btn_Next.png" alt="Next &raquo;" title="" />');
			$('#requestForm').append('<img id="btn_Back" src="_Presentation/Images/btn_Back.png" alt="&laquo; Back" title="" />');
			
			$('#btn_Submit').hide();
			$('#btn_Back').hide();
			
			$('#stepOne label').css({
				fontSize: '15px',
				fontWeight: 'bold'
			});
			
			$('#btn_Next').click(function () {
				var validStepOne = validate('stepOne');
				
				_gaq.push(['_trackPageview','/form/continue']);
				
				if (validStepOne) {
					if ( $('#source_code').val() == "ROCKET" )
					{
						$('#stepTwo').append('<!-- Code for Action: Ashford - Shopping Cart --><!-- Begin Rocket Fuel Conversion Action Tracking Code Version 7 --><img src="https://p.rfihub.com/ca.gif?rb=1207&ca=20477351&ra=%n" height=0 width=0 style="display:none" alt="Rocket Fuel"/><!-- End Rocket Fuel Conversion Action Tracking Code Version7 -->');
					}
					
					_gaq.push(['_trackEvent', 'Forms', 'next']);
					
					$('#stepOne').hide();
					$('#requiredFields').hide();
					$('#btn_Next').hide();
					$('#formHeader').hide();
					$('#moreInfo').hide();
					$('#requestForm').css({
						paddingTop: "0",
						marginTop: "-47px"
					});
					
					$('#militaryFriendly').css({top: 995});
					
					$('#stepTwo').show();
					$('#requiredFields2').show();
					$('#btn_Back').show();
					$('#btn_Submit').show();
					
					$('#contentArea2').css({height: $('#contentArea2').height() + 100});
					$('body').css({height: $('body').height() + 100});
					
					$('#stepIndicator').text("Step 2 of 2");
				}
			});
			
			$('#btn_Back').click(function () {
				$('#stepTwo').hide();
				$('#requiredFields2').hide();
				$('#btn_Back').hide();
				$('#btn_Submit').hide();
				
				$('#stepOne').show();
				$('#requiredFields').show();
				$('#btn_Next').show();
				$('#formHeader').show();
				$('#moreInfo').show();
				$('#requestForm').css({
						paddingTop: "90px",
						marginTop: "-4px"
					});
				
				$('#stepIndicator').text("Step 1 of 2");
			});
		}
				
		$('#program_code').attr('disabled', 'disabled');
		
		$('#contentArea, #militaryFriendly').supersleight();
		
		if ( $('#thanks').length != 0 )
		{  
			$('#militaryFriendly').css({top: 1050});
			$('body#Home, body#Financial_Aid').css({height: 1300});
		}
		
		
		
// Dynamic Removal of Various States Dependent On Program Selection ----------------------//

	// CAPTURE STATE DROPDOWN ON PAGE LOAD
	stateHTML = $('#state').html();

	$('#category').change(function() {
		//RESET STATE DROPDOWN TO DEFAULT ON EACH CHANGE OF PROGRAM CHOICE
		$('#state').html(stateHTML);

		switch( $(this).val() ) {
			
			// PROGRAMS ALLOWED IN KENTUCKY
			case "AA/Business":
			case "AA/Military Studies":
			case "AA/Organizational Management":
			case "BA/Accounting":
			case "BA/Adult Development":
			case "BA/Applied Behavioral Science":
			case "BA/Applied Linguistics":
			case "BA/Business Administration":
			case "BA/Business Economics":
			case "BA/Business Information Systems":
			case "BA/Business Leadership":
			case "BA/Child Development":
			case "BA/Cognitive Studies":
			case "BA/Communication Studies":
			case "BA/Complementary and Alternative Health":
			case "BA/Consumer and Family Financial Services":
			case "BA/Cultural Anthropology":
			case "BA/eMarketing":
			case "BA/English":
			case "BA/English Language Learner Studies":
			case "BA/Entrepreneurship":
			case "BA/Environmental Studies":
			case "BA/Finance":
			case "BA/Gerontology":
			case "BA/Health and Human Services":
			case "BA/Health and Marketing Communication":
			case "BA/Health and Wellness":
			case "BA/Health Care Administration":
			case "BA/Health Care Studies":
			case "BA/Health Informatics":
			case "BA/History":
			case "BA/Homeland Security and Emergency Management":
			case "BA/Human Resources Management":
			case "BA/Instructional Design":
			case "BA/International Business":
			case "BA/Journalism and Mass Communication":
			case "BA/Law Enforcement Administration":
			case "BA/Liberal Arts":
			case "BA/Library Science and Media":
			case "BA/Military Studies":
			case "BA/Operations Management and Analysis":
			case "BA/Organizational Management":
			case "BA/Political Science and Government":
			case "BA/Project Management":
			case "BA/Psychology":
			case "BA/Public Administration":
			case "BA/Public Relations and Marketing":
			case "BA/Real Estate Studies":
			case "BA/Service Management":
			case "BA/Social and Criminal Justice":
			case "BA/Social Science":
			case "BA/Sociology":
			case "BA/Sports and Recreation Management":
			case "BA/Supply Chain Management":
			case "BA/Sustainable Enterprise Management":
			
				// REWRITE STATE DISCLAIMER TO REMOVE KENTUCKY
				$('.state_disclaimer').text('** Ashford University does not currently accept students in Arkansas, Minnesota, or Mississippi.');
				
				// REMOVE ARKANSAS, MINNESOTA, AND MISSISSIPPI FROM STATE DROPDOWN
				$('#state option').each(function () {
					switch ($(this).val()) {
						case "AR":
						case "MN":
						case "MS":
							$(this).remove();
						break;
					}
				});
			break;
			
			// PROGRAMS ALLOWED IN MINNESOTA
			case "MA/Education":
			case "MA/Teaching and Learning with Technology":
			
				// REWRITE STATE DISCLAIMER TO REMOVE MINNESOTA
				$('.state_disclaimer').text('** Ashford University does not currently accept students in Arkansas, Kentucky, or Mississippi.');
			
				// REMOVE ARKANSAS, KENTUCKY, AND MISSISSIPPI FROM STATE DROPDOWN
				$('#state option').each(function () {
					switch ($(this).val()) {
						case "AR":
						case "KY":
						case "MS":
							$(this).remove();
						break;
					}
				});
			break;
			
			// PROGRAMS ALLOWED IN ARKANSAS **AND** MINNESOTA
			case "MA/Organizational Management":
			case "Master of Public Administration":
			
				// REWRITE STATE DISCLAIMER TO REMOVE ARKANSAS AND MINNESOTA
				$('.state_disclaimer').text('** Ashford University does not currently accept students in Kentucky or Mississippi.');
				
				// REMOVE KENTUCKY AND MISSISSIPPI FROM STATE DROPDOWN
				$('#state option').each(function () {
					switch ($(this).val()) {
						case "KY":
						case "MS":
							$(this).remove();
						break;
					}
				});
			break;
			
			// PROGRAMS ALLOWED IN ARKANSAS **AND** MINNESOTA **AND** KENTUCKY
			case "MA/Health Care Administration":
			case "MBA":
			
				// REWRITE STATE DISCLAIMER TO REMOVE ARKANSAS, MINNESOTA, AND KENTUCKY
				$('.state_disclaimer').text('** Ashford University does not currently accept students in Mississippi.');
				
				// REMOVE MISSISSIPI FROM STATE DROPDOWN
				$('#state option').each(function () {
					if ($(this).val() == 'MS') {
						$(this).remove();
					}
				}); 
			break;
			
			default:
				// RESET STATE DROPDOWN TO DEFAULT
				$('#state').html(stateHTML);
				
				// REWRITE STATE DISCLAIMER TO DEFAULT TEXT
				$('.state_disclaimer').text('** Ashford University does not currently accept students in Arkansas, Kentucky, Minnesota, or Mississippi.');
				
				// REMOVE ARKANSAS, KENTUCKY, MINNESOTA, AND MISSISSIPPI FROM STATE DROPDOWN
				$('#state option').each(function () {
					switch ($(this).val()) {
						case "AR":
						case "KY":
						case "MN":
						case "MS":
							$(this).remove();
						break;
					}
				});
			break;
		}
	});	
		
		ieSelectWidthFix();
	//--------------------------------------------------------------------------------------------------END Page initialization
});
