/**
* These bits of javascript are written specifically for the lowKate WP Plugin
* and are an extension of the jQuery library
*/
var lowKate	= {
	searchName: 		"",
	searchLocation:		"",
	searchService:		"",
	apiUrl: 			"/wp-content/plugins/lowKate/js/../api.php",
	map: 				"",
	init: 				function()
	{
		if (GBrowserIsCompatible()) {
			lowKate.map = new GMap2(document.getElementById("lk_map"));
			lowKate.map.setUIToDefault();
			lowKate.map.setCenter(new GLatLng(-33.8676, 131.204), 3); //default to Sydney
		}
		
		this.prepareForm();
		this.showSearchResults();
	},
	prepareForm: 		function()
	{
		var thisForm	= document.getElementById('LK_searchForm');
		thisForm.setAttribute('action', 'javascript:lowKate.showSearchResults()');
	},
	getSearchUrl:	 	function()
	{
		if (document.getElementById('LK_searchName')) lowKate.searchName		= document.getElementById('LK_searchName').value;
		if (document.getElementById('LK_searchLocation')) lowKate.searchLocation	= document.getElementById('LK_searchLocation').value;
		if (document.getElementById('LK_searchService')) lowKate.searchService		= document.getElementById('LK_searchService').value;
		
		var qs = '';
		if (lowKate.searchName != ''){
			qs = 'searchName='+ encodeURIComponent( lowKate.searchName ) + ((qs != "") ? '&'+qs : "");
		}
		if (lowKate.searchService != ''){
			qs = 'searchService=' + encodeURIComponent( lowKate.searchService ) + ((qs != "") ? '&'+qs : "");
		}
		
		return this.apiUrl + ((qs != "") ? '?'+qs : "");
	},
	showSearchResults: 	function()
	{
		if (! GBrowserIsCompatible()) {
			return false;
		}
		
		if (document.getElementById('LK_searchName')) lowKate.searchName		= document.getElementById('LK_searchName').value;
		if (document.getElementById('LK_searchLocation')) lowKate.searchLocation	= document.getElementById('LK_searchLocation').value;
		if (document.getElementById('LK_searchService')) lowKate.searchService		= document.getElementById('LK_searchService').value;
		
			
		if (lowKate.searchLocation != ''){
			var geocoder = new GClientGeocoder();
			geocoder.setBaseCountryCode('au');
			geocoder.getLocations(
			    lowKate.searchLocation,
				function(response) {
					if (!response || response.Status.code != 200) {
						alert("\"" + address + "\" not found");
					} else {
						place = response.Placemark[0];
					    point = new GLatLng(place.Point.coordinates[1],
					                        place.Point.coordinates[0]);
					    
						lowKate.map.setCenter( point, (place.AddressDetails.Accuracy * 3) );
					}
			  	}
			);
			
		}
		
		// remove the old overlays
		lowKate.map.clearOverlays();
		
		GDownloadUrl( this.getSearchUrl(), function(data, responseCode) {
			var xml 	= GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");
			
			var allLat = [];
			var allLng = [];
			
			for (var i = 0; i < markers.length; i++) {
				if (parseFloat(markers[i].getAttribute("lng")) == 0 && parseFloat(markers[i].getAttribute("lat")) == 0) continue;

				allLat.push( parseFloat(markers[i].getAttribute("lng")) );
				allLng.push( parseFloat(markers[i].getAttribute("lat")) ); 
				
				var point = new GLatLng(parseFloat(markers[i].getAttribute("lng")),
										parseFloat(markers[i].getAttribute("lat")) );
										
				marker	= new GMarker(point);
				lowKate.map.addOverlay(marker);
				
				var contentString = "<div class='mapPopup "+markers[i].getAttribute("services").split(",").join(" ")+"'>";
				if (markers[i].getAttribute("name") != ''){
					contentString += "<h1>"+markers[i].getAttribute("name")+"</h1>";
				}
				if (markers[i].getAttribute("address") != ''){
					contentString += "<address>"+markers[i].getAttribute("address").split(",").join("<br/>")+"</address>";
				}
				if (markers[i].getAttribute("phone") != ''){
					contentString += "<p class='phone'><strong>Ph:</strong> "+markers[i].getAttribute("phone")+"</p>";
				}
				if (markers[i].getAttribute("website") != 'http://'){
					contentString += "<p><a href='"+markers[i].getAttribute("website")+"'>"+markers[i].getAttribute("website")+"</a></p>";
				}
				if (markers[i].getAttribute("services") != ''){
					contentString += "<p class='services'><strong>Services:</strong> "+markers[i].getAttribute("services")+"</p>";
				}

				contentString += "<p><a href='http://www.google.com/maps?f=q&hl=en&q=" + escape("to:" + markers[i].getAttribute("address")) + "' target='_blank'>Get directions</a></p>";

				contentString += "</div>";
				
				lowKate.createMarker(marker, contentString );
			}
			
			
			if (allLat.length > 0 && lowKate.searchLocation == '') {
				var mapCentre = lowKate.calcMapCentre(allLat, allLng);
				lowKate.map.setCenter( new GLatLng(mapCentre.midLat, mapCentre.midLng), Math.min(mapCentre.zoom, 14));
			}
		});
	},
	createMarker: 		function(marker,content)
	{
		GEvent.addListener(marker, 'click', function() {
	      marker.openInfoWindowHtml(content);
	    });
	},
	calcMapCentre: 	function(allLat,allLng)
	{
		var minLat	= '';
		var minLng	= '';
		
		var maxLat	= '';
		var maxLng	= '';
		
		var thisLat, thisLong, i;

		for (i in allLat){
			thisLat = allLat[i];
			if ((minLat == '') || (thisLat < minLat)){
				minLat	= thisLat;
			}
			
			if ((maxLat == '') || (thisLat > maxLat)){
				maxLat	= thisLat;
			}
		}
		
		for (i in allLng){
			thisLng = allLng[i];
			if ((minLng == '') || (thisLng < minLng)){
				minLng	= thisLng;
			}
			
			if ((maxLng == '') || (thisLng > maxLng)){
				maxLng	= thisLng;
			}
		}
		
		var swPoint = new GLatLng(minLat,
									minLng);
		
		var nePoint = new GLatLng(maxLat,
									maxLng);
									

		return {midLat:(maxLat - minLat)/2+minLat, midLng:(maxLng - minLng)/2+minLng, zoom:lowKate.map.getBoundsZoomLevel( new GLatLngBounds(swPoint, nePoint) )};
	}
};

$().ready(function() {
	lowKate.init();
});
