﻿var map;
var geocoder;
var markersArray = [];
var infoWindow;

var mglocator = {


	initialize: function() {
		geocoder = new google.maps.Geocoder();

		var latlng = new google.maps.LatLng(43.5164221, -84.9057943);
		var options = {
			zoom: 5,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};

		map = new google.maps.Map(document.getElementById("map_canvas"), options);

		$("#btnGo").bind("click", mglocator.searchClick);
	},
	searchClick: function(e) {
		e.preventDefault();

		var loc = $.trim($("input[id$='txtStreetAddress']").val() + " " + $("input[id$='txtCityState']").val() + " " + $("input[id$='txtZipCode']").val());

		geocoder.geocode({ address: loc }, mglocator.geocodeCallback);
	},


	geocodeCallback: function(results, status) {
		var radius = $("select[$='ddlRadius'] option:selected").val();
		var type = $("select[id$='ddlDealerType']").val();
		var message = $("#message").html("<p>Searching... Please wait.</p>");

		switch (status) {
			case google.maps.GeocoderStatus.OK:
				map.setCenter(results[0].geometry.location);
				var locData = {
					latitude: results[0].geometry.location.lat(),
					longitude: results[0].geometry.location.lng(),
					radius: radius,
					type: type
				}

				$.ajax({
					type: "POST",
					contentType: "application/json; charset=utf-8",
					url: "/Modules/Services/GoogleService.asmx/GetLocations",
					data: $.toJSON(locData),
					dataType: "json",
					success: mglocator.ajaxCallback
				});
				break;
			default:
				message.html("<p>Geocode was not successful for the following reason: " + status + "</p>");
				break;
		}
	},


	ajaxCallback: function(response) {
		mglocator.deleteOverlays();

		var data = $.evalJSON(response.d);

		var message = $("#message").html("");
		var resultsPane = $("#results-pane").html("<ul></ul>");

		if (data && data.length > 0) {
			if (data.length >= 20) {
				message.append("<p class='results'>Top " + data.length + " closest results found.</p>").effect("highlight", {}, 2000);
			} else {
				message.append("<p class='results'>" + data.length + " results found.</p>").effect("highlight", {}, 2000);
			}

			var bounds = new google.maps.LatLngBounds();

			for (var i = 0; i < data.length; i++) {
				if (i == 0)
					mglocator.addMarker(data[i], true);
				else
					mglocator.addMarker(data[i], false);

				bounds.extend(new google.maps.LatLng(data[i].BgLat, data[i].BgLong));
			}

			map.fitBounds(bounds);
			map.panTo(bounds.getCenter());

			if (map.getZoom() > 15)
				map.setZoom(15);

			mglocator.showOverlays();
		} else {
			message.append("<p class='error'>No results found.  Please expand your search radius.</p>").effect("highlight", { color: 'red' }, 2000);
		}
	},


	addMarker: function(item, first) {
		var point = new google.maps.LatLng(item.BgLat, item.BgLong);

		var marker = new google.maps.Marker({
			position: point,
			map: map,
			title: item.CustomerName
		});

		switch (item.DealerTypeId) {
			case 1: marker.setIcon("http://gmaps-samples.googlecode.com/svn/trunk/markers/red/blank.png"); break;
			default: marker.setIcon("http://gmaps-samples.googlecode.com/svn/trunk/markers/orange/blank.png"); break;
		}

		var fromQuery = escape($("input[id$='txtStreetAddress']").val() + " " + $("input[id$='txtCityState']").val() + " " + $("input[id$='txtZipCode']").val());
		var directionsQuery = escape(item.CustomerName + " " + item.Street + " " + item.City + ", " + item.State + "  " + item.ZipCode);
		var markerHtml = "<div class='bubble-content'>" + "<h5>" + item.CustomerName + "</h5>";
		if (item.DealerTypeId == 3) {
			//1 = Sales, 2 = Repair/Service, 3 = both
			markerHtml += "<i>Sales and Service Location</i><br />";
		}
		else if (item.DealerTypeId == 2) {
			markerHtml += "<i>Service Location</i><br />";
		}
		else {
			markerHtml += "<i>Sales Location</i><br />";
		}
		markerHtml += item.Street + "<br />" +
		item.City + ", " + item.State + "&nbsp;&nbsp;" + item.ZipCode + "<br />";
		if (item.Website != null && item.Website != '') {
			var linkHref = item.Website;
			if (item.Website.indexOf("http://") == -1) {
				linkHref = "http://" + item.Website + "<br />";
			}
			markerHtml += "<a target='_blank' href='" + linkHref + "'>" + item.Website + "</a><br />";
		}
		if (item.Phone != null && item.Phone != '') {
			markerHtml += "p: " + item.Phone + "<br />";
		}
		markerHtml += "<a href='http://maps.google.com/maps?saddr=" + fromQuery + "&daddr=" + directionsQuery + "&hl=en' target='_blank'>Get directions to here.</a><br />";
		markerHtml += "</div>";

		google.maps.event.addListener(marker, "click", function() {
			if (infoWindow) {
				infoWindow.close();
				infoWindow = null;
			}

			infoWindow = new google.maps.InfoWindow({
				'size': new google.maps.Size(292, 120)
			});
			infoWindow.setContent(markerHtml);
			infoWindow.open(map, marker);

			map.panTo(point);
		});

		if (first) {
			$('div#results-pane ul:last').after("<ul>");
		}
		$('div#results-pane ul:last').append("<li>" + markerHtml + "</li>");

		markersArray.push(marker);
	},

	clearOverlays: function() {
		if (markersArray) {
			for (var i in markersArray) {
				markersArray[i].setMap(null);
			}
		}
	},

	showOverlays: function() {
		if (markersArray) {
			for (var i in markersArray) {
				markersArray[i].setMap(map);
			}
		}
	},

	deleteOverlays: function() {
		if (markersArray) {
			for (i in markersArray) {
				markersArray[i].setMap(null);
			}

			markersArray.length = 0;
		}
	}
};

$(document).ready(function() {
	mglocator.initialize();
});

