$(document).ready(function(){
	var MAX_RESULTS = 500;
	var map = new GMap2($("#map").get(0));
	var geocoder = new GClientGeocoder();

	var baseIcon = new GIcon(); 
	baseIcon.image = 'http://eagerbeavertrailers.com/mm_20_red.png';
	baseIcon.iconSize = new GSize(12, 20);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	baseIcon.infoShadowAnchor = new GPoint(18, 25);
	
	// Add controls, position lower on the page
	var mapTypeControl = new GLargeMapControl3D();
	var mapTypeCtr = new GMapTypeControl(true);
	var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10));
	var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
	map.addControl(mapTypeControl, topLeft);
	map.addControl(mapTypeCtr, topRight);
	map.setCenter(new GLatLng(37.09024, -95.712891), 4);

	// Listeners
	GEvent.addListener(map, 'moveend' ,function() {
		updateMarkers(false);
	});

	// Listeners
	$('#finddealer').click(function() {
		if (geocoder) {
			geocoder.getLocations($('#address').val(), addAddressToGMap);
		}
	});
	
	// initial map load
	get_form_values();
	
	function get_form_values() {
		// Only clear all markers when we have to.
		var clear = true;
		updateMarkers(clear);
	}

	//updateMarkers(false,xml_args);

	function updateMarkers(clear) {
		if(clear) map.clearOverlays();

		// map boundaries
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var getVars = 'ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue();

		GDownloadUrl("mapxml.php?"+getVars, function(data) {
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("m");
			var results = markers[0].getAttribute("rows");

			// clear the map if clear=true
			if(clear) map.clearOverlays();

			// check to see if we have too many markers
			if(results >= MAX_RESULTS) {
				map.clearOverlays();
				$('#overlay').html('<h1>Zoom in or change your search options</h1><p>Your current search criteria would display <span class="toomany">'+results+ '</span> results. There is a maximum display limit of <span class="toomany">500 pins</span>. Try narrowing your search options or zooming in.');
				$('#overlay').show();
			} else if(results == 0) {
				map.clearOverlays();
				$('#overlay').html('<h1>No results</h1><p>Your current search criteria or map view has no results returned. Try changing your location or widening your options.');
				$('#overlay').show();
			} else {
				$('#overlay').hide();
				for (var i = 1; i < markers.length; i++) {
					var id = markers[i].getAttribute("id");
					var point = new GLatLng(parseFloat(markers[i].getAttribute("la")), parseFloat(markers[i].getAttribute("lo")));
					var marker = createMarker(point, id);
					map.addOverlay(marker);
				}
			}
		});
	}

	function createMarker(point, id) {

		var marker = new GMarker(point, baseIcon);

		GEvent.addListener(marker, 'click', function() {
			// Get the bubble information dynamically on click
			GDownloadUrl("mapxml.php?id="+id, function(data) {
				var xml = GXml.parse(data);
				var markers = xml.documentElement.getElementsByTagName("m");

				var location_name = markers[0].getAttribute("location_name");
				var address1 = markers[0].getAttribute("address1");
				var phone = markers[0].getAttribute("phone");
				var zip_code = markers[0].getAttribute("zip_code");
				var city = markers[0].getAttribute("city");
				var state = markers[0].getAttribute("state");
				var country = markers[0].getAttribute("country");
				var lat = markers[0].getAttribute("lat");
				var lon = markers[0].getAttribute("lon");
				var email = markers[0].getAttribute("email");
				var website = markers[0].getAttribute("website");

				// create a simple bubble window
				var html = '<div style="padding:5px; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; color:#000000;text-align:left;">';
				html += '<b>' + location_name + "</b> <br/>";
				html += address1 + '<br />';
				html += city +', '+ state + ' ' + zip_code + '<br />';
				html += phone + '<br />';
				if(email != ''){
					html += '<a href="mailto:'+ email +'">' + email + '</a><br />';
				}
				if(website != ''){
					html += '<a href="http://'+ website +'" target="_blank">' + website + '</a><br />';
				}
				html += '</div>';

				var wtf = new GLatLng(37.09024, -95.712891);
				
				//marker.openInfoWindowHtml(marker.getLatLng(), html, {pixelOffset: new GSize(400,400)});
				marker.openInfoWindowHtml(html);
			}); // end GDownloadUrl
		});
		return marker;
	}

	// addAddressToMap() is called when the geocoder returns an
    // answer.  It adds a marker to the map with an open info window
    // showing the nicely formatted version of the address and the country code.
    function addAddressToGMap(response) {
      
      if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to locate the provided address");
      } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
		map.setCenter(point, 6);
      }
    }

	function showAddress(address) {
		if (geocoder) {
			geocoder.getLocations(address, addAddressToGMap);
		}
	}

});
