(function($){
	var records = false;
	$.fn.loadCountries = function(ref, selected = false){
		var element = $(this);
		if(!records) {
			$.ajax({
				url: "app/includes/ajax.php",
				type: "post",
				data: {action: "dir_get_countries"},
				async: false
			}).done(function(data){
				records = JSON.parse(data);
			});
		}
		var options = "";
		var countryKey = 0;
		for(var key in records.data) {
			options += "<option data-key="+key+" value=\""+records.data[key].name+"\">"+records.data[key].name+"</option>";
			if(selected && (records.data[key].name == selected)) {
				countryKey = key;
			}
		}
		$(element).html(options);
		$("#state-"+ref).loadStates(countryKey, element, ref);
		if($(element).data("default")) {
			$(element).val($(element).data("default"));
			$(element).data("default", false);
		}
		$(element).trigger("chosen:updated");
		return records;
	}

	$.fn.loadStates = function(key, country) {
		var element = $(this);
		var selected = $(this).data("default");
		if(!records) {
			records = $(country).loadCountries();
		}
		var options = "";
		for(var i in records.data[key].states) {
			options += "<option data-state_code="+records.data[key].states[i].state_code+" value=\""+records.data[key].states[i].name+"\"";
			options += (records.data[key].states[i].name == selected) ? ' selected' : '';
			options += ">"+records.data[key].states[i].name+"</option>";
		}
		$(element).html(options);
		$(element).trigger("chosen:updated");
	}
})(jQuery)

jQuery(document).ready(function($){
	$(".dir-country").each(function(element){
		var ref = $(this).data("ref");
		var selected = $(this).data("default");
		$(this).loadCountries(ref, selected);
	})
	$(document).on("change", ".dir-country", function(e){
		var ref = $(this).data("ref");
		var key = $(this).find(':selected').data("key");
		$("#state-"+ref).loadStates(key, this, ref);
	})
})