BingRoute = {};

(function () {

	BingRoute.Info = function(bingRouteObjName,BingDirectionMapObj)
	{

		// will need some methods to dynamically set the following variables
		var fromDivStr = "directionsFrom";
		var resultsDivStr = "myResultsDiv";
		var mapItBtnStr = "mapItBtn";

		var driveInstructionsTable = "driveInstructionsTable";
		var destinationDirectionsInstructions="destinationDirectionsInstructions";
		
		// hidden fields for the Pangea Hotel Level page
		var KilometerStr = "km";
		var distPrefStr = "distPref";
		var clearLabel = "clearLabel";
		var mapItLabel = "mapItLabel";
		var routeHdrLabel="routeHdrLabel";
		var maneuverLabel="ManeuverLabel";
		var distanceLabel = "DistanceLabel";
		var timeLabel ="TimeLabel";
		
		//Global Param for locale
		var isJPLocale = false;

		if(G_LOCALE=='ja_JP'){
			isJPLocale=true;
		}		
		// new vars
		var newAmbiguousPlace=null;
		var matchCD=null;

		var bingRouteObjNameStr = bingRouteObjName;

		// store bing map obj
		var bingDirectionMapObj = BingDirectionMapObj;
		var bingMapPOI;

		var showRoute = false;
		
		var toFromStatus = "to";

		var suggestionsArray;
		
		var origFrom;
		
		// get the map and the array of latlong from BingDirectionMap
		
		var latLongArray = bingDirectionMapObj.getLatLongArray();

		var getClearStr = function()
		{
			var value = "";
			var clearLabelDiv = document.getElementById(clearLabel);
			if (clearLabelDiv!=null && typeof clearLabelDiv != "undefined"){
				value = clearLabelDiv.value;
			} else{
				value = "Clear";
			}
			return value;
		};

		var getMapItLabelStr = function()
		{
			var value = "";
			var mapItLabelDiv = document.getElementById(mapItLabel);
			if (mapItLabelDiv!=null && typeof mapItLabelDiv != "undefined"){
				value = mapItLabelDiv.value;	
			} else {
				value = "Map it";
			}
			return value;
		};
		

		var getOrigin = function()
		{
			var originStr = document.getElementById(fromDivStr).value;
			if (originStr!=null && typeof originStr!= "undefined" && trim(originStr)!="")
			{
				return originStr;
			}
			else {
				return "";
			}	
		};

		var getUnit = function(){
			var prefUnit="";
			var distPref = document.getElementById(distPrefStr);
			if (distPref==null || typeof distPref == "undefined")
			{
				prefUnit=jQuery('#distPref').val();
								
			} else{
				var unit = distPref.value;
				if (unit==KilometerStr)
				{
					prefUnit=jQuery('#distPref').val();
				} else
				{
				prefUnit=jQuery('#distPref').val();
				}
			}
			return prefUnit;

		};

		var getVERouteDistanceUnit=function(){
			var veRouteDistanceUnit=null;
			var distPref = document.getElementById(distPrefStr);
			if (distPref==null || typeof distPref == "undefined")
			{
				veRouteDistanceUnit = VERouteDistanceUnit.Mile;
			} else{
				var unit = distPref.value;
				if (unit==KilometerStr)
				{
					veRouteDistanceUnit = VERouteDistanceUnit.Kilometer;
				} else
				{
					veRouteDistanceUnit = VERouteDistanceUnit.Mile;
				}
			}
			/*only for JP Locale*/
			if(isJPLocale){
			veRouteDistanceUnit = VERouteDistanceUnit.Kilometer;
			}
			return veRouteDistanceUnit;
		};

		 var getDirectionStr=function(){
			var value="";
			var directionStrDiv = document.getElementById(routeHdrLabel);
			if(directionStrDiv!=null||typeof directionStrDiv!="undefined"){
				value= directionStrDiv.value;
			} else{
				value = "Directions";
			}
			return value;
		 };

		 var getManeuverStr=function(){
			var value="";
			var maneuverStrDiv = document.getElementById(maneuverLabel);
			if(maneuverStrDiv!=""||typeof maneuverStrDiv!="undefined"){
			} else{
				//value = "Maneuver";
			}
			return value;

		 };

		 var getTimeStr=function(){
		 	var value="";
			var timeStrDiv = document.getElementById(timeLabel);
			if(timeStrDiv!=null||typeof timeStrDiv!="undefined"){
				//value= timeStrDiv.value;
			} else{
				//value = "Time";
			}
			return value;
		 };

		var getDistanceStr=function()
		{
			var value="";
			var DistanceStrDiv = document.getElementById(distanceLabel);
			if(DistanceStrDiv!=null||typeof DistanceStrDiv!="undefined"){
				//value= DistanceStrDiv.value;
			} else{
				//value = "Distance";
			}
			return value;
			
		};

		 var findCallback=function(layer, findResults, placeResults, moreResults, error)
		 {				
			var s='';
			var matchcd;
			
			for (var i=0; i < placeResults.length; ++i)
            {                
			   matchcd = placeResults[i].MatchCode;			 
            }

            var text = document.getElementById("directionsFrom").value;			
			var origination =  placeResults[0].Name;

			//gOrigin = origination;
			var destinLatLong = latLongArray[0];

			if(matchcd > 1){
				//document.getElementById("directionsFrom").value = origination;
				matchCD=matchcd;
				newAmbiguousPlace=origination;
			}
			else{
				matchCD=null;
				newAmbiguousPlace=null;
			}	
			Bing_Route.getDirectionsWithStringAndLatLong(origination,destinLatLong.Latitude,destinLatLong.Longitude);	 		             		
		 };
		 
		 
		 var showDirections=function(route)
		 {	
		 	thisroute = route;
			var myroute = eval(route);
		    if(myroute == 'undefined' || myroute == null)
			 {
			    jQuery('#updatingBlockOverlay').hide();
			    jQuery('#updatingBlock').hide();
			    jQuery('#autoHelpSuggestion').show();
			    return;
			 }
			var legs = route.RouteLegs;
			var leg  = null;
			var turnNum = 0;  // The turn #
			var routeTime = route.Time;
			var fromStr = getOrigin();						

			if(newAmbiguousPlace!=null){
				if(parseInt(matchCD) > 1){document.getElementById("directionsFrom").value = newAmbiguousPlace;}
			}
			
			if(routeTime != 0)
			{
				var turns = appendStrings(["<table width='100%' cellspacing=\"0\" cellpadding=\"0\" id=\"",driveInstructionsTable,"\"><tbody><tr><td colspan='4'><h2 class=\"",destinationDirectionsInstructions,"\">",getDirectionStr(),"</h2></td></tr>"]);
				var totalDistance =parseFloat('0.00');
			
				// 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 = appendStrings([turns,getTurnRow(turnNum,turn.Text,getTime(turn.Time),turn.Distance.toFixed(2))]);
					 turnNum++;
					 totalDistance=parseFloat(totalDistance)+parseFloat(turn.Distance.toFixed(2));
				  }
				}
				// last row of table			
				turns = appendStrings([turns,"</table><p>"+jQuery('#driveTime').val()+" ",getTime(routeTime),"<br/>"+jQuery('#driveDist').val()+" ",totalDistance.toFixed(2)," ",getUnit(),"</p>"]);	
				setDirectionsContent(turns);  
			}
			jQuery('#autoHelpSuggestion').hide();
		 }; 
		 
		var getTurnRow =function(turnNum,turnTxt,turnTime,turnDistance)
		{
			var turnRow="";
			if(turnDistance > 0){				
				turnRow = appendStrings([turnRow,"<tr><td width='0%' class=\"indexCol\">",turnNum,".</td><td width='90%' class=\"maneuverCol\"><div class=\"maneuver\">",turnTxt,"</div></td><td width='10%' class=\"distanceCol\">",turnDistance," ",getUnit(),"</td></tr>"]);
			}
			return turnRow;				 
				 
		};
		
		 // time is an integer representing seconds
		 // returns a formatted string
		 var getTime = function(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());
			}
		 };

		 var setDirectionsContent = function(content)
		{
			 
			 var resultsDiv = document.getElementById(resultsDivStr);
			 resultsDiv.innerHTML= content;
			 //jQuery('#myResultsDiv').toggle();
			 jQuery('#myResultsDiv').show();
		 	 jQuery('#updatingBlockOverlay').hide();
    		 jQuery('#updatingBlock').hide();
		 };


		 var setMapItLabel = function(content)
		{
			 var resultsDiv = document.getElementById(resultsDivStr);
			 resultsDiv.innerHTML= content;
		 };

		 // debugging
		var debug = function (str){
				document.getElementById("output").innerHTML=str;
		};

		// passing an array of strings and returned a joined string
		var appendStrings = function(list){
			 this.buffer = [];
			var i =0;
			for (i=0;i<list.length;i++){
				buffer.push(list[i]);
			}
			return buffer.join("");
		 };


		// trim the white space
		 var trim = function(string) {
			return string.replace(/^\s*/, "").replace(/\s*$/, "");
		 };
		 	
		return {

			 setPOI:function(POI)
			 {
			 	bingMapPOI = POI;
			 },
			
			getName:function()
			{
				return bingRouteObjNameStr;
			},

			setResulsDivStr:function(newResutsDivStr)
			{
				resultsDivStr = newResutsDivStr;
			},


			 getDirections:function(displayIt,toValue,arLen)
			 {
			 	var mapItBtn = document.getElementById(mapItBtnStr);
				
				/* block for did u mean */
				origFrom = document.getElementById("directionsFrom").value;
				
				if(displayIt == "true")
				 {
				
					jQuery('#autoHelpSuggestion').hide();
					//Bing_Route.doRoute();
					
					if(mapItBtn!=null && typeof mapItBtn!="undefined")
					{
						if (showRoute)
						{
							var map = bingDirectionMapObj.getMapObj();
							map.DeleteRoute();
							bingDirectionMapObj.resetZoom();
							setDirectionsContent("");
							showRoute=false;
							mapItBtn.innerHTML="<span>"+getMapItLabelStr()+"</span>";	
						} else {
							    if(arLen >1) document.getElementById("directionsFrom").value = suggestionsArray[toValue].name;
								Bing_Route.doRoute();
								showRoute=true;
								mapItBtn.innerHTML="<span>"+getClearStr()+"</span>";
							   }					
						var text = "";
												
						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("directionsFrom").value = text;
				  	 	 document.getElementById("mapItBtn").innerHTML = "<span>"+jQuery('#clearLabel').val()+"</span>";
				  	 	 var poi = document.getElementById("poi");						  	 	 				
						 bingMapPOI.enablePOIS(poi);	
			  		}
			  	}
				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();
			    				    	 	
					 	if(	toFromStatus == "from")
					 	{
					 		document.getElementById("directionsTo").value = document.getElementById("directionsFrom").value ;
					 	}
					    document.getElementById("directionsFrom").value = "";
					    toFromStatus = "to";
					    
					    var map = bingDirectionMapObj.getMapObj();
					    map.DeleteRoute();						
						var poi = document.getElementById("poi");						
						bingMapPOI.enablePOIS(poi);						
						if(latLongArray.length==1){
						    var checked2 = false;
							jQuery(".radio").each(function(){
							if(checked2 != true){
							 		checked2 = jQuery(this).attr('checked');
							 		}
   								 		
   								 });
   								 
   								 if(checked2 != true) {map.SetCenterAndZoom(latLongArray[0], 15);}
						
							//map.SetZoomLevel(10);
							//map.SetCenterAndZoom(latLongArray[0], 15);
						}
						else{
							 var checked2 = false;
							 jQuery(".radio").each(function(){
							 if(checked2 != true){
							 		checked2 = jQuery(this).attr('checked');
							 		}
   								 		
   								 });
   							   								
   								 if(checked2 != true) {map.SetCenter(latLongArray[0]);}
						}
						
						setDirectionsContent("");
						map.m_veambiguouslist.Hide();
						showRoute=false;
					 }
					 else
					 {
					 	jQuery('#updatingBlockOverlay').show();
					    jQuery('#updatingBlock').show();
					  	var searchQuery = document.getElementById('directionsFrom').value;
					  	MappingUtils.getAdhocResults( searchQuery, { callback:Bing_Route.buildDidYouMean, timeout:30000, errorHandler:Bing_Route.errorDidYouMean} );
			 		 }
				}  								
																																
			 },
						
			buildDidYouMean:function(e)
			{
			
			    jQuery('#listAutoHelpSuggestion').removeAttr('style');
				
				if(jQuery('#mapWindow_veplacelistpanel').show && jQuery('#updatingBlockOverlay').show)
				{				
				  jQuery('#updatingBlockOverlay').hide();
				  jQuery('#updatingBlock').hide();
				  
				}								
				suggestionsArray = eval( e );
				var inner;
				if((suggestionsArray != 'undefined') && (suggestionsArray != 'null'))
				{
					if(suggestionsArray.length == 1)
					{						
						Bing_Route.getDirections('true',0,1);
						return;
					}
					else
					{
						var DidYouMean = '<p class="didYouMean">'+jQuery('#didYouMeanLabel').val()+'<span style="text-align: right; padding-left:180px;"> <a href="javascript:Bing_Route.resetDidYouMean()">'+jQuery('#resetDidYouMeanLabel').val()+'</a></span></p>';
						document.getElementById("didYouMean").innerHTML = DidYouMean;
						inner = '<ul>';
						if(suggestionsArray.length > 25){jQuery('#listAutoHelpSuggestion').css('overflow-y','auto'); jQuery('#listAutoHelpSuggestion').css('height','465px'); }
					   	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:Bing_Route.getDirections(\'true\','+ i + ',' + 2 + ');">'+text+'</a></li>';						   
						}
						inner += '</ul>';
						
					}
				}
				else
				{
					inner = '<p class="didYouMean">'+jQuery('#addNotFoundLabel').val();
					inner += '</p>';
					inner += '<p/><p><a href="javascript:Bing_Route.resetDidYouMean()">'+jQuery('#closeDidYouMeanLabel').val()+'</a></p>';					
				}	
				
				document.getElementById("listAutoHelpSuggestion").innerHTML = inner;
				jQuery('#updatingBlockOverlay').hide();
			    jQuery('#updatingBlock').hide();
			    jQuery('#autoHelpSuggestion').show();
			},
						
			errorDidYouMean : function(e) {
				var inner;
				inner = '<p class="didYouMean">'+jQuery('#addNotFoundLabel').val();
				inner += '</p>';
				inner += '<p/><p><a href="javascript:Bing_Route.resetDidYouMean()">'+jQuery('#closeDidYouMeanLabel').val()+'</a></p>';
				document.getElementById("autoHelpSuggestion").innerHTML = inner;
			 	jQuery('#updatingBlockOverlay').hide();
			    jQuery('#updatingBlock').hide();
			  	jQuery('#autoHelpSuggestion').show();
			},

			resetDidYouMean : function()
			{
			  jQuery('#autoHelpSuggestion').hide();
			  document.getElementById("directionsFrom").value = "";
			},						
								
 			 doRoute:function()
			 {
				var map = bingDirectionMapObj.getMapObj();
				var locations;
				var originStr = getOrigin();
				var destinLatLong = latLongArray[0];
				//debug("lat long:"+destinLatLong.toString());
				
				var x = new VEGeocodeOptions();
				x.SetBestMapView = false;
				x.UseDefaultDisambiguation = true;					
				map.Geocode(originStr, findCallback, x);
				
				//this.getDirectionsWithStringAndLatLong(originStr,destinLatLong.Latitude,destinLatLong.Longitude);
			 },

			 getDirectionsWithStringAndLatLong:function(FromStr,toLat,toLong)
			 {
			 	var map = bingDirectionMapObj.getMapObj();
				var locations=null;
				var destinLatLong = null;				
				
				if (FromStr!= null && typeof FromStr !="undefined" && toLat!= null && typeof toLat !="undefined" && toLong!= null && typeof toLong !="undefined")
				{
					destinLatLong = new VELatLong(toLat,toLong);
					locations = new Array(FromStr, destinLatLong);

					var options = new VERouteOptions;

					// Otherwise what's the point?
					options.DrawRoute      = true;

					// reset map in order to get the right view
					options.SetBestMapView = true;

					// Call this function when map route is determined:
					options.RouteCallback  = showDirections;

					options.DistanceUnit   = getVERouteDistanceUnit();

					options.ShowDisambiguation = true;

					map.GetDirections(locations, options);
				}
			 },

			 getDirectionsWithLatLong:function(POIName,toFrom,fromLat,fromLong,toLat,toLong)
			 {
				var map = bingDirectionMapObj.getMapObj();
				var locations=null;
				var destinLatLong = null;
				//debug("lat long:"+destinLatLong.toString());
			    POIName = unescape(POIName);			
			    
				if(toFrom == 1)
				{
					if(toFromStatus == "to")
					{
						document.getElementById("directionsFrom").value = document.getElementById("directionsTo").value ;
					}
					document.getElementById("directionsTo").value = POIName;
					
					toFromStatus = "from";
				}
				else
				{
					if(toFromStatus == "from")
					{
						document.getElementById("directionsTo").value = document.getElementById("directionsFrom").value ;
					}
					
					document.getElementById("directionsFrom").value = POIName;
					toFromStatus = "to";
				}
				document.getElementById("mapItBtn").innerHTML = "<span>"+jQuery('#clearLabel').val()+"</span>";
				
						
				if (fromLat!= null && typeof fromLat !="undefined" && fromLong!= null && typeof fromLong !="undefined" && toLat!= null && typeof toLat !="undefined" && toLong!= null && typeof toLong !="undefined")
				{
					origLatLong = new VELatLong(fromLat,fromLong);
					destinLatLong = new VELatLong(toLat,toLong);
					locations = new Array(origLatLong, destinLatLong);

					var options = new VERouteOptions;

					// Otherwise what's the point?
					options.DrawRoute      = true;

					// reset map in order to get the right view
					options.SetBestMapView = true;

					// Call this function when map route is determined:
					options.RouteCallback  = showDirections;

					options.DistanceUnit   = getVERouteDistanceUnit();

					options.ShowDisambiguation = true;

					map.GetDirections(locations, options);
				}
			 }

 		};// closing return block

	};// constructor with private methods
})();
