var dirFromPoint;
var dirToPoint;

var gotFrom = false;
var gotTo = false;
var fromLat = null;
var fromLong = null;
var toLat = null;
var toLong = null;
var fromAdditional = ", 271 Walnut St., Phone: 314-231-2355"
var toAdditional = ", 1900 Market St., Phone:322-123-1231"

var fromBox;
var toBox;

function fixAddress(address) {
	address = address.toLowerCase();
	if (address.split(",").length <=1 ) {
		address = address + ", Philadelphia, PA";
	}
	return address;
}
function showDirections() {
	gotFrom = false;
	gotTo = false;

	closeHelp();
	fromAdditional = "";
	toAdditional = "";	
	
	fromBox = unescape($J.trim($J("#dirFrom").val()));
	toBox = unescape($J.trim($J("#dirTo").val()));
	
	if (fromBox == "" || fromBox == null) {
		alert("Please choose a location to get directions from.");
		return;
	}
	if (toBox == "" || toBox == null) {
		alert("Please choose a location to get directions to.");
		return;
	}	
	
	console.log("!!! SHOW DIRECTIONS");
	renderQueueClear();
	clearCheckboxes();
	clearRequests();
	
	var pars = sprintf('request=unitLookup&unitTitle=%s', fromBox);
	ajaxDirFrom = new Ajax.Request( "/map/MapsAjaxHandler.aspx", { method: 'get', onlyLatestOfClass: 'dirFrom', parameters: pars, onComplete: function(originalRequest) {		
		var response = originalRequest.responseText;
		//$D("SEARCH RESULTS:"  + response)
		eval(sprintf('dirFromPoint = %s.compact()', response ));
		//console.log("GOT POINT: " + dirFromPoint)
		if (dirFromPoint.length == 0) {
			console.log("no from point");			
			var address = fromBox;
			address = fixAddress(address);
			
			geocoderClient.getLatLng(
				address,
				function(point) {
				  if (!point) {
					alert(address + " not found");
				  } else {
					console.log(point);
					setFromPoint(point.x,point.y);
				  }
				}
			  );
		} else {
			setAdditionalInfo(dirFromPoint[0],0);			
			setFromPoint(dirFromPoint[0].Pos.x, dirFromPoint[0].Pos.y);
		}
		ajaxDirFrom = null;
	  }
	});
	
	var pars = sprintf('request=unitLookup&unitTitle=%s', toBox);
	ajaxDirTo = new Ajax.Request( "/map/MapsAjaxHandler.aspx", { method: 'get', onlyLatestOfClass: 'dirTo', parameters: pars, onComplete: function(originalRequest) {		
		var response = originalRequest.responseText;
		//$D("SEARCH RESULTS:"  + response)
		eval(sprintf('dirToPoint = %s.compact()', response ));
		if (dirToPoint.length == 0) {
			console.log("no to point");			
			var address = toBox;
			address = fixAddress(address);
			
			geocoderClient.getLatLng(
				address,
				function(point) {
				  if (!point) {
					alert(address + " not found");
				  } else {
					console.log(point);
					setToPoint(point.x,point.y);
				  }
				}
			  );
		} else {
			setAdditionalInfo(dirToPoint[0],1);
			setToPoint(dirToPoint[0].Pos.x, dirToPoint[0].Pos.y);
		}
		ajaxDirTo = null;
	  }
	});
	
}
function setAdditionalInfo(wPoint,wNum) {
	var iInfo = "";
	if (wPoint.UnitAddress1 != "") 	iInfo += ", " + wPoint.UnitAddress1;
	if (wPoint.UnitAddress2 != "") 	iInfo += ", " + wPoint.UnitAddress2;
	if (wPoint.UnitPhone != "") 	iInfo += ", " + wPoint.UnitPhone;		
	
	if (wNum == 0)
		fromAdditional = iInfo;
	if (wNum == 1)
		toAdditional = iInfo;
		
	console.log(toAdditional);
}

function setFromPoint(x,y) {
	gotFrom = true;
	fromLong = x;
	fromLat = y;
	displayDirections();
}

function setToPoint(x,y) {
	gotTo = true;
	toLong = x;
	toLat = y;
	displayDirections();
}

function displayDirections() {
	if (!gotTo) return;
	if (!gotFrom) return;	
	
	map.clearOverlays();
	clearDirections();

		//pars = pars.replace("’","'");
	//directions.load("from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)");
	directionString = sprintf('["%s@%s,%s", "%s@%s,%s"]',fromBox + fromAdditional , fromLat, fromLong,toBox + toAdditional, toLat, toLong);
	

	console.log(directionString);
	$J("#directionsFull").show();
	directionsClient.loadFromWaypoints(eval(directionString)); 
	setTimeout(function() {showStepArrow();},2000);

}

function fromHere(wString) {
	$J("#dirFrom").val(wString);
	showField("#dirFrom");
	showDirArrow(353);	
}

function showField(wField){
	cItem = $J(wField).parents(".dirItem").find("LABEL");
	cItem.animate({		
	  color:'#FFFFFF',
	  backgroundColor: '#379fc7'
	}, 1000, "easeOutCubic",function() { 
		cItem.animate({
		color:'#2c7c9b',
	 	backgroundColor: '#EDF4F6'
		}, 1000, "easeInCubic");
	
	});
}
function toHere(wString) {
	$J("#dirTo").val(wString);
	showField("#dirTo");	
	showDirArrow(377);
}


function showDirArrow(wTop) {
	if ($J("#dirArrow").queue().length > 0)
		return;
	$J("#dirArrow").hide();
	$J("#dirArrow").css("top", wTop);
	$J("#dirArrow").css("left", 100);
	$J("#dirArrow").animate({ left:10, opacity:"show"}, { easing:"easeOutBounce", duration:1000 }).animate({ right:10}, { duration:1000 }).animate({ opacity:"hide"}, {  easing:"easeInCubic",  duration:1000 })

}

function showStepArrow() {
	if ($J("#stepArrow").queue().length > 0)
		return;
	$J("#stepArrow").hide();
	$J("#stepArrow").css("bottom", 100);
	$J("#stepArrow").css("left", 20);	
	$J("#stepArrow").animate({ bottom:10, opacity:"show"}, { easing:"easeOutBounce", duration:1500 }).animate({ left:20}, { duration:1000 }).animate({ opacity:"hide"}, {  easing:"easeInCubic",  duration:1000 })

}
function selectField(wField) {
	wField.select();
}

function clearDirections() {
	directionsClient.clear();
	$J("#directionsFull").hide();
}

function formatLL(wNum) {
	roundTo = 1000000;
	wNum = wNum * roundTo;
	wNum = Math.round(wNum);	
	return wNum/roundTo;
}
function directionsGoogle() {
	var saddr = sprintf("%s,%s+(%s)", formatLL(fromLat), formatLL(fromLong), escape(fromBox));
	var daddr = sprintf("%s,%s+(%s)", formatLL(toLat), formatLL(toLong),escape(toBox));
		
	var baseURL = "http://maps.google.com/maps?saddr=" + saddr + "&daddr=" + daddr + "&dirflg=w"; // added walking flag
	baseURL = baseURL.replace("%u2019","'");
	console.log(baseURL);
	launchFullWindow(baseURL, 'GoogleMap')	
}

function printDirections() {
	window.print();
}