var places = new Array();
var types  = new Array();
var map = null;
var qProp = null;
var cstmPoint = new Array();

//Change to the path of your XML file
var url = 'xml/map.xml';

$(function() {   
	$('div#map-help').hide();
	
	if(window.location.search.substring(1)) {
		var query = window.location.search.substring(1);
		var qStrings = getQuery(query);
		if(qStrings['id'])
			url = "xml/map-"+qStrings['id']+".xml";
		if(qStrings['locID'])
			qProp = qStrings['locID'];
		if(qStrings['lat']) {
			cstmPoint[0] = qStrings['lat'];
			cstmPoint[1] = qStrings['long']
		}
	}

	loadXMLDoc();
	
	$("form#route-form").submit(function() { 
		var start = document.getElementById('txtStart').value;	
		var end = document.getElementById('txtEnd').value
		
		if(start == "" || end == "")
			alert("Please add a starting or ending location");
		else if(cstmPoint.length>1)
			map.GetRoute(start,new VELatLong(cstmPoint[0], cstmPoint[1]),VEDistanceUnit.Kilometers,VERouteType.Quickest, onGotRoute); 
		else
			map.GetRoute(start,end,VEDistanceUnit.Kilometers,VERouteType.Quickest, onGotRoute); 
		return false;
	});
		
	$("input#clear").click(function() {
		deleteRoute();
		return false;
	});
	
	$("a#center-map").click(function() { 
		centerMap(0, 9);
		return false; 
	});
	
	$("a#toggle-link").toggle(function() { map.HideDashboard(); return false; },
							  function() { map.ShowDashboard(); return false; });
	
	$("div#help-wrapper").hide();
	$("a#help-link").click(function() { 
		$("div#help-wrapper").show();
		return false; 
	});
	
	$("a#close-help").click(function() { 
		$("div#help-wrapper").hide();
		return false; 
	});
});

function loadXMLDoc() {
	if (window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = getData;
	xmlhttp.open("GET", url, true);
	xmlhttp.send(null);
}

function getQuery(query) {
	var vars = query.split("&");
	var pairs = new Array();
	for (var i=0;i<vars.length;i++) {
		var p = vars[i].split("=");
		pairs[p[0]] = p[1];
		}
	return pairs;
}

function getData() {
	if (xmlhttp.readyState==4) {
		if (xmlhttp.status==200) {
			var data = xmlhttp.responseXML.getElementsByTagName("channel")[0];
			var count = 0;
			for (i = 0; i < data.childNodes.length; i++) {
				if (data.childNodes[i].nodeType == 1) {
					record = data.childNodes[i];
					places[count] = new Array();
					for (j = 0; j < record.childNodes.length; j++) {
               			if (record.childNodes[j].nodeType == 1) {
							places[count][record.childNodes[j].tagName] = record.childNodes[j].firstChild.nodeValue;
						}
					}
					count++;
				}
			}
			getTypes();
			getMap();
		} else {
			alert("Problem retrieving XML data")
		}
	}
}

function getMap() {         
	map = new VEMap('map'); 
	map.SetDashboardSize(VEDashboardSize.Small);
	map.LoadMap(new VELatLong(places[0]['lat'], places[0]['long']), 9,'r' ,false);
	AddPushpin(0);
	if(qProp != null && qProp >= 1 && qProp < places.length ) {
		var tl = $('a.add-pin[rel="pin'+qProp+'"]')
		pinControl(qProp, tl);	
		showInfo(qProp);
	}
	if(cstmPoint.length>0) {
		AddPushpin(cstmPoint);
		$('input#txtEnd').val(new VELatLong(cstmPoint[0], cstmPoint[1]));
		$('input#txtStart').val(places[0]['address']);
	}
} 

function getTypes() {
	var l2, tem, temp;
	var l = places.length;
	loop:
	for(x = 0; x < l; x++){
		tem = places[x]['type'];
		l2 = types.length;
		for(y = 0; y < l2; y++){
			temp = types[y];
			if(temp === tem) continue loop;
		}
		types.push(tem);
	}
	$('div#d-push').append(printPlace(0));
	printTypes();
}

function printTypes() {
	var list = '<ul id="type-list">';
	for(x = 1; x < types.length; x++)
		list += '<li id="list-'+types[x]+'"><a href="#" class="choose-type" rel="'+types[x]+'">'+types[x]+'</a></li>';
	list +='</ul>';
	$('div#map-locations').before(list);
	
	printLocations();
}

function printLocations() {
	var ml = "";
	for(x = 0; x < types.length; x++) {
		ml += '<div id="map-'+types[x]+'">';
		for(y = 1; y < places.length; y++) {
			if(places[y]['type'] == types[x])
				ml += printPlace(y);
		}
		ml += '</div>';
	}
	$('div#d-push').append(ml);
	
	for(z = 2; z < types.length; z++)
		$('div#map-'+types[z]).css("display", "none");
	
	activateControls();
}

function printPlace(num, color) {
	var locs = '<div class="map-item">\n\
					<div class="map-location"><a href="#" class="add-pin" rel="pin'+num+'">'+places[num]['title']+'</a></div>\n\
					<div class="map-links">Directions: <a href="#" class="to-from start" rel="pin'+num+'">from</a> - <a href="#" class="to-from end" rel="pin'+num+'">to</a></div>\n\
					<div class="info-link"><a href="#" class="show-info" rel="pin'+num+'">Show Info Box</a></div>\n\
				</div>';
	return locs;
}

function activateControls() {
	$("a.add-pin").click(function(){ 
		var id = $(this).attr("rel").replace(/pin/,"");
		pinControl(id, $(this));
		return false;
	});
	
	$("a.to-from").click(function() { 
		var id = $(this).attr("rel").replace(/pin/,"");
		if(places[id]['shapeid'] == null) {
			pinControl(id, $(this));
			if($(this).is('.end')) 
				toDirections(id, "end");
			else 
				toDirections(id, "start");
		} else {
			if($(this).is('.end')) 
				toDirections(id, "end");
			else 
				toDirections(id, "start");
		}
		return false;
	});
	
	$("a.show-info").click(function(){ 
		var id = $(this).attr("rel").replace(/pin/,"");
		if(places[id]['shapeid'] == null) {
			pinControl(id, $(this));
			showInfo(id);
		} else {
			showInfo(id);
		}
		return false;
	});
	
	$('a.choose-type').click(function() {
		var dis = $(this).attr("rel");
		for(z = 0; z < types.length; z++)
			$('div#map-'+types[z]).css("display", "none");
		$('div#map-'+dis).css("display", "block");
		return false;
	});
}

function pinControl(id, aLink) {
	if(id == 0) {
		centerMap(id, 9);
	} else if(aLink.siblings().is('.remove')) {
		centerMap(id, 13);		
	} else {
		AddPushpin(id);
		aLink.parents('div.map-item').children('div.map-location').append('<span class="remove"><br /> [<a href="#" class="remove-point" rel="pin'+id+'">remove</a>]</span>');
		
		$("a.remove-point").click(function(){ 
			var id = $(this).attr("rel").replace(/pin/,"");
			removePoint(id);
			$(this).parent().remove();
			return false;
		});
	}	
}

function AddPushpin(id, l) {  
	if(id.length>1) {
		var lat = id[0];
		var long = id[1];
		
		shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, long));
		map.AddShape(shape);
	}
	else {
		var lat = parseFloat(places[id]['lat']);
		var long = parseFloat(places[id]['long']);

		shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, long));
		
		shape.SetCustomIcon(places[id]['pushpin']);
		shape.SetTitle(places[id]['title']); 
		shape.SetDescription(places[id]['description']); 
		shape.SetPhotoURL(places[id]['photo']);
		map.HideInfoBox();
		if(l) 
			l.AddShape(shape);
		else 
			map.AddShape(shape); 
	
		places[id]['shapeid'] = shape.GetID();
	}
}
	
function toDirections(location, point){
	if(point === "end") 
		$('input#txtEnd').val(places[location]['address']);
	else
		$('input#txtStart').val(places[location]['address']);
}
	
function onGotRoute(route) {
	$('div#route-info').html("");
	var routeinfo="<h2>Route info:</h2>";            
	routeinfo+="<p>Total distance: ";            
	routeinfo+=route.Itinerary.Distance+" ";            
	routeinfo+=route.Itinerary.DistanceUnit+"</p>"; 
	
	var mailinfo="Route info:%0A%0A";            
	mailinfo+="Total distance: ";            
	mailinfo+=route.Itinerary.Distance+" ";            
	mailinfo+=route.Itinerary.DistanceUnit+"%0A%0A"; 
	
	var steps=""; 
	var stepsmail=""; 
	var len = route.Itinerary.Segments.length;               
	for(var i = 0; i < len ;i++) {                  
		steps+=route.Itinerary.Segments[i].Instruction+" -- (";                  
		steps+=route.Itinerary.Segments[i].Distance+") ";                  
		steps+=route.Itinerary.DistanceUnit+"<br />";    
		stepsmail+=route.Itinerary.Segments[i].Instruction+" -- (";                  
		stepsmail+=route.Itinerary.Segments[i].Distance+") ";                  
		stepsmail+=route.Itinerary.DistanceUnit+"%0A";  
	}   
	steps += '</p>';
	routeinfo+="<p>Steps:<br />"+steps;           
	mailinfo+="Steps:%0D%0A"+stepsmail;
	
	routeinfo += '<span class="direction-function">\n\
					<a href="javascript:print()">Print</a> | <a href="mailto:?subject=Directions&body='+mailinfo+'">E-mail</a>\n\
				</span>';

	$('div#route-info').append(routeinfo);         
}

function deleteRoute() {
	$('div#route-info').html("");
	try { map.DeleteRoute(); }            
	catch (err) { alert(err.message); } 
	centerMap(0, 11);
}

function removePoint(rPoint) {
	var nShape = map.GetShapeByID(places[rPoint]['shapeid']);
	if(nShape != null) { 
		map.HideInfoBox();
		map.DeleteShape(nShape);
		places[rPoint]['shapeid'] = null;
	}
}

function showInfo(iPoint) {
	var nShape = map.GetShapeByID(places[iPoint]['shapeid']);
	map.HideInfoBox();
	if(nShape != null)
		map.ShowInfoBox(nShape, new VELatLong(places[iPoint]['lat'], places[iPoint]['long']) );
}

function centerMap(point, zoom) {
	map.SetCenterAndZoom(new VELatLong(places[point]['lat'], places[point]['long']), zoom)
}

function displayType(type) {
	if(layer) {
		map.DeleteShapeLayer(layer);
		layer = null;
	}
	
	layer = new VEShapeLayer();         
	map.AddShapeLayer(layer);
	
	for(x=0;x<places.length;x++)
		if(places[x]['type'] == type)
			AddPushpin(x, layer);
}