//Global Variables------------------ Start ------------------------//
//javascript objects for Basic Map Module
var map = null;
var baseLayer = null;
var ListContainer = null;
var HelpText = "Enter 'What , Where'...";
var Proxy = new svcProxy("/DesktopModules/KSTech.BasicMapModule/handlers/");
var k$ = jQuery.noConflict();
var ListLength = 0;
var TotalListLength = 0;

//Global Variables------------------ End --------------------------//

//DEFAULT JAVSCRIPT FUNCTIONS CLASSES ------------- Start ------------//

function fnSetDefaults(obj) {
	Globals = eval(obj);
}

k$(document).ready(function() {	
	map = new VEMap('Map');
	map.LoadMap(new VELatLong(Globals.Latitude, Globals.Longitude), Globals.ZoomLevel, VEMapStyle.Road);
	map.vemapcontrol.SetAnimationEnabled(false);
	//map.ShowMessageBox = false; //disable the ugly geocode errors from VE
	baseLayer = new VEShapeLayer();
	map.AddShapeLayer(baseLayer);

	//load in the html for the li items from the file
	k$("#liElemsHTMLContainer").load("/DesktopModules/KSTech.BasicMapModule/html/list.htm");

	k$("#OpenMapSearch").live("keypress", function(e) {
		if (e.which == 13) {
			k$(this).next().click();
			return false;
		}
	}).addClass("inputHelp").textboxhelp({
		help: HelpText,
		focuscls: "inputHelp"
	});

	k$("#aMapSearch").live("click", function(i) {
		try {
			var searchstring = k$("#OpenMapSearch").val();
			if (searchstring == HelpText) //dont search on the helper text
				return;
	
			map.DeleteRoute();
			k$("#searchStatus").show();
			k$("#_left_List_content").html("<ol id=\"list-results\"></ol>");
			k$("#list-results").empty();
			var _what = searchstring.substring(0, searchstring.indexOf(","));
			var _subWhat = _what.substring(0, _what.indexOf(" "));
			var _where = searchstring.substring(searchstring.indexOf(","), searchstring.length);

			if (_subWhat.length > 0 && isNaN(parseInt(_subWhat)) == false) { //assume its an address since the lead into the "what" is a number (assuming house index here)//
				_what = null;
				_where = k$("#OpenMapSearch").val();
			}

			map.Find(_what, _where, null, null, 0, Globals.RecordsPerTransaction, false, true, true, true, fnCallBack);
		}
		catch (e) {
			k$.facebox(e.message);
		}
	});

	function fnCallBack(layer, resultsArray, places, hasMore, veErrorMessage) {

		if (veErrorMessage != null && veErrorMessage.toString().length > 0) { //trap the error message (usually 'No Recs Found') an bailout unless there are places then let it go to pick up the place search at the end of the method - needs refactoring next release
			if (places == null) {
				k$.facebox(veErrorMessage);
				return;
			}
		}

		//clear selected category
		k$("#list-legend > li > a").removeClass("highlight");

		//hide the prev/next buttons
		k$("#btnPrev").hide();
		k$("#btnNext").hide();

		//hide the current left side content
		k$("#list-results").empty();

		//update the status message
		k$("#searchStatus").html("Quick Search Top " + Globals.RecordsPerTransaction + " Results");

		//update list and map items all in one call
		map.DeleteRoute();
		ClearMap(baseLayer);
		baseLayer = new VEShapeLayer();
		baseLayer.SetTitle("DEFAULT");
		map.AddShapeLayer(baseLayer);

		if (resultsArray != null) {
			k$.each(resultsArray, function(i, n) {
			
				var description = n.Description.toString();
				var address = "";
				
				if (description.length > 0)
				{
					address = description.substring(0, description.indexOf(','));
					var addressLength = address.length;
					address += "<br />";
					address += description.substring(addressLength + 1);
				}
				else
				{
					address = "<i>Address Not Available</i>";
				}
				
				
				var elem = k$("#liElemsHTMLContainer").html();
				elem = ReplaceToken(elem, "[LIST_NUMBER]", (i + 1));
				elem = ReplaceToken(elem, "[NAME]", n.Name.toString());
				elem = ReplaceToken(elem, "[ADDRESS]", address);
				//elem = ReplaceToken(elem, "[CITY]", places[0].Name); // Would be excessive since its <span> is going to be removed.
				//elem = ReplaceToken(elem, "[STATE]", "");
				//elem = ReplaceToken(elem, "[ZIP]", "");
				elem = ReplaceToken(elem, "[PHONE]", n.Phone.toString());
				elem = ReplaceToken(elem, "[WEBSITE]", "");
				elem = ReplaceToken(elem, "[GEOX]", n.LatLong.Latitude);
				elem = ReplaceToken(elem, "[GEOY]", n.LatLong.Longitude);
				
				var element = k$(elem);
				var addRest = element.find(".spAddRest");
				addRest.next().remove();
				addRest.remove();
				element.appendTo("#list-results");
				//k$(elem).appendTo("#list-results");
				
				var x = new VELatLong(n.LatLong.Latitude, n.LatLong.Longitude);
				var shape = new VEShape(VEShapeType.Pushpin, x);				
				shape.SetCustomIcon("<div class='pinStyle DEFAULT'><div class='text'>" + (i + 1) + "</div></div>");
				shape.SetDescription('<div class="balloon"><div class=\"balloon_top\"><div class=\"balloon_title\">' + n.Name + '</div><div class=\"balloon_description\">' + /*<br/>*/ '<span class=\"spAddress\">' + address + '</span><br />' + /*<span class=\"spAddRest\"></span><br />*/ '<strong>Phone:</strong> ' + n.Phone.toString() + '</div></div><div class=\"balloon_bottom\"><br /><a href="#" onclick="fnShowAddressBalloon(this);return false;">Get Directions</a><div class="addy_callout"><label for="txtAddress">Start: </label><input type="text" id="txtAddress"/>&nbsp;<a href="#GetDirections" class="srchDirections" onclick="fnCallGetDirectionsBalloon(this,' + n.LatLong.Latitude + ', ' + n.LatLong.Longitude + ')">go</></div></div></div>');
				baseLayer.AddShape(shape);
			});
		} else if (places != null) {
				
				var description = n.Description.toString();
				var address = "";
				
				if (description.length > 0)
				{
					address = description.substring(0, description.indexOf(','));
					var addressLength = address.length;
					address += "<br />";
					address += description.substring(addressLength + 1);
				}
				else
				{
					address = "<i>Address Not Available</i>";
				}
				
                shape.SetDescription('<div class="balloon">' +
                                        '<div class=\"balloon_top\">' +
                                            '<div class=\"balloon_title\">' + n.Name + '</div>' +
                                            '<div class=\"balloon_description\">' +
                                            '<br/>' +
                                            '<span class=\"spAddress\">' + address + '</span>' +
                                            '<br />' +
                                            /*'<span class=\"spAddRest\"></span>' +
                                            '<br />' +*/
                                            '<strong>Phone:</strong> ' + n.Phone.toString() +
                                        '</div>' +
                                      '</div>' +
                                      '<div class=\"balloon_bottom\">' +
										'<br />' +
                                        '<a href="#" onclick="fnShowAddressBalloon(this);return false;">Get Directions</a>' +
                                        '<div class="addy_callout">' +
                                            '<label for="txtAddress">Start: </label>' +
                                            '<input type="text" id="txtAddress"/>&nbsp;' +
                                            '<a href="#GetDirections" class="srchDirections" onclick="fnCallGetDirectionsBalloon(this,' + n.LatLong.Latitude + ', ' + n.LatLong.Longitude + ')">go</a>' +
                                        '</div>' +
                                     '</div>' +
                                 '</div>');
                baseLayer.AddShape(shape);
        } else if (places != null) {

            var elem = k$("#liElemsHTMLContainer").html();
			elem = ReplaceToken(elem, "[LIST_NUMBER]", 1);
			elem = ReplaceToken(elem, "[NAME]", k$("#OpenMapSearch").val());
			elem = ReplaceToken(elem, "[ADDRESS]", "");
			elem = ReplaceToken(elem, "[CITY]", "Lat:" + places[0].LatLong.Latitude);
			elem = ReplaceToken(elem, "[STATE]", "Long:" + places[0].LatLong.Longitude);
			elem = ReplaceToken(elem, "[ZIP]", "");
			elem = ReplaceToken(elem, "[PHONE]", "");
			elem = ReplaceToken(elem, "[WEBSITE]", "");
			elem = ReplaceToken(elem, "[GEOX]", places[0].LatLong.Latitude);
			elem = ReplaceToken(elem, "[GEOY]", places[0].LatLong.Longitude);
			k$(elem).appendTo("#list-results");
			var findPlaceResults = places[0].LatLong;
			var shape = new VEShape(VEShapeType.Pushpin, findPlaceResults);
			shape.SetCustomIcon("<div class='pinStyle DEFAULT'><div class='text'>1</div></div>");
			

            shape.SetDescription('<div class="balloon">' +
									'<div class=\"balloon_top\">' +
										'<div class=\"balloon_title\">' + k$("#OpenMapSearch").val() + '</div>' +
										'<div class=\"balloon_description\">' +
		                                    '<span class=\"spAddress\"></span>' +
		                                    '<br />' +
		                                    '<span class=\"spAddRest\"></span>' +
		                                '</div>' +
		                            '</div>' +
		                            '<div class=\"balloon_bottom\">' +
		                                '<a href="#" onclick="fnShowAddressBalloon(this);return false;">Get Directions</a>' +
		                                '<div class="addy_callout">' +
		                                    '<label for="txtAddress">Start: </label>' +
				                            '<input id="txtAddress" type="text" />&nbsp;' +
				                            '<a href="#GetDirections" class="srchDirections hide" onclick="fnCallGetDirectionsBalloon(this,' + places[0].LatLong.Latitude + ', ' + places[0].LatLong.Longitude + ')">go</a>' +
		                                '</div>' +
		                            '</div>' +
		                        '</div>');
            baseLayer.AddShape(shape);
		}

		//get the best updated view
		var rect = baseLayer.GetBoundingRectangle();
		map.SetMapView(rect);
	}


	//get the category list and bind the filter function
	k$("#list-legend > li > a").live("click", function() {
		map.DeleteRoute();
		k$("#searchStatus").show();
		k$("#OpenMapSearch").val("").addClass("inputHelp").textboxhelp({
			help: HelpText,
			focuscls: "inputHelp"
		}); ;
		k$("#_left_List_content").html("<ol id=\"list-results\"></ol>");
		k$("#list-results").empty();
		showLoader();
		Globals.Offset = 0;
		k$("#list-legend > li > a").removeClass("highlight");
		k$(this).addClass("highlight");
		Globals.CategoryFilter = k$(this).attr("href")
		Proxy.invoke("list.ashx", "{ 'CategoryFilter': " + Globals.CategoryFilter + ", 'Offset' : " + Globals.Offset + ", 'RecordsPerTransaction' : " + Globals.RecordsPerTransaction + ", 'dir' : 'start'}", fnBuildListObjects, fnInfoUserOfError);
		return false;
	})

	k$("#btnNext").live("click", function() {
		showLoader();
		Globals.Offset = Globals.Offset + Globals.RecordsPerTransaction;
		Proxy.invoke("list.ashx", "{ 'CategoryFilter': " + Globals.CategoryFilter + ", 'Offset' : " + Globals.Offset + ", 'RecordsPerTransaction' : " + Globals.RecordsPerTransaction + ", 'dir' : 'forward'}", fnBuildListObjects, fnInfoUserOfError);
		return false;
	})

	k$("#btnPrev").live("click", function() {
		showLoader();
		Globals.Offset = Globals.Offset - Globals.RecordsPerTransaction;
		Proxy.invoke("list.ashx", "{ 'CategoryFilter': " + Globals.CategoryFilter + ", 'Offset' : " + Globals.Offset + ", 'RecordsPerTransaction' : " + Globals.RecordsPerTransaction + ", 'dir' : 'Previous'}", fnBuildListObjects, fnInfoUserOfError);
		return false;
	})

	//startup filter
	showLoader();
	if (Globals.Source == "") { //no itinerary or event so default to deep link or first item
		if (Globals.CategoryFilter != -1) {
			k$("#list-legend > li").each(function(i, n) {
				var a = k$(this).children("a");
				if (Globals.CategoryFilter == a.attr("href"))
					a.addClass("highlight");
			});
			Proxy.invoke("list.ashx", "{ 'CategoryFilter': " + Globals.CategoryFilter + ", 'Offset' : " + 0 + ", 'RecordsPerTransaction' : " + Globals.RecordsPerTransaction + ", 'dir' : 'start'}", fnBuildListObjects, fnInfoUserOfError);
		}
		else {
			hideLoader();
			k$.facebox("Please Add Categories to the map via the Administration Screen to enable map module features!");
		}
	}
	else { // found cat or event so handle it
		if (Globals.Source == "event") {
			//handle event
			alert(Globals.SourceContent);
		} else {
			//handle event
			alert(Globals.SourceContent);
			//			var elem = k$("#liElemsHTMLContainer").html();
			//			elem = ReplaceToken(elem, "[LIST_NUMBER]", ((i + 1) + Globals.Offset));
			//			elem = ReplaceToken(elem, "[NAME]", n.ItemName.toString());
			//			elem = ReplaceToken(elem, "[ADDRESS]", n.ItemAddress.toString());
			//			elem = ReplaceToken(elem, "[CITY]", n.ItemCity.toString());
			//			elem = ReplaceToken(elem, "[STATE]", n.ItemState.toString());
			//			elem = ReplaceToken(elem, "[ZIP]", n.ItemZip.toString());
			//			elem = ReplaceToken(elem, "[PHONE]", n.ItemPhone.toString());
			//			elem = ReplaceToken(elem, "[WEBSITE]", fnCheckWebsite(n.ItemWebsite.toString()));
			//			elem = ReplaceToken(elem, "[GEOX]", n.GeoX.toString());
			//			elem = ReplaceToken(elem, "[GEOY]", n.GeoY.toString());
			//			k$(elem).appendTo("#list-results");

			//			setMapPoints(n);
			//			ToggleNavLinks();
			//			hideLoader();
		}
	}
});


function ToggleNavLinks() {
	var EndOffset = (Globals.Offset + Globals.RecordsPerTransaction);
	if (Globals.Offset == 0 && ((ListLength < Globals.RecordsPerTransaction) || EndOffset == TotalListLength)) {
		k$("#btnPrev").hide();
		k$("#btnNext").hide();
		return;
	} 
	else if ((ListLength < Globals.RecordsPerTransaction && Globals.Offset > 0) || EndOffset == TotalListLength) {
		k$("#btnPrev").show();
		k$("#btnNext").hide();
	} 
	else if (Globals.Offset == 0 && (ListLength == Globals.RecordsPerTransaction)) {
		k$("#btnPrev").hide();
		k$("#btnNext").show();
	}
	else {
		k$("#btnPrev").show();
		k$("#btnNext").show();
	}

}


function fnBuildListObjects(ret) {
	k$("#list-results").empty();
	k$("#searchStatus").html("Viewing results " + (parseInt(Globals.Offset) + 1) + " to " + (ret.CurTotal + Globals.Offset));
	k$.each(ret, function(i, n) {
		switch (i) {
			case "list":
				k$.each(n, function(i, n) {
					var elem = k$("#liElemsHTMLContainer").html();
					elem = ReplaceToken(elem, "[LIST_NUMBER]", ((i + 1) + Globals.Offset));
					elem = ReplaceToken(elem, "[NAME]", n.ItemName.toString());
					elem = ReplaceToken(elem, "[MESSAGE]", n.ItemMessage.toString());
					elem = ReplaceToken(elem, "[ADDRESS]", n.ItemAddress.toString());
					elem = ReplaceToken(elem, "[CITY]", (n.ItemCity != null && n.ItemCity.length > 0 ? n.ItemCity.toString() : ''));
					elem = ReplaceToken(elem, "[STATE]", (n.ItemState != null && n.ItemState.length > 0 ? ', ' + n.ItemState.toString() : ''));
					elem = ReplaceToken(elem, "[ZIP]", (n.ItemZip != null && n.ItemZip.length > 0 ? ' ' + n.ItemZip.toString() : ''));
					elem = ReplaceToken(elem, "[PHONE]", n.ItemPhone.toString());
					elem = ReplaceToken(elem, "[WEBSITE]", (typeof (n.ItemWebsite) !== 'undefined' && n.ItemWebsite != null) ? fnCheckWebsite(n.ItemWebsite.toString()) : fnCheckWebsite(null));
					elem = ReplaceToken(elem, "[GEOX]", n.GeoX.toString());
					elem = ReplaceToken(elem, "[GEOY]", n.GeoY.toString());
					k$(elem).appendTo("#list-results");
				});
				//Add this to fix live search inability to give me accurate results...  
				ListLength = k$(n).length;
				TotalListLength = ret.Total;
				setMapPoints(n);
				ToggleNavLinks();
				hideLoader();
				break;
		}
	});
}

function ReplaceToken(currString, token, val) {
	var i = currString.indexOf(token);
	var r = "";
	if (i == -1) return currString;
	r += currString.substring(0, i) + val;
	if (i + token.length < currString.length)
		r += ReplaceToken(currString.substring(i + token.length, currString.length), token, val);
	return r;
}

function fnInfoUserOfError(ret) {
	hideLoader();
	k$.facebox(ret);
}

function ClearMap(layer) {
	if (layer != null) {
		map.DeleteShapeLayer(layer);
		layer = null;
	}
}

function fnCheckWebsite(s) {
	var webUrlString = "";
	if (s != null && s.toString().length > 0) {
		if (s.toString().indexOf("//") > 0) {
			webUrlString = "<a href='" + s + "' target='_blank'>Website</a>&nbsp;|&nbsp;"
		} else {
			webUrlString = "<a href='http://" + s + "' target='_blank'>Website</a>&nbsp;|&nbsp;"
		}

		return webUrlString;
	}

	return webUrlString;
}

function setMapPoints(rows) {
	ClearMap(baseLayer);
	baseLayer = new VEShapeLayer();
	baseLayer.SetTitle("DEFAULT");
	map.AddShapeLayer(baseLayer);
	k$.each(rows, function(i, n) {
		var x = new VELatLong(n.GeoX, n.GeoY);
		var shape = new VEShape(VEShapeType.Pushpin, x);
		shape.SetCustomIcon("<div class='pinStyle DEFAULT'><div class='text'>" + ((i + 1) + parseInt(Globals.Offset)) + "</div></div>");
		shape.SetDescription('<div class="balloon">' +
		                        '<div class=\"balloon_top\">' +
		                            '<div class=\"balloon_title\">' + n.ItemName + '</div>' +
		                            '<div class=\"balloon_description\">' +
										'<span class=\"spDescription\">' + (n.ItemMessage != null && n.ItemMessage.length > 0 ? n.ItemMessage : '') + '</span><br />' + 
		                                '<span class=\"spAddress\">' + n.ItemAddress + '</span>' +
		                                '<br />' +
		                                '<span class=\"spAddRest\">' + (n.ItemCity != null && n.ItemCity.length > 0 ? n.ItemCity : '') + (n.ItemState != null && n.ItemState.length > 0 ? ', ' + n.ItemState : '') + (n.ItemZip != null && n.ItemZip.length > 0 ? ' ' + n.ItemZip : '') + '</span>' +
		                                '<br />' +
		                                '<strong>Phone:</strong> ' + n.ItemPhone +
		                            '</div>' +
		                        '</div>' +
		                        '<div class=\"balloon_bottom\">' +
									'<br />' +
		                            '<span class="web">' + fnCheckWebsite(n.ItemWebsite) + '</span><a href="#" onclick="fnShowAddressBalloon(this);return false;">Get Directions</a>' +
		                            '<div class="addy_callout">' +
		                                '<label for="txtAddress">Start: </label>' +
				                        '<input id="txtAddress" type="text" />&nbsp;' +
				                        '<a href="#GetDirections" class="srchDirections hide" onclick="fnCallGetDirectionsBalloon(this,' + n.GeoX + ', ' + n.GeoY + ')">go</a>' +
		                            '</div>' +
		                        '</div>' +
		                    '</div>');
		baseLayer.AddShape(shape);
	});
    var rect = baseLayer.GetBoundingRectangle();
	map.SetMapView(rect);
}

//used to set the zoom in fuction TODO -  make this a jQuery plugin
function fnSelectandZoom(obj) {
	var id = parseInt(k$(obj).parent().parent().children("td:first").children("span").text());
	id = id - Globals.Offset;
	for (var i = 0; i < map.GetShapeLayerCount(); i++) {
		var TargetLayer = map.GetShapeLayerByIndex(i);
		if (TargetLayer.GetTitle() == "DEFAULT") {
			var shape = TargetLayer.GetShapeByIndex(parseInt(id - 1));
        	map.SetCenterAndZoom(new VELatLong(shape.Latitude, shape.Longitude), 16);
			showBalloon(shape);
		}
	}

	return false;
}

function showBalloon(ob) {
	try {
		map.ShowInfoBox(ob);
	}
	catch (e) {
		k$.facebox("<div>" + e.description + "</div>");
	}

}

function showLoader() {
	//k$(".load_graphic").css({ "height": (getPageHeight()+getPageScroll()[1]) });
	k$(".load_graphic").show();
}

function hideLoader() {
	k$(".load_graphic").hide();
}


function fnShowAddress(obj) {
	var d = k$(obj).parent().parent().parent().next().find(".addy_callout");
	d.slideDown(500);
	d.find(".txtAddress").keypress(function(e) {
		if (e.which == 13) {
			k$(this).next().click();
			return false;
		}
	});
	
	return false;
}

function fnShowAddressBalloon(obj) {
	var d = k$(obj).parent().find(".addy_callout")
	d.slideDown(500);
	d.find("#txtAddress").keypress(function(e) {
		if (e.which == 13) {
			k$(this).next().click();
			return false;
		}
	});
	
	return false;
}

function fnCallGetDirectionsBalloon(obj, lat, lon) {
	var spAddRest = k$(obj).parent().parent().parent().parent().find(".spAddRest").html();
	var balloonTitle = k$(obj).parent().parent().parent().parent().find(".balloon_title").html();
	var spAddress = k$(obj).parent().parent().parent().parent().find(".spAddress").html();
	
	GLBL_ADDRESS = (balloonTitle != null && balloonTitle.length > 0 ? balloonTitle : '') + (spAddress != null && spAddress.length > 0 ? ', ' + spAddress : '') + (spAddRest != null && spAddRest.length > 0 ? ', ' + spAddRest : '');
	//alert(j$(obj).parent().parent().parent().parent().find("#").html());
	DIR_ARRAY = new Array();
	//grab address from input box
	DIR_ARRAY.push(k$(obj).parent().find("#txtAddress").val());
	//grab lat lon from point
	var pt = new VELatLong(lat, lon);
	DIR_ARRAY.push(pt);
	fnGenerateDirections();
}

function fnCallGetDirections(obj, lat, lon) {
	var spAddRest = k$(obj).parent().parent().parent().parent().find(".spAddRest").html();
	var mapEventTitle = k$(obj).parent().parent().parent().parent().find(".map_event_title").html();
	var spAddress = k$(obj).parent().parent().parent().parent().find(".spAddress").html();
	
	GLBL_ADDRESS = (mapEventTitle != null && mapEventTitle.length > 0 ? mapEventTitle : '') + (spAddress != null && spAddress.length > 0 ? ', ' + spAddress : '') + (spAddRest != null && spAddRest.length > 0 ? ', ' + spAddRest : '');
	DIR_ARRAY = new Array();
	//grab address from input box
	DIR_ARRAY.push(k$(obj).parent().find(".txtAddress").val());
	//grab lat lon from point
	var pt = new VELatLong(lat, lon);
	DIR_ARRAY.push(pt);
	fnGenerateDirections();
}

function fnGenerateDirections() {
	var options = new VERouteOptions;
	options.DrawRoute = true;
	// Call this function when map route is determined:
	options.RouteCallback = ShowTurnByTurn;
	// Show as miles
	options.DistanceUnit = VERouteDistanceUnit.Mile;
	options.ShowDisambiguation = true;
	map.GetDirections(DIR_ARRAY, options);

	return false;
}


// mao routing
// returns a formatted string
function GetTime(time) {
	if (time == null) {
		return ("");
	}

	if (time > 60) {                                 // if time == 100
		var seconds = time % 60;       // seconds == 40
		var minutes = time - seconds;  // minutes == 60
		minutes = minutes / 60;    // minutes == 1


		if (minutes > 60) {                                     // if minutes == 100
			var minLeft = minutes % 60;        // minLeft    == 40
			var hours = minutes - minLeft;   // hours      == 60
			hours = hours / 60;          // hours      == 1

			return (hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
		}
		else {
			return (minutes + " minutes, " + seconds + " seconds");
		}
	}
	else {
		return (time + " seconds");
	}
}

function ShowTurnByTurn(route) {
	var Hcontent = "<h3>Turn-by-Turn Directions</h3>";
	Hcontent += "<p><b>Distance:</b> " + route.Distance.toFixed(1) + " miles";
	Hcontent += "<br/><b>Time:</b> " + GetTime(route.Time) + "</p>";
	Hcontent += "<hr/>";

	// Unroll route and populate DIV
	var legs = route.RouteLegs;
	var leg = null;
	var turns = "";
	// Get intermediate legs
	for (var i = 0; i < legs.length; i++) {
		// Get this leg so we don't have to derefernce multiple times
		leg = legs[i];  // Leg is a VERouteLeg object
		// Unroll each intermediate leg
		var turn = null;  // The itinerary leg
		var legDistance = null;  // The distance for this leg

		for (var j = 0; j < leg.Itinerary.Items.length; j++) {

			turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
			turns += "<li class=\"Directions\">";
			if (j == 0) //begin departure
			{
				turns += "<b>Start: </b>\t" + turn.Text;
				
				turn.Shape.SetZIndex(10000);
				turn.Shape.SetDescription(turn.Text);
			}
			else if (j == (leg.Itinerary.Items.length - 1))//end arrive
			{
				turns += "<b>End: </b>\t" + GLBL_ADDRESS;
				
				turn.Shape.SetZIndex(10000);
				turn.Shape.SetDescription(GLBL_ADDRESS);
			}
			else {
				turns += "<b>" + j + "</b>\t" + turn.Text;
			}
			legDistance = turn.Distance;

			// So we don't show 0.0 for the arrival
			if (legDistance > 0.1) {
				// Round distances to 1/10ths
				turns += " (" + legDistance.toFixed(1) + " miles";

				// Append time if found
				if (turn.Time != null) {
					turns += "; " + GetTime(turn.Time);
				}

				turns += ")<br/>";
			}
			else {
				turns += "<br/>";
			}
			turns += "</li>";
		}
		// Populate with directions
		SetDirections(Hcontent, turns);
	}
}


function SetDirections(headerContent, liItems) {
	//header content on General Trip Estimates
	PREV_CONTENT = k$("#_left_List_content").html();
	//hide the next/prev buttons along with the notice of record viewing
	k$("#btnPrev").hide();
	k$("#btnNext").hide();
	k$("#searchStatus").hide();
	
	
	k$("#_left_List_content").html("");
	k$("#_left_List_content").html("<br />" +
	                               "<div style='text-align:center;'>" +
	                                    "<a href='#Print' onclick='fnPrintMap()'><img src='/DesktopModules/KSTech.BasicMapModule/images/print.gif' alt='Print' border='0' /></a>&nbsp;<a href='#Print' onclick='fnPrintMap()'>Print</a>&nbsp;&nbsp;&nbsp;" +
	                                    "<a href='#email' onclick='fnEmailMap()'><img src='/DesktopModules/KSTech.BasicMapModule/images/email.gif' alt='Email' border='0' /></a>&nbsp;<a href='#email' onclick='fnEmailMap()'>Email</a>&nbsp;&nbsp;&nbsp;" +
	                                    "<a href='#Clear' onclick='fnClearMap()'><img src='/DesktopModules/KSTech.BasicMapModule/images/hide.gif' alt='Hide' border='0' /></a>&nbsp;<a href='#Clear' onclick='fnClearMap()'>Hide</a>" +
	                                "</div>" +
	                                "<ol>" + liItems + "</ol>");
	//fnUpdateOrbs(ACTIVE_INDEX);
	
}

function fnPrintMap() {
	window.open('/DesktopModules/KSTech.BasicMapModule/html/PrintMap.htm');
}

function ClearAll() {
	map.DeleteRoute();
}

function fnEmailMap(list) {
	var dirs = "";
	k$("#_left_List_content  li.Directions").each(function() {
		dirs += k$(this).html();
	});
	//open the facebox with a field to enter the address for the user
	k$.facebox('<div id="Formemail"> \
				<p>Enter in the Email Address to send the directions to: </p> \
				<div><input type="text" class="fmLonger" id="frmEmailAddress" /></div> \
                <div><hr /></div> \
				<div class="confirmationButtons"> \
					<a href="#" id="btnSubmitEmail">Submit</a> | <a href="#" id="btnCancelEmail">cancel</a> \
				</div></div>');

	k$("#facebox .footer").hide();

	k$("#btnCancelEmail").click(function() {
		k$.facebox.close();
		return false;
	});

	k$("#btnSubmitEmail").click(function() {
		Proxy.invoke("email.ashx", "{ 'Address': '" + k$("#frmEmailAddress").val() + "', 'Body' : '" + dirs + "'}", fnEmailSentSuccessfully, fnInfoUserOfError);
		k$.facebox.close();
		return false;
	});
}

function fnEmailSentSuccessfully() {
	k$.facebox("<div>Email Sent Successful!</div>");
}

function fnClearMap() {
	map.DeleteRoute();
	k$("#_left_List_content").html(PREV_CONTENT);
	//hide the next/prev buttons along with the notice of record viewing
	ToggleNavLinks();
	k$("#searchStatus").show();
	return false;
}

//DEFAULT JAVSCRIPT FUNCTIONS CLASSES -------------- End -------------//
