﻿var icon;
var map;
var defaultPoints=100;
var mapType = "city";
var infoWindow = "0";
var version = 1;
var default_zoom;
var link = "";


//Multidim array to relate state Abbreviations to name, latitude and longitude

var province_list = new Array();
province_list["AB"]= new Array("Alberta", 55.078, -114.961);  
province_list["BC"]= new Array("British Columbia", 55.974, -124.980);
province_list["MB"]= new Array("Manitoba", 56.365, -97.0313);  
province_list["NB"]= new Array("New Brunswick", 46.9203, -66.0938);  
province_list["NL"]= new Array("Newfoundland and Labrador", 54.0594, -62.1387);  
province_list["NT"]= new Array("Northwest Territories", 63.07487, -113.379);  
province_list["NS"]= new Array("Nova Scotia", 45.0890, -63.8965);  
province_list["NU"]= new Array("Nunavut", 65.1830, -95.8008);  
province_list["ON"]= new Array("Ontario", 51.6180, -87.1875);  
province_list["PE"]= new Array("Prince Edward Island", 46.3773, -63.1055);  
province_list["QC"]= new Array("Quebec", 51.3443, -73.4766);  
province_list["SK"]= new Array("Saskatchewan", 54.3678, -106.1719);  
province_list["YT"]= new Array("Yukon", 64.053, -135.6152);  


var showTestInfo = (getQueryString("td") ) ? true : false;

function initialize(versionId, linkStr) 
	{
	var default_longitude = -101;
	var default_latitude = 62;
	default_zoom = 14;
	version = versionId;
	link = linkStr;
	
	if (GBrowserIsCompatible()) 
		{
		map = new GMap(document.getElementById("map_canvas"));
		map.centerAndZoom(new GPoint(default_longitude,default_latitude), default_zoom);
		geocoder = new GClientGeocoder();
		}
	icon = new GIcon();
	icon.image = "http://filterforgood.ca/images/map_the_pledge/droplet.png";
	icon.shadow = "http://filterforgood.ca/images/map_the_pledge/shadow50.png";
	icon.iconSize = new GSize(20, 34); 
	icon.shadowSize = new GSize(37, 34);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);
	
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());

	showMapBounds(map);
	GEvent.addListener(map, "zoomend", function(oldLevel,newLevel){ 	
													if ((oldLevel == 5) && (newLevel == 6)) {
														map.setZoom(9);
													} else if ((oldLevel == 9) && (newLevel == 8)) {
														map.setZoom(5);
													} else {
														showMapBounds (map);
													}
												} ); 
	}

function showMapBounds (map)
	{
	GEvent.clearListeners(map, "moveend");
	if (map.getZoom() <= 7) {
		mapType = "state";
	} else {
		mapType = "city";
		GEvent.addListener(map, "moveend", function() { if (infoWindow == "0") {
                                                            showMapBounds (map);
                                                    } else {
                                                        infoWindow = "0";
                                                    } } ); 
	}
		
	clearMap();
	var center = map.getCenter();
	
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();

	var lngSpan = northEast.lng() - southWest.lng();
	var latSpan = northEast.lat() - southWest.lat();

	var swLon = southWest.lng();
	var swLat = southWest.lat();
	var neLon = northEast.lng();
	var neLat = northEast.lat();

	var myMessage = "Southwest Lon: " + swLon;
	myMessage += "\n<br />Southwest Lat: " + swLat;
	myMessage += "\n<br /><br />" + "Northeast Lon: " + neLon;
	myMessage += "\n<br />Northeast Lat: " + neLat;
	myMessage += "\n<br /><br />Long Span: " + lngSpan;
	myMessage += "\n<br />Lat Span: " + latSpan;
	if (showTestInfo) { document.getElementById("coords").innerHTML =  myMessage; }
	url  =  "/php/map_the_pledge/getXML.php?swLat="+swLat+"&swLon="+swLon+"&neLat="+neLat+"&neLon="+neLon+"&count="+defaultPoints+"&mapType="+mapType;

	loadXMLDoc(url,mapType);
	}

function loadXMLDoc(url,mapType) 
	{
		
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) 
		{
		req = new XMLHttpRequest();
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
		} 
	// branch for IE/Windows ActiveX version
	else if (window.ActiveXObject) 
		{
		isIE = true;
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) 
			{
			req.onreadystatechange = processReqChange;
 			req.open("GET", url, true);
			req.send();
			}
		}
	}

// handle onreadystatechange event of req object
function processReqChange()
	{
	// only if req shows "loaded"
	if (req.readyState == 4) 
		{
		// only if "OK"
		if (req.status == 200)
			{
			//clearTopicList();
			//buildTopicList();
			buildTopicList();
			} 
		else 
			{
			alert("There was a problem retrieving the XML data:\n" + req.statusText);
			}
		}
	}

function clearMap()
	{
	map.clearOverlays();
	polyPoints = [];
	//document.getElementById("coords").value =  "&lt;-- Click on the map to digitize!";
	} 


// fill Topics select list with items from
// the current XML document
function buildTopicList() 
	{
	var items = req.responseXML.getElementsByTagName("pledge");
	// loop through <item> elements, and add each nested
	// <title> element to Topics select element
	//alert(items.length);
	//var version = 1;
	//version =  req.responseXML.getElementsByTagName("version").nodeValue;
	alertMarkers="";
	var message = "";
	//GEvent.clearInstanceListeners(map);

	if (mapType == "city") {
		for (var i = 0; i < items.length; i++) 
			{
			var lon = getElementTextNS("", "longitude", items[i], 0);
			var lat = getElementTextNS("", "latitude", items[i], 0);
			var city = getElementTextNS("", "city", items[i], 0);
			var province = getElementTextNS("", "state", items[i], 0);
			var bottle_count = getElementTextNS("", "bottle_count", items[i], 0);
			var zipcode = getElementTextNS("", "zipcode", items[i], 0);
			if (version == "1")
			{
				message = "<div class='bubble'><div class=\"bigZip\">" + city + ", " + province + ", " + zipcode + "</div><p>Based on the pledges we've received<br /> so far, an estimated <span class=\"red\">" + bottle_count + "</span> bottles <br />have been saved in this city.</p><p><img src=\"/images/map_the_pledge/bottle.gif\" title=\"Brita.com\" alt=\"Brita.com\" width=\"8\" height=\"20\" border=\"0\" />&nbsp;<a href=\"" + link + "\">Make your pledge today</a>.</p></div>"; 			

			}else{
				
message = "<div class='bubble'><div class=\"bigZip\">" + city + ", " + province + "</div><p>Sur la base des promesses que nous avons reçues<br /> jusqu'à présent, il y a <span class=\"red\">" + bottle_count + "</span> bouteilles <br />en moins";
message = message + "dans cette ville.</p><p><img src=\"/images/map_the_pledge/bottle.gif\" title=\"Brita.com\" alt=\"Brita.com\" width=\"8\" height=\"20\" border=\"0\" />&nbsp;<a href=\"" + link + "\">Faites votre promesse aujourd'hui.</a>.</p></div>"; 			
			}
			if (lat!=0 && lon!=0)
				{	
				var newPoint = new GPoint(lon, lat);
				var newMarker = new GMarker(newPoint, icon);
				newMarker.msg = message;
				map.addOverlay(newMarker);
				GEvent.addListener(newMarker, "click", function() { infoWindow = "1"; this.openInfoWindowHtml(this.msg); });
				}
			}
	} else {
		for (var i = 0; i < items.length; i++) {
			var province = getElementTextNS("", "state", items[i], 0);
			
			if (province_list[province]) {
			
				province_name = province_list[province][0];
				var bottle_count = getElementTextNS("", "bottle_count", items[i], 0);	
				var lat = province_list[province][1]; 
				var lon = province_list[province][2]; 
				
				//var message = "<div class='bubble'><div class=\"bigZip\">" + province_name + "</div><p>Based on the pledges we've received<br /> so far, an estimated <span class=\"red\">" + bottle_count + "</span> bottles <br />have been saved in this region.</p><p><img src=\"images/map_the_pledge/bottle.gif\" title=\"Brita.com\" alt=\"Brita.com\" width=\"8\" height=\"20\" border=\"0\" />&nbsp;<a href=\"take_the_pledge.php\">Make your pledge today</a>.</p></div>"; 
			if (version == "1")
			{
				message = "<div class='bubble'><div class=\"bigZip\">" + province_name + "</div><p>Based on the pledges we've received<br /> so far, an estimated <span class=\"red\">" + bottle_count + "</span> bottles <br />have been saved in this city.</p><p><img src=\"/images/map_the_pledge/bottle.gif\" title=\"Brita.com\" alt=\"Brita.com\" width=\"8\" height=\"20\" border=\"0\" />&nbsp;<a href=\"" + link + "\">Make your pledge today</a>.</p></div>"; 			

			}else{
				
message = "<div class='bubble'><div class=\"bigZip\">" + province_name + "</div><p>Sur la base des promesses que nous avons reçues<br /> jusqu'à présent, il y a <span class=\"red\">" + bottle_count + "</span> bouteilles <br />en moins";
message = message + "dans cette ville.</p><p><img src=\"/images/map_the_pledge/bottle.gif\" title=\"Brita.com\" alt=\"Brita.com\" width=\"8\" height=\"20\" border=\"0\" />&nbsp;<a href=\"" + link + "\">Faites votre promesse aujourd'hui.</a>.</p></div>"; 			
			}
			
				var newPoint = new GPoint(lon, lat);
				var newMarker = new GMarker(newPoint, icon);
				newMarker.msg = message;
				map.addOverlay(newMarker);
				GEvent.addListener(newMarker, "click", function() { this.openInfoWindowHtml(this.msg); });
			}
			
		}
		
	}

	// clear detail display
	alertMarkers = (alertMarkers.length>0) ? alertMarkers : "No Pledges in this view."
	if (showTestInfo) { document.getElementById("pledgePoints").innerHTML =  alertMarkers; }
	}


// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) 
	{
	var result = "";
	if (prefix && isIE)
		{
		// IE/Windows way of handling namespaces
		result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
		} 
	else 
		{
		// the namespace versions of this method 
		// (getElementsByTagNameNS()) operate
		// differently in Safari and Mozilla, but both
		// return value with just local name, provided 
		// there aren't conflicts with non-namespace element
		// names
		result = parentElem.getElementsByTagName(local)[index];
		}
	if (result) 
		{
		// get text, accounting for possible
		// whitespace (carriage return) text nodes 
		if (result.childNodes.length > 1)
			{
			return result.childNodes[1].nodeValue;
			} 
		else 
			{
				/*alert(result.childNodes.length);*/
				if (result.childNodes.length == 1)
				{
					return result.firstChild.nodeValue;
				}		
			}
		} 
	else
		{
		return "n/a";
		}
	}
	

function getQueryString(arg)
	{
	var _d = document.location.toString();
	if(_d.indexOf("?")>0)
		{
		var _e = _d.split("?")[1];
		var _parms = new Array();
		var _valus = new Array();
		// parameters must have a &
		var _f = _e.split("&");
		for(var i=0;i<_f.length;i++) 
			{
			if(_f[i].split("=")[0] == arg)
				{
		  		var qval = _f[i].split("=")[1];
		  		var qval_idx = qval.indexOf("#");
		  		if (qval_idx > -1)  { qval = qval.substring(0, qval_idx); }
				return unescape(qval.replace(/\+/," "));
				}
			}
		}
	return "";
	}


function showAddress(address , versionId)
	{
	mapType = "city";
	address = address + ", CA";
	version = versionId;
	if (geocoder)
		{
		geocoder.getLatLng
			(
			address,
			function(point)
				{
					if (!point) 
					{
					alert(address + " non trouvé");
					}
					else 
					{ 
					map.setCenter(point, 12); 
					}
				}
			);
		}
	}

