

//CAMERAS PAGE CONSTANTS
var pinID = 1; 
//var currentCamera = null;
//var trafficCameraID = 0;

var req;
var popupBody = "";


var timerRefCameraShutoffPop;
var cameraShutoffMilliSecondsPop = 20 * 1000;
var cameraShutoffPop = true;

function shutOffCamerasPop()
{
    //alert("Shutoff");
    cameraShutoffPop = true;
}




function load_TrafficCameras()
{
	// LOAD THE MAP
	//map.onLoadMap = WaitFunction(); 
	//map.LoadMap(new VELatLong(varLat, varLon), varZoom ,'r' , false);

    map.LoadMap();
	map.HideDashboard();
	

    varZoom = parseInt(varZoom)
    map.SetCenterAndZoom(new VELatLong(varLat,varLon), varZoom);
    map.SetMapStyle(VEMapStyle.Road);


    map.AttachEvent("onclick", OnMouseClickCameras);
    map.AttachEvent("onmouseover", onMouseOverCallback);


	//IF THE SESSION IS VIRGINIA (STATEWIDE), THEN SHOW THE BORDER AND SHADING
	if(sessionRegion == 1 && varShowVirginiaBorder == 'True')
	{
		showVirginiaBorder();
	}

    //parseCameras();
    //This delay allows the map to load without the pushpins.
    timerRef2 = setTimeout('AddCameraLayer()',10);

}


function AddCameraLayer()
{
    feedLayer1 = new VEShapeLayer();
    var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, 'webServices/GeoRSSFeed.asmx/GetGeorssCameras', feedLayer1);
    map.ImportShapeLayerData(veLayerSpec, onFeedLoadCameras, false);
}


function OnMouseClickCameras(e) 
{
    //var pinX, pinY, pinTitle, pinDetails, pinref

    if(e.elementID)
    {
        //mouse is over a pushpin (or over a shape)
        pinref = map.GetShapeByID(e.elementID);
        
        wid = getCameraWebid(pinref);
        getCamera(wid);

        //Will call finishPopup when the AJAX process is done.    
    }
}

function finishPopup()
{
    //Build description.
    pinref.SetDescription(popupBody);
    

    //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)
    {
        FixIE6div();
        timerRefPop = setInterval("waitForPopup()", 350);
    }

    afterPopup();
}



function getCamera(id)
{
    webserviceurl = "webServices/GeoRssFeed.asmx/GetCameraByWebID?webid=" + id;
    loadXMLDoc(webserviceurl);
}

function loadXMLDoc(url) {
	req = GetXmlHttpObject();

	if(req != null)
	{
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		//req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-Type", "text/xml");
		req.send("");
	}
}


function GetXmlHttpObject()
{
    var xmlHttp = null;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    return xmlHttp;
}


function processReqChange() 
{
    // only if req shows "loaded"
    if (req.readyState == 4) 
    {
        // only if "OK"
        if (req.status == 200) 
        {
            // ...processing statements go here...
            var dataXML = req.responseXML.documentElement;
            processXMLInfo(dataXML);
        } 
        else 
        {
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
    }
}

function processXMLInfo(XMLref) 
{
    var cameratag = XMLref.getElementsByTagName("camera");

    attr = cameratag[0].attributes;
    webid = attr.getNamedItem("webid").nodeValue;
    name = attr.getNamedItem("name").nodeValue;
    orientation = attr.getNamedItem("orientation").nodeValue;
    tempdis = attr.getNamedItem("tempdis").nodeValue;
    halfimage = XMLref.getElementsByTagName("halfimage")[0].childNodes[0].nodeValue + "&random=" + Math.random();
    fullimage = XMLref.getElementsByTagName("fullimage")[0].childNodes[0].nodeValue + "&random=" + Math.random();
    

    if(processType == "popup")
    {
       //Build the description for the popup; name, fullimage, orientation.
       popupBody = "";
       popupBody += "<font color=\"black\"><b>" + name + "</b><br />";
       popupBody += "<img id=\"imgTrafficCam\" src=\"" + fullimage + "\" height=\"240\" width=\"352\" border=\"0\" /><br />";
       popupBody += "<b>" + orientation + "</b></font><br />";
       
       finishPopup();
    }
    else
    {
        if(processType == "popupSelect")
        {
           //Build the description for the selectable popup; name, fullimage, orientation, selectable radio buttons.
            //descTextSelect &= "<form id=""frmSelectCamera""><img id=""imgTrafficCam"" src=""" & PageCameras.CameraArray(newArrayPointer).TL_FullImage & """ height=""240"" width=""352"" border=""0"" /><br/>"
            //descTextSelect &= PageCameras.CameraArray(newArrayPointer).TL_Orientation & "<br /><input type=""hidden"" id=""hidTrafficCamID"" value=""" & PageCameras.CameraArray(newArrayPointer).TL_Webid & """ /><span>Save as Traffic Camera: </span><input type=""Button"" id=""SaveCamera1"" value=""1"" onclick=""selectTrafficCam(" & PageCameras.CameraArray(newArrayPointer).TL_Webid & ", 1, '" & PageCameras.CameraArray(newArrayPointer).TL_Name & "')"" /><input type=""Button"" id=""SaveCamera2"" value=""2"" onclick=""selectTrafficCam(" & PageCameras.CameraArray(newArrayPointer).TL_Webid & ", 2, '" & PageCameras.CameraArray(newArrayPointer).TL_Name & "')"" /><input type=""Button"" id=""SaveCamera3"" value=""3"" onclick=""selectTrafficCam(" & PageCameras.CameraArray(newArrayPointer).TL_Webid & ", 3, '" & PageCameras.CameraArray(newArrayPointer).TL_Name & "')"" /><input type=""Button"" id=""SaveCamera4"" value=""4"" onclick=""selectTrafficCam(" & PageCameras.CameraArray(newArrayPointer).TL_Webid & ", 4, '" & PageCameras.CameraArray(newArrayPointer).TL_Name & "')"" /></form>"
           popupBody = "";
           popupBody += "<font color=\"black\"><b>" + name + "</b><br />";
           popupBody += "<img id=\"imgTrafficCam\" src=\"" + fullimage + "\" height=\"240\" width=\"352\" border=\"0\" /><br />";
           popupBody += "<b>" + orientation + "</b><br />";

           popupBody += "<form id=\"frmSelectCamera\">"
           popupBody += "<input type=\"hidden\" id=\"hidTrafficCamID\" value=\"" + webid + "\" /><span>Save as Traffic Camera: </span>"
           popupBody += "<input type=\"Button\" id=\"SaveCamera1\" value=\"1\" onclick=\"selectTrafficCam(" + webid + ", 1, '" + name + "')\" />&nbsp;&nbsp;"
           popupBody += "<input type=\"Button\" id=\"SaveCamera2\" value=\"2\" onclick=\"selectTrafficCam(" + webid + ", 2, '" + name + "')\" />&nbsp;&nbsp;"
           popupBody += "<input type=\"Button\" id=\"SaveCamera3\" value=\"3\" onclick=\"selectTrafficCam(" + webid + ", 3, '" + name + "')\" />&nbsp;&nbsp;"
           popupBody += "<input type=\"Button\" id=\"SaveCamera4\" value=\"4\" onclick=\"selectTrafficCam(" + webid + ", 4, '" + name + "')\" />"
           popupBody += "</font></form>"
           
           finishPopup();
        }
        else
        {
           //Static image; halfimage with name as alt tag.
        }
    }
}


function getCameraWebid(shape)
{
    var cameraWebid = 0;
	var v = shape.IconId.split("|");
	if (v[1] != undefined)
	{
		//ID
	  cameraWebid = v[1];
	}
	
	return cameraWebid;
}


function onFeedLoadCameras(feed)
{
    var numShapes = feed.GetShapeCount();
    //Loop over loaded elements and set icons
    for(var i=0; i < numShapes; ++i)
    {
		try
		{
			var s = feed.GetShapeByIndex(i);
			//Splitting IcondId because ID is in this field as well
			//georss references <icon> to virtual earths IconId property
			//so we are piggybacking values here
			//value should look like this "./imgref.gif|244"
			//where format is "Image|ID"
			var v = s.IconId.split("|");
			s.SetCustomIcon("<img src='"+ v[0]+"'/>");
	        
			if (v[1] != undefined){
				//ID
			  var cameraWebid = v[1];
			}
		 }catch(e){
			//alert('error: ' + e.message);
			//fail silently
		 } 
		 
		 if (i == 3)
		 {
		    currshape = s
		 }
    }
}


function afterPopup()
{
    cameraShutoffPop = false;
    // 7/28/2008 JH - Camera refresh limit removed.
    // JH - Added back in for TrafficLand.
    timerRefCameraShutoffPop = setTimeout("shutOffCamerasPop()", cameraShutoffMilliSecondsPop);
    timerRefCamera = setInterval("refreshPopupCamera()", 2000);
}




function parseCameras()
{
    //TestLoad();
    
    var shapes = new Array();

    try 
    {
        for (ptr=0; ptr<cameraArray.length; ptr++)
        {
            //AddPin(cameraArray[ptr][0], cameraArray[ptr][1], cameraArray[ptr][2], cameraArray[ptr][3], cameraArray[ptr][4], cameraArray[ptr][5]);
            isBad = false
            if (cameraArray[ptr][6] == "true")
            {
                isBad = true
            }
            shape1 = buildShape(cameraArray[ptr][0], cameraArray[ptr][1], cameraArray[ptr][2], cameraArray[ptr][3], cameraArray[ptr][4], cameraArray[ptr][5], isBad);
            shapes.push(shape1);

            //map.AddShape(shape1);
            //alert("shape added to array");
        }
    }

    catch (error)
    {
        //alert("Error adding shapes.");
    }
   	
    var newlayer = new VEShapeLayer();
    map.AddShapeLayer(newlayer);
    newlayer.AddShape(shapes);

    //alert("shapes added");
}


function buildShape(pinLat, pinLon, pinTitle, pinDirection, trafficCameraID, trafficCameraImage, isUnavailable) 
{
    try 
    {
        if(currentPage == 'EditPlaces.aspx')
        {
            varPinDescHTML = '<form id="frmSelectCamera"><img id="imgTrafficCam" src="' + trafficCameraImage + '&random=' + Math.random() + '" height="241" width="353" border="0" /><br/>Looking ' + pinDirection + '<br/><input type="hidden" id="hidTrafficCamID" value="' + trafficCameraID + '" /><span>Save as Traffic Camera: </span><input type="Button" id="SaveCamera1" value="1" onclick="selectTrafficCam(' + trafficCameraID + ', 1, \'' + pinTitle + '\')" /><input type="Button" id="SaveCamera2" value="2" onclick="selectTrafficCam(' + trafficCameraID + ', 2, \'' + pinTitle + '\')" /><input type="Button" id="SaveCamera3" value="3" onclick="selectTrafficCam(' + trafficCameraID + ', 3, \'' + pinTitle + '\')" /><input type="Button" id="SaveCamera4" value="4" onclick="selectTrafficCam(' + trafficCameraID + ', 4, \'' + pinTitle + '\')" /></form>'
        }
        else
        {
           varPinDescHTML = '<form><img id="imgTrafficCam" src="' + trafficCameraImage + '&random=' + Math.random() + '" height="241" width="353" border="0" /><br/><font color=black><b>' + pinDirection + '<input type="hidden" id="hidTrafficCamID" value="' + trafficCameraID + '" /></form>'
        }
        
        pinLat = pinLat * 1;
        pinLon = pinLon * 1;
        //alert("Lat: " + pinLat + ";  Long: " + pinLon);
        var shape2 = new VEShape(VEShapeType.Pushpin, new VELatLong(pinLat, pinLon, 0, VEAltitudeMode.RelativeToGround));
        //var shape2 = new VEShape(VEShapeType.Pushpin, new VELatLong(pinLat, pinLon));
        //var shape2 = new VEShape(VEShapeType.Pushpin, new VELatLong(38.858301, -77.069882));
        //var shape2 = new VEShape(VEShapeType.Pushpin, new VELatLong(38.858301, -77.069882, 0, VEAltitudeMode.RelativeToGround));
        //alert("New shape done.");

        if (isUnavailable == false)
        {
            shape2.SetCustomIcon("Images/camera.gif");
        }
        else
        {
            //Unavailable.
            shape2.SetCustomIcon("Images/camera_bad.gif");
        }
        shape2.SetTitle(pinTitle);
        shape2.SetDescription(varPinDescHTML);
    }
    
    catch (error)
    {
        //alert("Error building shape: " + error);
        //window.status = "Error building shape: " + error;
    }
    
    return shape2;
}

      
function refreshPopupCamera()
{
    if (cameraShutoffPop == false)
    {
        if (isPopupHidden() == false)
        {
            popCamera = document.getElementById("imgTrafficCam");
        	
            camSrc = popCamera.src;
            ptr = camSrc.lastIndexOf("&");
            if(ptr > 0)
            {
                camSrc = camSrc.substring(0, ptr);
        	
                camSrc = camSrc + "&random=" + Math.random();
            }
        	
            popCamera.src = camSrc;
        	
            //alert(camSrc);
            //alert("refresh: ok - " + timerRefCamera);
        }
        else
        {
            if (timerRefCamera != null)
            {
                clearInterval(timerRefCamera);
                timerRefCamera = null;
                //alert("refresh: hidden - " + timerRefCamera);
            }
        }
    }
    else
    {
        if (timerRefCamera != null)
        {
            clearInterval(timerRefCamera);
            timerRefCamera = null;
            //alert("refresh: shutoff- " + timerRefCamera);
        }
    }

}


function selectTrafficCam(cameraID, cameraPosition, cameraTitle)
{
    //alert('Camera ID: ' + cameraID +  ' Camera Position: ' +  cameraPosition +  ' Camera Title: ' +  cameraTitle)
    setCameraInfo(cameraPosition, cameraID, cameraTitle)
}


document.write("<style type='text/css'>@import url('App_Themes/VA/cameramap.css');</style>");
    
    
