var myMap;
var myMap2;
var newCenter = new MQLatLng(30.00000,30.00000);
var myPxyServer = "";
var myPxyPort = "";
var myPxyPath = "";
var mqMServer = "";
var mqRServer = "";
var mqGeoServer = "";
var mqServletPath = "";
var mqServletPort="";

var nearbyCounter = 0;
var nearbyArray = new Array();
var primaryHotel;
var poiCollectionArray = new Array();
var toFromStatus = "to";
//---MQ server variables----------------------------------------------

var mapExec;
var mqHTTPMServer;
var routeOpt;
var routeExec;
var myLocColl = new MQLocationCollection("MQGeoAddress");
var myGeoOptions = new MQGeocodeOptions();
var myRouteResults;
var mySessID;
var myBoundBox = new MQRectLL(new MQLatLng(),new MQLatLng());
var myRouteColl = new MQLocationCollection();
var myDistUnits = new MQDistanceUnits(0);
var myManeuvers = new MQManeuverCollection();
var myDC = new MQDeclutter();
var myPOI;
var suggestionsArray;
var navContent = new Array();
var lat;
var lon;
var poisBuilt = "false";
var primaryLatLongFound = "true";
MQInitOverlays(reCenter2);

function initPoiCollectionArray()
{
   for(var i = 0; i < (document.cbForm.poi.length); i++) {
   	 var mqCollection = new MQPoiCollection();
     var collectionType = document.cbForm.poi[i].value;
     var mqObject = { "Type" : collectionType, "PoiCollection" : mqCollection };
     poiCollectionArray[i] = mqObject;
   }
  
}

function buildPOIS( ) 
{
   // Loop over jsonContent array
   for (i = 0; i < navContent.length; i++) {
       	createPOI( navContent[i], (i+4), i );
       	//once we've built the initial set of poi's no need to re-create  
		poisBuilt = "true";
   }
   
   for (i=0; i < nearbyArray.length; i++)
   {
		createNearbyPoi( nearbyArray[i] );
   }

   jQuery('#updatingBlockOverlay').hide();
   jQuery('#updatingBlock').hide();
   
}

function createNearbyPoi( nrby )
{
	var latti = parseFloat( nrby.Latitude ) + 0.00;
	var longi = parseFloat ( nrby.Longitude ) + 0.00;
	if(( isNaN( latti ) ) || ( isNaN( longi ) ) )
	{
		return;
	}
 	var myNrby = new MQPoi(new MQLatLng( latti, longi ));
 	var headId = "nearby"+nrby.ID;
	var infoId = "info"+nrby.ID;
 
    myNrby.setInfoTitleHTML( document.getElementById(headId).innerHTML );
	myNrby.setInfoContentHTML( document.getElementById(infoId).innerHTML );
	
	//you can set a Key value to help keep track of the POIs you put on the map
	myNrby.setKey(nrby.ID);
	newIcon = new MQMapIcon();

	newIcon.setImage(nrby.Icon,40,40,true,true);
	myNrby.setIcon(newIcon);
	
	//Add the POI to the map
	myMap.addPoi(myNrby);
	nrby.Marker = myNrby;
	var collectionLength = poiCollectionArray.length - 1;
	poiCollectionArray[collectionLength].PoiCollection.add( myNrby );
 	
}

function enablePOIS( ) {
   // Loop over jsonContent array
   myMap.removeAllPois();
   var doBestFit = "false";
  	for(l = 0; l < poiCollectionArray.length; l++)
	{
	  var myNode = poiCollectionArray[l];
	  if( document.cbForm.poi[l].checked )
	  {
	  	myMap.addPois( myNode.PoiCollection );
	  	doBestFit = "true";
	  }
	}
	if( doBestFit == "true")
	{
		myMap.bestFit(true);
	}
}

function createPOI( jsonObj, i, originalIndex ) 
{

	var longi = parseFloat( (jsonObj.address.latLong.longitude).toFixed(5) ) + 0.00;
	var latti = parseFloat( (jsonObj.address.latLong.latitude).toFixed(5)  ) + 0.00;
	if(( isNaN( latti ) ) || ( isNaN( longi ) ) )
	{
		return;
	}
	
 	newPOI = new MQPoi(new MQLatLng( latti, longi ));
	
	var content = "";
	content += "<div class=\"mapPopPOIContent vcard\"><span class=\"adr\">" + jsonObj.address.addressLine+ "</span>";
	content += "<span class=\"mapPopPOILocale locale\">" + jsonObj.address.city;
	content += "," + jsonObj.address.postalCode + "," + jsonObj.address.countryCode + "</span></div>";
	content += '<p>'+jQuery('#poiGetDir').val()+'<a href="#" onClick="javascript:doPoiRouting( \'1\',\''+originalIndex+'\' );" >'+jQuery('#poiToHere').val()+'</a>  - ';
	content += '<a href="#" onClick="javascript:doPoiRouting( \'2\',\''+originalIndex+'\' )" >'+jQuery('#poiFromHere').val()+'</a></p>';
	
	var hd = "<h4 class=\"mapPopPOIName fn org\">" + jsonObj.name + "</h4>";
	newPOI.setInfoTitleHTML( hd );
	newPOI.setInfoContentHTML( content );
	newPOI.setKey( jsonObj.name );
	
	var image;
	if(jsonObj.type == "TRAINS")
	{
		image = jQuery('#trainPath').val();
	}
	else if(jsonObj.type == "BUSES")
	{
		image = jQuery('#busPath').val();
	}
	else if(jsonObj.type == "PLANES")
	{
		image = jQuery('#airportPath').val();
	}
	else if(jsonObj.type == "SUBWAY")	
	{
		image = jQuery('#subwayPath').val();
	}
	else if(jsonObj.type == "BOATS")	
	{
		image = jQuery('#ferryPath').val();
	}
	else
	{
		image = jQuery('#genericPath').val();
	}
	var newMarker = new MQMapIcon();
    newMarker.setImage(image,40,40,false,false);
	newPOI.setIcon(newMarker);
	jsonObj.Marker = newPOI;
	for(l = 0; l < poiCollectionArray.length; l++)
	{
	  var myNode = poiCollectionArray[l];
	  if(jsonObj.type == myNode.Type)
	  {
	  	myNode.PoiCollection.add( newPOI );
	  	l = poiCollectionArray.length;
	  }
	}
}

function doPoiRouting( toFrom, nodeIndex )
{
	var o1 = navContent[nodeIndex];
	jQuery('#myResultsDiv').hide();
	
	if(toFrom == 1)
	{
		if(toFromStatus == "to")
		{
			document.getElementById("directionsFrom").value = document.getElementById("directionsTo").value ;
		}
		document.getElementById("directionsTo").value = o1.name;
		toFromStatus = "from";
	}
	else
	{
		if(toFromStatus == "from")
		{
			document.getElementById("directionsTo").value = document.getElementById("directionsFrom").value ;
		}
		document.getElementById("directionsFrom").value = o1.name;
		toFromStatus = "to";
	}
	document.getElementById("mapItBtn").innerHTML = "<span>"+jQuery('#clearLabel').val()+"</span>";
	doRoute(nodeIndex, "poi");
	
}
function reCenter()
{
	myMap = new MQTileMap(document.getElementById('mapWindow'),4,newCenter,"");

}
//Recenter function - hardcoded to NY,NY lat/Lng
function reCenter2()
{
	//Create the base MQTileMap object and pass in the id of the DIVyou want to hold the map
 	jQuery('#updatingBlockOverlay').show();
    jQuery('#updatingBlock').show();

	initPoiCollectionArray();
	var zoomMap = 8;
	if(primaryLatLongFound == "false" )
	{
		zoomMap = 1;
	}
	  
	myMap = new MQTileMap(document.getElementById('mapWindow'),zoomMap,newCenter,"");
	myDC = myMap.getDeclutter();
	myDC.setLeaderLineDotMode(1);
	myDC.setLeaderLineColor("red");
    myDC.setDeclutterMode(2);
    myMap.getInfoWindow().setTitleBackgroundColor("#FFFFFF");
    myMap.getRolloverWindow().setTextLength("50");

	//Add the POI to the map
	if(primaryLatLongFound == "true" )
	{
		// Create a new Large Zoom control
		myLZControl = new MQLargeZoomControl;
	
		//tell the map to display the control we just attached
		myMap.addControl(myLZControl);
	
		//Create a map view type control
		myVControl = new MQViewControl(myMap);
		
		/*
		Display control - use the Corner placement constant to specify
		which corner, plus an MQSize object to specify X and Y "indent"
		offset
		*/
		myMap.addControl(myVControl, new MQMapCornerPlacement(MQMapCorner.BOTTOM_RIGHT, new MQSize(20,20)));

		//set any rollover and pop-up text]
		myPOI = new MQPoi( newCenter )
		myPOI.setInfoContentHTML( document.getElementById('hotelInfoDiv').innerHTML );
		myPOI.setInfoTitleHTML( document.getElementById('hotelAtrName').innerHTML );
		
		//you can set a Key value to help keep track of the POIs you put on the map
		myPOI.setKey(0);
		newIcon = new MQMapIcon();
		newIcon.setImage(primaryHotel.Icon,48,48,true,true);
		myPOI.setIcon(newIcon);

		myMap.addPoi(myPOI);
		primaryHotel.Marker = myPOI;
		myMap.getInfoWindow().setMinWidth("250px");

		//Hilton Hotels always go at the end of the collection array
		var collectionLength = poiCollectionArray.length - 1;
		poiCollectionArray[collectionLength].PoiCollection.add( myPOI );

		//DWR HERE WE GO
		MappingUtils.getPointsOfInterest( primaryHotel.Ctyhocn, 3, { callback:getDwrResultsPoi, timeout:30000, errorHandler:errorPoi } );
	}
	else
	{
	    document.getElementById("mapItBtn").disabled = true;
	    document.getElementById("mapItBtn").onclick = null;
		jQuery('#updatingBlockOverlay').hide();
	    jQuery('#updatingBlock').hide();
		alert( jQuery('#alertNoMap').val() );
	}
}

function getDwrResultsPoi( e ) 
{
	if((e != 'undefined') && (e != 'null'))
	{
		var tmpA = eval( e );
		//alert( "tmpA is type of " + typeof(tmpA) );
		if(typeof tmpA == "object")	
		{
			navContent = tmpA;
		}
		else
		{
			navContent = new Array();
		}	
		//alert("getDwrResultsPoi() = " + navContent.length );
	}
	else
	{
		navContent = new Array();
	}
	buildPOIS();	
}

function errorPoi( e ) 
{
	//alert("errorPoi() = " + e + ": poisBuilt = " + poisBuilt );
	if( poisBuilt == "false" )
	{
		buildPOIS();
	}
}

function echoNewHotel(  lat, lon, name, add, city, country, icon, ctyhocn ) 
{
	if(( isNaN( parseFloat(lat) ) ) || ( isNaN( parseFloat(lon) ) ) )
	{
		//set up a center somewhere in the middle of the world
		lat = 30.00000;
		lon = 30.00000;
		primaryLatLongFound = "false";	
	}
	var latti = parseFloat(parseFloat(lat).toFixed(5) + 0.00);
	var longi =	parseFloat(parseFloat(lon).toFixed(5) + 0.00);
	
	myPxyServer = jQuery('#hostPath').val();
	myPxyPort = jQuery('#hostPort').val();
	myPxyPath = jQuery('#mqProxy').val();
	mqServletPath = jQuery('#mqServletPath').val();
	mqServletPort = jQuery('#mqServletPort').val();
	mqMServer = jQuery('#mqMap').val();
	mqRServer = jQuery('#mqRoute').val();
	mqGeoServer = jQuery('#mqGeo').val();
	mqHTTPMServer = "http://" + mqMServer;
	
	newCenter = new MQLatLng(latti,longi);
	primaryHotel = { "Ctyhocn" : ctyhocn, "Name" : name, "Longitude" : longi, "Latitude" : latti, "Icon" : icon,  "Address" : add, "City" : city, "Country" : country };
}

function appendNearbyHotel( name, add, country, city, state, zip, icon, latitude, longitude )
{
	nearbyCounter++;
	var NearbyHotel = { "Name" : name, "Longitude" : longitude, "Latitude" : latitude, "Icon" : icon, "ID" : nearbyCounter, "Address" : add, "City" : city, "Country" : country };
	var arCtr = nearbyCounter - 1;
	nearbyArray[arCtr] = NearbyHotel;
}

//My Route Function
function doRoute( ctr, arrayType ) {
 	jQuery('#updatingBlockOverlay').show();
    jQuery('#updatingBlock').show();
	mapExec = new MQExec(mqMServer, mqServletPath, mqServletPort, myPxyServer,
                                 myPxyPath, myPxyPort );
	routeExec = new MQExec(mqRServer, mqServletPath, mqServletPort, myPxyServer,
                                 myPxyPath, myPxyPort );

	//geocode the addresses
	var geoAddr1 = new MQGeoAddress();
	var geoAddr2 = new MQGeoAddress();	
    var gaCollection = new MQLocationCollection("MQGeoAddress");
 
    var addressNode;
    if(arrayType == "nearby")
    {
    	//alert("found suggestions array of " + ctr );
	    addressNode = suggestionsArray[ctr];
	}
	else
	{
		addressNode = navContent[ctr];
	}
	
	if(addressNode.address!=null){
		geoAddr1.setStreet( addressNode.address.addressLine );
		geoAddr1.setCity( addressNode.address.city );
		geoAddr1.setState(addressNode.address.state);
		geoAddr1.setPostalCode(addressNode.address.postalCode);
		geoAddr1.setCountry( addressNode.address.countryCode );
		if(addressNode.address.latLong!=null){
			var longi = parseFloat( (addressNode.address.latLong.longitude).toFixed(5) ) + 0.00;
			var latti = parseFloat( (addressNode.address.latLong.latitude).toFixed(5)  ) + 0.00;
			var mqLat = new MQLatLng( latti, longi );
		  	geoAddr1.setMQLatLng( new MQLatLng( latti, longi ) );
 	 	}
  	}
		
    //populate the 2nd address object with the information from the form
    //and the lon/lat from our primary hotel poi on the map
    geoAddr2.setStreet( primaryHotel.Address );
    geoAddr2.setCity( primaryHotel.City );
    geoAddr2.setState("");
    geoAddr2.setPostalCode("");
    geoAddr2.setCountry(primaryHotel.Country);
    geoAddr2.setMQLatLng( primaryHotel.Marker.getLatLng() );
    
	var session = new MQSession();	
	var wayPoints = new MQLocationCollection();
	var myBB = new MQRectLL(new MQLatLng(),new MQLatLng());
	myRouteResults = new MQRouteResults();

	if(toFromStatus == "to")
	{
		wayPoints.add(geoAddr1);
		wayPoints.add(geoAddr2);
	}
	else
	{
		wayPoints.add(geoAddr2);
		wayPoints.add(geoAddr1);
	}
	
	routeOpt = new MQRouteOptions();
	routeOpt.setLanguage( jQuery('#langPref').val() ); 
	routeOpt.setCoverageName( "" );
	var d = parseInt( jQuery('#unitPref').val() ) + 0;
	routeOpt.setDistanceUnits( new MQDistanceUnits( d ) );
	var sessId = routeExec.createSessionEx(session);
	routeExec.doRoute(wayPoints,routeOpt,myRouteResults,sessId,myBB);
	myMap.addRouteHighlight(myBB,mqHTTPMServer,sessId,true);
	calculateRouteDistance();
}

// time is an integer representing seconds
// 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 + " " + jQuery('#hourPref').val() + ",  " + minLeft + " " + jQuery('#minPref').val() + ",  " + seconds + " " + jQuery('#secPref').val());
      }
      else
      {
         return(minutes + " " + jQuery('#minPref').val() + ",  " + seconds + " " + jQuery('#secPref').val());
      }
   }
   else
   {
      return(time + " " + jQuery('#secPref').val());
   }
}

function calculateRouteDistance()
{
    var myMinutes = myRouteResults.getTime();
    var myTotTime = GetTime( myMinutes );
    var myDist = Math.round(myRouteResults.getDistance()*100)/100;
	var myManStr = '<h2 class="destinationDirectionsInstructions">'+jQuery('#routeHdrLabel').val()+'</h2>';
	myManStr += '<ol class="destinationDirectionsInstructions">';

    for (intX = 0; intX < myRouteResults.getTrekRoutes().get(0).getManeuvers().getSize(); intX ++){
      myManDist = Math.round(myRouteResults.getTrekRoutes().get(0).getManeuvers().get(intX).getDistance()*100)/100;
	  myManStr += '	<li><span class="directionsCommand">';
	  myManStr += myRouteResults.getTrekRoutes().get(0).getManeuvers().get(intX).getNarrative()
	  myManStr += '</span><span class="directionsTime">'
	  myManStr += myManDist + " " +jQuery('#distPref').val() + "</span></li>";
    }
    
	myManStr += '</ol><p>'+jQuery('#driveTime').val() + "  " + myTotTime + "<br />"+jQuery('#driveDist').val() + "  "  + myDist + " " + jQuery('#distPref').val() + "</p>";
	document.getElementById("myResultsDiv").innerHTML = myManStr;
	jQuery('#myResultsDiv').toggle();
 	jQuery('#updatingBlockOverlay').hide();
    jQuery('#updatingBlock').hide();
}

function getDirections(displayIt,toValue,arLen)
{
 	 var directions = "";
	 if(displayIt == "true")
	 {
		jQuery('#autoHelpSuggestion').hide();
		doRoute(toValue,"nearby");
		var text = "";
		if( suggestionsArray[toValue].address.addressLine != "" ) { text += suggestionsArray[toValue].address.addressLine; }
		if( suggestionsArray[toValue].address.city != "" ) { text += ", " + suggestionsArray[toValue].address.city; }
		if( suggestionsArray[toValue].address.state != "" ) { text += ", " +  suggestionsArray[toValue].address.state; }
		if( suggestionsArray[toValue].address.countryCode != "" ) { text += ", " +  suggestionsArray[toValue].address.countryCode;}
		if( suggestionsArray[toValue].address.postalCode != "" ) { text += ", " +  suggestionsArray[toValue].address.postalCode;}
		if( text == "")
		{
		  text = suggestionsArray[toValue].name;
		}
	 	 
		 if(arLen > 1)
		 {
		 	//if the user was only returned 1 suggestion keep what they originally typed
		 	//else show what they selected from the list
		 	document.getElementById("directionsFrom").value = text;
		 }
  	 	 document.getElementById("mapItBtn").innerHTML = "<span>"+jQuery('#clearLabel').val()+"</span>";
  	}
	else
	{
		var mbtn = "";
		if(document.all){
 		    mbtn = document.getElementById('mapItBtn').innerText;
		} else{
		    mbtn = document.getElementById('mapItBtn').textContent;
		}	
		if( mbtn == jQuery('#clearLabel').val() )
		{
		    if(document.getElementById("autoHelpSuggestion").style.display != "none")
		    {
				jQuery('#autoHelpSuggestion').hide();
    	 	}
    	 	document.getElementById("mapItBtn").innerHTML = "<span>"+jQuery('#mapItLabel').val()+"</span>";
 		 	jQuery('#myResultsDiv').toggle();
    	 	myMap.removeRouteHighlight();
		 	myMap.bestFit(true);
		 	if(	toFromStatus == "from")
		 	{
		 		document.getElementById("directionsTo").value = document.getElementById("directionsFrom").value ;
		 	}
		    document.getElementById("directionsFrom").value = "";
		    toFromStatus = "to";
		 }
		 else
		 {
		 	jQuery('#updatingBlockOverlay').show();
		    jQuery('#updatingBlock').show();
		  	var searchQuery = document.getElementById('directionsFrom').value;
		  	MappingUtils.getAdhocResults( searchQuery, { callback:buildDidYouMean, timeout:30000, errorHandler:errorDidYouMean } );
 		 }
	}  
  
}

function buildDidYouMean(e) {
	suggestionsArray = eval( e );
	var inner;
	if((suggestionsArray != 'undefined') && (suggestionsArray != 'null'))
	{
		if(suggestionsArray.length == 1)
		{
			getDirections('true', 0, 1 );
			return;
		}
		else
		{
			inner = '<p class="didYouMean">'+jQuery('#didYouMeanLabel').val()+'</p>';
			inner += '<ul>';
		   	for (i=0; i < suggestionsArray.length; i++)
			{
			   var text = "";
			   if( suggestionsArray[i].suggestedQuery != "")
			   {
			   		text =  suggestionsArray[i].suggestedQuery;
			   }
			   else
			   {
				   if( suggestionsArray[i].address.addressLine != "" ) { text += suggestionsArray[i].address.addressLine; }
				   if( suggestionsArray[i].address.city != "" ) { text += ", " + suggestionsArray[i].address.city; }
				   if( suggestionsArray[i].address.state != "" ) { text += ", " +  suggestionsArray[i].address.state; }
				   if( suggestionsArray[i].address.countryCode != "" ) { text += ", " +  suggestionsArray[i].address.countryCode;}
				   if( suggestionsArray[i].address.postalCode != "" ) { text += ", " +  suggestionsArray[i].address.postalCode;}
			   }
			   if( text == "")
			   {
			     text = suggestionsArray[i].name;
			   }

			   inner += '<li><a href="javascript:getDirections(\'true\','+ i + ',' + 2 + ');">'+text+'</a></li>';
			}
			inner += '</ul>';
			inner += '<p><a href="javascript:resetDidYouMean()">'+jQuery('#resetDidYouMeanLabel').val()+'</a></p>';
		}
	}
	else
	{
		inner = '<p class="didYouMean">'+jQuery('#addNotFoundLabel').val();
		inner += '</p>';
		inner += '<p/><p><a href="javascript:resetDidYouMean()">'+jQuery('#closeDidYouMeanLabel').val()+'</a></p>';
		
	}	
	document.getElementById("autoHelpSuggestion").innerHTML = inner;
 	jQuery('#updatingBlockOverlay').hide();
    jQuery('#updatingBlock').hide();
  	jQuery('#autoHelpSuggestion').show();
	
}
function errorDidYouMean(e) {
	var inner;
	inner = '<p class="didYouMean">'+jQuery('#addNotFoundLabel').val();
	inner += '</p>';
	inner += '<p/><p><a href="javascript:resetDidYouMean()">'+jQuery('#closeDidYouMeanLabel').val()+'</a></p>';
	document.getElementById("autoHelpSuggestion").innerHTML = inner;
 	jQuery('#updatingBlockOverlay').hide();
    jQuery('#updatingBlock').hide();
  	jQuery('#autoHelpSuggestion').show();
}


function resetDidYouMean()
{
  jQuery('#autoHelpSuggestion').hide();
  document.getElementById("directionsFrom").value = "";
}


