// virtualEarth.js
(function(){

    var timer = null;
    function setTimer(method,scope,args){
        clearTimer();
        scope = scope || window;
        timer = setInterval(function(){
            method.apply(scope,args);
        },500);
    }

    function clearTimer(){
        if(timer != null){
            clearInterval(timer);
            timer = null;
        }
    }

    SW.widget.virtualEarth = {
        maps:[],
        getMap:function(mapId){
            for(var i = 0; i< this.maps.length; i++){
                if(this.maps[i][0]==mapId) {
                    return this.maps[i][1];
                }
            }
            return null;
        },
      addMap:function(mapId,mapHelper){
            this.flag=false;
            for(var i = 0; i< this.maps.length; i++){
                if(this.maps[i][0] == mapId) {
                    this.flag=true;
                    break;
                }
            }
              if(!this.flag) {
                    this.maps.push([mapId,mapHelper]);
                } else {
                   this.replaceMap(i,mapId);
              }

        },
        replaceMap: function(index,mapId) {
            this.maps[index][0] = mapId;
           this.maps[index][1] = new mapHelper(mapId);
        },
        initializeMap:function(mapId) {
            var mapHelperObj = new mapHelper(mapId);
            this.addMap(mapId,mapHelperObj);
            return mapHelperObj;
        }
    };

    function mapHelper(mapId){
        this.mapID = mapId;
        this.map = new VEMap(mapId);
        this.currentViewMode = "road";
        this.latLong = null;
        this.debug = false,
        this.rotateTimer = null,
        this.nElement = null,
        this.compass = null,
        this.currentIdx = 0,
        this.coords = [],
        this.positions = [],
        this.offset = [],
        this.center = [],
        this.birdsEyetoggle = [],
        this.labelsList = null,
        this.isChineseMap = null,
        this.countryCode = null,
        this.labelsChecked = null,
        this.birdsEyeTabObj = null,
        this.northLetter = null,
        this.nPosition = null,
        this.mapId = mapId;
        this.ccwObj = null,
        this.cwObj = null,
        this.dashBoardID = null,
        this.zoomIn = null,
        this.zoomOut = null,
        this.mapCenterLat = null,
        this.mapCenterLong = null
    }
    mapHelper.prototype = {
        setBirdsEyeView:function() {
            if(this.mapCenterLat != null) {
                this.tempLatLong = new VELatLong(this.mapCenterLat,this.mapCenterLong);
            }
            this.map.SetTrafficLegendText(this.labelsList.trafficLegend);
            if(this.birdsEyeTabObj.className != "disableControl") {
                this.currentIdx = 0;
                if(this.labelsChecked == 'true') {
                    this.map.SetMapStyle(VEMapStyle.BirdseyeHybrid );
                } else {
                    this.map.SetMapStyle(VEMapStyle.Birdseye);
                }
                document.getElementById(this.dashBoardID).className='birdsEye';
                this.setNPosition(this.currentIdx);
            }
            if(this.mapCenterLat != null) {
                this.map.SetCenter(this.tempLatLong);
            }
        },
        setLatLong:function(latLongObj){
            this.latLong = latLongObj;
        },
        setLabels:function(labels) {
            this.labelsList= labels;
        },
        loadMap: function(latLong) {
            this.latLong = latLong;
            this.map.LoadMap(latLong, 15 ,VEMapStyle.Road ,false);
        },
        changeOpacity :function(){
            var element = yuiDom.getElementsByClassName('mapControls', 'div');
            yuiDom.addClass(element, "bright");
        },
        resetOpacity: function (){
            var element = yuiDom.getElementsByClassName('mapControls', 'div');
            yuiDom.removeClass(element,"bright");
        },
        setNPosition: function(Index) {
            this.nPosition = this.positions[Index];
            this.northLetter.style.left = this.nPosition[0] - this.offset[0] + "px";
            this.northLetter.style.top = this.nPosition[1] - this.offset[1] + "px";
        },
        // navigation is based on initial local area map requirements
        // if other navigation panes are needed, this code should be refactored
        // and moved into localAreaMap.jsp
        createCustomDashboard:function(dashboardID){
            var that = this;
            // set all nav/controls here
            that.dashBoardID = dashboardID;
            var dashboard = document.createElement("div");
            yuiDom.addClass(dashboard,"road");
            dashboard.id= dashboardID;

            var mapControls = document.createElement("div");
            yuiDom.addClass(mapControls,"mapControls");
            yuiEvent.addListener(mapControls,"mouseover", this.changeOpacity,this,true);
            yuiEvent.addListener(mapControls,"mouseout", this.resetOpacity,this,true);

            var tabs = document.createElement("ul");
            yuiDom.addClass(tabs,"tabs");

            var roadTab = document.createElement("li");
            yuiDom.addClass(roadTab,"roadTab");
            yuiEvent.addListener( roadTab, "click", function() {
                that.currentViewMode="road";
                document.getElementById(that.dashBoardID).className='road';
                that.map.SetMapStyle(VEMapStyle.Road);
                that.setNPosition(0);
                that.map.SetTrafficLegendText("");
            });
            var roadSpan = document.createElement("span");
            roadSpan.innerHTML = this.labelsList.road;
            roadTab.appendChild(roadSpan);

            var aerialTab = document.createElement("li");

            if(this.isChineseMap != 'true') {
                yuiDom.addClass(aerialTab,"aerialTab");
                yuiEvent.addListener( aerialTab, "click", function() {
                    that.currentViewMode = "aerial";
                    document.getElementById(that.dashBoardID).className='aerial';
                    if(that.labelsChecked == 'true') {
                        that.map.SetMapStyle(VEMapStyle.Hybrid );
                    } else {
                        that.map.SetMapStyle(VEMapStyle.Aerial);
                    }
                    that.setNPosition(0);
                    that.map.SetTrafficLegendText("");
                });
            } else {
                yuiDom.addClass(aerialTab,"disableControl");
            }
            var aerialSpan = document.createElement("span");
            aerialSpan.innerHTML=this.labelsList.aerial+"&nbsp;";
            aerialTab.appendChild(aerialSpan);


            this.birdsEyeTabObj = document.createElement("li");
            yuiDom.addClass(that.birdsEyeTabObj,"disableControl");
            that.map.AttachEvent("onobliqueleave", function() {
                 that.birdsEyeTabObj.className="disableControl";
            });
            that.map.AttachEvent("onobliqueenter", function() {
                that.birdsEyeTabObj.className = "birdsEyeTab";
                yuiEvent.addListener(that.birdsEyeTabObj,"click", function() {
                  that.currentViewMode="birdsEye";
                  that.setBirdsEyeView();
                });
            });

            var birdSpan = document.createElement("span");
            birdSpan.innerHTML = this.labelsList.birdsEye;
            that.birdsEyeTabObj.appendChild(birdSpan);

            var collapse = document.createElement("div");
            yuiDom.addClass(collapse,"collapse");
            collapse.title = this.labelsList.hideControls;
            yuiEvent.addListener(collapse,"click", function() {
                document.getElementById(that.dashBoardID).className='collapse';
            } )
            var collapseSpan = document.createElement("span");
            collapseSpan.innerHTML = '&lt;&lt;';
            collapse.appendChild(collapseSpan);


            var expand = document.createElement("div");
            yuiDom.addClass(expand,"expand");
            expand.title=this.labelsList.showControls;
            yuiEvent.addListener(expand,"click", function() {
                document.getElementById(that.dashBoardID).className=that.currentViewMode;
            } );
            var expandSpan = document.createElement("span");
            expandSpan.innerHTML = "&gt;&gt;";
            expand.appendChild(expandSpan);

            that.roadTab = roadTab;
            that.aerialTab = aerialTab;
            that.birdsEyeTab = this.birdsEyeTabObj;

            tabs.appendChild(roadTab);
            tabs.appendChild(aerialTab);
            tabs.appendChild(that.birdsEyeTabObj);

            var controls = document.createElement("div");
            yuiDom.addClass(controls,"controls");
            controls.id='controls';

            this.addCompass(controls);

            var options = document.createElement('div');
            yuiDom.addClass(options,'options');

            this.addLabels( options);
            this.addTraffic( options);

            this.addZoom (options);

            controls.appendChild(options);

            mapControls.appendChild(tabs);
            mapControls.appendChild(collapse);
            mapControls.appendChild(expand);
            mapControls.appendChild(controls);
            dashboard.appendChild(mapControls);

            return dashboard;
        },
        mapZoomIn:function() {
            var that = this;
            that.map.ZoomIn();
        },
        mapZoomOut:function() {
            var that = this;
            that.map.ZoomOut();
        },

        addZoom: function(parent) {
            var that = this;

            var zoom = document.createElement("div");
            yuiDom.addClass(zoom,"zoomControll");
            that.zoomIn = document.createElement("div");
            that.zoomOut = document.createElement("div");

            yuiDom.addClass(that.zoomIn,"zoomIn");
            yuiDom.addClass(that.zoomOut,"zoomOut");
             yuiEvent.addListener(this.zoomIn, "click", function() {
                that.mapCenterLat = that.map.GetCenter().Latitude;
                that.mapCenterLong = that.map.GetCenter().Longitude;
                if(that.latLong!=null && that.map.GetZoomLevel() == 3) {
                    that.map.SetCenter(that.latLong);
                }
                that.map.ZoomIn();
                that.handleTrafficLegend();
            });

            yuiEvent.addListener(this.zoomOut, "click", function() {
                that.mapCenterLat = that.map.GetCenter().Latitude;
                that.mapCenterLong = that.map.GetCenter().Longitude;
                if(that.latLong!=null && that.map.GetZoomLevel == 3) {
                    that.map.SetCenter(that.latLong)
                }
                that.map.ZoomOut();
                that.handleTrafficLegend();
            });

            yuiEvent.addListener(this.zoomIn, "mousedown", function() {
                that.mapCenterLat = that.map.GetCenter().Latitude;
                that.mapCenterLong = that.map.GetCenter().Longitude;
                if(that.latLong!=null && that.map.GetZoomLevel == 3) {
                    that.map.SetCenter(that.latLong)
                }
                setTimer(that.mapZoomIn,that);
            });
            yuiEvent.addListener(this.zoomIn, "mouseup", function() {
                clearTimer();
            });

            yuiEvent.addListener(this.zoomOut, "mousedown", function() {
                that.mapCenterLat = that.map.GetCenter().Latitude;
                that.mapCenterLong = that.map.GetCenter().Longitude;
               if(that.latLong!=null && that.map.GetZoomLevel == 3) {
                    that.map.SetCenter(that.latLong)
                }
                setTimer(that.mapZoomOut,that);
            });
            yuiEvent.addListener(this.zoomOut, "mouseup", function() {
                clearTimer();
            });
            zoom.appendChild(that.zoomOut);
            zoom.appendChild(that.zoomIn);

            parent.appendChild(zoom);
            that.map.AttachEvent("onendzoom",function(e) {
                if(e.zoomLevel == '1') {
                    yuiDom.addClass(that.zoomOut ,"disableControl");
                } else  {
                    yuiDom.removeClass(that.zoomOut ,"disableControl");
                }
                if(e.zoomLevel == '19' || (e.zoomLevel == '2' && (that.map.GetMapStyle() == 'o' || that.map.GetMapStyle() == 'b'))) {
                    yuiDom.addClass(that.zoomIn ,"disableControl");
                } else {
                    yuiDom.removeClass(that.zoomIn ,"disableControl");
                }
            });

        },
        handleTrafficLegend:function() {
        var that = this;
         if(that.map.GetMapStyle() != "b") {
                   if(that.map.GetZoomLevel() >= 15) {
                       that.map.SetTrafficLegendText(that.labelsList.zoomOutForTraffic);
                   } else if(that.map.GetZoomLevel() <= 7) {
                       that.map.SetTrafficLegendText(that.labelsList.zoomInForTraffic);
                   } else {
                       that.map.SetTrafficLegendText('');
                   }
                }
        },
        addCompass: function(parent) {
            var that = this;
            var mapDiv = document.getElementById(this.mapID);
            that.compass = document.createElement("div");
            var ids = [mapDiv,that.compass];
            yuiDom.addClass(that.compass,"compass");
            var compassPan = function(e) {
                  if(that.mouseDownFlag=="true") {
                    var xyCoords = yuiEvent.getXY(e);
                    this.offset = yuiDom.getXY(this);
                    var centerX = this.offset[0] + 29;
                    var centerY = this.offset[1] + 21;
                    var xDiff = Math.round((xyCoords[0] - centerX)/2);
                    var yDiff = Math.round((xyCoords[1] - centerY)/2);
                    // Make sure that map panning speed is not more than 7
                    if(xDiff > 5) { xDiff = "7" };
                    if(xDiff < -5) { xDiff = "-7" };
                    if(yDiff > 5) { yDiff = "7" };
                    if(yDiff < -5) { yDiff = "-7" };
                    that.map.StartContinuousPan(xDiff, yDiff);
                }
            }
            yuiEvent.addListener(ids,"mousemove",compassPan,that);
            yuiEvent.addListener(that.compass,"mousedown",function(e) { that.mouseDownFlag = "true"; });
            yuiEvent.addListener(that.compass,"mousedown",compassPan, that);
            yuiEvent.addListener(ids,"mouseup",function(e) {
                if(that.mouseDownFlag == "true") {
                    that.mouseDownFlag = "false";
                    that.map.EndContinuousPan();
                }
            });

            that.northLetter = document.createElement("div");
            yuiDom.addClass(that.northLetter,"north");
            that.northLetter.innerHTML = "N";
            that.compass.appendChild(that.northLetter);

            var panLeft = document.createElement("div");
            yuiDom.addClass(panLeft,"leftArrow");
            yuiEvent.addListener(panLeft, "mousedown", function () {
                that.map.StartContinuousPan(-10, 0);
            })
            yuiEvent.addListener(panLeft,"mouseup",function () {
                that.map.EndContinuousPan();
            } )
            that.compass.appendChild(panLeft);

            var panBottom = document.createElement("div");
            yuiDom.addClass(panBottom,"bottomArrow");
            yuiEvent.addListener(panBottom, "mousedown", function () {
                that.map.StartContinuousPan(0,10);
            })
            yuiEvent.addListener(panBottom,"mouseup",function () {
                that.map.EndContinuousPan();
            })
            that.compass.appendChild(panBottom);

            var panRight = document.createElement("div");
            yuiDom.addClass(panRight,"rightArrow");
            yuiEvent.addListener(panRight, "mousedown", function () {
                that.map.StartContinuousPan(10, 0);
            })
            yuiEvent.addListener(panRight,"mouseup",function () {
                that.map.EndContinuousPan();
            })
            that.compass.appendChild(panRight);

            var panTop = document.createElement("div");
            yuiDom.addClass(panTop,"topArrow");
            yuiEvent.addListener(panTop, "mousedown", function () {
                that.map.StartContinuousPan(0,-10);
            })
            yuiEvent.addListener(panTop,"mouseup",function () {
                that.map.EndContinuousPan();
            })
            that.compass.appendChild(panTop);

            that.ccwObj = document.createElement("div");
            yuiDom.addClass(that.ccwObj,"ccw");
            yuiEvent.addListener(that.ccwObj,"click",that.turnRight,that,true);
            that.compass.appendChild(that.ccwObj);

            that.cwObj = document.createElement("div");
            yuiDom.addClass(that.cwObj,"cw");
            yuiEvent.addListener( that.cwObj,"click",that.turnLeft,that,true);
            that.compass.appendChild( that.cwObj);

            parent.appendChild(that.compass);


        },

        panMap: function (x,y) {
            this.map.Pan(x,y);
        },

        addTraffic: function(parent) {
            var that = this;
            var traffic = document.createElement("div");
            yuiDom.addClass(traffic,"traffic")
            var trafficInput = document.createElement("input");
            trafficInput.type="checkbox";
            trafficInput.name="traffic";
            if(that.countryCode != 'US' && that.countryCode != 'CA') {
                yuiDom.addClass(parent,"noTraffic");
            }
            yuiEvent.addListener(trafficInput, "click", function() {
                if(trafficInput.checked)
                {
                    that.map.LoadTraffic(true);
                    that.map.ShowTrafficLegend();
                }
                else{
                    that.map.HideTrafficLegend();
                    that.map.ClearTraffic();
                };
            })
            var trafficLabel = document.createElement("label");
            trafficLabel.innerHTML = this.labelsList.traffic;
            traffic.appendChild(trafficInput);
            traffic.appendChild(trafficLabel);
            parent.appendChild(traffic);
        },

        addLabels: function(parent) {
            var that = this;
            var label = document.createElement("div");
            yuiDom.addClass(label,"labels")
            var labelInput = document.createElement("input");
            labelInput.type="checkbox";
            labelInput.name="labels";
//            IE Fix
            labelInput.setAttribute('defaultChecked', 'defaultChecked');
            labelInput.setAttribute('checked', 'checked');
            yuiEvent.addListener(labelInput, "click", function() {
                if(labelInput.checked) {
                    that.labelsChecked = 'true';
                    if(that.map.GetMapStyle()==VEMapStyle.Aerial) {
                        that.map.SetMapStyle(VEMapStyle.Hybrid);
                    } else {
                        that.map.SetMapStyle(VEMapStyle.BirdseyeHybrid );
                    }
                } else {
                    that.labelsChecked = 'false';
                    if(that.map.GetMapStyle()==VEMapStyle.Hybrid) {
                        that.map.SetMapStyle(VEMapStyle.Aerial);
                    } else {
                        that.map.SetMapStyle(VEMapStyle.Birdseye );
                    }
                };
            })
            var labelsLabel = document.createElement("label");
            labelsLabel.innerHTML = this.labelsList.label;
            label.appendChild(labelInput);
            label.appendChild(labelsLabel);
            parent.appendChild(label);
        },

        initializeRotate:function(){
            if(this.northLetter){
                this.setCoords();
            }
        },
        setMapZoom:function(zoom) {
            this.map.SetZoomLevel(zoom);
        },
        setZoomtoLinks:function(latitude,longitude, zoom) {
            this.propertyLatLong = new VELatLong(latitude,longitude);
            this.map.SetCenterAndZoom(this.propertyLatLong,zoom);
        },
        getMicrosoftZoom:function(propertyZoom) {
            var MSVE_ZoomLevel = 16 - (propertyZoom -1);
            return MSVE_ZoomLevel;
        },
        setCoords:function(){
            var cWidth,cHeight,nWidth,nHeight;
            this.offset = yuiDom.getXY(this.compass);
            cWidth = parseInt(yuiDom.getStyle(this.compass,"width"));
            cHeight = parseInt(yuiDom.getStyle(this.compass,"height"));
            nWidth = parseInt(yuiDom.getStyle(this.northLetter,"width"));
            nHeight = parseInt(yuiDom.getStyle(this.northLetter,"height"));

            this.positions = [];
            this.positions.push([ this.offset[0] + (cWidth/2 - nWidth/2), this.offset[1] - nHeight -3 ]);
            this.positions.push([ this.offset[0] + cWidth - 7, this.offset[1] + (cHeight/2 - nHeight/2 )]);
            this.positions.push([ this.offset[0] + (cWidth/2 - nWidth/2), this.offset[1] + cHeight ]);
            this.positions.push([ this.offset[0] - nWidth + 7, this.offset[1]  + (cHeight/2 - nHeight/2 )]);

            if(this.debug){
                yuiDom.getElementsByClassName("coord","div").forEach(function(div){
                    div.parentNode.removeChild(div);
                });
                this.coords.forEach(function(coord){
                    var div = document.createElement("div");
                    yuiDom.addClass(div,"coord");
                    yuiDom.setStyle(div,"left",coord[0] +"px");
                    yuiDom.setStyle(div,"top",coord[1] +"px");
                    yuiDom.get('controls').appendChild(div);
                });
                this.positions.forEach(function(coord){
                    var div = document.createElement("div");
                    yuiDom.addClass(div,"coord");
                    yuiDom.setStyle(div,"left",coord[0] +"px");
                    yuiDom.setStyle(div,"top",coord[1] +"px");
                    yuiDom.get('controls').appendChild(div);
                });
            }
            this.setInitialPosition();

        },
        setInitialPosition:function(){
            yuiDom.setStyle(this.nElement,"left",this.positions[0][0] - this.offset[0] +"px");
            yuiDom.setStyle(this.nElement,"top",this.positions[0][1] - this.offset[1] +"px");
        },
        setBirdsEyeOrientation:function(Index) {
            switch(Index) {
                case 1:
                    this.map.SetBirdseyeOrientation(VEOrientation.West);
                    this.setNPosition(this.currentIdx);
                    break;
                case 2:
                    this.map.SetBirdseyeOrientation(VEOrientation.South);
                    this.setNPosition(this.currentIdx);
                    break;
                case 3:
                    this.map.SetBirdseyeOrientation(VEOrientation.East);
                    this.setNPosition(this.currentIdx);
                    break;
                default:
                    this.map.SetBirdseyeOrientation(VEOrientation.North);
                    this.setNPosition(this.currentIdx);
                    break;
            }
        },

        turn:function(direction){

            var control;
            this.currentIdx += direction;
            if(this.currentIdx < 0){
                this.currentIdx = 3;
            } else if(this.currentIdx > 3){
                this.currentIdx = 0;
            }
            this.setBirdsEyeOrientation(this.currentIdx);
        },
        turnLeft:function(){
            this.turn(-1);
        },
        turnRight:function(){
            this.turn(1);
        }
    };

})();
