$(document).ready(function() {

	$('select.countries').change(
		function() {
			var parent = $(this).closest('tbody')[0];
			var states = $(parent).find('select.states');
			var selected_state = states.val();
			var selected_state_field = states.parent().parent();

			var selected_country = $(this).val();

			var blank_top_entry = states.hasClass('blank_top_entry');

			if (selected_country.match(/[0-9]{1,2}/)) {
				$.ajax({
						url: '/profile/get_states', 
						cache: false,
						data: {'country_id': selected_country},
						dataType: 'json',
						success: function(states_array) {
							var html = '';
							if (blank_top_entry) {
								html += '<option value="">---</option>';
							}
							
							if (states_array.length>0) {							
								for (var i = 0; i < states_array.length; i++) {
									var temp = '<option ';
									if (states_array[i]._id == selected_state) {
										temp += 'selected="true" ';
									}
									temp += 'value="' + states_array[i]._id + '">' + states_array[i].name + 
										'</option>\n';
									html += temp;
								}
								states.html(html);
								selected_state_field.show()
							}
							else {
								states.html('<option value="">---</option>');
								states.html(html);
								selected_state_field.hide();
							
							}
						}
					}
				);
			} else if (blank_top_entry) {
				states.html('<option value="">---</option>');
			}

		}
	);

	$('select.countries').change();

});
