$(function() {
	s = "#loginForm input[type=text]"
	s += ",#profileForm input[id=profile_FIRSTNAME]"
	s += ",#passwordForm input[type=password]"
	s += ",#personalForm input[type=text]"
	s += ",#addressForm input[type=text]",
	s += ",#biographicalForm input[type=radio]"
	s += ",#enrollmentForm input[type=radio]"
	s += ",#essayForm input[type=radio]"
	s += ",#recommendationForm input[type=text]"
	s += ",#testForm select"
	s += ",#excurrForm input[type=radio]"
	s += ",#familyRelationshipsForm select"
	s += ",#userForm input[type=text]"
	$(s).eq(0).focus();
	
	$(".institution_selector").autocomplete({
	  ajax: '/institutions.js',
	  match: function(typed) { return true; },
	  insertText: function(obj) { return obj.text.name},
		onSelect: function(obj, input) { 
			input.parent().find('.institution_selector_ceeb_code').val(obj.text.ceeb_code);
			input.parent().find('.institution_selector_school_name').val(obj.text.name);
			input.val(obj.text.name);
		},
		onKeyPress: function() { },
		onCancel: function(input, originalValue) { 
			input.val("");
			input.parent().find('.institution_selector_ceeb_code').val(null);
			input.parent().find('.institution_selector_school_name').val(null);
		},
	  templateText: "<li id='<<<= text.ceeb_code >>>' ><<<= text.name >>> <<<= text.city_and_state >>></li>"
	});
	
	if($("#student_application_application_type_id").length) {
		$("#new_student_application_form").submit(function() {
			var btn = $("#student_application_submit");
			origBtnVal = btn.attr("value");
			btn.attr("disabled", "true").attr("value", "Submitting..."); 
			if (confirm('Please make sure you have selected the correct application. This cannot be changed after clicking OK.')){
				return true;
			}
			else{
				btn.removeAttr("disabled").attr("value", origBtnVal);
				return false;
			}
		});
	}
	
});

var form_rules = {};

var statesStuff = {
	hideAndClear: function(className) {
		$(className).hide().attr('name','').val(null);
		statesStuff.clearValidationRules(className);
	},
	getFormRules: function(input) {
		var key = input.closest("FORM").attr("id");
		if (form_rules != undefined) {
		  return form_rules[key];
		}
		return null;
	},
	clearValidationRules: function(selector) {
		// There may be no validations on this form
		if (statesStuff.getFormRules($(selector).eq(0)))
			$(selector).rules("remove");
	},
	reapplyValidationRules: function(input) {
		var all_rules = statesStuff.getFormRules(input);
		if (all_rules && (cached_rules = all_rules[input.attr("name")])) {
		  var rules = {};
			for (i in cached_rules) { rules[i] = cached_rules[i]; }
			// Reapply any cached rules - minLength and maxLength aren't valid for SELECTS
			if (input.is("SELECT")) {
				delete rules.maxlength;
				delete rules.minlength;
			}
			input.rules("remove");
			input.rules("add", rules);
		}
	},
 	showAndSetFirstOption: function(className, stateId, inputName) {
		var input = $(className).show().filter("INPUT,SELECT,OPTION,TEXTAREA").attr('name', inputName).eq(0);

		if (input) 
		  statesStuff.reapplyValidationRules(input);
		
		hasPrompt = false;
		var stateElt = $("#" + stateId);
		// only show the "Choose a state..." if the user hasn't already chosen one
		if (stateElt.val() == "" || stateElt.val() == null) {
		  	if (stateElt.children("[value=]").length == 0) 
				stateElt.prepend('<option value="">Choose a State...</option>');
			stateElt.val("");
			stateElt.selectedIndex = 0;
		}
	}
}
statesStuff.stateRules = {};
function showStatesForCountry(model, state_column, country_column) {
	// Some variables that store the DOM IDs of the country input state inputs.
	countryId = model + '_' + country_column
	stateId = model + '_' + state_column
	// Name attribute of the state field we will be disabling and enabling.
	inputName = model + '[' + state_column + ']'
	// Class names for each type of field.
	unitedStatesClassName = '.united_states_' + country_column
	canadaClassName = '.canada_' + country_column
	otherClassName = '.other_' + country_column
	// Do some special things to format the variables if there is no prefix.
	if(country_column == null) {
		countryId = model + '_country'
		inputName = model + '[state]'
		unitedStatesClassName = '.united_states'
		canadaClassName = '.canada'
		otherClassName = '.other'
	}

	// Check to see what the country value is and enable/disable appropriate fields.
	var countryElt = $("#" + countryId);
	if(countryElt.val() == "United States") {
		statesStuff.showAndSetFirstOption(unitedStatesClassName, stateId, inputName);
		statesStuff.hideAndClear(canadaClassName);
		statesStuff.hideAndClear(otherClassName);
	} else if (countryElt.val() == "Canada") {
		statesStuff.showAndSetFirstOption(canadaClassName, stateId, inputName);
		statesStuff.hideAndClear(otherClassName);
		statesStuff.hideAndClear(unitedStatesClassName);
	} else {
		statesStuff.showAndSetFirstOption(otherClassName, stateId, inputName);
		statesStuff.hideAndClear(unitedStatesClassName);
		statesStuff.hideAndClear(canadaClassName);
	}

}

var noResults = [	{"text": {	"name": "Domestic High School Not Found",
															"ceeb_code": "960000", 
															"city_and_state": ""}}, 
									{"text": {	"name": "International High School Not Found",
															"ceeb_code": "969999", 
															"city_and_state": ""}},
									{"text": {	"name": "General Education Development",
															"ceeb_code": "960057", 
															"city_and_state": ""}},
									{"text": {	"name": "Home Schooling",
															"ceeb_code": "960028", 
															"city_and_state": ""}},
									{"text": {	"name": "Domestic College Not Found",
															"ceeb_code": "990000", 
															"city_and_state": ""}},
									{"text": {	"name": "International School Not Found",
															"ceeb_code": "999999",
															"city_and_state": ""}}];

// Extend autocomplete so we can grab data from an ajax call															
(function($) {
  $.ui = $.ui || {};
  $.ui.autocomplete = $.ui.autocomplete || {};
  $.ui.autocomplete.ext = $.ui.autocomplete.ext || {};
  
  $.ui.autocomplete.ext.ajax = function(opt) {
    var ajax = opt.ajax;
    return { getList: function(input) { 
			if (input.val() == '') { input.trigger("updateList", [noResults]); }
			if (input.val().match(/^\s*$/)) return false;
			$('#throbber').show();
      $.getJSON(	ajax, 'q=' + escape(input.val()),
									function(json) {
										if (json=='') { input.trigger("updateList", [noResults]); }
										else { input.trigger("updateList", [json]); }
										$('#throbber').hide(); }
								); 
    } };
  };
  
  $.ui.autocomplete.ext.templateText = function(opt) {
    var template = $.makeTemplate(opt.templateText, "<<<", ">>>");
    return { template: function(obj) { return template(obj); } };
  };
  
})(jQuery);
															
$.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}})