
//Inject the VE Map control tag into the page.
//document.write("<script type='text/javascript' src='http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1'></script>");

// Override the Virtual Earth drawing function to use SVG method for any of these rendering engines regardless of browser or version 
if (/(?:Gecko\/|AppleWebKit\/|Opera\/|KHTML)/.test(navigator.userAgent))
{
    Msn.Drawing.Graphic.CreateGraphic = function(f, b) {
        return new Msn.Drawing.SVGGraphic(f, b);
    }
}

var images = "/images/shared/map/yellow/";
var panSpeed = 70;
var compass_click = false;

// YPG VE Map Control 
// This class wraps the VE Control and exposes methods to create, load, navigate and 
// hide the VE Map controls.
// Constructor Parameter:   controlId   string  This is the id of the div element that
// the map is to be displayed in.
function YPGMapControl(controlId)
{
    //The map Id and the id of the div element that will hold the map.
    this.controlId = controlId;
    
    //This is the actual VEMap object.  It is accessable outside of the class but it is
    //preferrable to use the YPGMapControl methods as these are tailored to ypg's mapping
    //requirements.
    //this.mapInstance = null;
    
    //This is the url of the image that will be used when a pushpin is added to the map
    //indicating a location of interest.
    this.pushPinIcon = null;
    
    //This is a VECustomIconSpecification to be applied to all pushpins being added
    //This can be overriden by passing the customIconSpecification parameter to AddLocation.
    this.customIconSpecification = null;
    
    //The unit of measure to be displayed on the map.
    this.distanceUnits = VEDistanceUnit.Kilometers;
    
    //This hides the intrinsic VE controls, displaying only the map.
    this.HideVEControls = function()
    {
        if (this.mapInstance != null)
        {
            this.mapInstance.HideDashboard();
        }
    }
    
    //This displays the intrinsic VE controls.
    this.ShowVEControls = function()
    {
        if (this.mapInstance != null)
        {
            this.mapInstance.ShowDashboard();
        }    
    }
    
   //Moves the map to be centered on the given latitude and longitude and then
    //adjusts the zoom to the given level.
    this.SetCenterAndZoom = function(latLong, zoomLevel){
        if (this.mapInstance != null)
        {
            this.mapInstance.SetCenterAndZoom(latLong, zoomLevel);
        }
    }
    
    
    //Initializes the internal map instance and requests the appropriate tile set to be
    //displayed.
    //Parameters:   latLong A VELatLong representing the center of the map.
    //              zoom    The zoom level at which the map is to be displayed.
    //              style   The type of map to display (VEMapStyle enumeration)
    //              fixed   Boolean value indicating whether the map is fixed (i.e. cannot
    //                      be navigated using the map control)
    //              mode    Indicates whether 3D is enabled (VEMapMode enumeration)
    //              showSwitch  Boolean value indicating whether the 2D/3D switch is visible
    //              clientToken Virtual Earth Customer Identification
    this.CreateAndLoadMap = function(latLong, zoom, style, fixed, mode, showSwitch, clientToken)
    {
        this.mapInstance = new VEMap(controlId);
        
        this.mapInstance.AttachEvent('ontokenexpire', MyHandleTokenExpire);
		this.mapInstance.AttachEvent('ontokenerror', MyHandleTokenError);

        if (clientToken != "") {
        	this.mapInstance.SetClientToken(clientToken);
        }
        this.mapInstance.LoadMap(latLong, zoom, style, fixed, mode, showSwitch);
        this.mapInstance.SetScaleBarDistanceUnit(this.distanceUnits);

		if(!document.getElementById('ypgBody')) {
        	//Added in order to remove North arrow when in birdseye view
        	this.mapInstance.AttachEvent('onchangemapstyle',NorthArrowOff);
        	this.AddCompassRose();
        }
        
        if(document.getElementById('ypgBody')) {
        	this.mapInstance.AttachEvent('onchangemapstyle',eventTriggeredUpdateSelectedMapStyleIndicator);
        	// Let me know if a birdseye scene is available
			this.mapInstance.AttachEvent("onobliqueenter", OnObliqueEnterHandler);
			this.mapInstance.AttachEvent("onobliqueleave", OnObliqueLeaveHandler);
			this.mapInstance.AttachEvent("onmouseout", MouseoutCB);
        }
        
		//Needed in order for IE Printing hack to work
		this.m_vetilesourcemanager = this.mapInstance.m_vetilesourcemanager;
		this._dm = this.mapInstance._dm;		
		this.pushpins = this.mapInstance.pushpins;
		this._dm.veroutecache = this.mapInstance._dm.veroutecache;		
    }
    
	//Pans the map to the latlong specified
	//Parameters:  latLong A VELatLong to pan to
	this.PanToLatLong = function(latLong)
	{
			this.mapInstance.PanToLatLong(latLong);
	}

    //Creates and injects the compass div that appears on the top right hand corner of the map
    this.AddCompassRose = function()
    {
        var targetMap = document.getElementById(controlId);
        var target = findPos(targetMap);
        var targetWidth = targetMap.style.width;
        
        
        var d = document.createElement( "DIV" );
        //Added in order to remove North arrow when in birdseye view
        d.id = 'ypgmap-north';
        d.className = 'ypgmap-north'; 
        
        d.style.backgroundColor = 'transparent';
        d.style.zIndex = '999';
        d.style.right = '40px';
        d.style.top = '7px';
        d.style.backgroundImage = 'url(http://dev.cb.yp.ca/map/North_icon.gif)';
        d.style.width = '18px';
        d.style.height = '25px';
		d.style.backgroundRepeat = 'no-repeat';
        d.style.position = 'absolute';
        targetMap.appendChild( d );
    }
    //Creates a new instance of the map.  This needs to be followed by the LoadMap call 
    //to display a map.
    this.Create = function(){
        this.mapInstance = new VEMap(controlId);
    }
    
    //Loads the map and if provided sets the appropriate view.
     //Parameters:   latLong A VELatLong representing the center of the map.
    //              zoom    The zoom level at which the map is to be displayed.
    //              style   The type of map to display (VEMapStyle enumeration)
    //              fixed   Boolean value indicating whether the map is fixed (i.e. cannot
    //                      be navigated using the map control)
    //              mode    Indicates whether 3D is enabled (VEMapMode enumeration)
    //              showSwitch  Boolean value indicating whether the 2D/3D switch is visible
    this.LoadMap = function(latLong, zoom, style, fixed, mode, showSwitch){
        this.mapInstance.LoadMap(latLong, zoom, style, fixed, mode, showSwitch);
	}

	//Gets the current map style
	//Returns the current map style
    this.GetMapStyle = function(){
        return this.mapInstance.GetMapStyle();
    }

var Utf8 = {

    // public method for url encoding
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // public method for url decoding
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

	function convertUTF8()
	{
		document.getElementById("MSVE_navAction_ObliqueMapView").title = "Afficher la vue aÃ©rienne";
	}

    //Sets the Url to the image that is the custom Icon
    //Parameters:   shape   A VEShape for which the custom Icon is to be set
    //              imageUrl    A Url to the image file.
    //Translate the dashboard into French
	this.DashboardTranslateFR = function()
	{	
		 document.getElementById('MSVE_navAction_FlatlandMapMode').title = 'Visualisez les cartes en 2D';
         document.getElementById('MSVE_navAction_View3DMapMode').title = "Visualisez les cartes en 3D en utilisant le programme beta Virtual Earth 3D";
         document.getElementById('MSVE_navAction_RoadMapStyle').title = 'Passez à la vue Route';
         document.getElementById('MSVE_navAction_AerialMapStyle').title = 'Passez à la vue Aérienne';
         document.getElementById('MSVE_navAction_ObliqueMapView').title = 'Passez à la vue de dessus';
         document.getElementById('Compass').title = "Effectuez un panoramique dans n'importe quelle direction";
		 document.getElementById('MSVE_navAction_tinyZoomBar_plus').title = "Zoom avant. Pour zoomer sans interruption, cliquez sur le bouton de la souris et maintenez-le enfoncé. Le recadrage est possible dans tous les sens";
		 document.getElementById('MSVE_navAction_tinyZoomBar_minus').title = "Zoom arrière. Pour zoomer sans interruption, cliquez sur le bouton de la souris et maintenez-le enfoncé. Le recadrage est possible dans tous les sens.";
         document.getElementById('MSVE_obliqueNotifyText').innerHTML = "Afficher une vue aérienne de ce lieu";
         document.getElementById('MSVE_navAction_toggleGlyphWrapper').title = "Masquez le contrôle de la vue";

         document.getElementById('MSVE_navAction_RoadMapStyle').innerHTML = "Route";
         document.getElementById('MSVE_navAction_AerialMapStyle').innerHTML = "Aérienne";
         //document.getElementById('MSVE_navAction_HybridMapStyle').innerHTML = "Hybride";
         document.getElementById('MSVE_navAction_ObliqueMapView').innerHTML = "Dessus"; 

         document.getElementById('MSVE_navAction_showLabels').innerHTML = "Libellés";
         //document.getElementById('MSVE_navAction_toggleGlyphWrapper').title = Utf8.decode("Masquez le control de la vue");
		
		 //Disable 3D mode since Bird's eye text cannot be changed to enable 3D
		 document.getElementById('MSVE_navAction_View3DMapMode').style.display="block";
		 document.getElementById('MSVE_navAction_FlatlandMapMode').style.display="block";


		document.getElementById('MSVE_navAction_ccw').title = "Faire pivoter l'angle de la caméra vers la gauche";
		document.getElementById('MSVE_navAction_cw').title = "Faire pivoter l'angle de la caméra vers la droite";
		
		//setTimeout(convertUTF8, 3000);

		 //Translate Bird's eye images tooltips only when in oblique view
		 //this.mapInstance.AttachEvent('onchangemapstyle',TranslateObliqueFR);
	}

/*  This is original version in this file, it does not have as many translations and translations are different than version in fr version of this file.
    //Sets the Url to the image that is the custom Icon
    //Parameters:   shape   A VEShape for which the custom Icon is to be set
    //              imageUrl    A Url to the image file.
    
	//Translate the dashboard into French
	this.DashboardTranslateFR = function()
	{
		 document.getElementById('MSVE_navAction_FlatlandMapMode').title = 'Visualisez les cartes en 2D';
		 document.getElementById('MSVE_navAction_View3DMapMode').title = "Visualisez les cartes en 3D en utilisant le programme beta Virtual Earth 3D";
		 document.getElementById('MSVE_navAction_RoadMapStyle').title = 'Passez à la vue Route';
		 document.getElementById('MSVE_navAction_AerialMapStyle').title = 'Passez à la vue Aérienne';
		 document.getElementById('MSVE_navAction_HybridMapStyle').title = 'Passez à la vue Hybride';
		 document.getElementById('MSVE_navAction_ObliqueMapView').title = 'Passez à la vue de dessus';
		 document.getElementById('Compass').title = "Effectuez un panoramique dans n'importe quelle direction";
		 document.getElementById('MSVE_navAction_tinyZoomBar_plus').title = "Zoom avant. Pour zoomer sans interruption, cliquez sur le bouton de la souris et maintenez-le enfoncé. Le recadrage est possible dans tous les sens";
		 document.getElementById('MSVE_navAction_tinyZoomBar_minus').title = "Zoom arrière. Pour zoomer sans interruption, cliquez sur le bouton de la souris et maintenez-le enfoncé. Le recadrage est possible dans tous les sens.";
		 document.getElementById('MSVE_obliqueNotifyText').innerHTML = "Voyez cet emplacement au moyen de la vue de dessus";
		 document.getElementById('MSVE_navAction_toggleGlyphWrapper').title = "Masquez le contrôle de la vue";

		 document.getElementById('MSVE_navAction_RoadMapStyle').innerHTML = "Route";
		 document.getElementById('MSVE_navAction_AerialMapStyle').innerHTML = "A&eacute;rien";
		 document.getElementById('MSVE_navAction_HybridMapStyle').innerHTML = "Hybride";
		 document.getElementById('MSVE_navAction_ObliqueMapView').innerHTML = "Dessus";

		 //Disable 3D mode since Bird's eye text cannot be changed to enable 3D
		 document.getElementById('MSVE_navAction_View3DMapMode').style.display="none";
		 document.getElementById('MSVE_navAction_FlatlandMapMode').style.display="none";

		 //Translate Bird's eye images tooltips only when in oblique view
		 this.mapInstance.AttachEvent('onchangemapstyle',TranslateObliqueFR);
	}
*/	
	//Translate bird's eye tooltip text
	function TranslateObliqueFR(e)
	{
			/*//check if map is in oblique (birds eye) mode using the Map Event object
			if(e.mapStyle == "o")
			{
		 	document.getElementById('MSVE_obliqueCompassContainer').title = "Changez la direction de la vue"; 		 
			document.getElementById('MSVE_navAction_ccw').title = "Faites tourner l'angle de la caméra dans le sens contraire des aiguilles d'une montre";
		 	document.getElementById('MSVE_navAction_cw').title = "Faites tourner l'angle de la caméra dans le sens des aiguilles d'une montre";
			}*/
	}
	//Sets the Url to the image that is the custom Icon
	//Parameters:   shape   A VEShape for which the custom Icon is to be set
	//              imageUrl    A Url to the image file.	
	this.SetCustomIcon = function(shape, imageUrl)
    {
        if(shape != null)
        {
            if(imageUrl!=null &&imageUrl!='')
            {
                shape.SetCustomIcon(imageUrl);
            }
        }
    }
   
    
    //Adds a pushpin the the map
    //Parameter:    pushpin A VE shape to be added to the map.
    this.AddPushpin = function(pushPin)
    {
        if (this.mapInstance != null)
        {
            this.mapInstance.AddShape(pushPin);
        }
    }
    
    
    //Adds a location pushpin to the map with the details for the info box set
    //Parameters:   lat The latitude of the location
    //              lon The longitude of the location
    //              coyName The company name or a display name
    //              address The address
    //              city    The city
    //              prov    The province
    //              postalCode  The postal code
    //              phone   The phone
    //              customIconSpecification HTML or VECustomIconSpecification that overrides the customIcon and customIconSpecification properties of this class
    this.AddLocation = function(lat, lon, coyName, address, city, prov, postalCode, phone, customIconSpecification)
    {
        var newPin = null;
        if (this.mapInstance != null)
        {
            var newPin = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
            newPin.SetTitle(coyName);
            var contactBlock = ((address) ? address + "<br/>" : "") +
                               ((city) ? city + "<br/>" : "") +
                               ((prov) ? prov + "<br/>" : "") +
                               ((postalCode) ? postalCode + "<br/>" : "") +
                               ((phone) ? phone + "<br/>" : "");
            newPin.SetDescription(contactBlock);
            if(customIconSpecification == null || customIconSpecification == 'undefined')
            {
                if(this.pushPinIcon != null)
                {
                    this.SetCustomIcon(newPin, this.pushPinIcon);
                }
                if(this.customIconSpecification != null)
                {
                   this.SetCustomIcon(newPin, this.customIconSpecification);
                }
            }
            else
            {
                this.SetCustomIcon(newPin, customIconSpecification);
            }        
            this.AddPushpin(newPin);
        }
        
    }
    
    //Adds multiple locations to the map
    //Parameter:    locations an array of locations.
    this.AddLocations = function(locations, skipBestFit)
    {
        var lat; 
        var lon; 
        var coyName; 
        var address; 
        var city; 
        var prov; 
        var postalCode; 
        var phone;
        var customIconSpecification;
        var pointArray = new Array();
        if (this.mapInstance != null){
            for (var i = 0; i<locations.length; i++)
            {
                lat = locations[i][0];
                lon = locations[i][1];
                coyName = locations[i][2];
                address = locations[i][3];
                city = locations[i][4];
                prov = locations[i][5];
                postalCode = locations[i][6];
                phone = locations[i][7];
                customIconSpecification =locations[i][8];
                this.AddLocation(lat, lon, coyName, address, city, prov, postalCode, phone, customIconSpecification);
                pointArray.push(new VELatLong(lat,lon));
            }
            if (pointArray.length>0){
            	if (!skipBestFit || (skipBestFit && skipBestFit == false)) {
                	this.mapInstance.SetMapView(this.mapInstance.GetShapeLayerByIndex(0).GetBoundingRectangle());
                }
            }
        }   
     }       

	//Deletes all shapes in all layers, leaving empty layers behind
    this.DeleteAllShapes = function()
	{
			this.mapInstance.DeleteAllShapes();
	}	

	//Deletes a VEShape Class object from any layer, including the base map layer.
	//Parameter:  shape  The VEShape to remove
    this.DeleteShape = function(shape)
	{
			this.mapInstance.DeleteShape(shape);
	}
	
	//Gets the direction manager used for V5 routing
	//Returns: _dm  The direction manager containing the V5 route pushpins
	this.Get_dm = function()
	{
			return this.mapInstance._dm;
	}
    //Finds a location, not really used at this stage but here if necessary.
    this.FindLocation = function(address, city, prov, postalCode)
    {
        var searchAddress = '';
        var what = null;
        var findType = null;
        var shapeLayer = null;
        var startIndex = null;
        var numberOfResults = null; 
        var showResults = false;
        var createResults = false; 
        var useDefaultDisambiguation = false; 
        var setBestMapView = true;
        
        if (address != null && address != '')
        {
            searchAddress = searchAddress + address;
        }
        searchAddress = searchAddress + ', ';
        
        if (city != null && city != '')
        {
            searchAddress = searchAddress + city;
        }
        searchAddress = searchAddress + ', ';
        
        if (prov != null && prov != '')
        {
            searchAddress = searchAddress + prov;
        }
        searchAddress = searchAddress + ', ';
        
        if (postalCode != null && postalCode != '')
        {
            searchAddress = searchAddress + postalCode;
        }
        
        if (this.mapInstance!=null)
        {
            this.mapInstance.Find(what, searchAddress, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, onGotFindResults);
        }
    }
    
    //Gets a route (V5)
    //Parameters:   start   VELatLong or string address of the starting location
    //              end     VELatLong or string address of the ending locations
    //              units   VEDistanceUnits enum    {kilometers|miles}
    //              routeType   VERouteType enum    {shortest|quickest}
    this.GetRoute = function(start, end, units, routeType, callback)
    {
        if (this.mapInstance != null)
        {
            if (callback == null) callback = onGotRoute;
            this.mapInstance.GetRoute(start, end, units, routeType, callback);
        }    
    }
	//Disable birds eye mode and text
	this.DisableBirdseye = function()
	{
			document.getElementById('MSVE_navAction_ObliqueMapView').style.display ="none";
			document.getElementById('MSVE_navAction_separator2').style.left="7px";
			//document.getElementById('MSVE_navAction_HybridMapStyle').innerHTML = "Hybride";
	}

    //Gets a route (V6)
    //Parameters:   locations   An array of objects specifying the points through which the route must pass. 
	//							The points can be either VELatLong Class objects or String objects.
    //              options     A VERouteOptions Class object specifying the routing options.
    //              clientToken Virtual Earth Customer Identification
	this.GetDirections = function(locations, options, clientToken)
	{
		options.DistanceUnit   = VERouteDistanceUnit.Kilometer;
		
        if (this.mapInstance != null)
        {
	        if (clientToken != "") {
	        		this.mapInstance.SetClientToken(clientToken);
        	}
			this.mapInstance.GetDirections(locations,options);
		}
	}
	//Translates the route driving directions into French (V5)
	//Parameters:   route   A VERoute Class object returned from a V5 GetRoute call 
	//Returns:      route   A VERoute Class object returned from a V5 GetRoute call
	this.GetRouteTranslateFR = function(route)
	{
		var len = route.Itinerary.Segments.length;
            for(var i = 0; i < (len) ;i++)
            {
				route.Itinerary.Segments[i].Instruction = TranslateFR(route.Itinerary.Segments[i].Instruction);
			}
		return route;
	}
	
	//Gets the number of shape layers in the map
	//Returns:      int   the number of layers in the map
	this.GetShapeLayerCount = function()
	{
		return this.mapInstance.GetShapeLayerCount();
	}	
	//Gets the shape layer by its index
	//Parameters:   index  The index of the requested layer
	//Returns:      VEShapeLayer a reference to the requested layer
	this.GetShapeLayerByIndex = function(index)
	{
		return this.mapInstance.GetShapeLayerByIndex(index);
	}	
	
	//Translates the route driving directions into French (V6)
	//Parameters:   route   A VERoute Class object returned from a V6 GetDirections call 
	//Returns:      route   A VERoute Class object returned from a V6 GetDirections call 
	this.GetDirectionsTranslateFR = function(route)
	{
	   //clear original route pushpins
		map.DeleteAllShapes();
		
	   // Unroll route
	   var routeinfo="";
	   var steps = "";
	   var legs = route.RouteLegs;
	   var leg = null;
	   var legCount = 0;
	   var shape = null;
	   
	   var	totalDistance = route.Distance;
	       	totalDistance = totalDistance.toFixed(1);
	   var	totalTime = route.Time;
	   		totalTime = totalTime*1000;
						
			//alert(time(totalTime));
			
			totalTime = time(totalTime);

	   // 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
		   for(var j = 0; j < leg.Itinerary.Items.length; j ++)
		   {
			var turn = leg.Itinerary.Items[j];
			var turnDistance = turn.Distance;
			
			legCount = j+1;
			
			turnDistance = turnDistance.toFixed(1);
			
			//turn = TranslateFR(turn.Text);  // turn is a VERouteItineraryItem object			
			
			shape = new VEShape(VEShapeType.Pushpin,leg.Itinerary.Items[j].LatLong )
			if(legCount == 1)
			{
				shape.SetDescription(legCount + " : Partez de " + displayfromAddress);
				shape.SetCustomIcon("/images/circA.gif");
				//shape.SetCustomIcon("http://dev.virtualearth.net/mapcontrol/v6/i/bin/1.0.20070926140324.39/pins/mapicon_start.gif");
			}
			else if(legCount == leg.Itinerary.Items.length)
			{
				shape.SetDescription(legCount + " : Arriv&eacute;e " + displaytoAddress);
				shape.SetCustomIcon("/images/circB.gif");
				//shape.SetCustomIcon("http://dev.virtualearth.net/mapcontrol/v6/i/bin/1.0.20070926140324.39/pins/mapicon_end.gif");
			}
			else
			{
				//shape.SetDescription(legCount + " : " + turn);
				//shape.SetCustomIcon("http://dev.virtualearth.net/mapcontrol/v6/i/bin/1.0.20070926140324.39/pins/RedCircle"+ legCount +".gif");
                shape.SetDescription(legCount + " : " + turn.Text);
                var customIconSpecification = new VECustomIconSpecification();
                customIconSpecification.CustomHTML = "<div id='vedir_l" + legCount + "' class='poistep'><span class='text'>" + legCount + "</span></div>";      //2D Maps custom spec
                shape.SetCustomIcon(customIconSpecification);
				
			}
			
			map.AddPushpin(shape);
			
			//steps += GenerateResults([turn, turnDistance, totalDistance, totalTime], j, leg.Itinerary.Items.length);
			steps += GenerateResults([turn.Text, turnDistance, totalDistance, totalTime], j, leg.Itinerary.Items.length);
		   }
		   
		}
		
		routeinfo = steps;
   
	   var ourDiv=document.getElementById('drivingDirections');
	   
	   	ourDiv.innerHTML = routeinfo;
	
		___lastRoute = route;
	//return route;
	}
	
	this.GetDirectionsEN = function(route)
	{
	   //clear original route pushpins
		map.DeleteAllShapes();
	   
	   // Unroll route
	   var routeinfo="";
	   var steps = "";
	   var legs = route.RouteLegs;
	   var leg = null;
	   var legCount = 0;
	   var shape = null;
	   
	   var	totalDistance = route.Distance;
	       	totalDistance = totalDistance.toFixed(1);
	   var	totalTime = route.Time;
	   		totalTime = totalTime*1000;
						
			//alert(time(totalTime));
			
			totalTime = time(totalTime);
			
	   // 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
		   for(var j = 0; j < leg.Itinerary.Items.length; j ++)
		   {
			var turn = leg.Itinerary.Items[j];
			var turnDistance = turn.Distance;
			
			legCount = j+1;
			
			turnDistance = turnDistance.toFixed(1);
			
			shape = new VEShape(VEShapeType.Pushpin,leg.Itinerary.Items[j].LatLong )
			if(legCount == 1)
			{
				shape.SetDescription(legCount + " : Depart " + displayfromAddress);
				shape.SetCustomIcon("/images/circA.gif");
				//shape.SetCustomIcon("http://dev.virtualearth.net/mapcontrol/v6/i/bin/1.0.20070926140324.39/pins/mapicon_start.gif");
			}
			else if(legCount == leg.Itinerary.Items.length)
			{
				shape.SetDescription(legCount + " : Arrive " + displaytoAddress);
				shape.SetCustomIcon("/images/circB.gif");
				//shape.SetCustomIcon("http://dev.virtualearth.net/mapcontrol/v6/i/bin/1.0.20070926140324.39/pins/mapicon_end.gif");
			}
			else
			{
				shape.SetDescription(legCount + " : " + turn.Text);
				//shape.SetCustomIcon("http://dev.virtualearth.net/mapcontrol/v6/i/bin/1.0.20070926140324.39/pins/RedCircle"+ legCount +".gif");
                var customIconSpecification = new VECustomIconSpecification();
                customIconSpecification.CustomHTML = "<div id='vedir_l" + legCount + "' class='poistep'><span class='text'>" + legCount + "</span></div>";      //2D Maps custom spec
                shape.SetCustomIcon(customIconSpecification);
			}
			
			map.AddPushpin(shape);
			
			
			steps += GenerateResults([turn.Text, turnDistance, totalDistance, totalTime], j, leg.Itinerary.Items.length);
		   }
		}
		
		routeinfo = steps;
   
	   var ourDiv=document.getElementById('drivingDirections');
	   
	   ourDiv.innerHTML = routeinfo;
	   
	   ___lastRoute = route;
		
	//return route;
	}

	//Translates directions into French
	//Parameters:   itineraryText   The driving itinerary directions that need to be translated
	//Returns:      itineraryText   The driving itinerary directions that need to be translated
	function TranslateFR(itineraryText)
	{
		/* itineraryText = itineraryText.replace(/At roundabout take exit number/gi, 'Au carrefour giratoire, prenez la sortie n&deg;');
		itineraryText = itineraryText.replace(/Exit roundabout at exit number/gi, 'Sortez du carrefour giratoire &agrave; la sortie n&deg;');
		
		itineraryText = itineraryText.replace(/Road name changes to/gi, 'Le nom de la rue devient');
		itineraryText = itineraryText.replace(/Turn is potentially restricted/gi, 'Il se peut que le virage soit interdit');
		itineraryText = itineraryText.replace(/Stop for toll booth/gi, 'Arr&ecirc;tez au poste de p&eacute;age');
		itineraryText = itineraryText.replace(/Check the time table/gi, 'Consultez l&rsquo;horaire');
		itineraryText = itineraryText.replace(/and then immediately bear/gi, 'et continuez imm&eacute;diatement vers');
		itineraryText = itineraryText.replace(/and then immediately turn/gi, 'et tournez imm&eacute;diatement');
		itineraryText = itineraryText.replace(/Enter roundabout and take/gi, 'Prenez le carrefour giratoire, puis prenez');
		itineraryText = itineraryText.replace(/Pass through 1 roundabout/gi, 'Traversez un carrefour giratoire');
		itineraryText = itineraryText.replace(/Make a U-turn at/gi, 'Faites demi-tour &agrave;');
		itineraryText = itineraryText.replace(/Make a U-turn/gi, 'Faites demi-tour');
		
		itineraryText = itineraryText.replace(/to stay on/gi, 'pour rester sur');
		itineraryText = itineraryText.replace(/on the right/gi, '&agrave; votre droite');
		itineraryText = itineraryText.replace(/on the left/gi, '&agrave; votre gauche');
		itineraryText = itineraryText.replace(/Gate access required/gi, 'Il vous faut un droit d&rsquo;acc&egrave;s');
		itineraryText = itineraryText.replace(/Road name changes/gi, 'Rue change de nom');
		itineraryText = itineraryText.replace(/and follow signs/gi, 'et suivez la signalisation');
		itineraryText = itineraryText.replace(/and then immediately/gi, 'puis imm&eacute;diatement');
		itineraryText = itineraryText.replace(/and then bear/gi, 'puis continuez');
		itineraryText = itineraryText.replace(/Take ramp toward/g, 'Prenez la bretelle vers');
		itineraryText = itineraryText.replace(/take ramp toward/g, 'prenez la bretelle vers');
		itineraryText = itineraryText.replace(/Exit roundabout at/gi, 'Sortez du carrefour giratoire &agrave;');
		itineraryText = itineraryText.replace(/Exit roundabout onto/gi, 'Sortez du carrefour giratoire vers');
		
		itineraryText = itineraryText.replace(/to stay/gi, 'pour rester');
		itineraryText = itineraryText.replace(/and then/gi, 'et ensuite');
		itineraryText = itineraryText.replace(/Keep straight/g, 'Continuez tout droit');
		itineraryText = itineraryText.replace(/keep straight/g, 'continuez tout droit');
		itineraryText = itineraryText.replace(/Keep left/g, 'Gardez la gauche');
		itineraryText = itineraryText.replace(/keep left/g, 'gardez la gauche');
		itineraryText = itineraryText.replace(/Keep right/g, 'Gardez la droite');
		itineraryText = itineraryText.replace(/keep right/g, 'gardez la droite');
		itineraryText = itineraryText.replace(/1st exit/gi, 'la 1<sup>re</sup> sortie');
		itineraryText = itineraryText.replace(/2nd exit/gi, 'la 2<sup>e</sup> sortie');
		itineraryText = itineraryText.replace(/3rd exit/gi, 'la 3<sup>e</sup> sortie');
		itineraryText = itineraryText.replace(/4th exit/gi, 'la 4<sup>e</sup> sortie');
		itineraryText = itineraryText.replace(/Local road\(s\)/gi, 'voie r&eacute;gionale');
		itineraryText = itineraryText.replace(/Toll road/gi, 'Route &agrave; p&eacute;age');
		itineraryText = itineraryText.replace(/Arrive At/gi, 'Arriv&eacute;e &agrave;');
		itineraryText = itineraryText.replace(/Depart from/gi, 'D&eacute;part de');
		itineraryText = itineraryText.replace(/and keep/gi, 'puis gardez');
		itineraryText = itineraryText.replace(/Turn back/gi, 'Faites demi-tour');
		itineraryText = itineraryText.replace(/Merge onto/gi, '&Agrave; la jonction, continuez sur / vers');
		itineraryText = itineraryText.replace(/Stay on/gi, 'Restez sur');
		itineraryText = itineraryText.replace(/At exit/gi, '&Agrave; la sortie n&deg;');
		itineraryText = itineraryText.replace(/Take ramp/g, 'Prenez la bretelle');
		itineraryText = itineraryText.replace(/take ramp/g, 'prenez la bretelle');
		itineraryText = itineraryText.replace(/Exit onto/gi, 'Sortez sur');
		itineraryText = itineraryText.replace(/Enter roundabout/gi, 'Prenez le carrefour giratoire');
		itineraryText = itineraryText.replace(/Pass through/gi, 'Traversez');
		itineraryText = itineraryText.replace(/At roundabout,/gi, 'Au carrefour giratoire,');
		
		itineraryText = itineraryText.replace(/\bnortheast\b/gi, 'nord-est');
		itineraryText = itineraryText.replace(/\bnorthwest\b/gi, 'nord-ouest');				  
		itineraryText = itineraryText.replace(/\bsoutheast\b/gi, 'sud-est');				  
		itineraryText = itineraryText.replace(/\bsouthwest\b/gi, 'sud-ouest');				  
		itineraryText = itineraryText.replace(/\bwest\b/gi, 'ouest');				  
		itineraryText = itineraryText.replace(/\bsouth\b/gi, 'sud');
		itineraryText = itineraryText.replace(/\beast\b/gi, 'est');
		itineraryText = itineraryText.replace(/\bnorth\b/gi, 'nord');
		itineraryText = itineraryText.replace(/LEFT/gi, '&agrave; gauche');				  
		itineraryText = itineraryText.replace(/RIGHT/gi, '&agrave; droite');
		itineraryText = itineraryText.replace(/STRAIGHT/gi, 'tout droit');				  
		itineraryText = itineraryText.replace(/Unknown/gi, 'Inconnu');
		itineraryText = itineraryText.replace(/Ferry/gi, 'Traversier');
		itineraryText = itineraryText.replace(/Entering/gi, 'Entr&eacute;e');
		itineraryText = itineraryText.replace(/\bfor\b/gi, 'pour');
		itineraryText = itineraryText.replace(/\bAt\b/gi, '&Agrave;');
		itineraryText = itineraryText.replace(/\bonto\b/gi, 'sur');
		itineraryText = itineraryText.replace(/exit/g, 'sortie');
		itineraryText = itineraryText.replace(/\bto\b/gi, 'vers');
		itineraryText = itineraryText.replace(/\bon\b/gi, 'sur');
		itineraryText = itineraryText.replace(/Turn/g, 'Tournez');
		itineraryText = itineraryText.replace(/turn/g, 'tournez');
		itineraryText = itineraryText.replace(/Return/gi, 'Retournez vers');
		itineraryText = itineraryText.replace(/Take/g, 'Prenez');
		itineraryText = itineraryText.replace(/take/g, 'prenez');
		itineraryText = itineraryText.replace(/toward/gi, 'vers');
		itineraryText = itineraryText.replace(/Exit/g, 'Sortie');
		itineraryText = itineraryText.replace(/Arrive/gi, 'Arriv&eacute;e');
		itineraryText = itineraryText.replace(/Bear/gi, 'Continuez');
		itineraryText = itineraryText.replace(/Ramp/gi, 'Bretelle');
		itineraryText = itineraryText.replace(/Depart/gi, 'D&eacute;part');
		itineraryText = itineraryText.replace(/\bContinue\b/gi, 'Continuez');
		itineraryText = itineraryText.replace(/Keep/g, 'Gardez');
		itineraryText = itineraryText.replace(/keep/g, 'gardez');
		itineraryText = itineraryText.replace(/Stay/gi, 'Restez');
		itineraryText = itineraryText.replace(/Start/gi, 'Commencez');
		itineraryText = itineraryText.replace(/\bthe\b/gi, '');
		itineraryText = itineraryText.replace(/\bW\b/gi, ' O ');
		itineraryText = itineraryText.replace(/Hwy/gi, 'Aut');
		itineraryText = itineraryText.replace(/roundabouts/gi, 'carrefours giratoires');

		return itineraryText;*/
	}
    //Move the center of the map
    //Parameters:   deltaX  change in x
    //              deltaY  change in y
    this.Pan = function(deltaX, deltaY)
    {
        if (this.mapInstance != null)
        {
            this.mapInstance.Pan(deltaX, deltaY);
        }
    }
    
    //Set the location of the map center to the given latLong
    //Parameter:    latLong VELatLong
    this.SetCenter = function(latLong)
    {   
        if (this.mapInstance !=null)
        {
            this.mapInstance.SetCenter(latLong);
        }
    }
    
    //Get the location of the map center to the given latLong
    this.GetCenter = function()
    {   
        var center = null;
        if (this.mapInstance !=null)
        {
            center= this.mapInstance.GetCenter();
        }
        return center;
    }
    
    //Get the location of the map center to the given latLong
    this.GetZoomLevel = function()
    {   
        var level = null;
        if (this.mapInstance !=null)
        {
            level= this.mapInstance.GetZoomLevel();
        }
        return level;
    }

	/**
	* Adds the main navigation control to the map
	*/
	this.AddNavControl = function() {
	    var el = document.createElement("div");
	    el.id = "navcontrol";

	    //Changed back to opaque $(el).setOpacity( 0.7 ); // this works for everyone
	    
	    //el.style.opacity="0.7";  // does not work for IE without applying IE filter
	    //el.style.top = resources.NavControlTop;

		var expandStyle = "none";
		var contractStyle = "none";
		
	    el.innerHTML="<div class='tl_imap'></div><div class='tr_imap'></div><div id='navPanel'><div id='navDir'><img id='North' src='/images/shared/map/yellow/North.gif' alt='" + resourcePan + "' class='handicon' onmouseover='NavMouseOver(\"North\");' onmouseout='NavMouseOut(\"North\");' onmousedown='NavMouseDown(\"North\");' onmouseup='handleCompassClick(true);'/>" +
	    "<img id='East' src='/images/shared/map/yellow/East.gif' alt='" + resourcePan + "' class='handicon' onmouseover='NavMouseOver(\"East\");' onmouseout='NavMouseOut(\"East\");' onmousedown='NavMouseDown(\"East\");' onmouseup='handleCompassClick(true);'/>" +
	    "<img id='West' src='/images/shared/map/yellow/West.gif' alt='" + resourcePan + "' class='handicon' onmouseover='NavMouseOver(\"West\");' onmouseout='NavMouseOut(\"West\");' onmousedown='NavMouseDown(\"West\");' onmouseup='handleCompassClick(true);'/>" +
	    "<img id='South' src='/images/shared/map/yellow/South.gif' alt='" + resourcePan + "' class='handicon' onmouseover='NavMouseOver(\"South\");' onmouseout='NavMouseOut(\"South\");' onmousedown='NavMouseDown(\"South\");' onmouseup='handleCompassClick(true);'/></div>" +
	    "<div id='zoomControl'><img id='ZoomIn' src='/images/shared/map/yellow/ZoomIn.gif' alt='" + resourceZoomIn + "' class='handicon' onmouseover='NavMouseOver(\"ZoomIn\");' onmouseout='NavMouseOut(\"ZoomIn\");' onmousedown='NavMouseDown(\"ZoomIn\");' onmouseup='handleCompassClick(true);'/>" +
	    "<img id='ZoomOut-Min' src='/images/shared/map/yellow/ZoomOut-Min.gif' alt='" + resourceZoomOut + "' class='handicon' onmouseover='NavMouseOver(\"ZoomOut-Min\");' onmouseout='NavMouseOut(\"ZoomOut-Min\");' onmousedown='NavMouseDown(\"ZoomOut-Min\");' onmouseup='handleCompassClick(true);'/></div>" +
	    "<div id='veMapStylesContainer'><div id='birdseye' class='veNavTextContainer lastVeNavText'><a id='a_birdseye' class='handicon veNavText' onmousedown='NavMouseDown(\"birdseye\");'>" + resourceBirdseye + "</a></div>" +
	    "<div id='aerial' class='veNavTextContainer'><a id='a_aerial' class='handicon veNavText' onmousedown='NavMouseDown(\"aerial\");'>" + resourceAerial + "</a></div>" +
	    "<div id='road' class='veNavTextContainer'><a id='a_road' class='handicon veNavText ypgNavSelected' onmousedown='NavMouseDown(\"road\");'>" + resourceRoad +"</a></div><div class='ypgClear'></div></div>" +
	    //"<div id='hybrid' class='veNavTextContainer'><a class='handicon veNavText' onmousedown='NavMouseDown(\"hybrid\");'>Hybrid</a></div>" +
	    "<img id='Expand' src='/images/shared/map/Expand.gif' class='handicon' style='display:" + expandStyle + "' onmouseover='NavMouseOver(\"Expand\");' onmouseout='NavMouseOut(\"Expand\");' onmousedown='NavMouseDown(\"Expand\");'/></div>" +
	    "<img id='Contract' src='/images/shared/map/Contract.gif' class='handicon' style='display:" + contractStyle + "' onmouseover='NavMouseOver(\"Contract\");' onmouseout='NavMouseOut(\"Contract\");' onmousedown='NavMouseDown(\"Contract\");'/></div></div>";
	
	    //this.mapInstance.AddControl(el);
	    
		/* Moved placement of navcontrol out of div for VE map control per TAXI update
		var targetMap = document.getElementById(controlId);
		
		el.style.position = 'absolute';
	    el.style.top ="0px";
	    el.style.left="0px";
		el.style.zIndex = '201';
		targetMap.appendChild( el );
		*/

		el.style.position = 'relative';
/*		var targetMap = document.getElementById('mapBorder');
		targetMap.appendChild( el );*/
		/* Could not use simple css with :hover on anchor tag to show border because IE6 seems to ignore rules with :hover ... guessing because map dashboard added to DOM via js causes bug???. */
		$(controlId).insert({before:el});
		$('a_road').observe('mouseover', respondToMouseOver);
		$('a_road').observe('mouseout', respondToMouseOut);
		$('a_aerial').observe('mouseover', respondToMouseOver);
		$('a_aerial').observe('mouseout', respondToMouseOut);
		$('a_birdseye').observe('mouseover', respondToMouseOver);
		$('a_birdseye').observe('mouseout', respondToMouseOut);
		OnObliqueLeaveHandler(); // Run once to set initial state
	}

	/**
	 * Handles mouseout event to evaluate what to do when mouseout of pin.
	 * Prevent the default VE action of hiding ERO
	 *
	 * @param e - Event object
	 */
	/*
	this.mouseoutCB = function(e)
	{
		if (e.elementID != null && map.mapInstance.GetShapeByID(e.elementID) != null) {
			var shape = map.mapInstance.GetShapeByID(e.elementID);
			if(shape._customIcon != undefined) {
				var curCustomIconClass = shape._customIcon.match(/class=(["'])?([\w\s]*)\1/)[2];
				if (curCustomIconClass.match(/^mapIcon|^pin_nonad/i) != null)
					return true; //Cancel default action
				else
					return false;
			}
		} else {
			return false;
		}	
	}
	*/
}//end

/**
 * Handles mouseout event to evaluate what to do when mouseout of pin.
 * Prevent the default VE action of hiding ERO
 *
 * @param e - Event object
 */	
function MouseoutCB(e)
{
	if (e.elementID != null && map.mapInstance.GetShapeByID(e.elementID) != null) {
		var shape = map.mapInstance.GetShapeByID(e.elementID);
		if(shape._customIcon != undefined) {
			var curCustomIconClass = shape._customIcon.match(/class=(["'])?([\w\s]*)\1/)[2];
			if (curCustomIconClass.match(/^mapIcon|^pin_nonad/i) != null)
				return true; //Cancel default action
			else
				return false;
		}
	} else {
		return false;
	}	
}

function respondToMouseOver(event) {
	var element = event.element();
	element.addClassName('pseudoHover');
	event.stop();
}

function respondToMouseOut(event) {
	var element = event.element();
	element.removeClassName('pseudoHover');
	event.stop();
	//alert("Tag Name : " + element.tagName );
}

// Map style updated by VE event, onchangemapstyle, because user scrolled into area with no more
// birdseye imagery so need to update display indicator of currently selected map style
function eventTriggeredUpdateSelectedMapStyleIndicator(e) {
	var mapStyleID;
	
	if(e.mapStyle == "b") { // birdseye hybrid
		mapStyleID = "a_birdseye";
	} else if(e.mapStyle == "r") { // road
		mapStyleID = "a_road";
	} else if(e.mapStyle == "h") { // aerial hybrid
		mapStyleID = "a_aerial";
	}
	
	var anchors = $$('#veMapStylesContainer a');
	if (anchors) {
		anchors.each(function(anchor) {
			if(!$(anchor).empty()) {
				anchor.removeClassName('ypgNavSelected');
			}
		})
	}
	$(mapStyleID).addClassName('ypgNavSelected');
}

function OnObliqueEnterHandler()
{
	if(map.mapInstance.IsBirdseyeAvailable())
	{
		$('a_birdseye').removeClassName('ypgNavDisabled');
	}
}

function OnObliqueLeaveHandler()
{
	if(!map.mapInstance.IsBirdseyeAvailable())
	{
		$('a_birdseye').addClassName('ypgNavDisabled');
	}
}

/**
* Redraw images on nav control on user mouse overs
*/
function NavMouseOver(imageName)
{
    if(imageName == "hide" && navHidden == true)
    {
        document.getElementById(imageName).src = images + "nav/showOn.gif";
    }
    else
    {
        document.getElementById(imageName).src = images + imageName + "-onEnter.gif";
    }
}

/**
* Redraw images on nav control on user mouse overs
*/
function NavMouseOut(imageName)
{
    if(imageName == "hide" && navHidden == true)
    {
        document.getElementById(imageName).src = images + "nav/showOff.gif";
    }
    else
    {
        document.getElementById(imageName).src = images + imageName + ".gif";
    }
    handleCompassClick(true);
}

/**
* Pan map based on direction selected by user
* Also manages buttons on nav control
* @param string imageName   The name of the image that was clicked
*/
function NavMouseDown(imageName)
{
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();

    switch(imageName)
    {
        case "North":
            compass_x = 0;
            compass_y = -panSpeed;
            handleCompassClick(false);
            doPan();
            break;
        case "East":
            compass_x = panSpeed;
            compass_y = 0;    
            handleCompassClick(false);
            doPan();
            break;
        case "South":
            compass_x = 0;
            compass_y = panSpeed;     
            handleCompassClick(false);
            doPan();
            break;
        case "West":
            compass_x = -panSpeed;
            compass_y = 0;    
            handleCompassClick(false);
            doPan();
            break;
        case "ZoomIn":
            handleCompassClick(false);
            doZoomIn();
            break;
        case "ZoomOut-Min":
            handleCompassClick(false);
            doZoomOut();
            break; 
        case "road":
            map.mapInstance.SetMapStyle(VEMapStyle.Road);
            break;
        case "aerial":
            map.mapInstance.SetMapStyle(VEMapStyle.Hybrid); //Aerial
            break;
        case "hybrid":
            map.mapInstance.SetMapStyle(VEMapStyle.Hybrid);
            break;
        case "birdseye":
            // Change only if there is birdseye imagery
            if(map.mapInstance.IsBirdseyeAvailable()) {
                map.mapInstance.SetMapStyle(VEMapStyle.BirdseyeHybrid);
            }
            break;
        case "Expand":
        	//isMPMapExpanded = true;
        	//mapManager.OnMapResize(null);
            //mapManager.MapResize();
            $('Expand').style.display = "none";
			$('Contract').style.display = "block";
            break;
        case "Contract":
        	//isMPMapExpanded = false;
        	//mapManager.OnMapResize(null);
            //mapManager.MapResize();
            $('Expand').style.display = "block";
			$('Contract').style.display = "none";
            break;  
        case "hide":
            var control = document.getElementById("hide");
            if(navHidden == false)
            {
                control.src = images + "nav/showOff.gif";
                document.getElementById(navcontrolId).style.height="17px"; 
                document.getElementById('navPanel').style.display ="none";
                document.getElementById('hide').style.top = "0px";
                navHidden = true;
            }
            else
            {
                control.src = images + "nav/hideOff.gif";
                document.getElementById(navcontrolId).style.height="229px";
                document.getElementById('navPanel').style.display ="block";                
                document.getElementById('hide').style.top = "212px";
                navHidden = false;
            }
            break;
    }
}

/**
* Manage when to cancel map pans
*/
function handleCompassClick(mouseOut)
{
    if(mouseOut)
    {
        compass_click = false;
    }
    else
    {
        compass_click = true;
    }
}

/** 
* continue pan
*/
function doPan()
{
	if(compass_click)
	{
		map.mapInstance.Pan(compass_x,compass_y);
		setTimeout("doPan()",30);
	}
}

/**
* Continue zooming in
*/
function doZoomIn()
{
    if(compass_click)
	{
		map.mapInstance.ZoomIn();
		setTimeout("doZoomIn()",30);
	}
}

/**
* Continue zooming out
*/
function doZoomOut()
{
    if(compass_click)
	{
		map.mapInstance.ZoomOut();
		setTimeout("doZoomOut()",30);
	}
}

//Callback Functions
//probably don't need this as the start and end locations of the GetRoute take address strings as well as
//lat/longs
function onGotFindResults (shapeLayer, findResults, locations, hasMoreResults)
{}

//a dummy function to use if no callback is wanted, same behavior as passing a null to the callback.
function onGotRouteNOP(){}

//Work around for VE not yet having turn by turn maps.  When VE 6 releases with Maneuver maps
//change this method to utilize that functionality.  Currently it creates a new map and route
//then zooms in and centers on the area of the specific instruction.
//Parameters:   route   VERoute
//              stepNumber  the current step
function GenerateDDMap(route, stepNumber)
{
    var ddMap = new YPGMapControl("ddmap" + stepNumber);
    var legs = route.RouteLegs;
    
     // 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
		  	try{
				___lastStepNumber = stepNumber;
				___lastCenter = leg.Itinerary.Items[stepNumber].LatLong;
				ddMap.CreateAndLoadMap(leg.Itinerary.Items[stepNumber].LatLong, 17, VEMapStyle.Road, true, null, false);
				ddMap.HideVEControls();
				___lastMap = ddMap;
				var routeShape = leg.Itinerary.Items[stepNumber].Shape;
				ddMap.AddPushpin(routeShape);

			}catch(ex){
				alert(ex.message);
			}
		}
}

//Opens the Turn By Turn map.
//TODO: fix behaviour
function OpenMapDiv(route)
{
    var stepNumber = ___lastStepNumber;
    var center = route.Itinerary.Segments[stepNumber].LatLong;
    var ddMap = ___lastMap;
    ddMap.SetCenterAndZoom(center, 17);
    var ourDiv = document.getElementById('ddmap' + stepNumber);
    //ourDiv.style.display = "block";
    //ourDiv.style.height = 214;
    var linkElement = document.getElementById('text' + stepNumber);
    linkElement.setAttribute('onclick', "CloseMapDiv(" + stepNumber + ")"); 
}

//Closes the Turn By Turn map.
//TODO: fix this behavior
function CloseMapDiv(stepNumber)
{
    var ourDiv = document.getElementById('ddmap' + stepNumber);
    //ourDiv.style.display = "none";
    //ourDiv.style.height = 0;
    var linkElement = document.getElementById('text' + stepNumber);
    linkElement.setAttribute('onclick', "GenerateDDMap(___lastRoute, " + stepNumber + ")");
}    


//Verifies the browser is compliant.  
IsBrowserVECompliant = function()
{				
	//firefox
	var firefox_index = navigator.userAgent.indexOf(FIREFOX_AGENTID);
	if (firefox_index != -1)
	{			
		var firefox_version = parseFloat(navigator.userAgent.substring(firefox_index + FIREFOX_AGENTID.length));									
		return firefox_version >= 1.5;				
	}
	
	//internet explorer		
	var ie_index = navigator.userAgent.indexOf(IE_AGENTID);
	if (ie_index != -1)
	{			
		var ie_version = parseFloat(navigator.userAgent.substring(ie_index + IE_AGENTID.length)); 				
		return ie_version >= 6;	
	} 
	
	return false;		
 }  
 
 
 function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

 
 //Global variables
 var ___lastCenter = null;
 var ___lastRoute = null;  
 var ___lastStepNumber = 0;
 var ___lastMap = null;



function two(x) {return ((x>9)?"":"0")+x}
function three(x) {return ((x>99)?"":"0")+((x>9)?"":"0")+x}

function time(ms) {
var sec = Math.floor(ms/1000)
ms = ms % 1000

var min = Math.floor(sec/60)
sec = sec % 60
t = two(sec) + "sec"

var hr = Math.floor(min/60)
min = min % 60
t = two(min) + "min " + t

var day = Math.floor(hr/60)
hr = hr % 60
hr = two(hr)


if(hr != 00) { t = hr + "h " + t }
if(day != 0) { t = day + "day " + t }

return t
}

//Added in order to remove North arrow when in birdseye view
function NorthArrowOff(e)
{
        if (e.mapStyle == "b") {
                document.getElementById('ypgmap-north').style.zIndex="-999";
        } else {
                document.getElementById('ypgmap-north').style.zIndex="999";
        }
}


function MyHandleTokenExpire()
{
   // insert code here to handle token expiration
   //alert("Virtual Earth token expiration!");
}

function MyHandleTokenError()
{
   // insert code here to handle token errors
   //alert("Virtual Earth token error!");
}   

