$(function() {
	$("#id_city").attr("disabled","disabled");
	
	$("#id_state").change(
		function(e) {
			if(e.target.value)
			{
				$.ajax({
					url: "/ajax/state/"+e.target.value+"/",
					beforeSend: function() {
						$("#right-col").html('<h2>Searching...</h2><div id="spinner"><img src="/images/searching.gif"></div>');
						countryHtml = $("#country").html();
						$("#country").html(countryHtml);
					},
					complete: function() {

					},
					success: function(data) {
						$("#id_city").html(data);
						if($("#id_city option").length > 1)
						{
							$("#id_city").removeAttr("disabled");
							$("#right-col").html('<h2>Results</h2><p>Please choose a location on the left.</p>');
						}
						else
						{
							$("#id_city").attr("disabled","disabled");
							$("#right-col").html('<h2>No Results</h2><p>Sorry, there are no locations in this state.</p>');
						}
						
					}
				});
			}
			else
			{
				$("#id_city").html('<option selected="selected" value="">Select One</option>');
				$("#id_city").attr("disabled","disabled");
				$("#right-col").html('<h2>Results</h2><p>Please choose a location on the left.</p>');
			}
		}
	);
	
	$("#id_city").change(
		function(e) {
			if(e.target.value)
			{
				$.ajax({
					url: "/ajax/city/"+$("#id_state option:selected").attr("value")+"/"+e.target.value+"/",
					beforeSend: function() {
						$("#right-col").html('<h2>Searching...</h2><div id="spinner"><img src="/images/searching.gif"></div>');
					},
					complete: function() {

					},
					success: function(data) {
						displayPage(data);
					}
				});
			}
			else
			{
				$("#right-col").html('<h2>Results</h2><p>Please choose a location on the left.</p>');
			}
		}
	);
	
	$("#country").change(
		function(e) {
			if(e.target.value)
			{
				$.ajax({
					url: "/ajax/country/"+e.target.value+"/",
					beforeSend: function() {
						$("#right-col").html('<h2>Searching...</h2><div id="spinner"><img src="/images/searching.gif"></div>');
						$("#id_city").html('<option selected="selected" value="">Select One</option>');
						$("#id_city").attr("disabled","disabled");
						stateHtml = $("#id_state").html();
						$("#id_state").html(stateHtml);
					},
					complete: function() {

					},
					success: function(data) {
						displayPage(data);
						
					}
				});
			}
			else
			{
				
				$("#right-col").html('<h2>Results</h2><p>Please choose a location on the left.</p>');
			}
		}
	);

});


function displayPage(data)
{
	$("#right-col").html(data);
	$("#page-nav a").each(function() {
		$(this).click(function(){
			$.ajax({
				url: $(this).attr("href"),
				complete: function() {

				},
				success: function(data) {
					displayPage(data);

				}
			});

			return false;
		});
	});
}
