var map = null;
var controls = true;
var pinID = 1;
var layerid = 1;
var allLocations = new Array();
var initialCenter, destination, req, indexnum, numShapes ;
var id = geturlparam('id');
//var url = 'http://www.destinationvacationrental.com/property-xml/map-' + id + '.xml';
var url = 'xml/map.xml';
//var url = 'http://localhost/squawcreek_com/xml/map.xml';

$(function() {
	//$('div#routefinder').hide();
	$('div#directions').hide();
	$('div#help-wrapper').hide();

	// Shows Static JPEG for Safari and Opera
	if($.browser.safari || $.browser.opera) { $( function() { $('div#map-wrapper').html('<img src="images/property/alt-map-'+ id +'.jpg" alt="Alternative Map" />'); }); }

	loadXMLDoc();

	map = new VEMap('map');
	map.SetDashboardSize(VEDashboardSize.Small);
	
	// If It Pulls in XML Uncomment
	map.LoadMap();
	AddMyLayer();
	
	map.AttachEvent("onmouseover",ShapeHandler);
    map.AttachEvent("onmouseout",ShapeHandler);

	$("a#help-link").toggle(function() { $("div#help-wrapper").show("fast"); }, 
							function() { $("div#help-wrapper").hide("fast"); });
	
	$("a#toggle-link").toggle(function() { map.HideDashboard();	}, 
							  function() { map.ShowDashboard(); });

	$("a#plan-link").toggle(function() {
		$("div#directions").show("fast");
		$("div#routefinder").show("fast");
	}, function() {
		$("div#directions").hide("fast");
		$("div#routefinder").hide("fast");
	});

	$("a#zoom-link").click (function() { map.SetCenterAndZoom(initialCenter, 7); });

	$("form#route-form").submit(function() { 
		map.GetRoute(document.getElementById('txtStart').value, document.getElementById('txtEnd').value,null,VERouteType.Quickest,onGotRoute); 
		return false;
	});
	

});

// Retrieves the ID URL Param from the URL
function geturlparam(name) {
  var name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
	return "";
  else
	return results[1];
}

function loadXMLDoc() {
	if (window.XMLHttpRequest){
		req=new XMLHttpRequest();
	}
	// code for IE
	else if (window.ActiveXObject){
		req=new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.onreadystatechange = processReqChange;
	req.open("GET", url, true);
	req.send(null);
}

function processReqChange() {
	// only if req shows "complete"
	if (req.readyState == 4) {
		// only if "OK"
		if (req.status == 200) {
			// ...processing statements go here...
			var z=req.responseXML.documentElement.getElementsByTagName('item');
			var hotelinfo="";
			for (i=0;i<req.responseXML.documentElement.getElementsByTagName('item').length;i++) {
				if (z[i].nodeType!=3) {
					var refTest = z[i].getAttributeNode("id");
					var placeArray = new Array();
					placeArray['index'] = i;
					placeArray['id'] = z[i].getAttributeNode("id").value;
					placeArray['type'] =  z[i].getElementsByTagName('type')[0].childNodes[0].nodeValue;
					placeArray['title'] =  z[i].getElementsByTagName('title')[0].childNodes[0].nodeValue;
					placeArray['description'] =  z[i].getElementsByTagName('description')[0].childNodes[0].nodeValue;
					placeArray['address'] =  z[i].getElementsByTagName('address')[0].childNodes[0].nodeValue;
					//placeArray['webaddress'] =  z[i].getElementsByTagName('webaddress')[0].childNodes[0].nodeValue;
					//placeArray['webtext'] =  z[i].getElementsByTagName('webtext')[0].childNodes[0].nodeValue; 
					if (document.getElementById) {
						placeArray['geolat'] =  z[i].getElementsByTagName('geo:lat')[0].childNodes[0].nodeValue
						placeArray['geolong'] =  z[i].getElementsByTagName('geo:long')[0].childNodes[0].nodeValue
					} else {
						placeArray['geolat'] =  z[i].getElementsByTagName('lat')[0].childNodes[0].nodeValue
						placeArray['geolong'] =  z[i].getElementsByTagName('long')[0].childNodes[0].nodeValue
					}
                    
					allLocations[i] = placeArray;

					hotelinfo += "<div id='directions"+placeArray['id']+"' class='place-info'>";
					hotelinfo += "<p><strong>" + placeArray['title'] + "</strong></p>";
					hotelinfo += "<p>get directions - <a href='#' id='"+placeArray['index']+"' class='getdirectionto'>to</a> <a href='#' id='"+placeArray['index']+"' class='getdirectionfrom'>from</a></p>";
					hotelinfo += "<p><a href='#' id='"+placeArray['index']+"' class='findloc'>find on map</a></p>";
					//hotelinfo += "<p class=\"no-bottom-margin\">"+placeArray['address']+"</p>";
					//hotelinfo += placeArray['webtext'];
					hotelinfo += "</div>";
				}
			}
            
			document.getElementById('locationsdiv').innerHTML += hotelinfo;
            
		}
		$('#dest-points div.place-info:first').addClass("current-loc");
		$('#dest-points a.findloc').bind('click', function() {
			FindOnMap($(this).attr('id'));
			$("#dest-points div.place-info").removeClass("current-loc");
			$(this).parents('div.place-info').addClass("current-loc");
			return false;
		});
		$('#dest-points a.getdirectionto').bind('click', function() {
			toDirections('to',$(this).attr('id'))
			return false;
		});
		$('#dest-points a.getdirectionfrom').bind('click', function() {
			toDirections('from',$(this).attr('id'))
			return false;
		});




	}
}

function AddMyLayer() {
	var type = VEDataType.GeoRSS;       
	var l = new VEShapeLayer();
	var veLayerSpec = new VEShapeSourceSpecification(type, url, l);
	map.ImportShapeLayerData(veLayerSpec, onFeedLoad);
}   

function onFeedLoad(feed) { 
	feed.Hide();
	numShapes = feed.GetShapeCount();
	var titleindex;
	//map.ShowInfoBox(feed.GetShapeByIndex(0));
	for(var i=0; i < numShapes; ++i){
		var s = feed.GetShapeByIndex(i);
		var st = s.GetTitle();
		var sid = s.GetID();
		//if (i == 0 ) 
			s.SetCustomIcon("<div class='pin' id="+ sid +"><img src=\"images/interior/pin.gif\" alt=\"\" style=\"float:left;display:inline;\" /></div>");
		allLocations[i]['shapeid'] = s.GetID();
	}
	feed.Show();
	initialCenter = map.GetCenter(); 
}

function FindOnMap(findplace) {
	var shape;
	for (i = 1; i<numShapes; i++){
	}

	shape = map.GetShapeByID(allLocations[findplace]['shapeid']);
	map.HideInfoBox();
	
	
	map.ShowInfoBox(shape, new VELatLong(allLocations[findplace]['geolat'],allLocations[findplace]['geolong']));

		var elemwrapPos = document.getElementById('map-wrapper');
		var posid = allLocations[findplace]["shapeid"];
		var elemPos = document.getElementById(posid);
		
		var elemPos2 = $(elemPos).parents('.VEAPI_Pushpin').attr('id');
		elemPos2 = document.getElementById(elemPos2);
		
		var mapoffset = $(".MSVE_Map").css('top');
		
		var mof = mapoffset.search(/px/);
		mapoffset = parseInt(mapoffset.substring(0,mof));
		
		//alert(elemPos2.offsetTop);
		$(".ero-leftBeak").css('top', (elemPos2.offsetTop + elemwrapPos.offsetTop + mapoffset - 10)+ 'px');
		$(".ero-leftBeak").css('bottom', (0)+ 'px');
		$(".ero-beak").css('top', (25)+ 'px');	
	


}
/*
function ShapeHandler(e){
	var newid = e.elementID;
	if (e.elementID != null){
		for (i = 0; i< allLocations.length; i++){
			if ( e.elementID == ( allLocations[i]['shapeid'] + "_1000" + i ) ){
				$("#dest-points p").removeClass("current-loc");
				$("#dest-points p:eq("+i+")").addClass("current-loc");
			} else if ( e.elementID == 'msftve_1001_200000_10000_l' ) {
				$("#dest-points p").removeClass("current-loc");
				$("#dest-points p:eq(0)").addClass("current-loc");
			}
		}
	}
}
*/
function ShapeHandler(e){
	if (e.elementID != null){
		for (i = 0; i< allLocations.length; i++){
			if ( e.elementID == ( allLocations[i]['shapeid'] + "_1000" + i ) ){
				$("#dest-points p").removeClass("current-loc");
				$("#dest-points p:eq("+i+")").addClass("current-loc");
			} else if ( e.elementID == 'msftve_1001_200000_10000_l' ) {
				$("#dest-points p").removeClass("current-loc");
				$("#dest-points p:eq(0)").addClass("current-loc");
			}
		}
	}
	$('.VEAPI_Pushpin').mouseover( function() {
		var elemwrapPos = document.getElementById('map-wrapper');
		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 - 10)+ 'px');
		$(".ero-leftBeak").css('bottom', (0)+ 'px');
		$(".ero-beak").css('top', (25)+ 'px');
	});
}





// Gets Directions when clicked from Info box
function toDirections(direction,linked){
	for (i = 0; i < allLocations.length; i++){
		if (allLocations[i]['id'] == linked) indexnum = i;
	}
	document.getElementById("directions").style.display = "block";
	document.getElementById("routefinder").style.display = "block";
	if (direction == 'to') { 
		document.getElementById('txtEnd').value = allLocations[linked]['address']; 
	} else {
		document.getElementById('txtStart').value = allLocations[linked]['address']; 
	}
}

// Displays the directions on the Page
function onGotRoute(route) {
   var routeinfo="<div class='driving-directions'><h4>Driving Directions</h4>";
   routeinfo += "<strong>Route info:</strong><br />";
   routeinfo += "<strong>Total distance:</strong>";
   routeinfo += route.Itinerary.Distance+" ";
   routeinfo += route.Itinerary.DistanceUnit+"<br />";

   var steps="";
   var stepsemail="Driving Directions%0D%0A";
   var len = route.Itinerary.Segments.length;
   for(var i = 0; i<len ;i++) {
	  steps+=route.Itinerary.Segments[i].Instruction+" -- (";
	  stepsemail+=route.Itinerary.Segments[i].Instruction+" -- (";
	  steps+=route.Itinerary.Segments[i].Distance+") ";
	  stepsemail+=route.Itinerary.Segments[i].Distance+") ";
	  steps+=route.Itinerary.DistanceUnit+"<br />";
	  stepsemail+=route.Itinerary.DistanceUnit+"%0D%0A";
   }
   routeinfo += "<strong>Steps:</strong><br />"+steps;

   routeinfo += "<span class='direction-function'><a href=\"javascript:print()\">Print</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href=\"mailto:?body="+stepsemail+"\">E-mail</a> </span><br /><br />";
   routeinfo += "</div>";
   
   if (destination == undefined) { destination = ""; }
   
   $('div#routefinder').show();
   $('#directions').show().html(routeinfo);
}

function testy(obj) {
	obj.style.color = '#cc0000';
	var testing = $(obj).parent().attr("class");
	if ($(obj).html() == 'View Details') {
		$(obj).parent().siblings(".long-desc").show();
		$(obj).html("Close");
	} else {
		$(obj).parent().siblings(".long-desc").hide();								  
		$(obj).html("View Details");
	}
}
