
var mapH = 200;
var mapW = 200;

var zoomLat = 0;
var zoomLon = 0;

//Set Maximum and minimum line width
var maxwidth = 11;
var minwidth = 8;
//These 4 values matching up is a coincidence
//Set the max and minimum zoom scale
var MaxMapZoomLevel = 14;
var MinMapZoomLevel = 7;
	

var isTripPlanning = false;


addWindowLoadEvent(StartupLoadMap, "start")

function StartupLoadMap()
{
    fld = document.getElementById('myMap');
    if (fld)
    {
        getMapDivSize();
		GetMap(varMapType);
	
	    // Disable zooming with mouse wheel.
        //map.AttachEvent("onmousewheel", mouseWheelDisable);
	    // Limit zooming with mouse wheel.
        map.AttachEvent("onmousewheel", mouseWheelLimit);
        // Zooms in and move the slider.
        map.AttachEvent("ondoubleclick", mouseDoubleClick);
        map.AttachEvent('onendzoom', functionEndZoom);
        
    }
	
}

window.onresize = function()
{
	resizeOneMap();

    return false;
}

function resizeOneMap()
{
	getMapDivSize();
	
    var Width = parseInt(mapW);
    var Height = parseInt(mapH);

	//alert("h = " + Height + " :: w = " + Width);
	map.Resize(Width, Height);
	
	//alert("Map resized.");

	//map.Resize(Msn.VE.API.Globals.vemapwidth, Msn.VE.API.Globals.vemapheight)
}


var pinX, pinY, pinTitle, pinDetails, pinref
var timerRefPop, timerRefCamera


function onMouseOverCallback(e)
{
    // check to see if we have hovered over a pushpin
    if(e.elementID != null)
    {
        //mouse is over a pushpin (or over a shape)
        pinref = map.GetShapeByID(e.elementID);

        pts = pinref.GetPoints();

        pinTitle = pinref.GetTitle();
        pinDetails = pinref.GetDescription();
        
        return true;
    } 

}


function OnMouseClickV5(e) 
{
    if(e.elementID)
    {
        //mouse is over a pushpin (or over a shape)
        pinref = map.GetShapeByID(e.elementID);

        //showShapePinDetails();
        //pinref.Show();
        

        window.ero.setBoundingArea(
        new Msn.VE.Geometry.Point(0,0),
        new Msn.VE.Geometry.Point(document.body.clientWidth,
            document.body.clientHeight));

        map.ShowInfoBox(pinref);

        if(isIE6)
        {
            if(isTripPlanning == false)
            {
                FixIE6div();
            }
            timerRefPop = setInterval("waitForPopup()", 350);
        }

        afterPopup();
    }
}


function getInfoReference()
{
    var infoDiv = null;

    /*
    var divs = document.getElementsByTagName("div") ;
    for( var i=0; i<divs.length; i++ ) {
        var e = divs[i] ;
        if((e.className == "ero ero-leftBeak") || (e.className == "ero ero-rightBeak")) {
            //alert("Found " + e.offsetTop);
            infoDiv = e;
            break;
        }
    }
    */
    
    //infoDiv = document.getElementById("MSVE_navAction_palette").nextSibling;
    
    infoDiv = window.ero.getElement();

    return infoDiv;

}


function waitForPopup()
{
    if (isPopupHidden() == false)
    {
        clearInterval(timerRefPop);
        timerRefPop = setInterval("checkPopupHide()", 100);
    }
}


function checkPopupHide()
{
    if (isPopupHidden() == true)
    {
        if(isIE6)
        {
            clearInterval(timerRefPop);
            HideFixIE6div();
        }
    }
}


function isPopupHidden()
{
    isHidden = false;

    try
    {
        //var InfoBoxElement = document.getElementById("MSVE_navAction_palette").nextSibling;
        var InfoBoxElement = getInfoReference();
        

        if( InfoBoxElement.style.visibility == "hidden" ) 
        {
            isHidden = true;
        }
    }
    catch(error)
    {
        //alert("Error finding infobox: " + error);
    }
    
    return isHidden;
}

function FixIE6div()
{
    var DivRegion = document.getElementById(DivRegionRef);
    
    DDRegionX = getLeftX(DivRegion);
    DDRegionWidth = parseInt(DivRegion.offsetWidth);
    DDRegionY = getTopY(DivRegion);
    DDRegionHeight = parseInt(DivRegion.offsetHeight);
    DDRegionBottom = DDRegionY + DDRegionHeight;

    try
    {
        var InfoBoxElement = getInfoReference();
		var popTop = getTopY(InfoBoxElement)

		if(popTop < DDRegionBottom)
		{
			var frm = document.getElementById("theframe");
	    	
			frm.style.top = parseInt(DivRegion.offsetTop) + "px";
			frm.style.height = DDRegionHeight;

			if(InfoBoxElement.className.indexOf("ero-leftBeak") == -1)
			{
    			frm.style.left = getLeftX(InfoBoxElement) - 207 + "px";
			}
			else
			{
    			frm.style.left = getLeftX(InfoBoxElement) - 188 + "px";
			}
		    frm.style.width = (parseInt(InfoBoxElement.offsetWidth) - 16) + "px";
	    	
			frm.style.display = "block";
		}

	}
    catch(error)
    {
        //alert("Error finding infobox: " + error);
    }

	//alert("DDbottom = " + DDRegionBottom + "\nDDRegionY = " + DDRegionY);
	//alert("top = " + DivRegion.offsetTop);
}

function HideFixIE6div()
{
	var frm = document.getElementById("theframe");
	frm.style.left = "-300px";
	frm.style.top = "-300px";
	frm.style.height = "10px";
	frm.style.width = "10px";
	frm.style.display = "block";	
}

function getLeftX(elemID)
{
    x = elemID.offsetLeft;
	tempEl = elemID.offsetParent;
	while (tempEl != null) {
		x += tempEl.offsetLeft;
  		tempEl = tempEl.offsetParent;
	}
	return x;
}

function getTopY(elemID)
{
    y = elemID.offsetTop;
	tempEl = elemID.offsetParent;
	while (tempEl != null) {
		y += tempEl.offsetTop;
  		tempEl = tempEl.offsetParent;
	}
	return y;
}


function showCurrentInfoBox()
{
    map.ShowInfoBox(pinref);
}


function setPinGlobals(x, y, title, details)
{            
    pinX = x;
    pinY = y;
    pinTitle = title;
    pinDetails = details;
}

 
 
 
 function ChangeMapStyle(newStyle)
 {
	switch (newStyle){
        case 'r':
            map.SetMapStyle(VEMapStyle.Road);
            break;
			
        case 'a':
            map.SetMapStyle(VEMapStyle.Aerial);
            break;
			
        case 'h':
            map.SetMapStyle(VEMapStyle.Hybrid);
            break;
			
        case 'o':
            if (map.IsBirdseyeAvailable())
            {
                map.SetMapStyle(VEMapStyle.Birdseye);
                //Get current scene
                    var beScene = map.GetBirdseyeScene();
                    if(beScene != null)
                    {
                        //You can get any scene that is neighboring the current
                        //scene such as North, East, West, South, Northeast
                        //and so on
                        /*
                        var neighbor = beScene.GetNeighborSceneID(VEOrientation.East);
                        var neighbor = beScene.GetNeighborSceneID(VEOrientation.West);
                        var neighbor = beScene.GetNeighborSceneID(VEOrientation.South);
                        var neighbor = beScene.GetNeighborSceneID(VEOrientation.North);
                        . . .
                        */
                        //For now get Northeast scene
                        var neighbor = beScene.GetNeighbor(VEOrientation.NorthEast);
                        map.SetBirdseyeScene(neighbor.GetID()); 
                    }
                    
            }
            else
            {
                map.ShowMessage('Birdseye view unavailable for this location and zoom level. Please try a different location and/or increase the zoom level.');
            }
            break;
                              
        default : map.SetMapStyle(VEMapStyle.Road);
    }
	
}


function showZoomLevel()
{
    alert(map.GetZoomLevel());
}


// Disable zooming with mouse wheel.
function mouseWheelDisable(e) {
    return true;
}

// Limit the zooming with mouse wheel.
function mouseWheelLimit(e) {
    var currentZoom = map.GetZoomLevel();

    if (event.wheelDelta) { /* IE/Opera. */
            delta = event.wheelDelta/120;
            /** In Opera 9, delta differs in sign as compared to IE.
             */
            if (window.opera)
                    delta = -delta;
    } else if (event.detail) { /** Mozilla case. */
            /** In Mozilla, sign of delta is different than in IE.
             * Also, delta is multiple of 3.
             */
            delta = -event.detail/3;
    }
    
    if(currentZoom >= MaxMapZoomLevel && delta > 0)
    {
        //map.SetZoomLevel(MaxMapZoomLevel);
        return true;
    }
    
    else
    {
        if(currentZoom <= MinMapZoomLevel && delta < 0)
        {
            //map.SetZoomLevel(MinMapZoomLevel);
            return true;
        }
        else
        {
            if(delta > 0)
            {
                map.ZoomIn()
                return true;
            }
            else
            {
                map.ZoomOut()
                return true;
            }
        }
    }
    
}

// Zooms in and move the slider.
function mouseDoubleClick(e) {
    //map.ZoomIn();

    if(!e.elementID)
    {
    
		//Get the current zoom level
		var currentZoomLevel;
		currentZoomLevel = map.GetZoomLevel();
		//Recenter map based on where the user clicked

		//Get the x pixel
		var x = e.mapX;
		//Get the y pixel
		var y = e.mapY;
		//Create a VEPixel object
		pixel = new VEPixel(x, y);

		//Convert the pixel to a lat/long
		var LatLon = map.PixelToLatLong(pixel);
		//Set the new center (based on where user clicked) and zoom.
		if (currentZoomLevel != MaxMapZoomLevel){
		map.SetCenterAndZoom(LatLon, currentZoomLevel + 1);
		}else{
		map.SetCenterAndZoom(LatLon, currentZoomLevel);
		}


		//slider.setValue(map.GetZoomLevel() * keyIncrement);
		//SetSlider();
	}
    //Return true to override the Virtual Earth default double-click event
    return true;
}	



function changeZoomLevel(zoomDirection)
{
    var currentZoom = map.GetZoomLevel();
    
    if(zoomDirection == 'in' && currentZoom != MaxMapZoomLevel)
    {
        map.ZoomIn();
    }
    
    if(zoomDirection == 'out' && currentZoom != MinMapZoomLevel)
    {
        map.ZoomOut();
    }
    //slider.setValue((MaxMapZoomLevel - map.GetZoomLevel()) * keyIncrement);
//    SetSlider();
	
}


function SetSlider()
{    
	//alert('setting slider');
    slider.setValue(Math.round((MaxMapZoomLevel - map.GetZoomLevel()) * keyIncrement));
}



//DETERMINE BROWSER VERSION
// If the browser is Firefox get the version number
//THIS ALLOWS THE LINE TO GET PLOTTED ON THE MAP FOR TRIP PLANNING
var ffv = 0;
var ffn = "Firefox/"
var ffp = navigator.userAgent.indexOf(ffn);
if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
// If we're using Firefox 1.5 or above override the Virtual Earth drawing functions to use SVG
if (ffv >= 1.5) {
  Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }
}

var panning = false;
var fromClick = false;


function showClickLatLong(e)
{
	
    alert(e.view.LatLong)

}

function DoPixelToLL(x,y)
{
	
    var ll = map.PixelToLatLong(x,y).toString()
    alert("The latitude,longitude of the pixel at ("+x+","+y+") is: "+ll)
	
}
 
 
function DoLLToPixel(varLatLong)
{
	
    var center = map.LatLongToPixel(map.GetCenter());
    alert("The center of the map is at pixel: x="+center.x+", y="+center.y)
	
}






function getMapDivSize()
{
	
	mapWrapperDiv = document.getElementById("mapWrapper");
	controlsDiv = document.getElementById("controlsWrapper");
	mapDiv = document.getElementById("myMap");
	
	var mapWrapperSizeObj = new GetDivDim(mapWrapperDiv);
	var ControlsSizeObj = new GetDivDim(controlsDiv);
	var mapDivSizeObj = new GetDivDim(mapDiv);
	
	//alert("mapWrapperSizeObj = " + mapWrapperSizeObj.Width + " :: ControlsSizeObj = " + ControlsSizeObj.Width + " :: mapDivSizeObj = " + mapDivSizeObj.Width);

    w = mapWrapperSizeObj.Width - ControlsSizeObj.Width - 14;
    h = 510;
	mapDiv.style.width = w + "px";
	mapDiv.style.height = h + "px";
	//alert("width = " + w);
	
	//w = mapDiv.style.width;
	//h = mapDiv.style.height;
	//alert("w = " + w);

	//Msn.VE.API.Globals.vemapheight = h;
	//Msn.VE.API.Globals.vemapwidth = w;
	
	mapH = h;
	mapW = w;
  
	//alert("h = " + h + " :: w = " + w);
}

function GetDivDim(divID)
{
	
	this.Width = 0;
	this.Height = 0;
	
	if( divID && ( divID.offsetWidth || divID.offsetHeight ) )
	{
		this.Width = divID.offsetWidth;
		this.Height = divID.offsetHeight;
		this.Left = divID.offsetLeft;
	}
	
}


function GetBrowserDim()
{
	
	this.Width = 0;
	this.Height = 0;
	
	if( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		this.Width = window.innerWidth;
		this.Height = window.innerHeight;
	} 
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	{
		//IE 6+ in 'standards compliant mode'
		this.Width = document.documentElement.clientWidth;
		this.Height = document.documentElement.clientHeight;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
	{
		//IE 4 compatible
		this.Width = document.body.clientWidth;
		this.Height = document.body.clientHeight;
	}
	
}


function setMapCenter()
{
	
	//var m = map.GetMapView();
	//alert("Click cTOP LEFT" + m.TopLeftLatLong);
	//alert("Click cBOTTOM RIGHT" + m.BottomRightLatLong);
	map.SetCenter(new VELatLong(varLat, varLon))
	//map.PanToLatLong(new VELatLong(varLat, varLon)); 	

}


function StartPan(x, y)
{
	
	map.StartContinuousPan(x,y);
	
}

function StopPan()
{
	
	map.EndContinuousPan();
	
}


//This function is run from the onEndZoom event from VE
function functionEndZoom()
{
    var zoomint = map.GetZoomLevel();
    // This code added for trip planning to make sure that after directions are zoomed into
    // the map will stay within the zoom boundaries
    if (zoomint > MaxMapZoomLevel) {
        map.SetZoomLevel(MaxMapZoomLevel);
    }else if (zoomint < MinMapZoomLevel) {
        map.SetZoomLevel(MinMapZoomLevel);
        varLat = LAT_VIRGINIA;
        varLon = LON_VIRGINIA;
        setMapCenter();
    }
    
	//Position slider
	SetSlider();
	//On zoom change, set line width for georss:line objects
	setwidth(determineLineWidth(map.GetZoomLevel()));
	
}

//Determine what the width of the line should be given the zoom level
function determineLineWidth(currZoom){
	
	// to match up scales
	// (maxwidth-minwidth)/(maxZoom-minzoom) = .4
	// Then multiply currZoom by .4 and add the MinWidth to make sure the line width
	// is at least that
	var scalevalue = (maxwidth-minwidth)/(MaxMapZoomLevel-MinMapZoomLevel)
	var returnVal = Math.round(((MaxMapZoomLevel-currZoom)*scalevalue)+minwidth);
	return returnVal
}

//Used to set the width of the lines on the map
function setwidth(val){
	//feedLayer1 is the conditionLine feed layer
	try
	{
		var numShapes = feedLayer1.GetShapeCount();
		//Loop over loaded elements and set icons
		//alert(val);
		for(var i=0; i < numShapes; ++i)
		{
			try
			{
				var s = feedLayer1.GetShapeByIndex(i);
				s.SetLineWidth(val);
			 }catch(e){
				//alert('error: ' + e.message);
				//fail silently
			 } 
			 
		}
		//feedLayer2 is the EventLine layer
		var numShapes = feedLayer2.GetShapeCount();
		//Loop over loaded elements and set icons
		for(var i=0; i < numShapes; ++i)
		{
			try
			{
				var s = feedLayer2.GetShapeByIndex(i);
				s.SetLineWidth(val);
			 }catch(e){
				//alert('error: ' + e.message);
				//fail silently
			 } 
			 
		}
	}catch(e){
	//fail silently
	}

}

function trimString (str) {
	str = this != window? this : str;
	return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}


function checkIE6()
{
    var isIE6 = false;
    
    //check for IE6 on Windows.
    if(BrowserDetect.OS == "Windows" && BrowserDetect.browser == "Explorer" && BrowserDetect.version >=6 && BrowserDetect.version < 7)
        isIE6 = true;
    
    if(BrowserDetect.OS == "Mac" && BrowserDetect.browser == "Firefox")
        isIE6 = true;

    return isIE6;
}


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};



BrowserDetect.init();

var isIE6 = false;

//check for IE6 on Windows.
if(BrowserDetect.OS == "Windows" && BrowserDetect.browser == "Explorer" && BrowserDetect.version >=6 && BrowserDetect.version < 7)
    isIE6 = true;

//if(BrowserDetect.OS == "Mac" && BrowserDetect.browser == "Firefox")
//    isIE6 = true;

if(isIE6)
{
    document.write("<iframe id=\"theframe\" src=\"\" class=\"frmcls\" frameborder=\"0\" scrolling=\"no\"></iframe>");
    HideFixIE6div();
}



var boolHasShown = false;

function centerZoom(varLat, varLon, varZoom)
{
	map.SetCenterAndZoom(new VELatLong(varLat,varLon), varZoom);
}

function GetShapeByLatLon(varLat, varLon)
{
    var shape = null;
    var numShapes = feedLayer1.GetShapeCount();
    //Loop over loaded elements and set icons
    for(var i=0; i < numShapes; ++i)
    {
		try
		{
			var s = feedLayer1.GetShapeByIndex(i);
            var pts = s.GetPoints();

			if ((pts[0].Latitude == varLat) && (pts[0].Longitude == varLon))
			{
                //alert("lat = " + pts[0].Latitude + "\nlong = " + pts[0].Longitude);
			    shape = s;
			    break;
			}
		 }catch(e){
			//alert('error: ' + e.message);
			//fail silently
		 } 
    }
    
    return shape;
}

function centerAndShowInfo(varLat, varLon)
{
    if (boolHasShown == false)
    {
	    varZoom = 12;
        currshape = GetShapeByLatLon(varLat, varLon)
	    //centerZoom(anchorLatLong.Latitude, anchorLatLong.Longitude, varZoom);

        if (currshape == null)
        {
	        centerZoom(varLat, varLon, varZoom);
        }
        else
        {
	        map.SetCenterAndZoom(currshape.GetIconAnchor(), varZoom);
        

            timedCall = "showInfo(currshape)"
            timerRef = setTimeout(timedCall, 500);
            
            //Call it again in case it didn't show up during map move.
            timerRef2 = setTimeout(timedCall, 1000);
	    }
	}
	boolHasShown = true;
}

function showInfo(objShape)
{
	//alert('show');
    map.ShowInfoBox(objShape);
}

