﻿var WxGMap;

var WxGMap_div;
var WxGMap_divID = "WxGMap";

var WxGMap_geocoder;
var WxGMap_zoomError;
var WxGMap_zoomErrorLevel;
var WxGMap_items = new Array (300);

var WxGMap_zoomControls;
var WxGMap_initCenterLatLng;

var WxGMap_IDs = new Array ();
var WxGMap_capitalIDs;
var WxGMap_zipcodeIDs;
var WxGMap_selectedID;
var WxGMap_currentID;
var WxGMap_maxVisibleItems = 100;
var WxGMap_optimalVisibleItems = 15;
var WxGMap_baseDataURL = webRoot + "/Data/WxGMapLoadCameras.aspx?";
var WxGMap_locationSearchControlContainer;
var WxGMap_locationSearchControlSelection;
var WxGMap_statusControl;
var WxGMap_LOD = 0;
var WxGMap_opening = 0;
var WxGMap_loading = 0;

var WxGMap_ShowButton = 0;
var WxGMap_countryFilter = null;
var WxGMap_maxZoom = -1;
var WxGMap_maxBounds = null;

var WxGMap_TooltipID = "WxGMapTooltip";
var WxGMap_ShowTooltips = 0;
var WxGMap_toolTipsShowing = 0;
var WxGMap_toolTipClass = "WxGMap_toolTipClass";
var WxGMap_windowClass = "WxGMap_windowClass";
var WxGMap_extraTooltipHTML = null;
var WxGMap_extraWindowHTML = null;

var WxGMap_StatusImgURL = imageRoot + "limitedViewText.gif";
var WxGMap_LoadingImgURL = imageRoot + "loader.gif";
var WxGMap_CurrentItemImgURL = imageRoot + "star.gif";
var WxGMap_CurrentItemImgHeight = "8";
var WxGMap_CurrentItemImgWidth = "8";

var cameraMap = false;
var startId = "0";
var isTraffic = 0;

function WxGMapLoad(inAddress, inBaseURL, SWLat, SWLng, NELat, NELng) {                          
    if(inBaseURL != null){
        WxGMap_baseDataURL = inBaseURL;
    }
    if (inAddress == null){
        inAddress = "Germantown, MD";
    }
    if (GBrowserIsCompatible()) {
        // initialization code
        WxGMap_div = document.getElementById(WxGMap_divID)
        WxGMap = new GMap2(WxGMap_div, {logoPassive:true});
        //set the Terms of Use link to open in a new window
        var GfwTouNode = document.getElementsByTagName("A"); 
        for (var i = 0; i < GfwTouNode.length; i++) { 
            if(GfwTouNode[i].innerText == "Terms of Use")
                GfwTouNode[i].target="_blank"; 
        }
        WxGMap_geocoder = new GClientGeocoder();
        try{
            GDownloadUrl(WxGMapCreateLocationDataFeedURL(inAddress), function(data, responseCode){
                var theLocations = eval("(" + data + ")");

                    var theLatLng = theLocations[0];
                    if (theLatLng != null){
                    
                        // create controls      
                        WxGMap_zoomControls = new GSmallZoomControl();                        
                        WxGMap.addControl(new StatusControl ());
                        WxGMap.addControl(WxGMap_zoomControls);            
      //                  WxGMap.addControl (new LocationSearchControl ());
                        WxGMap.addControl(new LoadingControl ());
                    
                        // initialize map extents
                        WxGMap_initCenterLatLng = new GLatLng(theLatLng.Lat, theLatLng.Lng);
                        WxGMap.setCenter(WxGMap_initCenterLatLng,7);
                        WxGMap_zoomError = false;
                        WxGMap_zoomErrorLevel = WxGMap.getCurrentMapType().getMaximumResolution(WxGMap.getCenter());
                        G_NORMAL_MAP.getErrorMessage = function (){

                            WxGMap_zoomError = true;
                            WxGMap_zoomErrorLevel = WxGMap.getCurrentMapType().getMaximumResolution(WxGMap.getCenter());
                        }                         
                   
                        
                        if(inAddress == null){
                            inAddress = "Germantown, MD";
                        }
                        
                     //   WxGMapSearchLocation(inAddress, false);\
                        // If there are bounds specified for the map, add drag control events and zoom in
                        if (SWLat != null && SWLng != null && NELat != null && NELng != null){
                            GEvent.addListener(WxGMap,"movestart", function (){                            
                                WxGMap.savePosition();
                                
                            });
                            

                            GEvent.addListener(WxGMap,"moveend", function(){
                                if (!WxGMap_maxBounds.contains(WxGMap.getCenter())){
                                    WxGMap.returnToSavedPosition();
                                }                                 
                            });

                            GEvent.addListener(WxGMap,"zoomend", function (oldzoom,newzoom){

                                if (newzoom < WxGMap_maxZoom){

                                    WxGMap.setZoom(oldzoom);
                                } 
                            });
                           

                            WxGMapZoomToBounds(SWLat, SWLng, NELat, NELng);
                        } else {
                            // If there are no bounds specified for the map, add move control events and zoom into the number
                            GEvent.addListener(WxGMap,"zoomend", function (oldzoom,newzoom){
                                
                                WxGMap.clearOverlays ();
           
                            });
                           
                            GEvent.addListener(WxGMap,"moveend", function(){
                                if(WxGMap_opening == 0){
                                    ChangeLoading(true);  
                                    WxGMapProcessBounds();
                                    
                                } else {
                                    WxGMap_opening = 0;
                                }
                            });
                            WxGMapZoomToCertainNumber (WxGMap.getBounds(),WxGMap_optimalVisibleItems,WxGMap.getZoom());
                        }
                    }

            });
        } catch (ex) {

        }




    }
}



function WxGMapAddCountryFilter(inCountry){
    if (WxGMap_countryFilter == null){
        WxGMap_countryFilter = new Array (0);
    }

    WxGMap_countryFilter[inCountry] = 1;
}

function WxGMapRemoveCountryFilter(inCountry){
    if (WxGMap_countryFilter != null){
        WxGMap_countryFilter[inCountry] = 0;
    }
}

function WxGMapDisableCountryFilter(inCountry){
    delete WxGMap_countryFilter;
    WxGMap_countryFilter = null;
}

// Handle functions, these functions are handles for the website to call to access the interface
function WxGMapHandleMove (){
    WxGMapProcessBounds();
}

function WxGMapHandleSearchLocation (inAddress){
    WxGMapSearchLocation(inAddress,true);
}


function HandleSelectItem (){
    alert(WxGMap_selectedID);
}
   
   
function WxGMapSelectDefaultItem(inItemID){
    var curItem = WxGMap_items[inItemID];
    if(curItem != null){
        WxGMap_selectedID = inItemID;
        WxGMapCreateInfoWindowHTML(curItem,WxGMap_items[inItemID].Marker);    
    }
}

function WxGMapCreateDataFeedURL (bounds){
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();

    var datafeedURL = WxGMap_baseDataURL + "func=loadbylatlng&SWLatLng="+southWest.toUrlValue()+"&NELatLng="+northEast.toUrlValue()+ "&max=" + WxGMap_maxVisibleItems + "&startid=" + startId;

    return datafeedURL;
}

function WxGMapCreateHTMLDataFeedURL (itemID){
    var datafeedURL = WxGMap_baseDataURL + "func=htmlforid&id=" + itemID;
    return datafeedURL;
}

function WxGMapCreateLocationDataFeedURL (inAddress){
    var datafeedURL = WxGMap_baseDataURL + "func=locationsearch&location=" + inAddress;
   
    return datafeedURL;
}

function WxGMapCreateOptimalDataFeedURL (bounds, inZoom){
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var datafeedURL = WxGMap_baseDataURL + "func=optimalzoombylatlng&SWLatLng="+southWest.toUrlValue()+"&NELatLng="+northEast.toUrlValue()
                        + "&zoom=" + inZoom + "&optimal=" + WxGMap_optimalVisibleItems;
    return datafeedURL;
}

var calls = 0;
function WxGMapZoomToCertainNumber (inBounds,inCount,inZoom){
    try {

        GDownloadUrl(WxGMapCreateOptimalDataFeedURL(inBounds,inZoom), function(data, responseCode){

            var theZoom = eval("(" + data +")");
            WxGMap.setCenter(inBounds.getCenter(),theZoom);

        });
    } catch (ex) {
       alert(ex);
    }
}

function WxGMapZoomToBounds (SWLat, SWLng, NELat, NELng){
        var theBounds = new GLatLngBounds (new GLatLng (SWLat, SWLng), new GLatLng (NELat, NELng));
        var theZoom = WxGMap.getBoundsZoomLevel(theBounds);
        WxGMap_maxZoom = theZoom;
        WxGMap_maxBounds = theBounds;

        WxGMap.setCenter(theBounds.getCenter(), theZoom);
        WxGMapProcessBounds();
        WxGMap.savePosition();
}


function WxGMapDrawItem (curItem){
    if(curItem != null && curItem.marker == null){

        var newPoint = new GLatLng (curItem.Lat,curItem.Lng, false);

        var iconItem = new GIcon();
        if (curItem.ID != WxGMap_currentID){
            iconItem.image = curItem.image;
            iconItem.iconSize = new GSize(curItem.width,curItem.height);
        } else {
            iconItem.image = WxGMap_CurrentItemImgURL;
            iconItem.iconSize = new GSize(WxGMap_CurrentItemImgWidth,WxGMap_CurrentItemImgHeight);
        }
        iconItem.iconAnchor = new GPoint(curItem.width/2,curItem.height/2);
        iconItem.infoWindowAnchor = new GPoint(curItem.width/2,0);
        var marker = new GMarker(newPoint,iconItem);

        GEvent.addListener(marker,"click",function(){
            if (WxGMapMarkerClicked (curItem.ID)){
                if (isTraffic > 0)
                {   
                    if (curItem.image.indexOf("na.gif")<0)
                    {
                        try
                        {   
                            isClick = true;
                            
                            if (camTimer != null)
                            {
                                clearTimeout(camTimer);
                            }
                        }catch(e){}
                        WxGMap_selectedID = curItem.ID;
                        window.parent.location.href = camUrl.replace("$$traffic-cam$$",WxGMap_selectedID);//camUrl + WxGMap_selectedID;
                    }
                }
                else
                {
                    WxGMapCreateInfoWindowHTML(curItem,marker);
                    WxGMap_selectedID = curItem.ID;
                    WxGMapSelectionBoxSelectByItemID (WxGMap_selectedID);
                }
            }
        });


        GEvent.addListener(marker, "mouseover", function (){
            
            if(WxGMap_ShowTooltips == 1 && WxGMap_loading == 0){
                WxGMapShowTooltip(curItem,marker);
            }
        });
        
        GEvent.addListener(marker, "mouseout", function (){
            if(WxGMap_ShowTooltips == 1){
                WxGMapHideTooltip(curItem);
            }
        });
        
       
       // attach the marker to the item in case there are anymore changes to the marker beyond initialization
       WxGMap_items[curItem.ID].Marker = marker;

       WxGMap.addOverlay(marker);

    }
}

function WxGMapMarkerClicked (){
    return true;
}

function WxGMapShowTooltip(item,marker){

    WxGMap_toolTipsShowing = 1;
    var theTooltip = document.getElementById (WxGMap_TooltipID);

    if (theTooltip == null)
    {
        theTooltip = document.createElement ("div");
        theTooltip.id = WxGMap_TooltipID;
        theTooltip.style.position = "absolute";
        theTooltip.style.top = "20px";
        theTooltip.style.left = "20px";
        theTooltip.className = WxGMap_toolTipClass;
        theTooltip.style.className = WxGMap_toolTipClass;
        WxGMap_div.appendChild(theTooltip);
        theTooltip.style.visibility="visible";
    }

    var point=WxGMap.getCurrentMapType().getProjection().fromLatLngToPixel(WxGMap.getBounds().getSouthWest(),WxGMap.getZoom());

	var offset=WxGMap.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),WxGMap.getZoom());

	var anchor=marker.getIcon().iconAnchor;

	var width=marker.getIcon().iconSize.width;

    var theX = offset.x - point.x - anchor.x + width + 5;

    var theY = WxGMap.getSize().height - (- offset.y + point.y +anchor.y) - 15;

    theTooltip.style.left = theX + "px";
    theTooltip.style.top = theY + "px";
   
    GDownloadUrl(WxGMapCreateHTMLDataFeedURL(item.ID), function(data, responseCode){
        theTooltip.innerHTML = data ;
        if (WxGMap_extraTooltipHTML != null){
            theTooltip.innerHTML = theTooltip.innerHTML + WxGMap_extraTooltipHTML;
        }
        
        if (theTooltip.currentStyle){
		    var theWidth = theTooltip.currentStyle["width"];
		    var theHeight = theTooltip.currentStyle["height"];
	    }
	    else if (window.getComputedStyle){
		    var theWidth = document.defaultView.getComputedStyle(theTooltip,null).getPropertyValue("width");
		    var theHeight = document.defaultView.getComputedStyle(theTooltip,null).getPropertyValue("height");
		}

        theWidth = parseInt(theWidth);        
        theHeight = parseInt(theHeight);
        theTooltip.style.left = "0px";
        
        if (theTooltip.currentStyle)
		    var theFullWidth = theTooltip.currentStyle["width"];
	    else if (window.getComputedStyle)
		    var theFullWidth = document.defaultView.getComputedStyle(theTooltip,null).getPropertyValue("width");
        
        theFullWidth = parseInt(theFullWidth);

		if (theX + theWidth > WxGMap.getSize().width){
		    
		    theX = offset.x - point.x -(- anchor.x + width + 5 + theFullWidth);
		    theTooltip.style.left = theX + "px";
		} 
		if (theY < 0){
		    theY = 0;
		}
		if (theY + theHeight > WxGMap.getSize().height){
		    theY = WxGMap.getSize().height - theHeight;
		}
		theTooltip.style.left = theX + "px";
		theTooltip.style.top = theY + "px";
		
		

        if(WxGMap_toolTipsShowing == 1){
            theTooltip.style.visibility="visible";  
        }

    });     
   
}

function WxGMapHideTooltip (){
    WxGMap_toolTipsShowing = 0;
    var theTooltip = document.getElementById (WxGMap_TooltipID);
    if (theTooltip != null && WxGMap_toolTipsShowing == 0)
    {
        theTooltip.style.visibility="hidden";
    }
    
}

function WxGMapAddItem (curItem){

    if(WxGMap_items[curItem.ID] == null && curItem != null){
        
        if (WxGMap_countryFilter != null){

            if (WxGMap_countryFilter[curItem.State] != null && WxGMap_countryFilter[curItem.State] == 1){

                curItem.Distance = 0;
                WxGMap_items[curItem.ID] = curItem; 
                return true;
            }
        } else {
            
            curItem.Distance = 0;
            WxGMap_items[curItem.ID] = curItem; 
            return true;
        }
    }
    if (WxGMap_items[curItem.ID] != null)
    {
        return true;
    }
}

// WxGMapProcessBounds determines what items lie in the LatLng boundaries and adds them to the WxGMap if they haven't already been added to the WxGMap
function WxGMapProcessBounds(){

    var bounds = WxGMap.getBounds();
    var mapzoom = WxGMap.getZoom();

    ChangeLoading(true);
    // Datafeed Request for items contained within the bounds
    GDownloadUrl(WxGMapCreateDataFeedURL(bounds), function(data, responseCode){
        WxGMapSelectionBoxClear();

  
     //   WxGMap_items = new Array (300);

        ChangeLoading(false);
        var latLngItems;
        try{
            var dataReturn = eval("(" + data + ")");

            if (dataReturn.level != 0){
                ChangeStatus (1);

            } else {
                ChangeStatus (0);
            }
            latLngItems = dataReturn.items;
        } catch (ex){
            alert(ex);
            alert(data);
        }
        

        
        // iterate through the items and add them to the WxGMap if they haven't been added and add them to the select box
        for(j = 0; j < latLngItems.length; ++ j){
            var curItem = latLngItems[j];
            if (WxGMapAddItem(curItem)){                
                WxGMapDrawItem(curItem);
                WxGMapSelectionBoxAddItem(curItem); 
            }                
        }

        // make sure the selected item is still selected
        if(WxGMap_selectedID != null){     
            WxGMapSelectionBoxSelectByItemID(WxGMap_selectedID);
        }
    }); 
}


// Just refreshes the selection box for now
function WxGMapRefreshUserMarker(){
    WxGMapSelectionBoxRefreshSelections();         
}

// helper math functions to determine and max and min
function max(x,y){
    if(x > y){
        return x;
    } else {
        return y;
    }
}

function min(x,y){
    if(x < y){
        return x;
    } else {
        return y;
    }
}

function WxGMapCreateInfoWindowHTML(curItem, marker) {

    WxGMap_opening = 1;
    GDownloadUrl(WxGMapCreateHTMLDataFeedURL(curItem.ID), function(data, responseCode) {
    var windowHTML = "<div id='WxGMap_infoWindow' class='WxGMap_windowClass'>" + data;
        if (WxGMap_extraWindowHTML != null) {
            windowHTML = windowHTML + WxGMap_extraWindowHTML;
        }
        windowHTML = windowHTML + "</div>";
        marker.openInfoWindowHtml(windowHTML, { maxWidth: WxGMap.getSize().width - 50 });
    });
   
    return;
}

// StatusControl - a control that displays the status of the map
function StatusControl (){
}

    StatusControl.prototype = new GControl ();

    StatusControl.prototype.initialize = function(WxGMap) {
    WxGMap_statusControlContainer = document.createElement("div");

    var statusImg = document.createElement("img");
    statusImg.id = "WxGMapStatusImg";
    statusImg.style.display = "none";
    statusImg.src = WxGMap_StatusImgURL;
    WxGMap_statusControlContainer.appendChild(statusImg);

    WxGMap.getContainer().appendChild(WxGMap_statusControlContainer);
    WxGMap_statusControl = this;
    return WxGMap_statusControlContainer;
}

function ChangeStatus (inStatus){
    var statusImgElement = document.getElementById("WxGMapStatusImg");
    if (inStatus == 1){
        
        statusImgElement.style.display = "inline";
    } else {
        statusImgElement.style.display = "none";
    }
}

StatusControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 20));
}


// LoadingControl - a control that displays the loading of the map
function LoadingControl (){
}

LoadingControl.prototype = new GControl ();

LoadingControl.prototype.initialize = function (WxGMap){
    WxGMap_loadingControlContainer = document.createElement("div");
    
    var loadingIMG = document.createElement("img");
    loadingIMG.id = "WxGMapLoadingIMG";
    loadingIMG.src = WxGMap_LoadingImgURL;
    loadingIMG.style.display = "inline";
    WxGMap_loadingControlContainer.appendChild(loadingIMG);
       
    WxGMap.getContainer().appendChild(WxGMap_loadingControlContainer);
    WxGMap_loadingControl = this;
    return WxGMap_loadingControlContainer;
}

function ChangeLoading (inShow){
    var loadingImgElement = document.getElementById("WxGMapLoadingIMG");
        WxGMap_loading = inShow;
    if(inShow == true){
        
        loadingImgElement.style.display = "inline";
    }
    else {
        loadingImgElement.style.display = "none";
    }
}

LoadingControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(WxGMap.getSize().width/2-72, WxGMap.getSize().height/2-46));
}
