// JavaScript Document

$(document).ready(function() { 
	
	// Create the map on the page
	var map = new GMap2(document.getElementById('mapAPI'));
	var gdir = new GDirections(map, document.getElementById("routeResults"));
	var vejerCA = new GLatLng(36.253314, -5.962535);
    map.setCenter(vejerCA, 16);
	map.setUIToDefault();
	
	// Check to find if a URL call has been made
	if (urlItem.type != "none") {
		// Set the marker on the map
		var urlPoint = new GLatLng(urlItem.latitude, urlItem.longitude);
		urlMarker = new GMarker(urlPoint);
		urlMarkerTxt = "<h5>" + urlItem.name + "</h5><h6>" + urlItem.meta + "</h6>";
		GEvent.addListener(urlMarker, "click", function() {
			urlMarker.openInfoWindowHtml(urlMarkerTxt);
		});
		map.addOverlay(urlMarker);
		// Center the map on the marker
		map.setCenter(urlPoint, 16);
		// Add the data to the list
		var urlList = $('<li style="background-image:url(assets/graphics/markers/marker.png)"><h5><a href="#">' + urlItem.name + '</a></h5><h6>' + urlItem.meta + '</h6></li>');
		// Add the click function to the link
		$('a', urlList).click(function(){
			map.panTo(urlMarker.getLatLng());
			map.setZoom(16);
			urlMarker.openInfoWindowHtml(urlMarkerTxt);
			return false;
		});
		// Append the entry to the list
		urlList.appendTo('#categoryResults ol');
	}
	
	// Setup the Business Search Form to run an ajax call to the service
	$('#categorySearch').submit(function(){
		
		// Remove any previous map points, listings and routes
		map.clearOverlays();
		$('#categoryResults ol').html('');
		$('#routeResults').html('');
		$('#routeResults #routeSelect').val(0);
		
		// Get the category selected
		var catSelect = $('#cat', this).val();
		
		// Make the ajax call (return in json format)
		$.getJSON("http://www.vejer.com/services/business.cfc?method=search&returnformat=json&queryformat=column", {categoryID:catSelect}, function(dataCall){
			
			// Init the arrays
			var markers = [];
			var points = [];
			var names = [];
			var addresses = [];
			var markerImages = [];
			var markerNum = 0;
			
			// Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
			var baseIcon = new GIcon(G_DEFAULT_ICON);
			baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			baseIcon.iconSize = new GSize(20, 34);
			baseIcon.shadowSize = new GSize(37, 34);
			baseIcon.iconAnchor = new GPoint(9, 34);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			
			for (var i=0; i < dataCall.ROWCOUNT; i++) {
				if (dataCall.DATA.LATITUDE[i] && dataCall.DATA.LONGITUDE[i]) {
					
					// Create the icon for this marker
					var markerIcon = new GIcon(baseIcon);
					markerNum++;
					var imageFile = "http://www.vejer.com/assets/graphics/markers/marker" + markerNum + ".png";
					markerIcon.image = imageFile;
					markerOptions = { icon:markerIcon };
					
					// Add the marker to the map
					var point = new GLatLng(dataCall.DATA.LATITUDE[i], dataCall.DATA.LONGITUDE[i]);
					marker = new GMarker(point, markerOptions);
					map.addOverlay(marker);
					
					// Save the data to the arrays
					markers.push(marker);
					points.push(point);
					names.push(dataCall.DATA.NAME[i]);
					addresses.push(dataCall.DATA.ADDRESS[i]);
					markerImages.push(imageFile);
				}
			}
			
			// Loop through the marker array created in the previous step
			$(markers).each(function(x,marker){
									 
				// Create the business entry HTML and the info window HTML
				var linkItem = $('<li style="background-image:url(' + markerImages[x] + ')"><h5><a href="#">' + names[x] + '</a></h5><h6>' + addresses[x] + '</h6></li>');
				var infoItem = '<h5>' + names[x] + '</h5><h6>' + addresses[x] + '</h6>';
				
				// Add the click function to the link
				$('a', linkItem).click(function(){
					map.panTo(marker.getLatLng());
					map.setZoom(16);
					marker.openInfoWindowHtml(infoItem);
					return false;
				});
				
				// Append the business entry to the list
				linkItem.appendTo('#categoryResults ol');
				
				// Add the event listener to the marker on the map
				GEvent.addListener(marker, "click", function(){
					map.panTo(marker.getLatLng());
					marker.openInfoWindowHtml(infoItem);
				});
		
			});
			
			if (markers.length) {
				// Zoom the map to show all markers
				var latlngbounds = new GLatLngBounds( );
				for (var y=0; y < points.length; y++ ) {
					latlngbounds.extend(points[y]);
				}
				map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));
			} else {
				// Show a message that no businesses were found
				var noneFoundMsg = $('<li><h5>Sorry, no businesses found</h5></li>');
				noneFoundMsg.appendTo('#categoryResults ol');
			}

		});
		
		return false;
		
	});
	
	// Setup the Route Search Form
	$('#routeSearch').submit(function(){
		// Remove any previous category listings, markers, and set the category option to first (all)
		$('#categoryResults ol').html('');
		$('#categorySearch #cat').val(0);
		map.clearOverlays();
		
		// Get the options selected then run the directions
		var fromCoor = $('#routeSelect', this).val();
		var toCoor = "36.253314, -5.962856";
		var locale = $('#locale', this).val();
		gdir.load("from: " + fromCoor + " to: " + toCoor, { "locale": locale });
		return false;
	});
	
});
