/**
 * This script makes a country dropdown update a corresponding state/province
 * dropdown to only show states for the selected country, or disable it if none
 * exist. The script assumes the states dropdown is generated with the macro
 * @spring.singleSelectCustom, exposing the property "country".
 *
 * <@spring.singleSelectCustom path='state' options=stateOptions selectLabel="Select a state..." exposeProperties="country" />
 *
 * To support multiple state/country combos on one page (like on individual
 * registration), the two select elements currently must be exclusive siblings.
 * We could enhance bindStatesToCountry to look higher for a common ancestor.
 */

function setUpK12Fields() {
    $("#orgType").change(function() {
        var publicK12 = (this.value=="US_PUBLIC_K12");
        $("#publicK12").css("display", publicK12?"block":"none");
        $("#publicK12").attr("disabled", publicK12?"":"disabled");
    })
}
$(document).ready(setUpK12Fields);

function updateStatesForCountry() {
    var states = $(this).data("states");
    states.find("[country]").hide();
    var matches = states.find("[country="+this.value+"]");
    matches.show();
    states.find(":selected:hidden").attr("selected", false); // if invalid state already selected
}

function bindStatesToCountry() {
    $("select:has([country])").each(function() { // "state" dropdowns
        var firstCountry = $(this).find("[country]").attr("country");
        var countries = $(this).siblings("select:has([value="+firstCountry+"])"); // "country" dropdown
        countries.data("states", $(this));
        countries.change(updateStatesForCountry).change();
    })
}

$(document).ready(bindStatesToCountry);

function setConfirmEmailFieldBlank(){
 	$("input[@name=confirmEmail]").val("");
}

$(document).ready(function(){
	$("input[@name=contactInfo.email]").change(setConfirmEmailFieldBlank);
});


function enableFormSection(sectionID) {
    $("#schoolFields").removeClass('disabled');
    $("#schoolFields :input").removeAttr("disabled");
}

function disableFormSection() {
    // Be carefull about state of form when errors are returned
	if ($('.studentRadio:checked').val() != "true") {
	    $("#schoolFields").addClass('disabled');
	    $("#schoolFields :input").attr("disabled", true);
    }
}

function bindFormSectionToggling() {
	$(".studentRadio").each(function() {
	    $(this).click(function () {
	    	if ($('.studentRadio:checked').val() == "true") {
                enableFormSection();
	    	}
	    	else {
                disableFormSection();
	    	}
	    });
	});
}

$(document).ready(bindFormSectionToggling);
$(document).ready(disableFormSection);
