$(document).ready(function(){
	directory_populate_state();
	
	$('#zip').val($('#last_zip').val());
	$('#proximity').val($('#last_rad').val());
});

function address_populate_city() {
    var e = $('#city');
    e.empty();
    var state_id = $('select#state option:selected').val();
    if (state_id) {
        $.post('/ajax/get_cities', { 'state_id': state_id, 'course_only': 'true' },
            function(data){
				var count = 0;
				e.append($('<option value="">Optional - You may click now to search</option>'));
                $.each(data.cities, function(index, value) {
					if(value) {
						count++;
						if($('#last_city').val() == value) {
							var selected = ' selected';
						}
						else {
							var selected = '';
						}
	                    e.append($('<option value="' + value + '"' + selected + '>' + value + '</option>'));
					}
                });

				if(count) {
					$('#city_tr').css('display', '');
				}
				else {
					$('#city_tr').css('display', 'none');
					$('#city').val('');
				}

            }, "json");
    }
	else {
		$('#city_tr').css('display', 'none');
		$('#city').val('');
	}
}

function directory_populate_state() {
    var country_id = $('select#country option:selected').val();
    var e = $('#state');


	if($('#country option:selected').text() == 'United States') {
		$('#zip_tr, #or_zip').css('display', '');
		$('#state_td').text('State:');
	}
	else {
		$('#zip_tr, #or_zip').css('display', 'none');
		$('#zip').val('');
		$('#state_td').text('Region/Province:');
	}

    if (country_id) {
        $.post('/ajax/get_states', { 'country_id': country_id, 'course_only': 'true' },
            function(data){
				$('#city_tr').css('display', 'none');
				$('#city').val('');
			    e.empty();
				e.append($('<option value="">Optional - You may click now to search</option>'));
                selected_id = $('#last_state').val();
				var count = 0;
                $.each(data, function(id, name) {
					if(name) {
						count++
	                    var selected = '';
	                    if (id == selected_id) {
	                        selected = ' selected';
	                    }
	                    e.append($('<option value="' + id + '"' + selected + '>' + name + '</option>'));
					}
                });

				if(count) {
					$('#state_tr').css('display', '');
				}
				else {
					$('#state_tr').css('display', 'none');
					$('#state').val('');
				}
				address_populate_city();
            }, "json");
    }
	else {
		$('#state_tr').css('display', 'none');
		$('#state').val('');
		$('#city_tr').css('display', 'none');
		$('#city').val('');
	}
}


