/*
Lake Washington School District
School Map Using Microsoft Virtual Earth
By: Josiah Mault
jamault@pioneernet.net
10/31/2007
*/


var map = null;
var pinTitleGbl = null;
var addrInput = null;
var polygon = new Array();
var marker = new Array();
var boundary = new Array();;
var control = null;
var directionType = null;
var iconFile;
var iconOther = '../PublishingImages/iconOther.gif';
var iconStar = '../PublishingImages/iconStar.gif';
var useUrl = 0;
var mapType = null;

var URLvariable = getUrlVars();

// Read a page's GET URL variables and return them as an associative array.
//http://snipplr.com/view/799/get-url-variables/
function getUrlVars(){
	if (window.location.href.indexOf('?') != -1){
		var vars = [];
		var URL = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&&');
		useUrl = 1;
		for(var i = 0; i < URL.length; i++)    {
			URLvariable = URL[i].split('=');
			vars.push(URLvariable[0]); //get variable name
			vars[URLvariable[0]] = URLvariable[1].replace(/%20/g," "); //set variable and replace %20 with space
		}
		return vars;
		} else {
		return 0;}
	}
	
function getSelectedSchool() {
    var school = document.getElementById('selectSchool').value;
  if (school != 'null') {
  	var currentURL = window.location.href;
  	if (window.location.href.indexOf('?') != -1){
			var replaceTXT = currentURL.slice(currentURL.indexOf('?'));
  		currentURL = currentURL.replace(replaceTXT,"");
  	}
	  window.location.href = currentURL + '?' + school;
  }
}
  
function GetMap(mapType) {
	if (('undefined' != typeof URLvariable['mapType']) && (useUrl == 1)) {
		mapType = URLvariable['mapType'];
	}

	map = new VEMap('myMap');
	map.SetDashboardSize('small');
	map.LoadMap(new VELatLong(47.674167,-122.12027), 11, 'r', false, VEMapMode.Mode2D, false);
	createLayer(VEDataType.GeoRSS,mapType);

	map.AttachEvent("onmouseover",ShapeMouseOverHandler);
	map.AttachEvent("onmouseout",ShapeMouseOutHandler);
	map.AttachEvent("onclick",  mapclicked);

	if (('undefined' != typeof URLvariable['school']) && (useUrl == 1)) {
		checkMarker();
		useUrl = 0;
		} else { useUrl = 0; };

		mapTitle(mapType);
}

function checkMarker() {
	if ('undefined' == typeof marker[0]) {
		setTimeout("checkMarker()",1000);
		} else {
			showSchool();
		}
	}

function showSchool() {
	for (i=0; i<marker.length; i++) {
		var schoolName = URLvariable['school'];

		if ( marker[i][0] == schoolName ){
			var pinIDx=[];
			pin = map.GetShapeByID(marker[i][1]);
			pinIDx = new Array(pin.GetID());
		}
	}
	var j = 0;
	for (i=0; i<polygon.length; i++) {
		if ( polygon[i][0] == pin.GetTitle() ){
			boundary[j] = map.GetShapeByID(polygon[i][1])
			boundary[j].SetFillColor(new VEColor(0, 0, 255, 0.1));
			j++;
		}
	}
	map.SetCenterAndZoom(pin.GetIconAnchor(), 13); //zoom map in and set center using ancohor lat long value
	var boxID = map.GetShapeByID(pinIDx[0]);
	setTimeout(function(){map.ShowInfoBox(boxID,map.GetCenter());},1000);
}

function createLayer(layerType,mapType) {
	if (mapType == 'Jr') {
		mapFilePins = '../MapFiles/jrSchool.xml';
		mapFileBoundary = '../MapFiles/jrSchoolBoundary.xml';
		iconFile = '../PublishingImages/iconJR.gif';
		} else if (mapType == 'HS') {
			mapFilePins = '../MapFiles/hsSchool.xml';
			mapFileBoundary = '../MapFiles/hsSchoolBoundary.xml';
			iconFile = '../PublishingImages/iconHS.gif';
		} else if (mapType == 'Other') {
			mapFilePins = '../MapFiles/other.xml';
			mapFileBoundary = '../MapFiles/otherBoundary.xml';
			iconFile = iconOther;
			} else {
				mapFilePins = '../MapFiles/elSchool.xml';
				mapFileBoundary = '../MapFiles/elSchoolBoundary.xml';
				iconFile = '../PublishingImages/iconEL.gif';
			}

			var pinLayer = new VEShapeLayer();
			var veLayerSpec = new VEShapeSourceSpecification(layerType, mapFilePins, pinLayer);

			var boundaryLayer = new VEShapeLayer();
			var veLayerSpecBoundary = new VEShapeSourceSpecification(layerType, mapFileBoundary, boundaryLayer);


			map.ImportShapeLayerData(veLayerSpec,onFeedLoad);
			map.ImportShapeLayerData(veLayerSpecBoundary,onFeedLoadBoundary);
}

function tohere(lat, long, pinID, pinTitle, pinDescription) {
	directionType = 'TO';
	var routeTo = '<br><br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + lat + ',' + long + ',' + "'" + pinID + "'" + ",'" + pinTitle + "','" + pinDescription + "'" +')">From here</a>' +
	'<br>Start address:' +
	'<table width="160" border="0" cellspacing="2" cellpadding="0"><tr><td width="125"><input type="text" size=20 maxlength=100 name="Addr" id="Addr" value="" /></td>' +
	'<td width="35"><a href="javascript:routeDirections(' + lat + ',' + long + ',' + "'" + pinTitle + "'" + ');"><img src="../PublishingImages/arrow_blue_on_white.gif" width="25" height="25" border="0" onmouseover="this.src=\'../PublishingImages/arrow_yellow_on_white.gif\'" onmouseout="this.src=\'../PublishingImages/arrow_blue_on_white.gif\'" title="Get Directions"></a></td></tr></table>';

	pin = map.GetShapeByID(pinID);
	pin.SetDescription(pinDescription + routeTo);
	map.HideInfoBox();
	map.ShowInfoBox(pin);
}

function fromhere(lat, long, pinID, pinTitle, pinDescription) {
	directionType = 'FROM';
	var routeFrom = '<br><br>Directions: <a href="javascript:tohere(' + lat + ',' + long + ',' + "'" + pinID + "'" + ",'" + pinTitle + "','" + pinDescription + "'" +')">To here</a> - <b>From here</b>' +
	'<br>End address:' +
	'<table width="150" border="0" cellspacing="2" cellpadding="0"><tr><td width="125"><input type="text" size=20 maxlength=100 name="Addr" id="Addr" value="" /></td>' +
	'<td width="25"><a href="javascript:routeDirections(' + lat + ',' + long + ',' + "'" + pinTitle + "'" + ');"><img src="../PublishingImages/arrow_blue_on_white.gif" width="25" height="25" border="0" onmouseover="this.src=\'../PublishingImages/arrow_yellow_on_white.gif\'" onmouseout="this.src=\'../PublishingImages/arrow_blue_on_white.gif\'" title="Get Directions"></a></td></tr></table>';

	pin = map.GetShapeByID(pinID);
	pin.SetDescription(pinDescription + routeFrom);
	map.HideInfoBox();
	map.ShowInfoBox(pin);
}

function routeDirections(lat,long,pinTitle) {
	pinTitleGbl = pinTitle;
	var coords = new VELatLong(lat, long);
	addrInput = document.getElementById('Addr').value;
	if (directionType == 'FROM'){
		map.GetRoute(coords, addrInput,null,null,onGotRoute);
		} else if (directionType == 'TO') {
			map.GetRoute(addrInput,coords,null,null,onGotRoute);
		}
}

function onGotRoute(route) {
	var routeSummary = '<b>Route Summary</b><br>';
	if (directionType == 'FROM'){
		var startLocation = pinTitleGbl;
		var endLocation = addrInput;
	} else if (directionType == 'TO') {
			var startLocation = addrInput;
			var endLocation = pinTitleGbl;
	}
		routeSummary+= '<font color="#008000">Start:</font> ' + startLocation + '<br>' + '<font color="#FF0000">End:</font> ' + endLocation;
		routeSummary+='<br>Total distance: ' + route.Itinerary.Distance + ' ' + route.Itinerary.DistanceUnit + '<br>Total Time: ' + route.Itinerary.Time;
		routeSummary+='<p><a href="javascript:print();">Print Directions</a><br><br><a href="javascript:clearDirections();">Clear Directions</a></p>';

		var directions = '<b>Driving Directions</b><br><table id="routeStepsTbl" width="300" border="0" cellspacing="1" cellpadding="2">';
		var steps="";
		var len = route.Itinerary.Segments.length - 1;
		for(var i = 1; i < len ;i++) {
			steps+='<tr><td>';
			steps+=route.Itinerary.Segments[i].Instruction+" -- (";
			steps+=route.Itinerary.Segments[i].Distance+") ";
			steps+=route.Itinerary.DistanceUnit + '</td></tr>';
		}
		directions+=steps + '</table>';
		displayDirections(routeSummary,directions);
}

function displayDirections(routeSummary,text) {
	var d=document.getElementById("directionsDiv");
	d.style.visibility="visible";

	document.getElementById("routeSummary").innerHTML = routeSummary;
	document.getElementById("directionsText").innerHTML = text;

	var tbl =document.getElementById("routeStepsTbl");
	for (i=0;i<tbl.rows.length;i++) {
		if (i%2==0) {tbl.rows[i].style.background="#F0F0F0"; }
	}
	window.scroll(0,550); // horizontal and vertical scroll targets
}

function ShapeMouseOverHandler(e){
	//check a shape was actually clicked on, rather than just the map itself
	if (e.elementID != null){
		//fix for firefox if not implemented, title will get stuck showing and info box may not show.
		if (control != null){ //fix for mouseout exception in firefox
			map.DeleteControl(control);
			control = null;
		}

		pin = map.GetShapeByID(e.elementID);
		if (pin.GetType() == 'Point'){
			titleTEST = pin.GetTitle();

			control = document.createElement("div");
			control.id = "tooltip";
			control.style.top =e.mapY;
			control.style.left = e.mapX + 10;
			control.style.border = "2px solid black";
			control.style.background = "White";
			control.innerHTML = titleTEST;
			map.AddControl(control);

			return true;
		}
	}
	return false;
}

function ShapeMouseOutHandler(e) {
	if (control != null){ //fix for mouseout exception
		map.DeleteControl(control);
		control = null;
	}
}

function mapclicked(mapeventargs) {
	//fix for firefox if not implemented, title will get stuck showing and info box may not show.
	if (control != null){ //fix for mouseout exception
		map.DeleteControl(control);
		control = null;
	}

	if (mapeventargs.elementID !=null) {
		clearBoundaries();
		ShapeMouseOutHandler(mapeventargs);

		var pinIDx=[];

		pin = map.GetShapeByID(mapeventargs.elementID);
		pinIDx = new Array(pin.GetID());

		var j = 0;
		for (i=0; i<polygon.length; i++) {
			if ( polygon[i][0] == pin.GetTitle() ){
				boundary[j] = map.GetShapeByID(polygon[i][1])
				boundary[j].SetFillColor(new VEColor(0, 0, 255, 0.1));
				j++;
			}
		}
		map.SetCenterAndZoom(pin.GetIconAnchor(), 13);
		var boxID = map.GetShapeByID(pinIDx[0]);
		setTimeout(function(){map.ShowInfoBox(boxID,map.GetCenter());},800);
	}
}

function clearBoundaries() {
	if (boundary != null) {
		for (i=0; i<boundary.length; i++) {
			boundary[i].SetFillColor(new VEColor(0, 0, 255, 0.0));
		}
	}
}

function onFeedLoad(layer) {
	var numShapes = layer.GetShapeCount();

	for(var i=0; i < numShapes; ++i) {
		var s = layer.GetShapeByIndex(i);
		var pinID = s.GetID();
		var pinTitle = s.GetTitle();
		var pinPoint = s.GetPoints();
		var pinRoute = '<br><br>Directions: <a href="javascript:tohere(' + pinPoint + ',' + "'" + pinID + "'" + ",'" + pinTitle + "','" + s.GetDescription() + "'" +')">To here</a> - ' +
		'<a href="javascript:fromhere(' + pinPoint + ',' + "'" + pinID + "'" + ",'" + pinTitle + "','" + s.GetDescription() + "'" +')">From here</a>';
		
/*		if (s.GetTitle() == 'Resource Center' || s.GetTitle() == 'Support Services Center') {
			s.SetCustomIcon("<img src='" + iconOther + "'/>");
			s.SetDescription(s.GetDescription() + pinRoute);
		} else {
			s.SetCustomIcon("<img src='" + iconFile + "'/>");
			s.SetDescription(s.GetDescription() + pinRoute);
		}
		*/
		s.SetCustomIcon("<img src='" + iconFile + "'/>");
		s.SetDescription(s.GetDescription() + pinRoute);
		
		marker[i] = new Array(s.GetTitle(),s.GetID());
	}
}

function onFeedLoadBoundary(layer) {
	var numShapes = layer.GetShapeCount();
	for(var i=0; i < numShapes; ++i) {
		var s = layer.GetShapeByIndex(i);
		if ((URLvariable == 'mapType') && (URLvariable['school']== s.GetTitle())) {
			s.SetFillColor(new VEColor(0, 0, 255, 0.1));
			} else {
				s.HideIcon();
				s.SetFillColor(new VEColor(0, 0, 255, 0.0));
			}
			polygon[i] = new Array(s.GetTitle(),s.GetID());
		}
}

function findAddress(address) {
	try {
		map.Find(null, address, null, null, null, null, null, null, null, null, plotFindAddr);
		} catch(e) {
			alert(e.message);
		}
}

function plotFindAddr(){
	var pin = map.AddPushpin(map.GetCenter());
	pin.SetTitle(document.getElementById('findAddressFld').value);
	pin.SetCustomIcon("<img src='" + iconStar + "'/>");
}

function mapTitle(mapType) {
	if (mapType == 'Jr') {
		title = 'Jr. High Schools';
		} else if (mapType == 'HS') {
			title = 'High Schools';
		} else if (mapType == 'Other') {
			title = 'Other Facilities';
			} else { title = 'Elementary Schools'; }

			controlTitle = document.createElement("div");
			controlTitle.id = "mapTitle";
			controlTitle.style.top =35;
			controlTitle.style.left = 41;
			controlTitle.style.border = "1px solid #FFFFFF";
			controlTitle.style.background = "#1E7D9B";
			controlTitle.style.color = "#FFFFFF";
			controlTitle.style.padding = "2px";
			controlTitle.style.width = "199px";
			controlTitle.innerHTML = title;
			map.AddControl(controlTitle);
}

function clearDefaultTxt(input) {
	if (input.defaultValue == input.value) { input.value = ""};
}

function clearDirections() {
	map.DeleteRoute();
	var d=document.getElementById("directionsDiv");
	d.style.visibility="hidden";
}