///**********************************************/
////Static Virtual Earth Specific Converters 
///***********************************************/
//// All methods on this static
//				  
//Type.registerNamespace("MapsDirect");    
//MapsDirect.VE = function(){};
// 
//MapsDirect.VE.mapUnitExtentTo_VELatLongRectangle = function(map, mapUnitExtent)
function mapUnitExtentTo_VELatLongRectangle (map, mapUnitExtent) {
    if (!map._mapUnitProj) 
        return null;
        
    var topLeftDD = MapsDirect.Converter.mapUnitPointToDDPoint(map, mapUnitExtent.get_topLeftPoint());
    var bottomRightDD = MapsDirect.Converter.mapUnitPointToDDPoint(map, mapUnitExtent.get_bottomRightPoint());
    var topRightDD = MapsDirect.Converter.mapUnitPointToDDPoint(map, mapUnitExtent.get_topRightPoint());
    var bottomLeftDD = MapsDirect.Converter.mapUnitPointToDDPoint(map, mapUnitExtent.get_bottomLeftPoint());    
    
    var TopLeftLatLong = new VELatLong(topLeftDD.y, topLeftDD.x);
    var BottomRightLatLong = new VELatLong(bottomRightDD.y, bottomRightDD.x);
    var TopRightLatLong = new VELatLong(topRightDD.y, topRightDD.x);
    var BottomLeftLatLong = new VELatLong(bottomLeftDD.y, bottomLeftDD.x);
    
    return new VELatLongRectangle(TopLeftLatLong, BottomRightLatLong, TopRightLatLong, BottomLeftLatLong);
};

//function VEMap_MapUnitExtent (map, VELatLongRect) {
//    if (!map._mapUnitProj) 
//        return null;
//        
//    var topLeftDD = MapsDirect.Converter.mapUnitPointToDDPoint(map, mapUnitExtent.get_topLeftPoint());
//    var bottomRightDD = MapsDirect.Converter.mapUnitPointToDDPoint(map, mapUnitExtent.get_bottomRightPoint());
//    var topRightDD = MapsDirect.Converter.mapUnitPointToDDPoint(map, mapUnitExtent.get_topRightPoint());
//    var bottomLeftDD = MapsDirect.Converter.mapUnitPointToDDPoint(map, mapUnitExtent.get_bottomLeftPoint());    
//    
//    var TopLeftLatLong = new VELatLong(topLeftDD.y, topLeftDD.x);
//    var BottomRightLatLong = new VELatLong(bottomRightDD.y, bottomRightDD.x);
//    var TopRightLatLong = new VELatLong(topRightDD.y, topRightDD.x);
//    var BottomLeftLatLong = new VELatLong(bottomLeftDD.y, bottomLeftDD.x);
//    
//    return new VELatLongRectangle(TopLeftLatLong, BottomRightLatLong, TopRightLatLong, BottomLeftLatLong);
//};

function VEMap_ToMapUnitExtent (veMapControl) {
    var map = veMapControl.map;
    if (!map.get_mapUnitProj()) 
        return null;
        
    var v = veMapControl.veMap.GetMapView();
    var tl = v.TopLeftLatLong;
    var br = v.BottomRightLatLong;
    
    var TopLeftDDPoint = new MapsDirect.Geometry.Point(tl.Longitude, tl.Latitude);
    var BottomRightDDPoint = new MapsDirect.Geometry.Point(br.Longitude, br.Latitude);
    //var TopRightDDPoint = new MapsDirect.Geometry.Point(br.Longitude, tl.Latitude);
    //var BottomLeftDDPoint = new MapsDirect.Geometry.Point(tl.Longitude, br.Latitude);
    
    var TopLeftMapPoint = MapsDirect.Converter.ddPointToMapUnitPoint(map, TopLeftDDPoint);
    var BottomRightMapPoint = MapsDirect.Converter.ddPointToMapUnitPoint(map, BottomRightDDPoint);
    //var TopRightMapPoint = MapsDirect.Converter.ddPointToMapUnitPoint(TopRightDDPoint);
    //var BottomLeftMapPoint = MapsDirect.Converter.ddPointToMapUnitPoint(BottomLeftDDPoint);
    
    return new MapsDirect.WebControls.Extent(TopLeftMapPoint.x, BottomRightMapPoint.y, BottomRightMapPoint.x, TopLeftMapPoint.y);
};

//MapsDirect.VE.registerClass("MapsDirect.VE");

//if (typeof (Sys) != "undefined")     
//{     
//	Sys.Application.notifyScriptLoaded();     
//};
///**********************************************/
////End of Static Converters
///***********************************************/


var virtualEarthControl = null;

VirtualEarthControlTool = function(map, floatingPanelId, veMapDivID, veMapBuddyDivID)
{
    this.map = map;
    this.veCenterPoint = null;
    
	this.floatingPanelId = floatingPanelId;
	this.floatingPanel = $find(floatingPanelId);
    this.map.showHelpByDefault = true;
    
	this.veMapDivID = veMapDivID; 
	this.veMapBuddyDivID = veMapBuddyDivID;
	
	this.veMapDiv = $get(this.veMapDivID);
	this.veMapBuddyDiv = $get(this.veMapBuddyDivID);
	
	this.veMap = null;    
	this.veMapBuddy = null; 
	 
    this.veLoaded = false;   
    this.veEventSpawned=false;	
	
	this.open = false;
	this.usePushpin = false;
	this.vePushpin = null;
	
//	this.map.add_scaleChanged(this.ParentMapScaleChanged);
	this.parentMapScale = null;
		
	this.floatingPanel.add_close(Function.createDelegate(this, this._onClosePanel));
};

VirtualEarthControlTool.prototype = 
{	
    width : function()
    {
       return parseInt(this.veMapDiv.style.width);
    },
    
    height : function()
    {
       return parseInt(this.veMapDiv.style.height);
    },
    
    aspectRatio : function()
    {
        return ( this.width()/this.height() );
    },
    
	show : function()
	{
		//floatingPanelManager.closeAll();
		floatingPanelManager.open(this.floatingPanelId);
		this.open = true;
		this.veMapDiv.style.width="100%";
		//this.veMapDiv.style.height="100%";
		
		this.GetVEMap();
		this.CenterVE();
	},
          
    _onClosePanel: function()
    {
        this.open = false;
        this.map.remove_extentChanged(this.CenterVE);	
    },
    
    GetVEMap: function()       
    {            
        if (!this.veMap)  {
            this.parentMapScale = this.map.get_scale();
            //var parentMapDDExtent = MapsDirect.Converter.mapUnitExtentToDDExtent(this.map, this.map.get_extent());
            var initialMapView = mapUnitExtentTo_VELatLongRectangle(this.map, this.map.get_extent());
            
            this.veMap = new VEMap(this.veMapDivID);  
            this.veMap.LoadMap();  
            
            //this.veMap.SetMapMode(VEMapMode.Mode2D);
            //this.veMap.SetMapStyle(VEMapStyle.Aerial);
            this.veMap.SetMapView(initialMapView);
            
            this.veLoaded = true;   
            
            this.map.add_extentChanged(this.CenterVE);	       
            this.veMap.AttachEvent("onmousedown", this.MouseDownHandler);
            this.veMap.AttachEvent("onmousewheel", this.MouseWheelHandler);
            this.veMap.AttachEvent("onobliqueenter", this.ObliqueEnterHandler); 
            this.veMap.AttachEvent("onendpan", this.EndPanHandler); 
            this.veMap.AttachEvent("onendzoom", this.EndZoomHandler); 
            
            this.veMap.SetMouseWheelZoomToCenter(false); 
            
            //get center of parent (mapsdirect map)
            var targetLatLonPoint = this.parentMapCenterPoint_AsVELatLonArray();
            //create a pushpin representing the center   
            if (this.usePushpin) { 
                this.vePushpin = this.createPushpin(targetLatLonPoint, "Current Map Focus", "This is the current map focus point");
                this.veMap.AddShape(this.vePushpin);  
            }
        }     
    },         

    parentMapCenterPoint_AsVELatLonArray : function()
    {
        //get center of parent (mapsdirect map)
        var mdMapCenterPoint = this.map.get_extent().get_centerPoint();
        var latLonPoint = MapsDirect.Converter.mapUnitPointToDDPoint(this.map, mdMapCenterPoint);
        
        return [ new VELatLong(latLonPoint.y, latLonPoint.x) ];
    },
    
    createPushpin : function(latLon, titleText, descriptionText)      
    {          
        var shape = new VEShape(VEShapeType.Pushpin, latLon);          
        shape.SetTitle(titleText);          
        shape.SetDescription(descriptionText);                 
        return shape;    
    },
    
    placePushpin : function()
    {
        //alert("placing");
        this.vePushpin.SetPoints(this.parentMapCenterPoint_AsVELatLonArray());
        //alert("placed");
    },
    
    CenterVE : function()
    {
        var me = virtualEarthControl;
        
        if (me.open) {
            //make sure map exists
            //also, make sure that the VE control is NOT currently the master navigatin control on the page
            //if so, it should not respond to events from other controls
            //this could result in cascading events!!!
            if (me.veMap && me.map.masterNavigationControlID != me.veMapDivID) {
                var mdMapCenterPoint = me.map.get_extent().get_centerPoint();
                var latLonPoint = MapsDirect.Converter.mapUnitPointToDDPoint(me.map, mdMapCenterPoint);
                var targetLatLonPoint = new VELatLong(latLonPoint.y, latLonPoint.x);
                
                try {
                    if (this.usePushpin)
                        me.placePushpin();
                    
                    if (me.parentMapScale == me.map.get_scale()) {
                        //pan to new map center
                        me.veMap.PanToLatLong(targetLatLonPoint);
                    } else {
                        var mapView = mapUnitExtentTo_VELatLongRectangle(me.map, me.map.get_extent().advancedFixAspectRatio(me.aspectRatio(), true));
                        //TODO: cascading events!!!
                        me.veMap.SetMapView(mapView);
                        //me.veMap.PanToLatLong(targetLatLonPoint);
                    }
                } catch (ex) {
                    //problem, so let'd reload the map
                    me.veMap.LoadMap(targetLatLonPoint,16); 
                }
            } else {
            }
        } else {
            //tool is not open: this is an error
        }
    },
    
    CenterBuddyMap : function(encryptedLatLonPoint)
    {
        var me = virtualEarthControl;
        
        if (!me.veMapBuddy) {
            me.veMapBuddy = new VEMap(me.veMapBuddyDivID);  
            me.veMapBuddy.LoadMap(encryptedLatLonPoint,17); 
            me.veMapBuddy.HideMiniMap();
            me.veMapBuddy.Hide3DNavigationControl();
            me.veMapBuddy.HideScalebar();
            me.veMapBuddy.HideDashboard();
        } else {
            me.veMapBuddy.PanToLatLong(encryptedLatLonPoint);
            var latLonCenterPoint = me.GetVECenterLatLonPoint(me.veMapBuddy);
            var mapCoordPoint = MapsDirect.Converter.ddPointToMapUnitPoint(me.map, latLonCenterPoint);
            me.map.centerOnPoint(mapCoordPoint);
        }
    },  
    
    //gets the map view rectangle for a birds eye scene
    getBirdsEyeMapView : function(veMapControl)   
    {
        var result;
        var v = veMapControl.GetMapView;
        var dc = new VELatLongDecoder();
        var tl = dc.Decode(v.TopLeftLatLong);
        var br = dc.Decode(v.BottomRightLatLong);
        //check birds eye direction and correct rectangle
        var be = veMapControl.GetBirdseyeScene();//need to flip some lat long if the scene has been rotated
        switch(be.GetOrientation()){
            case VEOrientation.North:
                result = new VELatLongRectangle(tl,br,null,null);
                break;
            case VEOrientation.East:
                //flip long
                result = new VELatLongRectangle(new VELatLong(tl.Latitude,br.Longitude),new VELatLong(br.Latitude,tl.Longitude),null,null);
                break;
            case VEOrientation.South:
                //flip lat and long
                result = new VELatLongRectangle(br,tl,null,null);
                break;
            case VEOrientation.West:
                //flip lat
                result = new VELatLongRectangle(new VELatLong(br.Latitude,tl.Longitude),new VELatLong(tl.Latitude,br.Longitude),null,null);
                break;                                    
        }
        
        return result;
    }, 

    GetVECenterLatLonPoint : function(veMapControl)
    {
        var latLonCenterPoint = null;
        var latLonCenterPointString = "";
        var lat = null;
        var lon = null;
        
        //Check if in Birdseye or Oblique Map Style
        if (veMapControl.GetMapStyle() == VEMapStyle.Birdseye || veMapControl.GetMapStyle() == VEMapStyle.BirdseyeHybrid)
        {
//           var theViewRect = getBirdsEyeMapView(veMapControl);
//           var be = veMapControl.GetBirdseyeScene();

//           // Get pixel info about center of the map
//           var pixel = be.LatLongToPixel(veMapControl.GetCenter(), veMapControl.GetZoomLevel());

//           var info = "Map center pixel coordinates are : (" + pixel.x + ", " + pixel.y + ")\n\n";
//           
//           var rect = be.GetBoundingRectangle();

//           // Display bounding rectangle property values to user
//           info += "Top-left corner: (" + 
//                   rect.TopLeftLatLong.Latitude + 
//                   ", " +
//                   rect.TopLeftLatLong.Longitude +
//                   ")\n";
//           
//           if(veMapControl.GetMapMode() == VEMapMode.Mode3D)
//           {
//              info += "Top-right corner: (" + 
//                      rect.TopRightLatLong.Latitude + 
//                      ", " +
//                      rect.TopRightLatLong.Longitude +
//                      ")\n";
//           }

//           info += "Bottom-right corner: (" + 
//                   rect.BottomRightLatLong.Latitude + 
//                   ", " +
//                   rect.BottomRightLatLong.Longitude +
//                   ")\n";
//                   
//           if(veMapControl.GetMapMode() == VEMapMode.Mode3D)
//           {
//              info += "Bottom-left corner: (" + 
//                      rect.BottomLeftLatLong.Latitude + 
//                      ", " +
//                      rect.BottomLeftLatLong.Longitude +
//                      ")\n";
//           }
//           alert(info);
        }
        else
        {
            // NOT in Birdseye or Oblique Map Style
            latLonCenterPoint = veMapControl.GetCenter(); 
        }
        
        if (latLonCenterPoint) {
            lat = latLonCenterPoint.Latitude;
            lon = latLonCenterPoint.Longitude;
        //    var latLonCenterPointStringArray = latLonCenterPointString.Split(',');
        //    var lat = parseFloat(latLonCenterPointStringArray[0].Trim());
        //    var lon = parseFloat(latLonCenterPointStringArray[1].Trim());
            
            var latLonPoint = new MapsDirect.Geometry.Point(lon, lat);
            //alert('GetVECenterLatLonPoint...'+latLonPoint.y+','+latLonPoint.x);
            return latLonPoint;
        } else {
            alert("GetVECenterLatLonPoint()->veMapControl.GetCenter() failed");
        }
        return null;
    },

    MouseDownHandler : function()
    {
        var me = virtualEarthControl;
        me.map.masterNavigationControlID = me.veMapDivID;
    },
    
    MouseWheelHandler : function()
    {
        var me = virtualEarthControl;
        me.map.masterNavigationControlID = me.veMapDivID;
    },
    
    GetEncryptedCenterPointOfBirdsEyeView : function(veMapControl)
    {
        if (veMapControl.IsBirdseyeAvailable())
        {
            var be = veMapControl.GetBirdseyeScene();
            var pixel = be.LatLongToPixel(veMapControl.GetCenter(), veMapControl.GetZoomLevel());
            encLatLong = be.PixelToLatLong(pixel, veMapControl.GetZoomLevel());
            return encLatLong;
        }
        return null;
    },
      
    EndPanHandler : function()
    {
        var me = virtualEarthControl;
        
        if (me.map.masterNavigationControlID != me.veMapDivID) {
            //alert("ve is not the master nav control");
            return true;
        }    
        

        if (me.veMap.GetMapStyle() == VEMapStyle.Birdseye || me.veMap.GetMapStyle() == VEMapStyle.BirdseyeHybrid) {    
            //pan buddy map
            var encLatLonCenterPoint = me.GetEncryptedCenterPointOfBirdsEyeView(me.veMap);
            me.CenterBuddyMap(encLatLonCenterPoint);
        } else {
            var latLonCenterPoint = me.GetVECenterLatLonPoint(me.veMap);
            if (latLonCenterPoint) {
                var mapCoordPoint = MapsDirect.Converter.ddPointToMapUnitPoint(me.map, latLonCenterPoint);
                me.map.centerOnPoint(mapCoordPoint);
            }
            //alert('end pan...\nlatLonCenterPoint:' + latLonCenterPoint.y+','+latLonCenterPoint.x+"\nmapCoordPoint:"+mapCoordPoint.y+','+mapCoordPoint.x);
        }
    },

    EndZoomHandler : function()
    {
        var me = virtualEarthControl;
        
        if (me.map.masterNavigationControlID != me.veMapDivID) {
            //alert("VE EndZoomHandler cancelled as VE not registered as the masterNavigationControl");
            return true;
        }
        
        if (me.veMap.GetMapStyle() == VEMapStyle.Birdseye || me.veMap.GetMapStyle() == VEMapStyle.BirdseyeHybrid) {
            //do nothing now
        } else {
            var mapExtent = VEMap_ToMapUnitExtent(me);
            var centerPoint = mapExtent.get_centerPoint();
            var targetScale = me.map.get_scale(mapExtent);
            
            var snappedTargetExtent = me.map.zoomToScale(targetScale, centerPoint, true, false);
            var snappedTargetScale = me.map.get_scale(snappedTargetExtent);
            me.map._animateToScale_CenteredOnMapPoint(snappedTargetScale, centerPoint, null);
        }
    }, 
    
    ObliqueEnterHandler : function()
    {
        //alert("ObliqueEnterHandler()");
    },
         
    OrientVE : function(direction)
    {
        this.veMap.SetBirdseyeOrientation(VEOrientation.South);
    }

};



//function GetVECenterLatLonPoint(vemap)
//{
//    var latLonCenterPointStringArray = vemap.GetCenter().Split(',');
//    var lat = parseFloat(latLonCenterPointStringArray[0].Trim());
//    var lon = parseFloat(latLonCenterPointStringArray[1].Trim());
//    
//    var latLonPoint = new MapsDirect.Geometry.Point(lat, lon);
//    alert('GetVECenterLatLonPoint...'+latLonPoint.y+','+latLonPoint.x);
//    return latLonPoint;
//};   

    
//    OnObliqueEnterHandler : function(veLat, veLon)         
//    {        
//        
//        //this.veMap.LoadMap(targetLatLonPoint, 17);
//        
//        //alert("OnObliqueEnterHandler -> this.veLoaded="+this.veLoaded);
//        if (this.veLoaded) {

//            try {
//                this.veMap.PanToLatLong(targetLatLonPoint);
//                
//    //            if(this.veMap.IsBirdseyeAvailable())            
//    //            {                       
//    //                this.veMap.SetBirdseyeScene(targetLatLonPoint);            
//    //            }       
//            } catch (ex) {
//                //alert("exception caught");
//                this.veMap.LoadMap(targetLatLonPoint,17); 
//            }
//        }  else {
//            alert("dupliate map being created");
//            this.veMap.LoadMap(targetLatLonPoint,17); 
//            veLoaded=true;
//        }
//    },
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();