var places = new Array();
var types = new Array()
var map = null;
var shape = null;
var layer = null;
var query = null;

//Change to the path of your XML file
var url = '/xml/map.xml';

$(function() {   
	
	// Shows Static JPEG for Safari and Opera
	if($.browser.safari || $.browser.opera) { 
		$(function() { 
			$('div#map').html('<img src="images/map/alt-map.jpg" alt="Alternative Map" />'); 
		});
	}
	
	query = parseInt(getQuery("locID"));
	loadXMLDoc();
	
	$("form#route-form").submit(function() { 
		map.GetRoute(document.getElementById('txtStart').value, document.getElementById('txtEnd').value,VEDistanceUnit.Kilometers,VERouteType.Quickest, onGotRoute); 
		return false;
	});
		
	$("button#clear").click(function() {
		$('div#route-info').html("");
		deleteRoute();
	});
	
	$('div#map-help').hide();
	//$("a#help-link").click(function() { $("div#map-help").animate({height: 'toggle'}, "slow"); return false; });
	$("a#help-link").click(function() { 
		$("div#map-help").show(); return false;
	});
	
	$("a#close-help").click(function() { 
		$("div#map-help").hide();
		return false; 
	});
});

function loadXMLDoc() {
	if (document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.onload = getData;
	}
	else if (window.ActiveXObject) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4) getData();
		};
 	}
	else {
		alert('Your browser can\'t handle this script');
		return;
	}
	xmlDoc.load(url);
}

function getQuery(vari) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == vari) {
			return pair[1];
		}
	}
}

function getData() {
    var data = xmlDoc.getElementsByTagName("channel")[0];
    var record, obj;
    for (i = 0; i < data.childNodes.length; i++) {
        if (data.childNodes[i].nodeType == 1) {
            record = data.childNodes[i];
            obj = places[places.length] = new Object( );
            for (j = 0; j < record.childNodes.length; j++) {
                if (record.childNodes[j].nodeType == 1) {
                    obj[record.childNodes[j].tagName] = 
                        record.childNodes[j].firstChild.nodeValue;    
                }
            }
        }
    }
	getTypes();
	getMap();
}

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(query != null && query >= 1 && query < places.length ) {
		var tl = $('a.add-pin[rel="pin'+query+'"]')
		pinControl(query, tl);	
		showInfo(query);
	}
	
	map.AttachEvent("onmouseover",ShapeHandler);
    map.AttachEvent("onmouseout",ShapeHandler);
} 

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#location-wrapper').prepend(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#map-locations').append(ml);
	
	for(z = 2; z < types.length; z++)
		$('div#map-'+types[z]).css("display", "none");
	
	activateControls();
}

function printPlace(num) {
	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");
	});
}

function pinControl(id, aLink) {
	if(id == 0) {
		centerMap(id, 11);
	} else if(aLink.siblings().is('.remove')) {
		centerMap(id, 11);		
	} else {
		AddPushpin(id);
		aLink.parents('div.map-item').children('div.map-location').append('<span class="remove"> [<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) {  
	var lat = parseFloat(places[id]['lat']);
	var long = parseFloat(places[id]['long']);

	shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, long));
	
	var sid = shape.GetID();
	shape.SetCustomIcon("<div id="+ sid +" class='pin'>"+places[id]['pushpin']+"</div>");
	
	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) {  
	if(!$('input#m-routes').is(':checked'))
		$('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";  
	}   
	
	routeinfo+="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() {            
	try { map.DeleteRoute(); }            
	catch (err) { alert(err.message); } 
	centerMap(0, 9);
}

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);
}


function ShapeHandler(e){
	
	$('.VEAPI_Pushpin').mouseover( function() {
		var elemwrapPos = document.getElementById('ve-map');
		var elemPos = this;
			
		var mapoffset = $(".MSVE_Map").css('top');
		var mof = mapoffset.search(/px/);
		mapoffset = parseInt(mapoffset.substring(0,mof));
		
		$(".ero-leftBeak").css('top', (elemPos.offsetTop + elemwrapPos.offsetTop + mapoffset - 20)+ 'px');
		$(".ero-leftBeak").css('bottom', (0)+ 'px');
		$(".ero-beak").css('top', (25)+ 'px');
	});
}
