$().ready(function () {
	bindStates();
});

function bindStates() {
	$('#country').change(function() {
		fetchStates();
		fetchPostalFormat();
	});
	
	var country_id = $('#country').attr('value');
	
	if ($('#region').children('option').length == 1) {
		$('#region').parent().hide();
	}
	
	fetchPostalFormat();
}

function fetchStates() {
	$.ajax({
		url:'/libs/requests.php',
		type:'POST',
		data:({
			req:'states',
			country_id:$('#country').attr('value')
		}),
		dataType:'json',
		success:function(states) {
			var html = '<option value=""></option>';

			if(states == null || states.length == 0) {
				$('#region')
					.html(html)
					.parent().hide();
			} else {
				for (var i = 0; i < states.length; i++) {
					html += '<option value="' + states[i].id + '">' + states[i].name + '</option>';
				}
				
				$('#region')
					.html(html)
					.parent().show();
			}
		}
	});
}

function fetchPostalFormat() {
	$.ajax({
		url:'/libs/requests.php',
		type:'POST',
		data:({
			req:'postal_fmt',
			country_id:$('#country').attr('value')
		}),
		dataType:'json',
		success:function(fmt) {
			if (fmt == null) {
				$('#zip').parent().children('span.required').hide();
			} else {
				$('#zip').parent().children('span.required').show();
			}
		}
	})
}
