// Google Maps for Encorp Collection Sites

var map = null;
var geocoder = null;
var bounds = null;
var http_request = false;
var iconbev = null;
var iconmilk = null;
var iconelec = null;
var iconyou = null;

function loadMap(size) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(53.500000,-124.892578), 5);
		if (size=='sm') {
			map.addControl(new GSmallMapControl());
		} else {
			map.addControl(new GLargeMapControl());
		}
		map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();

		geocoder = new GClientGeocoder();
		geocoder.setBaseCountryCode('CA');

		iconbev = new GIcon();
		iconbev.image = "http://www.encorp.ca/images/encp_map_ri-bev.png";
		iconbev.shadow = "http://www.encorp.ca/images/encp_map_ri-shadow.png";
		iconbev.iconSize = new GSize(40, 40);
		iconbev.shadowSize = new GSize(62, 40);
		iconbev.iconAnchor = new GPoint(21, 40);
		iconbev.infoWindowAnchor = new GPoint(32, 20);
	
		iconmilk = new GIcon();
		iconmilk.image = "http://www.encorp.ca/images/encp_map_ri-milk.png";
		iconmilk.shadow = "http://www.encorp.ca/images/encp_map_ri-shadow.png";
		iconmilk.iconSize = new GSize(40, 40);
		iconmilk.shadowSize = new GSize(62, 40);
		iconmilk.iconAnchor = new GPoint(21, 40);
		iconmilk.infoWindowAnchor = new GPoint(32, 20);
	
		iconelec = new GIcon();
		iconelec.image = "http://www.encorp.ca/images/encp_map_ri-elec.png";
		iconelec.shadow = "http://www.encorp.ca/images/encp_map_ri-shadow.png";
		iconelec.iconSize = new GSize(40, 40);
		iconelec.shadowSize = new GSize(62, 40);
		iconelec.iconAnchor = new GPoint(21, 40);
		iconelec.infoWindowAnchor = new GPoint(32, 20);

		iconyou = new GIcon();
		iconyou.image = "http://www.encorp.ca/images/mm_20_green.png";
		iconyou.shadow = "http://www.encorp.ca/images/mm_20_shadow.png";
		iconyou.iconSize = new GSize(12, 20);
		iconyou.shadowSize = new GSize(22, 20);
		iconyou.iconAnchor = new GPoint(6, 20);
		iconyou.infoWindowAnchor = new GPoint(7, 2);
	}
}

function createMarker(point,mapicon,info) {
	var marker = new GMarker(point,mapicon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(info);
	});
	return marker;
}

function resizeMap() {
	if (GBrowserIsCompatible()) {
		var center = map.getCenter();
		map.checkResize();
		map.panTo(center);
	}
}

function showAddress(address,icontype,info,depotid) {
	if (geocoder) {
		geocoder.getLatLng(
			address + ", BC, Canada",
			function(point) {
				if (!point) {
					alert("Unable to map address:\n" + address + " not found.");
				} else {
					var lat = point.lat();
					var lng = point.lng();
					showGeopoint(lat,lng,15,icontype,info);
					if (depotid) {
						saveGeopoint(depotid,lat,lng);
					}
				}
			}
		);
	}
}

function showGeopoint(lat,lng,zoom,icontype,info) {
	var point = new GLatLng(lat,lng);
	if (!point) {
		alert(address + " not found");
	} else {
		var mapicon = iconbev;
		if (icontype=='elec') {
			mapicon = iconelec;
		} else if (icontype=='milk') {
			mapicon = iconmilk;
		} else if (icontype=='you') {
			mapicon = iconyou;
		}
		map.setCenter(point,zoom);
		map.addOverlay(createMarker(point,mapicon,info));
	}
}

function showUpdateMarker(latid,lngid,zoomid) {
	var lat = document.getElementById(latid).value;
	var lng = document.getElementById(lngid).value;
	var selected = document.getElementById(zoomid).selectedIndex;
	var level = document.getElementById(zoomid)[selected].value;
	point = new GLatLng(lat,lng);

	map.setZoom(level);
	map.panTo(point);

	var marker = new GMarker(point,{draggable: true});
	map.addOverlay(marker);
	GEvent.addListener(marker, "dragend", function() {
		var point = marker.getPoint();
		document.getElementById("lat").value = point.lat();
		document.getElementById("lng").value = point.lng();
	});

}

function getAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
			address + ", BC, Canada",
			function(point) {
				if (!point) {
					alert(address + " not found");
				} else {
					document.getElementById("lat").value = point.lat();
					document.getElementById("lng").value = point.lng();
				}
			}
		);
	}
}

function makePOSTRequest(url,parameters) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = alertContents;
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}

function alertContents() {
	// used mainly for debugging
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			//alert(http_request.responseText);
			//result = http_request.responseText;
			//document.getElementById('myspan').innerHTML = result;				
		} else {
			//alert('There was a problem with the request.');
		}
	}
}

function zoomMap(zoomid) {
	var selected = document.getElementById(zoomid).selectedIndex;
	var level = eval(document.getElementById(zoomid)[selected].value);
	map.setZoom(level);
}

function saveGeopoint(depotid,lat,lng) {
	var poststr = "Latitude=" + lat + "&Longitude=" + lng
	var requrl = "index.cfm?It=902&Id=" + depotid;
	makePOSTRequest(requrl, poststr);
	document.getElementById("lat").value = lat;
	document.getElementById("lng").value = lng;
}

function findNearest(address,sect) {
	if (geocoder) {
		geocoder.getLatLng(
			address + ", BC, Canada",
			function(point) {
				if (!point) {
					alert("Unable to map address:\n" + address + " not found.");
				} else {
					map.clearOverlays();
					bounds = new GLatLngBounds;
					bounds.extend(point);
					var lat = point.lat();
					var lng = point.lng();
					var info = "Your address:<br/>" + address;
					showGeopoint(lat,lng,15,'you',info);
					showNearest(lat,lng,sect);
					map.openInfoWindowHtml(point,info);
				}
			}
		);
	}
}

function showNearest(lat,lng,sect) {
	var urlstr = "index.cfm?It=902&Se=" + sect + "&Sv=nearlookup&Lat=" + lat + "&Lng=" + lng;
	var request = GXmlHttp.create();
	request.open('GET', urlstr , true);	// request XML with AJAX call
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			locations = xmlDoc.documentElement.getElementsByTagName("location");
			markers = [];
			if (locations.length){
				for (var i = 0; i < locations.length; i++) { // cycle thru locations
					var newlat = locations[i].getAttribute("lat");
					var newlng = locations[i].getAttribute("lng");
					var point = new GLatLng(newlat,newlng);
					var sect = locations[i].getAttribute("minsect");
					var info = '<b>' + locations[i].getAttribute("name") + '</b><br/>';
						info = info + locations[i].getAttribute("address") + '<br/>';
						info = info + '<a href="javascript:getDirections(\'' + lat + ',' + lng + ' to ' + newlat + ',' + newlng + '\')">Get Directions</a> | ';
						info = info + '<a href="index.cfm?It=902&Id=' + locations[i].getAttribute("itemid") + '&Se=' + sect + '">Show Details</a> &raquo;';
					var mapicon = iconbev;
					if (sect==40) {
						mapicon = iconelec;
					} else if (sect==39) {
						mapicon = iconmilk;
					}
					map.addOverlay(createMarker(point,mapicon,info));
					bounds.extend(point);
				}
				map.setZoom(map.getBoundsZoomLevel(bounds)-1);
				map.setCenter(bounds.getCenter());
			}
		}
	}
	request.send(null);
}

var directionsPanel;
var directions;

function getDirections(route) {
	directionsPanel = document.getElementById("directions");
	directionsPanel.innerHTML = '';
	if (directions) {
		directions.clear();
	}
	directions = new GDirections(map, directionsPanel);
	directions.load(route);
}
