﻿$(document).ready(function() {


	// Initialize all googleMap DIVs as maps
	$("div.gMap").each(function() {
		var j = $(this);
		var map = this.map = new google.maps.Map2(this);

		// Set map options
		map.disableDoubleClickZoom();

		// Add common regions
		map.auBounds = new google.maps.LatLngBounds(new GLatLng(-46.55886030311717, 112.1484375), new GLatLng(-6.489983332670651, 156.357421875));
		map.auCentre = new google.maps.LatLng(-28.38173504322308, 134.296875);

		if (j.hasClass("gSmallMapControl")) map.addControl(new GSmallMapControl());
		if (j.hasClass("gShowPanZoom")) map.addControl(new GLargeMapControl());
		if (j.hasClass("gAU")) map.setCenter(map.auCentre, 4);
		if (j.hasClass("gScrollWheelZoom")) map.enableScrollWheelZoom();
	});

	var mapFilter = "all";
	var qs = window.location.search.substring(1);
	//Check for a recylce flag in the query string
	if (qs.indexOf("recycle") != -1) {
		mapFilter = "rec";
		$("#filter option[@selected='selected']").removeAttr("selected");
		$("#filter option[@value='rec']").attr("selected", "selected"); ;
	}

	$("#fbmMap").each(function() {
		var map = this.map;
		var stateThreshold = 4;

		// Filter by recycling or platinum
		//mapFilter = "";
		map.filter = function(filter) {
			mapFilter = filter;

			if (this.states) {
				this.clear();
				for (var i = 0; i < this.states.length; i++)
					for (var j = 0; this.states[i].centres.length > j; j++) {
					var centre = this.states[i].centres[j];
					if (mapFilter == "pla" && centre.data.pla) centre.show();
					else if (mapFilter == "rec" && centre.data.rec) centre.show();
					else if (mapFilter == "all") centre.show();
					else centre.hide();
				}
			}
		}

		// Reset the map and hide info windows
		map.clear = function() {
			if (this.directions) this.directions.clear();
			this.closeInfoWindow();
			$("#fbmHow").hide();
			$("#fbmDirections").hide();
			$("#fbmDirectionsTo").hide();
		};
		map.clear();

		// Get an AU configured geocoder object
		map.geocoder = function() {
			var geocoder = new google.maps.ClientGeocoder();
			geocoder.setBaseCountryCode("au");
			//geocoder.setViewport(this.auBounds);
			return geocoder;
		}

		// Show a state or states
		map.showState = function showState(states) {
			// If we're passed a single state then convert it to an array.
			if (!states.length) states = [states];
			// Establish the bounds of the markers
			var bounds = new google.maps.LatLngBounds();
			for (var i = 0; i < states.length; i++)
				if (states[i].centres.length > 0)
				for (var j = 0; j < states[i].centres.length; j++)
				bounds.extend(states[i].centres[j].getPoint());
			var zoom = this.getBoundsZoomLevel(bounds);
			this.clear();
			this.setCenter(bounds.getCenter(), ((zoom > 12) ? 12 : ((zoom < 4) ? 4 : zoom)));

		}

		// Show a specific agent
		map.showAgent = function(marker) {
			this.clear();
			this.setCenter(marker.getPoint(), 14);
			this.marker = marker;
			setTimeout(function() { map.showBalloon(marker); }, 10);
			$("#fbmHow").show();
		}

		// Display a popup balloon for an agent
		map.showBalloon = function(marker) {
			marker.openInfoWindowHtml(this.centreDetails());
		}

		map.centreDetails = function() {
			var data = this.marker.data;
			var info = '<div id="balloon">'
                + '<b>' + data.name + '</b>'
                + '<address>' + data.str + '<br/>' + data.sub + ' ' + data.sta + ' ' + data.pc + '</address>'
                + ((data.pla) ? '<b>Platinum Service Centre</b>' : '')
                + ((data.rec) ? '<br/><b>Recycle Point</b>' : '')
                + '<table>'
                + '<tr><td>Phone</td><td>' + data.phone + '</td></tr>'
                + '<tr><td>Fax</td><td>' + data.fax + '</td></tr>'
                + ((data.hrs) ? '<tr><td>Trading hours</td><td>' + data.hrs + '</td></tr>' : '')
                + ((data.email) ? '<tr><td>Email</td><td><a href="mailto:' + data.email + '">' + data.email + '</a></td></tr>' : '');

			if (data.serv.length > 0) {
				info += '<tr><td>Services</td><td>';
				for (var i = 0; i < data.serv.length; i++) {
					if (i > 0) info += '<br/>';
					switch (data.serv[i]) {
						case 0: info += 'Domestic Cleaners'; break;
						case 1: info += 'Commercial Cleaners'; break;
						case 2: info += 'Central Vacuum Systems'; break;
						case 3: info += 'Small Appliances'; break;
						case 4: info += 'Own Sales Only'; break;
					}
				}
			}

			info += '</td></tr>'
                + '</table>'
                + '</div>';
			return info;
		}

		map.findNearest = function(postcode) {
			map.geocoder().getLatLng(postcode + " Australia",
                function(pointFrom) {
                	var markerTo = null;
                	if (!pointFrom) {
                		alert(postcode + ' not found.');
                	} else {
                		//console.log("finding nearest: " + pointFrom);
                		var closest = 1000000000;
                		var states = map.states;
                		for (var i = 0; i < states.length; i++)
                			for (var j = 0; j < states[i].centres.length; j++)
                			if (states[i].centres[j]) {
                			if ((mapFilter == "pla" && states[i].centres[j].data.pla) || (mapFilter == "rec" && states[i].centres[j].data.rec) || (mapFilter == "all")) {
                				var distance = pointFrom.distanceFrom(states[i].centres[j].getPoint());
                				if (distance < closest) {
                					closest = distance
                					markerTo = states[i].centres[j];
                				}
                			}
                		}
                		map.showAgent(markerTo);
                	}
                }
            );
		}

		map.reset = function() {
			this.clearOverlays();
			var state = null;
			if (this.states && this.states.length > 0)
				for (var i = 0; i < this.states.length; i++) {
				state = this.states[i];
				if (state.centres && state.centres.length > 0)
					for (var j = 0; j < state.centres.length; j++)
					state.centres[j].visible = false;
			}
			this.drawMarkers();
		}

		// As soon as we get above zoom level 5, start a timer to draw the markers.
		google.maps.Event.addListener(map, "moveend", function() {
			if (!this.drawn && this.getZoom() > 4) {
				this.drawn = true;
				setTimeout(function() { map.drawMarkers(0, 0); }, 1);
			}
		});
		map.drawMarkers = function(state, centre) {
			var temp = null;
			for (var i = 0; i < 50; i++) {
				if (centre >= this.states[state].centres.length) {
					centre = 0;
					state++;
				}
				if (state >= this.states.length) return;
				temp = this.states[state].centres[centre];
				this.addOverlay(temp);
				if ((mapFilter == "rec" && !temp.data.rec) || (mapFilter == "pla" && !temp.data.pla)) temp.hide();
				centre++;

			}
			setTimeout(function() { map.drawMarkers(state, centre); }, 1);
		}

		// Marker click handler
		google.maps.Event.addListener(map, "click", function(marker, point) {
			if (marker && marker.data)
				if (marker.data.centres)
				this.showState(marker);
			else
				this.showAgent(marker);
		});

		$("#postcodeGo").click(function() {

//			var maptemp = new GMap2(document.getElementById("fbmMap"));
//			var geocoderTemp = new GClientGeocoder();

//			geocoderTemp.getLatLng("4 ross street, gladeville, sydney, australia",
//			function(point) {
//				if (!point) {
//					alert("address not found");
//				} else {
//					alert(point);
//				}
//			});

			// Get the map
			var postcode = $("#postcode").attr("value");
			map.findNearest(postcode);
			return false;
		});

		// Load and create all the markers
		jQuery.ajax({
			type: 'GET',
			url: '/Include/ServiceCentres.ashx',
			process: 'true',
			dataType: 'json',
			data: window.location.search.substring(1),
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$('#fbmStates tr').empty().append('<th>Error loading service centres: ' + textStatus + '</th>');
			},
			success: function(states) {
				map.states = states;
				$("#fbmStates tr").empty();
				if (states.length > 0) {
					for (var i = 0; i < states.length; i++) {
						var state = states[i];
						if (state.centres.length > 0)
							for (var j = 0; j < state.centres.length; j++) {
							var centre = new google.maps.Marker(
                                    new google.maps.LatLng(state.centres[j].lat, state.centres[j].lng)
                                );
							centre.data = state.centres[j];
							state.centres[j] = centre;
						}
						$("#fbmStates tr").append(
                            $('<td>' + state.name + '</td>').each(function() {
                            	this.state = state;
                            }).click(function() {
                            	map.showState(this.state);
                            })
                        );
					}
					map.showState(states);

				}
				else
					$("#fbmStates tr").append('<th>No locations found.</th>');

				// Process query for parameters
				var param = document.location.search.substring(1).split("&");
				for (var i = 0; i < param.length; i++) {
					var pair = param[i].split("=");
					if (pair.length == 2)
						switch (pair[0].toLowerCase()) {
						case "postcode":
							$("#postcode").attr("value", pair[1]);
							$("#postcodeGo").click();
							break;
					}
				}
			}
		});
	});





	$("#directionsGo").click(function() {
		// Get the map
		var map = null;
		$("#fbmMap").each(function() { map = this.map; });

		var address = $("#address").attr("value") + ", Australia";
		$("#fbmDirections").show();
		$("#fbmDirectionsTo").show();
		$("#fbmAgent").empty().append(map.centreDetails());
		map.geocoder().getLatLng(address,
            function(pointFrom) {
            	if (!pointFrom) {
            		alert(Address() + ' not found');
            	} else {
            		map.closeInfoWindow();
            		if (!map.directions) map.directions = new google.maps.Directions(map, document.getElementById("fbmDirections"));
            		map.directions.clear();
            		map.directions.loadFromWaypoints([pointFrom, map.marker.getPoint()], { locale: "en_AU" });
            	}
            }
        );
		return false;
	});


	$("#filter").change(function() {
		var filter = this.value;
		$("#fbmMap").each(function() { this.map.filter(filter); });
	});

});