/*
Lake Washington School District
Boundary Scenario Maps Using Microsoft Virtual Earth
By: Josiah Mault
jamault@pioneernet.net
12.18.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 title = null;
var iconStar = '../../../SiteCollectionImages/News/Star.gif'; 
var scenario = null;

function getSelectedSchool(scenarioTitle) {
	if (scenarioTitle == null) {
    scenarioTitle = document.getElementById('selectScenario').value;
  }
    scenarioTitleArray = scenarioTitle.split('&&');
    scenario = scenarioTitleArray[0];
    title = scenarioTitleArray[1];
    
    map.DeleteAllShapes();
    createLayer(scenario, title);
}

function GetMap() {
	
	map = new VEMap('myMap');
	map.SetDashboardSize('small');
	map.LoadMap(new VELatLong(47.6235,-122.0415), 12, 'r', false, VEMapMode.Mode2D, false);
	createLayer(scenario,title);

	map.AttachEvent("onmouseover",ShapeMouseOverHandler);
	map.AttachEvent("onmouseout",ShapeMouseOutHandler);
	map.AttachEvent("onclick",  mapclicked);
	
}

function createLayer(scenario,title) {
	  var layerType = VEDataType.GeoRSS;
	if (scenario == null) {
//		scenario = 'currentBoundaries';
//		title = 'Current Boundaries';
		scenario = 'finalRecommendation';
		title = 'Boundary Recommendation';

	}
		
		mapFilePins = '../MapFiles/elSchool.xml';
		mapFileBoundary = '../MapFiles/' + scenario + '.xml';
		iconFile = '../../../SiteCollectionImages/News/icon-EL.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);
			
			mapTitle(title);
}

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="../../../SiteCollectionImages/News/arrow_blue_on_white.gif" width="25" height="25" border="0" onmouseover="this.src=\'../../../SiteCollectionImages/News/arrow_yellow_on_white.gif\'" onmouseout="this.src=\'../../../SiteCollectionImages/News/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="../../../SiteCollectionImages/News/arrow_blue_on_white.gif" width="25" height="25" border="0" onmouseover="this.src=\'../../../SiteCollectionImages/News/arrow_yellow_on_white.gif\'" onmouseout="this.src=\'../../../SiteCollectionImages/News/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, .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>';

		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);
		s.SetLineColor(new VEColor(0, 0, 255, 1.0)); //set line color default is blue .1 opacity if this line is not here
		
	//	if ((URLvariable['scenario']== s.GetTitle())) {
		//	s.SetFillColor(new VEColor(0, 0, 255, .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(title) {

			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";
}
