var map;
var markers;
var map_data;
$(document).ready(function() {
	$("#find-location").dialog({
		autoOpen: false,
		modal: false,
		width: 760,
		height: 'auto',
		resizable: true,
		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);
			}
			if($("#find-location-zip:visible").length == 1) {
				geocoder = new GClientGeocoder();
				geocoder.setCache(null);
				geocoder.getLocations($("#find-location-zip").val(), addressResolved);
			} else {
				var bounds = new GLatLngBounds();
				for(i in map_data) {
					var loc     = map_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"] + "<br />");
					info.push(loc["phone"] + "</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"]+"/\">Request Info</a><span style=\"margin: 0 10px;\">|</span><a href=\"/signup/"+loc["subdomain"]+"/\">FREE Session</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 />"+loc["phone"]+"</div>");
				}
				map.setCenter(bounds.getCenter(), Math.min(map.getBoundsZoomLevel(bounds)-1, 16));
				$(".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");
					}
				});
			}
		}
	});
	
	$("#toggle-search-type").click(function() {
		$(this).parent().siblings('div').children('div').toggle('fast');
		if($(this).text() == "Search by state/province") {
			$("#find-location-zip-error").hide();
			$(this).text("Search by zip/postal code");
		} else {
			$("#find-location-state-error").hide();
			$(this).text("Search by state/province");
		}
		return false;
	});
	
	$("form[name=find-a-fitclub]").submit(function() {
		if($("#find-location-zip:visible").length == 1) {
			var zip = $("#find-location-zip").val();
			if(zip.length) {
				$("#find-location-zip-error").hide();
				$("#find-location").dialog('open');
			} else {
				$("#find-location-zip-error").show();
			}
		} else {
			var state = $("#find-location-state").val();
			if(state.length) {
				$("#find-location-state-error").hide();
				$.getJSON("/ajax/locations-state/", {state: state}, function(data, status) {
					if(data.length == 0) {
						$("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...</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();
								}
							});
						});
						return;
					} else {
						map_data = data;
						$("#find-location").dialog('open');
					}
				});
			} else {
				$("#find-location-state-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) {
			$("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...</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"] + "<br />");
			info.push(loc["phone"] + "</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"]+"/\">Request Info</a><span style=\"margin: 0 20px;\">|</span><a href=\"/signup/"+loc["subdomain"]+"/\">FREE Session</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");
			}
		});
	});
}
