$(document).ready(function() {
	var $selectedCountry;
	var $selectedProvState;
	var $selectedCity;

	$('#select_country').change(function() {
		$selectedCountry = $(this).val();
		$showProvState = '#select_provstate_' + $selectedCountry;

		//init and hide all provstate selects
		$('.provstate-list').hide();
		$('.city-list').hide();
		$('.stores-list').hide();
		$('#error_message').hide();

		if ($selectedCountry) {
			//show the correct provstate select and hide the dummy
			$($showProvState).toggle();
			$($showProvState).val('');
			$($showProvState).focus();

			$('#select_city').show();
			$('#select_provstate').hide();
		} else {
			//hide any city lists that are visible and show the dummies
			$('.city-list').hide();

			$('#select_provstate').show();
			$('#select_city').show();
		}
	});

	$('.provstate-list').change(function() {
		$selectedProvState = $(this).val();
		$showCity = '#select_city_' + $selectedProvState;

		//init and hide all city lists and the error message
		$('.city-list').hide();
		$('.stores-list').hide();
		$('#error_message').hide();

		if ($($showCity).length) {
			$($showCity).toggle();
			$($showCity).val('ALL');
			$($showCity).change();
			$($showCity).focus();
		} else {
			//no city list exists for that provstate show the dummy and a message
			$('#select_city').show();
			$('#error_message').show();
		}
	});

	$('.city-list').change(function() {
		$selectedCity = $(this).val();
		$showStores = '#' + $selectedProvState + ' #' + $selectedCity;
		$showStoresAll = '#' + $selectedProvState + ' #ALL';
		$showAllLocations = '.' + $selectedProvState;

		//init and hide all the store lists
		$('.stores-list').hide();
		$('#error_message').hide();

		if ($selectedCity) {
			//first show the one with ALL if it exists
			if ($($showStoresAll).length) {
				$($showStoresAll).fadeToggle();
			}

			//then the city specific ones if the only option isn't ALL
			if ($selectedCity != 'ALL') {
				 $($showStores).fadeToggle();
			}

			if ($selectedCity == 'ALL') {
				$($showAllLocations).fadeIn();
			}
		}
	});

	//$('.city-list').sortSelect();
});
