(function($){
/*
In this version of jquery.state-country.js:
There is a Country question, and an initially hidden State question
If "United States" or "Canada" is chosen in the Country question, then the State question will appear
The State question will only show the list of States associated with the chosen country
In reporting, the State selection shows up in the "State" column - regardless of which country was chosen (there is no separate "Province" column)
*/
try{


var states = {
	"alberta": "Canada",
	"british columbia": "Canada",
	"manitoba": "Canada",
	"new brunswick": "Canada",
	"newfoundland and labrador": "Canada",
	"northwest territories": "Canada",
	"nova scotia": "Canada",
	"nunavut": "Canada",
	"ontario": "Canada",
	"prince edward island": "Canada",
	"quebec": "Canada",
	"saskatchewan": "Canada",
	"yukon": "Canada",
	"alabama": "United States",
	"alaska": "United States",
	"arizona": "United States",
	"arkansas": "United States",
	"california": "United States",
	"colorado": "United States",
	"connecticut": "United States",
	"delaware": "United States",
	"florida": "United States",
	"georgia": "United States",
	"hawaii": "United States",
	"idaho": "United States",
	"illinois": "United States",
	"indiana": "United States",
	"iowa": "United States",
	"kansas": "United States",
	"kentucky": "United States",
	"louisiana": "United States",
	"maine": "United States",
	"maryland": "United States",
	"massachusetts": "United States",
	"michigan": "United States",
	"minnesota": "United States",
	"mississippi": "United States",
	"missouri": "United States",
	"montana": "United States",
	"nebraska": "United States",
	"nevada": "United States",
	"new hampshire": "United States",
	"new jersey": "United States",
	"new mexico": "United States",
	"new york": "United States",
	"north carolina": "United States",
	"north dakota": "United States",
	"ohio": "United States",
	"oklahoma": "United States",
	"oregon": "United States",
	"pennsylvania": "United States",
	"rhode island": "United States",
	"south carolina": "United States",
	"south dakota": "United States",
	"tennessee": "United States",
	"texas": "United States",
	"utah": "United States",
	"vermont": "United States",
	"virginia": "United States",
	"washington": "United States",
	"west virginia": "United States",
	"wisconsin": "United States",
	"wyoming": "United States",
	"district of columbia": "United States",
	//This unnecessary entry means all lines with actual data end in ,
	"n/a": null
};

$(document).ready(function(){
	// Set up variables
	// Determine what kind of State and County questions we're dealing with
	var $conditionalState = $('.country-conditional-state');
	var $countryQuestion = $('.country.wizard-question');
	var $stateQuestion = $('.state');

	var countryQuestionType = "";
	if($countryQuestion.hasClass('freetext-question')) {
		countryQuestionType = "freetext-question";
	} else if($countryQuestion.hasClass('select-question')) {
		countryQuestionType = "select-question";
	}

	var stateQuestionType = "";
	if($stateQuestion.hasClass('freetext-question')) {
		stateQuestionType = "freetext-question";
	} else if($stateQuestion.hasClass('select-question')) {
		stateQuestionType = "select-question";
	}

	// If the country question is free_text...
	if(countryQuestionType === "freetext-question" && stateQuestionType === "select-question") {
		// When a state is chosen, check whether is has an associated country
		// If so, set the country input value to that country (and prevent editing that field unless they change the state selection)
		$stateQuestion.on('selected cvb_init_field', function(e){
			var state = $(e.target).closest('label').text().toLowerCase();
			var country = states[state];
			
			if(country){
				$('.country input').val(country).trigger('cvb_field_change').prop('readonly', true);
			}else{
				$('.country input').prop('readonly', false);
			}
		});

	} else if($conditionalState.length) {
		// Set selectedCountry variable on page load - if Wizard is in edit mode this may trigger things immediately
		var selectedCountry = $('.selected-value', $countryQuestion).attr('data-value');
		
		var $stateListItems = $('.options li', $stateQuestion);
		var $stateInputs = $('input', $stateQuestion);
		var selectedState = $('.selected-value', $stateQuestion).attr('data-value');
		var stateRequired = false;
		// Check to see if the state question is required
		if($stateQuestion.hasClass('required')) {
			stateRequired = true;
		}

		// Identify states and provinces (will filter which are shown)
		// there will be some inputs outside of this - like .no-anwer or an N/A option
		$stateListItems.each(function(){
			var associatedCountry = states[$(this).text().trim().toLowerCase()];
			if(associatedCountry === "United States") {
				$(this).addClass('us-state');
			} else if(associatedCountry === "Canada") {
				$(this).addClass('canada-province');
			}
		});
		var $usStates = $('.us-state');
		var $canadaProvinces = $('.canada-province');

		// Filter the state options on page load
		filterStateOptions(selectedCountry);

		// Set up conditional stateQuestion animator - register(elements, activeState, inactiveState, initiallyOn, transitionTime)
		var animator = cvb.animatedToggle.register(
			$stateQuestion,
			{'opacity':1},
			{ 'opacity':0,'binary':{'display':'none'} },
			selectedCountry === "United States" || selectedCountry === "Canada" ,
			250
		);

		// Add an accessibility note
		$countryQuestion.find('.select-bar').append('<span class="visual-hidden">Selecting Canada or United States will reveal a Province/State fieldset below.</span>');

		// When a country is selected...
		$countryQuestion.on('selected', function(e){
			// update the selectedCountry variable
			selectedCountry = $(e.target).closest('label').text().trim();
			// and determine whether to turn the animator on or off
			// filter the state options either way
			if(selectedCountry === "United States" || selectedCountry === "Canada") {
				animator.turnOn(filterStateOptions(selectedCountry));
			} else {
				animator.turnOff(filterStateOptions(selectedCountry));
			}
			
		});

		function filterStateOptions(country){
			// get the current selected state, and update the variable
			selectedState = $('.selected-value', $stateQuestion).attr('data-value');
			// we are going to change the label of the state question, depending on what country was selected - set up that variable
			var labelText = "Prov/State";
			// define the appropriate label text, and hide the state options that are associated with other countries
			if(country === "United States") {
				labelText = "State";
				// using hide() and show() (instead of class of visual-hidden) so that keyboard navigation skips them as well
				$canadaProvinces.hide().addClass('invalid');
				$usStates.removeClass('invalid').show();
			} else if(country === "Canada") {
				labelText = "Province";
				$usStates.hide().addClass('invalid');;
				$canadaProvinces.removeClass('invalid').show();
			}
			// Clear selections
			// If the selected state is not associated with the selected country, clear state selections
			if(states[selectedState.toLowerCase()] !== country) {
				$('input, option', $stateQuestion).each(function (){
					cvb.removeSelection( $(this).val() );
					$(this).prop('checked', false);
				});
				if(stateRequired){
					labelText += '*';
				}
				// set the state question label text. Add and remove a class to make sure the css refreshes its content to the data-value (in some browser/device combos it doesn't)
				$('.selected-value', $stateQuestion).attr('data-value', labelText)
					.find('.selected-text').html(labelText);
			}

			// The following is related to The Constraint Validation API, which is built into HTML validation
			// If the state question is required, it's possible to trigger an error by choosing US or Canada, then clicking View Now with no selection
			// Triggering an error sets a custom validation message on the first input
			// When setCustomValidity() was called, it considers the input invalid
			// The first input will have $(this).get(0).validity.customError: true, and $(this).get(0).validity.valid: false
			// If required, clear out the setCustomValidity
			if(stateRequired) {
				// If an error was previously set, clear the setCustomValidity - it will get set again if the field is still invalid when trying to submit
				$stateInputs.each(function (){
					$(this).get(0).setCustomValidity('');
				});
			}	
		}

		// If a selection was previously made, and then cleared, the previous selection is still the e.target when you open/click the select question
		// This then triggers 'selected' on that input, which we do not want if the state no longer matches the country
		$('input', $stateQuestion).on('click', function(e){
			// if the stateQuestion is visible, list items will have a class of 'invalid' if they don't match the selected country
			var invalidState = $(e.target).closest('li').hasClass('invalid');
			var noAnswer = $(e.target).closest('li').hasClass('no-answer');
			// If the previous selection is no longer valid, preventDefault
			if(invalidState || noAnswer) {
				// prevent trigger('selected')
				e.preventDefault();
			} else {
				// The following is related to The Constraint Validation API, which is built into HTML validation
				// If an error was previously triggered, then a custom validation message was set on the first visible input
				// Here, we know the user is choosing a valid option, so we clear out setCustomValidity so the Constraint Validation API considers all inputs valid
				$stateInputs.each(function (){
					$(this).get(0).setCustomValidity('');
				});
				// Select the option that was clicked, which is a valid state option
				$(e.target).prop('checked', true).closest('.option').trigger('selected');
			}
		});
	}
	
});


}catch(ex){
	console.error(ex);
}

})(jQuery);