function log(msg) {
    if (window.console && window.console.log) {
        console.log(msg);
    }
}

$(document).ready(function() {
	var loading = $("span.loading-indicator");
	
	loading.show();
	// FIXME: 20090714 - name attribute was left off of original markup and not submitting zip code when entered
	$("#zip").attr("name","data[Territory][zip]");

	//var url = "http://beta.topcondev.com/dealers/getProductLinesList/?jsoncallback=?";
	var url = "http://www.topconsupport.com/dealers/getProductLinesList/?jsoncallback=?";
	$.getJSON(url, function(json) {
		$("#product").empty();
		$("#product").html(json.html);
	});

	var defaultProductLine = "Agriculture";
	
	var ajaxTargetStem;
	//ajaxTargetStem = "http://topconbeta.jtjdev.com";
	ajaxTargetStem = "http://www.topconsupport.com";
	
	var showStates = "";
	var showZips = "";

	// Initialize Map
	var key = $("#apiKey").val();
	//"ABQIAAAAXmM1o7y9YlK-CqEfqFE2kRTeZf3mW9qfFX_sOVwxBUxEFhjOLBRtPQWv4NcLk_EqfokT5Dt7DJwmHA";

	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		var bounds = new GLatLngBounds();
		map.setCenter(new GLatLng(0, 0), 1);
		map.setUIToDefault();
	}
	
	loading.hide();

	// Re-hide form on dealer form change
	$("#dealer-locator-form select").change(function() {
		map.clearOverlays();
		map.setCenter(new GLatLng(0, 0), 1);
		$("#no-dealer-form-wrapper").hide();
		$("div.messaging").empty();
		$("#zip").val("");
		$("#results").html("</p>Please make a selection with the Dealer Locator above.</p>");
	});

	// Populate Country dropdown
	$("select#product").change(function() {
		loading.show();
		var pl = $(this).val();
		var url = ajaxTargetStem + "/dealers/getCountriesFor/"+pl+"/?jsoncallback=?";
		
		$("select#country option").remove();
		
		$.getJSON(url, function(json) {
			var html = "";
			$.each(json.items, function(i, item) {
				html += '<option value="' + item.Region.id + '">' + item.Region.name + '</option>';
			});
			html += '<option value="Other">Other&hellip; </option>';

			showStates = String(json.regionsWithChildren);
			showZips = String(json.regionsWithZips);

			$("#country").append(html);
			$("label#for-state").hide();
			$("label#for-zip").hide();
			loading.hide();
		});
	});

	// Populate State dropdown if needed
	$("select#country").change(function() {
		loading.show();
		var countryId = $(this).val();
		var pl = $("#product").val();
		var url = ajaxTargetStem + "/dealers/getStatesFor/"+pl+"/" + countryId + "/?jsoncallback=?";

		if (showStates.indexOf(countryId) != -1) {
			$("label#for-zip").hide();
			// If country has states, state ID becomes region param
			$(this).attr("name", "");
			$("select#state").attr("name", "data[Territory][region]");
			$("input#zip").val("");

			// Reset dropdown list values (for example, if Australia was selected, then reset for US)
			$("select#state option").remove();

			$.getJSON(url, function(json) {
				var html = "";
				$.each(json.items, function(i, item) {
					html += '<option value="' + item.Region.id + '">' + item.Region.name + '</option>';
				});
				html += '<option value="Other">Other&hellip; </option>';
				$("select#state").append(html);
				$("label#for-state").show();
				
				// Show zip if needed
				if (showZips.indexOf(countryId) != -1) {
					$("label#for-zip").show();
				}
			});
		} else {
			// Reset Country ID as parameter
			$("label#for-state, label#for-zip").hide();
			$("select#state").val("");
			$("select#state").attr("name", "");
			$(this).attr("name", "data[Territory][region]");
		}
		loading.hide();
	});

	// Retrieve Results
	
	/*===========================================================================
		Retrieve Results
	===========================================================================*/
	
	$("#dealer-locator-form ul.form-buttons input").click(function() {
		log("form button clicked");
		getLocatorResults();
		log("form button clicked finished");
		return false;
	});
	
	$("#dealer-locator-form").submit(function() {
		log("form submitted");
		getLocatorResults();
		log("form submitted finished");
		return false;
	});
	
	function getLocatorResults() {
		log("get results");
		loading.show();

		var data = $("#dealer-locator-form").serialize();
		var url;
		url = $("form#dealer-locator-form").attr("action") + "?" + data + "&jsoncallback=?";
		url  = ajaxTargetStem + "/dealers/find/" + "?" + data + "&jsoncallback=?";
		
		function pause(x) {
			var date = new Date();
			var curDate = null;

			do {
				curDate = new Date();
			} while(curDate-date < x);
		}

		$.getJSON(url, function(json) {
			var html = '';

			if (json.items != '') {
				// Can't guarantee what data will exists for each dealer so display only what's provided
				html = '<ul>';
				$.each(json.items, function(i, dealer) {
					pause(150);

					/* ===== Text results ===== */
					html += '<li><ul class="vcard"><li class="fn">';
					if (dealer.website) {
						if (dealer.website.indexOf("http://") == -1) {
							dealer.website = "http://" + dealer.website;
						}
						html += '<a href="' + dealer.website + '" class="url">' + dealer.name + '</a></li>';
					} else {
						html += dealer.name + '</li>';
					}

					if (dealer.address_state_c == null) {
						dealer.address_state_c = dealer.shipping_address_state;
					}

					html += '<li class="adr">';

					if (dealer.address1_c) {
						html += '<span class="street-address">' + dealer.address1_c + " " + dealer.address2_c + '</span><br />';
					}

					html += '<span class="locality">' + dealer.address_city_c + '</span>, <span class="region">' + dealer.address_state_c + '</span> <span class="postal-code">' + dealer.address_zip_postal_c + '</span></li>';

					if (dealer.phone_c) {
						html += '<li class="tel"><span class="type">Phone</span>: <span class="value">' + dealer.phone_c + '</span></li>';
					}

					if (dealer.phone_fax) {
						html += '<li class="tel"><span class="type">Fax</span>: <span class="value">' + dealer.phone_fax + '</span></li>';
					}

					html += '</ul></li><!-- /.vcard -->';

					function createMarker(point,data) {
						var marker = new GMarker(point);
						GEvent.addListener(marker,"click",function() {
							marker.openInfoWindowHtml(data);
						});
					
						map.addOverlay(marker);
					
						return marker;
					}
					
					/* ===== Map results ===== */
					// Needed for map geocoding
					var fullAddress = dealer.address1_c + " " + dealer.address_city_c + " " + dealer.address_state_c + " " + dealer.address_zip_postal_c;
					var str = fullAddress.replace(/ /g,"+");
					var url = 'http://maps.google.com/maps/geo?q=' + str + '&output=json&oe=utf8&sensor=false&key=' + key + '&callback=?';
					$.getJSON(url, {}, (function(i) {
						map.clearOverlays();
						bounds = new GLatLngBounds();
						log("hit url " + url);
					
						return function(mapLocation) {
							log(fullAddress + " " + mapLocation.Status.code + " " + mapLocation.Placemark);
							if (mapLocation.Status.code == 200) {
								// status code 200: OK
								point = new GLatLng(mapLocation.Placemark[0].Point.coordinates[1], mapLocation.Placemark[0].Point.coordinates[0]);
								//var data = $("#results ul > li:eq("+i+")").html();
								var data = "<strong>" + $("#results ul > li:eq("+i+")").find("li.fn").html() + "</strong><br />";
								data += $("#results ul > li:eq("+i+")").find("li.adr").html();
								createMarker(point,data);
					
								// Re-draw the map
								bounds.extend(point);
								map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
								if (json.items.length == 1) {
									map.setZoom(13);
								}
					
							} else if (mapLocation.Status.code == 602 || mapLocation.Status.code == 603) {
								fullAddress = dealer.address_city_c + " " + dealer.address_state_c;
								str = fullAddress.replace(/ /g,"+");
								url = 'http://maps.google.com/maps/geo?q=' + str + '&output=json&oe=utf8&sensor=false&key=' + key + '&callback=?';
					
								$.getJSON(url, {}, (function(i) {
									return function(mapLocation) {
										log("Retry: " + fullAddress + " " + mapLocation.Status.code + " " + mapLocation.Placemark);
										// status code 602 or 603: Unknown address, try with just zipcode
										point = new GLatLng(mapLocation.Placemark[0].Point.coordinates[1], mapLocation.Placemark[0].Point.coordinates[0]);
										var data = $("#results ul > li:eq("+i+")").find("li.adr").html();
										createMarker(point,data);
					
										// Re-draw the map
										bounds.extend(point);
										map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
										if (json.items.length == 1) {
											map.setZoom(13);
										}
									}
								})(i));
							}
						}
					})(i));
				});
				html += '</ul>';
				// Clear results div and add most recent request
				$("#results").empty().append(html);
			 	$("#no-dealer-form-wrapper").hide();
			} else {
				// No results returned, update and display no dealer found form
				map.clearOverlays();
				map.setCenter(new GLatLng(0, 0), 1);
				$("#results").empty();

				var country = $("#dealer-locator-form #country option:selected").text();
				var countryId = $("#dealer-locator-form #country option:selected").val();

				if (showStates.indexOf(countryId) != -1) {
					$(".state_block").show();
					// var state = $("#dealer-locator-form #state option:selected").text();
					// $(".state_block span").text(state);
					// $("input.state_block").val(state);
				} else {
					$(".state_block").hide();
					$("input.state_block").val("");
				}

				if (showZips.indexOf(countryId) != -1) {
					$(".zip_block").show();
					// var zip = $("#dealer-locator-form #zip").val();
					// $(".zip_block input").val(zip);
				} else {
					$(".zip_block").hide();
					$("input.zip_block").val("");
				}

				// Country is always shown
				// $(".country_block span").text(country);
				// $("input.country_block").val(country);

				$("#no-dealer-form-wrapper").show();
			}
			loading.hide();
		});
		return false;
	}
});

// Destroy map
$(window).unload(function() {
	GUnload();
});
