/*
 * Copyright 2007 Alan Schneider (alan AT dashmaps <dot> com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");  you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by 
 * applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
 * KIND, either express or implied. See the License for the specific language 
 * governing permissions and limitations under the License.
 *
 */

var gSMA = new Array(); // Search marker array
var gCGC = new GClientGeocoder();

var gMarkers	  = [];
var gMarkersIdx  = 0;
var gSidebarHtml = "";

var gCity = "";
var gCityURL = "";


// Create a new, round icon.  Size must be mod 2
//
function ni(iconFilename, iconSize) {
	var icon = new GIcon();
	icon.image				= iconFilename;
	icon.iconSize			= new GSize(iconSize, iconSize);
	icon.iconAnchor		 = new GPoint(iconSize/2, iconSize/2);
	icon.shadowSize		 = new GSize(0, 0);
	icon.infoShadowAnchor = new GPoint(0, 0);
	icon.infoWindowAnchor = new GPoint(0, 0);
	return icon;
}

// Process parameters in the URL.  Currently, this only supports 
// an address search function.
//
// Parameters supported:
//
//	srch
//	--------------------------------------------------------------------------
//	Description - Plot a marker for a given address.
//	Usage		 - ?srch=<street, city, state>
//	Example	  - ?srch=32%20Academy%20Hill%20road,%20boston,%20ma
//	
function procparam() {
	var srch	 = "";
	var query = location.search.substring(1); // skip the first character, we are not interested in the "?"
	var pairs = query.split("&"); // split at each ampersand to give a list of  "argname=value" pairs

	for(var i=0; i<pairs.length; i++) {
		// break each pair at the first "=" to obtain the argname and value
		var pos	   = pairs[i].indexOf("=");
		var argname = pairs[i].substring(0,pos).toLowerCase();
		var val	   = pairs[i].substring(pos+1).toLowerCase();

		// We only process a search address string
		//
		if (argname == "srch") { 
			srch = val; 
         posn = srch.indexOf("%20");
         while(posn > -1) {
            srch = srch.substring(0,posn) + " " + srch.substring(posn+3);
            posn = srch.indexOf("%20");
         }
		}
	}
	
	if(srch != "") dosrch(srch);

}

// Search for an address.  Called when a user types in
// an address in the search text box and hits "Mark"
//
function sa() {
	var s = document.getElementById("search").value;
	dosrch(s);
}

// Searches for a given address and plots a marker for said address, if it exists.
//
function dosrch(srch) {
	var reasons=[];
	reasons[G_GEO_SUCCESS]				  = "Success";
	reasons[G_GEO_MISSING_ADDRESS]	  = "The address field is empty!";
	reasons[G_GEO_UNKNOWN_ADDRESS]	  = "Sorry - Couldn't find the address :(";
	reasons[G_GEO_UNAVAILABLE_ADDRESS] = "The given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]				  = "Bad Key!";
	reasons[G_GEO_TOO_MANY_QUERIES]	  = "Sorry - The daily geocoding quota for this site has been exceeded :0  Try again tomorrow...";
	reasons[G_GEO_SERVER_ERROR]		  = "Server error >=0";
	
	gCGC.getLocations(srch, 
		function (result) { 
			if (result.Status.code == G_GEO_SUCCESS) {
				// Loop through the results, placing markers
				//
				for (var i=0; i<result.Placemark.length; i++) {
					var p		        = result.Placemark[i].Point.coordinates;
               var ll           = new GLatLng(p[1],p[0]);
					var marker       = new PdMarker(ll);
               var title        = "<b>" + srch + "</b>";
               var urlSearchStr = gCityURL + "?srch=" + srch.replace(/ /g, "%20");
               var info         = title + "<br><a href=" + urlSearchStr + ">Link</a>";

               marker.setTooltip(title);
					marker.setOpacity(0);
			 
					// Dirty hack to get the marker to show up in 2.63+ gmap api...
					//
					GEvent.addListener(marker, "mouseover", function() { }); 
					GEvent.addListener(marker, "mouseout",  function() { }); 

            	GEvent.addListener(marker, "click", function() {
            		map.openInfoWindowHtml(ll, info);
	            });

					map.addOverlay(marker);
					gSMA.push(marker);
				}
	
				var p = result.Placemark[0].Point.coordinates;
				map.setCenter(new GLatLng(p[1],p[0]));
			}
			else {
				var reason="Code "+result.Status.code;
				if (reasons[result.Status.code]) {
					reason = reasons[result.Status.code]
				} 
				alert(reason);
			}
	});
}

// Clear the address search markers.  Called when a user
// types in an address in the search text box and hits "Clear"
//
function cm() {
	for(var i = gSMA.length - 1; i >= 0; --i) {
		var m = gSMA.pop();
		map.removeOverlay(m);
		m = null;
	}
}


// HTML Sidebar
//
var gStations = new Array();
var gSidebarHtmlArr = [];

function addToSidebar(marker, station_name) {
	gMarkers[gMarkersIdx] = marker;
 //  gSidebarHtml += '<a href="javascript:sidebarClick(' + gMarkersIdx + ')">' + station_name + '</a><br>';
	gStations[gMarkersIdx] = station_name;
	gSidebarHtmlArr[station_name] = '<a href="javascript:sidebarClick(' + gMarkersIdx + ')">' + station_name + '</a><br>';

	++gMarkersIdx;
	
}

function sidebarClick(i) {
	GEvent.trigger(gMarkers[i], "click");
}

function addSidebar() {
	var sortedStations = gStations.sort();

	for(var i = 0; i < sortedStations.length; ++i) {
		gSidebarHtml += gSidebarHtmlArr[sortedStations[i]];
	}

	document.getElementById("mapSidebar").innerHTML = gSidebarHtml;

}


// Metro points
//
function MPT(station_name, website, lat, lng, metroIcon) {
	this.name_			  = station_name;
	if(website != "")
		this.title_	= "<a href=\"" + website + "\"><b>" + this.name_ + "</b></a>";
	else
		this.title_	= "<b>" + this.name_ +"</b>";
	this.addr_		    = "";
	this.marker_info_	 = "";
	this.lat_		    = lat;
	this.lng_	       = lng;
	this.icon_			 = metroIcon;
	this.mli_			 = "";
	this.mlt_			 = "";
	this.notes_			 = "";
}

MPT.prototype.addAddr = function(addr) {
	this.addr_ += addr + "<br/>";
}

MPT.prototype.addNotes = function(notes) {
	this.notes_ += notes + "<br/>";
}

// Add metro line image
//
MPT.prototype.addMLI = function(imgSrc) {
	this.mli_ += "<img src=\"" + imgSrc + "\">&nbsp;";
}

// Add metro line text
//
MPT.prototype.addMLT = function(txt) {
	this.mlt_ += txt;
}

MPT.prototype.draw = function(map) {
	var ll		= new GLatLng(this.lat_, this.lng_);
	var marker  = new PdMarker(ll, {icon:this.icon_});
	var info	 = this.title_ + "&nbsp;" + this.mli_;
	if(this.mlt_ != "") {
		info += this.mlt_ + "<br><br>";
	}
	if(this.addr_ != "") {
		info += "<br/><br/><b>Address</b><br/><br/>";
		info += this.addr_;
	}
	if(this.notes_ != "") {
		info += "<br/><b>Notes</b><br/><br/>";
		info += this.notes_;
	}

	marker.setTooltip("<b>" + this.name_ + "</b>&nbsp;" + this.mli_ + this.mlt_ + "<br/><br/>"+this.notes_);
	marker.setOpacity(0);

	// Dirty hack to get the marker to show up in 2.63+ gmap api...
	//
	GEvent.addListener(marker, "mouseover", function() { }); 
	GEvent.addListener(marker, "mouseout",  function() { }); 
		
	GEvent.addListener(marker, "click", function() {
		map.openInfoWindowHtml(ll, info);
	});
	addToSidebar(marker, this.name_);
	map.addOverlay(marker);
}


GPolygon.prototype.Contains = function(point) {
	var j		  = 0;
	var oddNodes = false;
	var x		  = point.lng();
	var y		  = point.lat();
	
	for (var i=0; i < this.getVertexCount(); i++) {
      j++;
      if(j == this.getVertexCount()) 
         j = 0;
	
      if(((this.getVertex(i).lat() < y) && (this.getVertex(j).lat() >= y)) || 
			((this.getVertex(j).lat() < y) && (this.getVertex(i).lat() >= y)))
      {
         if(this.getVertex(i).lng() + (y - this.getVertex(i).lat()) / 
           (this.getVertex(j).lat() - this.getVertex(i).lat())	  * 
           (this.getVertex(j).lng() - this.getVertex(i).lng()) < x ) 
	      {
			  oddNodes = !oddNodes
		   }
      }
   }
	return oddNodes;
}

GPolyline.prototype.Contains = GPolygon.prototype.Contains;

var px1 = new GIcon();
px1.image				= "images/1px.png";
px1.iconSize			= new GSize(1, 1);
px1.iconAnchor		   = new GPoint(1, 1);
px1.shadowSize		   = new GSize(0, 0);
px1.infoShadowAnchor = new GPoint(0, 0);
px1.infoWindowAnchor = new GPoint(0, 0);
	
// Metro polygons
//
function MPLYG(station_name, website, points) {
	this.name_			  = station_name;
	if(website != "")
		this.title_	= "<a href=\"" + website + "\"><b>" + this.name_ + "</b></a>";
	else
		this.title_	= "<b>" + this.name_ +"</b>";
	this.addr_			   = "";
	this.marker_info_	   = "";
	this.mli_				= "";
	this.mlt_				= "";
	this.notes_			   = "";
	this.points_			= points;
}

MPLYG.prototype.addAddr = function(addr) {
	this.addr_ += addr + "<br/>";
}

MPLYG.prototype.addNotes = function(notes) {
	this.notes_ += notes + "<br/>";
}

// Add metro line image
//
MPLYG.prototype.addMLI = function(imgSrc) {
	this.mli_ += "<img src=\"" + imgSrc + "\">&nbsp;";
}

// Add metro line text
//
MPLYG.prototype.addMLT = function(txt) {
	this.mlt_ += txt;
}

MPLYG.prototype.draw = function(map) {
	var plyg	 = new GPolygon(this.points_, "#000000", 2, 1, "#FFFFFF", 1);
	var marker  = new PdMarker(this.points_[0], {icon:px1});
	var info	 = this.title_ + "&nbsp;" + this.mli_;
	
	if(this.mlt_ != "") {
		info += this.mlt_ + "<br><br>";
	}
	if(this.addr_ != "") {
		info += "<br/><br/><b>Address</b><br/><br/>";
		info += this.addr_;
	}
	if(this.notes_ != "") {
		info += "<br/><b>Notes</b><br/><br/>";
		info += this.notes_;
	}

	marker.setTooltip("<b>" + this.name_ + "</b>&nbsp;" + this.mli_ + this.mlt_ + "<br/><br/>"+this.notes_);
	marker.setOpacity(0);

	
	// Dirty hack to get the marker to show up in 2.63+ gmap api...
	//
	GEvent.addListener(marker, "mouseover", function() { }); 
	GEvent.addListener(marker, "mouseout",  function() { }); 

	GEvent.addListener(map, "mousemove", function (p) {
		if (plyg.Contains(p))  marker.showTooltip();
		else						 marker.hideTooltip();
	});

	GEvent.addListener(map, "click", function(overlay,point) {
	  if (point) {
		 if (plyg.Contains(point))
	  map.openInfoWindowHtml(point, info);
	  }
	});
	map.addOverlay(plyg);
	map.addOverlay(marker);
}


// Write head section of document.  NOTE: this will also set the global city variable
// c  - city
// di - base directory
//
function wh(c, di) {
/*
	var d = document;
	d.write('<script src="http://www.google.com/uds/solutions/mapsearch/gsmapsearch.js" type="text/javascript"></script>');
	d.write('<meta http-equiv="content-type" content="text/html; charset=utf-8"/>');
	d.write('<title>dashmaps/' + c + '</title>');
	d.write('<link rel="stylesheet" type="text/css" href="' + di + 'style/main.css"/>');
	d.write('<script src="m.js" type="text/javascript"></script>');
*/
   gCity = c;
   gCityURL = "http://www.dashmaps.com/" + gCity;
}

// Write page.  
// s  - suffix of 'city, state'
// di - base directory.
//
function wp(s, di) {
	var d = document;
/*
	d.write('<body onload="l()" onunload="GUnload()">');
	d.write('<img href="http://www.google.com/mapfiles/marker.png" style="display:none">');
	d.write('<img href="http://www.google.com/mapfiles/shadow50.png" style="display:none">');
	d.write('<img href="http://www.google.com/mapfiles/markerTransparent.png" style="display:none">');
	d.write('<img href="http://www.google.com/mapfiles/markerie.gif" style="display:none">');
	d.write('<img href="http://www.google.com/mapfiles/dithshadow.gif" style="display:none">');
	d.write('<img href="' + di + 'images/mb16.png" style="display:none">');
	d.write('<img href="' + di + 'images/mb32.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg16.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg16b.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg16c.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg16d.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg16e.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg32.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg32b.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg32c.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg32d.png" style="display:none">');
	d.write('<img href="' + di + 'images/mg32e.png" style="display:none">');
	d.write('<img href="' + di + 'images/mo16.png" style="display:none">');
	d.write('<img href="' + di + 'images/mo32.png" style="display:none">');
	d.write('<img href="' + di + 'images/mr16.png" style="display:none">');
	d.write('<img href="' + di + 'images/mr32.png" style="display:none">');
	d.write('<img href="' + di + 'images/ms16.png" style="display:none">');
	d.write('<img href="' + di + 'images/ms32.png" style="display:none">');
	d.write('<img href="' + di + 'images/mw16.png" style="display:none">');
	d.write('<img href="' + di + 'images/mw28.png" style="display:none">');
	d.write('<img href="' + di + 'images/mw32.png" style="display:none">');
	d.write('<img href="' + di + 'images/my16.png" style="display:none">');
	d.write('<img href="' + di + 'images/my32.png" style="display:none">');
	d.write('<div id="dmaps_top_toolbar" class="yuimenubar">');
	d.write('<div class="bd">');
	d.write('<ul class="first-of-type"><li class="yuimenubaritem first-of-type"><a href="' + di + '">dashmaps</a></li>');
	d.write('<li class="yuimenubaritem">other cities</a></li>');
	d.write('</ul></div></div>');

	d.write('<div id="map"></div>');
	d.write('<div id="mapSidebar"></div>');

	d.write('<div id="mapSearch">');
	d.write('<form name="frmSearch" onsubmit="sa(); return false">');
	d.write('<input id="search" size="60" type="text" value="<replace with address>, ' + s + '"/>');
	d.write('<input type="submit" value="Mark" name="x" class="btn"');
	d.write('onMouseOver="goLite(this.form.name,this.name)"');
	d.write('onMouseOut="goDim(this.form.name,this.name)">');
	d.write('<input type="button" value="Clear" name="y" class="btn"');
	d.write('onclick="cm();return false"');
	d.write('onMouseOver="goLite(this.form.name,this.name)"');
	d.write('onMouseOut="goDim(this.form.name,this.name)"><br>');
	d.write('<b style="color:#FFF000;">Note:</b> <i style="color:#FFF000;">You can submit multiple addresses</i><br>');
	d.write('</form>');
	d.write('</div>');

	d.write('<div id="digg">');
	d.write('<script type="text/javascript">');
	d.write('digg_url="http://www.dashmaps.com";');
	d.write('digg_bgcolor="#7a8c9d";');
	d.write('digg_skin="compact";');
	d.write('</script>');
	d.write('<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script>');

	d.write('</body>');
	d.write('<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">');
	d.write('</script>');
	d.write('<script type="text/javascript">');
	d.write('_uacct = "UA-1221817-1";');
	d.write('urchinTracker();');
	d.write('</script>');
	d.write('</div>');
*/
}

// Toggle the color of "Mark" and "Clear" buttons
//
function goLite(FRM,BTN) {
	window.document.forms[FRM].elements[BTN].style.backgroundColor = "#00FFFF";
}
function goDim(FRM,BTN){
	window.document.forms[FRM].elements[BTN].style.backgroundColor = "#00CCFF";
}

