$(document).ready(function(){
	var MAX_RESULTS = 500;

	var map = new GMap2($("#map").get(0));
	var logs = $(".logtext");
	var xml_args = '';

	var iconBlue = new GIcon(); 
	iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
	iconBlue.iconSize = new GSize(12, 20);
	iconBlue.shadowSize = new GSize(22, 20);
	iconBlue.iconAnchor = new GPoint(6, 20);
	iconBlue.infoWindowAnchor = new GPoint(5, 1);

	var iconRed = new GIcon(); 
	iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
	iconRed.iconSize = new GSize(12, 20);
	iconRed.shadowSize = new GSize(22, 20);
	iconRed.iconAnchor = new GPoint(6, 20);
	iconRed.infoWindowAnchor = new GPoint(5, 1);

	var customIcons = [];
	customIcons[0] = iconBlue;
	customIcons[1] = iconRed

	// 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(210,10));
	var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(210,10));
	map.addControl(mapTypeControl, topLeft);
	map.addControl(mapTypeCtr, topRight);
	map.setCenter(new GLatLng(40.695, - 74.00), 15);

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

	// Listener for form click actions
	$(':input').change(get_form_values);
	
	// initial map load
	get_form_values();
	
	function get_form_values() {

		// Only clear all markers when we have to.
		var clear = true;
		if (this.name == 'stars' || this.name == 'cost') {
			if(this.checked) {
				clear = false;
			}
		} else if (this.name == 'cp' && !this.checked) {
			clear = false;
		}

		// Bars or Restaurants
		var str_type = $('input[name=type]:checked').val();

		if(str_type == 'rest') {
			// Restaurants
			$('#features-disp-bars').hide();
			$('#features-disp').show();
			$("#cuisine").attr("disabled", false);
			$("input[name=stars]").attr("disabled", false);
			$("input[name=cost]").attr("disabled", false);

			var str_features = '&features=' + $('#features').val();

		} else {
			// Bars
			$('#features-disp-bars').show();
			$('#features-disp').hide();
			$('#cuisine').val('All');
			$("#cuisine").attr("disabled", true);
			$("input[name=stars]").attr("disabled", true);
			$("input[name=cost]").attr("disabled", true);

			var str_features = '&features=' + $('#features-bars').val();

		}

		str_type = 'type=' + str_type;

		// Critric Picks
		if ( $('#cp').attr('checked') )
			var str_cp = '&cp=on';
		else
			var str_cp = '&cp=off';

		var query_string = '';
		var str_stars = '';
		$("#stars input").each(function() {
			if(this.checked)
				query_string += this.value + ',';

			// remove last comma
			if(query_string != '') str_stars = '&stars=' + query_string.substring(0,query_string.length-1);
		});

		var query_string = '';
		var str_cost = '';
		$("#cost input").each(function() {
			if(this.checked)
				query_string += this.value + ',';

			// remove last comma
			if(query_string != '') str_cost = '&cost=' + query_string.substring(0,query_string.length-1);
		});

//		var str_features = '&features=' + $('#features').val();
		var str_cuisine = '&cuisine=' + $('#cuisine').val();

		xml_args = str_type + str_cp + str_cost + str_stars + str_cuisine + str_features;
		updateMarkers(clear,xml_args);
	}

	//updateMarkers(false,xml_args);

	function updateMarkers(clear,xml_args) {

		if(clear) map.clearOverlays();

	 	// setup a logging div
		logs.append('<br>starting update..');

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

		logs.append('<br>zoom is: ' + zoomLevel);
	  	logs.append('<br>center is: ' + mapcenter);
	  	logs.append('<br>string is: <a href="mapxml.php?'+getVars+'">'+getVars+'</a>');

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

			logs.append('<br>markers shown: ' + markers.length);
			logs.append('<br>results returned: ' + results);

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

			// check to see if we have too many markers
			if(results >= MAX_RESULTS) {
				logs.append('<br>Too many 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) {
				logs.append('<br>No results to show');
				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 type = markers[i].getAttribute("cp");
		        		var marker = createMarker(point, type, id);
		        		map.addOverlay(marker);
				}
			}
			$('#resultcount').html(results);
		});
	}

	function createMarker(point, type, id) {

		var marker = new GMarker(point, customIcons[type]);

		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 name = markers[0].getAttribute("name");
				var url = markers[0].getAttribute("url");
				var address = markers[0].getAttribute("address");
				var cost = markers[0].getAttribute("cost");
				var note = markers[0].getAttribute("note");
				var critrating = markers[0].getAttribute("critrating");

				var cr = '<br /><br />Critics\' Rating: ';

				for(var x=1;x<=critrating;x++)
					cr += '&#9733;';

				if (critrating == 0) cr = '';

				// create a simple bubble window
				var html = '<div style="width:250px;">';
				html += '<b>' + name + "</b> <br/>" + address + "</b>";
				html += '<br /><br />' + note;
				html += '<br /><br />Cost: ' + cost;
				html += cr;
				html += '<br/><br><a href="' + url + '" target="_blank" >View on nymag.com</a>';
				html += '<br /><br />';
				html += '</div>';

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

});