var map;
var markers;
$(document).ready(function() {
	$("#find-location").dialog({
		autoOpen: false,
		modal: false,
		width: 760,
		height: 476,
		resizable: false,
		open: function(event, ui) {
			if(GBrowserIsCompatible()) {
				markers = [];
				$("#map_sidebar").empty();
				map = new GMap2(document.getElementById("map_pane"));
				map.addControl(new GSmallMapControl());
				map.enableScrollWheelZoom();
				point = new GLatLng(39.30029918615029, -95.888671875);
				zoom  = 3;
				map.setCenter(point, zoom);
			}
			geocoder = new GClientGeocoder();
			geocoder.setCache(null);
			geocoder.getLocations($("#find-location-zip").val(), addressResolved);
		}
	});
	
	$("form[name=find-a-fitclub]").submit(function() {
		var zip = $("#find-location-zip").val();
		if(zip.length) {
			$("#find-location-zip-error").hide();
			$("#find-location").dialog('open');
		} else {
			$("#find-location-zip-error").show();
		}
		return false;
	});
	
	$("form#freeform").live("submit", function() {
		var valid = true;
		if($("input[name=name]").val() == "") {
			valid = false;
			$("input[name=name]")
				.animate({backgroundColor: "#f47621"}, 1000)
				.animate({backgroundColor: "#ffffff"}, 1000);
		}
		if($("input[name=postalcode]").val() == "") {
			valid = false;
			$("input[name=postalcode]")
				.animate({backgroundColor: "#f47621"}, 1000)
				.animate({backgroundColor: "#ffffff"}, 1000);
		}
		if(!$("input[name=email]").val().match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i)) {
			valid = false;
			$("input[name=email]")
				.animate({backgroundColor: "#f47621"}, 1000)
				.animate({backgroundColor: "#ffffff"}, 1000);
		}
	
		return valid;
	});
});

// callback from geocode request
function addressResolved(response) {
	if(!response || !response.Placemark || !response.Placemark[0]) {
		$("#find-location-zip-error").show();
		$("#find-location").dialog('close');
		return;
	}
	var place = response.Placemark[0];
	var lat = place.Point.coordinates[1];
	var lon = place.Point.coordinates[0];
	$.getJSON("/ajax/locations/", {lat: lat, lon: lon}, function(data, status) {
		if(data.length == 0) {
			// $("<div style=\"display: none;\" id=\"no-locations-found\" title=\"No Nearby Locations\"><p>Sorry, no Koko FitClub locations were found near the zipcode you entered.</p></div>").dialog({
			$("body").append("<div id=\"dialog\"></div>");
			$("#dialog").load("/notify/form/", function() {
				$(this).dialog({
					modal: true,
					resizable: false,
					draggable: false,
					width: 400,
					title: "No Koko FitClub Locations Found",
					buttons: {
						"No Thanks": function() { $(this).dialog('close'); },
						"Notify Me": function() {
							$("#freeform").submit();
						}
					},
					open: function() {
						$(this).prepend("<h2>Koko's not there yet...<br />but we hope to be soon!</h2><h3>Fill out the form below and we'll notify you when Koko arrives in your area.</h3>");
						if(place.AddressDetails && 
						   place.AddressDetails.Country && 
						   place.AddressDetails.Country.AdministrativeArea &&
						   place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea &&
						   place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality && 
						   place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) {
							var zip = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
							$("input[name=postalcode]").val(zip);
						}
						$("#freeform").children("input[type=submit]").remove();
						$("#find-location").dialog('close');
					}
				});
			});
			return;
		}
		var bounds = new GLatLngBounds();
		for(i in data) {
			var loc     = data[i];
			var coords  = new GLatLng(loc["latitude"], loc["longitude"]);
			var tmpmark = new GMarker(coords, {title: loc['title']});
			var info = [];
			bounds.extend(coords);
			info.push("<div class=\"infowindow\">");
			if(loc['picture']) {
				info.push("<img src='/images/uploads/"+loc["picture"]+"' style='float: right;' />");
			}
			info.push("<h3>"+loc["title"]+"</h3>");
			info.push("<p>" + loc["address"] + "<br />");
			info.push(loc["city"] + ", " + loc["state"] + " " + loc["zipcode"] + "</p>");
			info.push("<p><strong>Staffed Hours</strong><br />"+loc["staff_hours"]+"<br />");
			info.push("<strong>Members-only Access</strong><br />"+loc["key_access"]+"<br />");
			info.push("<p><a href=\"/signup/"+loc["subdomain"]+"/\">schedule your FREE private demo</a></p>");
			info.push("</div>");
			tmpmark.bindInfoWindowHtml(info.join(""));
			map.addOverlay(tmpmark);
			markers[loc["entry_id"]] = tmpmark;
			$("#map_sidebar").append("<div class=\"map_location\" id=\"location_"+loc["entry_id"]+"\"><strong>"+loc["title"]+"</strong><br />"+parseFloat(loc["distance"]).toFixed(1)+" miles away</div>");
		}
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-1);
		$(".map_location").mouseenter(function() {
			$(this).css("background-color", "#c5c5c5");
		}).mouseleave(function() {
			$(this).css("background-color", "#e1e1e1");
		}).click(function() {
			var entry_id = $(this).attr("id").split("_")[1];
			if(markers[entry_id]) {
				map.panTo(markers[entry_id].getLatLng());
				GEvent.trigger(markers[entry_id], "click");
			}
		});
	});
}