/*
#
#
# +-----+	Copyright 2008, Telvent Farradyne Inc.
# | TFI |					All Rights Reserved
# +-----+--------------------------------------------------------------
# This file is property of Telvent Farradyne Inc. Any unauthorized user or
# duplication of this file, or removal of the header, constitutes
# theft or intellectual property.
#
# File Name: createCCTVPopups.js
#
# Component Name:
# 
# Prepared By: Telvent Farradyne Inc.
#
# Environmental Constraints: None
# 
# Description: used to create CCTV markers to be displayed on Google
#			   maps. Each marker will contain the attributes listed below
#			   as well as the info to display in the marker popup window
#				
# History: 8/04/08 - Created - JZ
#
# $Log$
#
*/

var cctvMarkers = new Array();
var clusteredCCTVMarkers = new Array();

var existingCCTVArray = new Array();
var addCCTVFlag = true;
var checkExistingCCTV = false; //flag to check existing array - only changes if we've already gotten data

var cctvsExist = false;

var cctvImageInc = 0;
var tmpImagePath = "";

browserType = navigator.appName;
var CCTVPopupDisplayed = false; 

//question mark fools server into thinking image is unique so it never caches
var tmpImagePath = "";

var selectedCameraID = "";

var dly;
var cctvInt = 4000; //cctv interval for looping
var x = 0;

function createCCTVPopups(elem, xmlDoc) {
   initializeEventMarkers(cctvMarkers);
   
	
   //var url = "cctvImageGetter.aspx?&";
   var item = "cctv";
   	
   drawingCameras = true;
   	
   for (i = 0; i < elem.length; i++) {	

		var name = xmlDoc.getElementsByTagName("CCTV_Name")[i].firstChild.nodeValue;
		var lon = xmlDoc.getElementsByTagName("Longitude")[i].firstChild.nodeValue;
		var lat = xmlDoc.getElementsByTagName("Latitude")[i].firstChild.nodeValue;
		var reportedBy = xmlDoc.getElementsByTagName("Owner_Name")[i].firstChild.nodeValue;
		var lastUpdated = xmlDoc.getElementsByTagName("LastUpdated")[i].firstChild.nodeValue;	
		var cctv_ID = xmlDoc.getElementsByTagName("CCTV_ID")[i].firstChild.nodeValue;	
		var cctvDesc = xmlDoc.getElementsByTagName("Description")[i].firstChild.nodeValue;		
		
		name = name.replace("'","\'");
				
		if (lat > 90 || lat < -90)
		{
			lat = lat*.000001;
		}
		if (lon > 180 || lon < -180)
		{
			lon = lon*.000001;
		}
			
		var textColor = "#990000";		
			
		if (checkExistingCCTV) {
		    //we already have data in the array, now check to see if we need to remove markers
            for (var n = 0; n < cctvMarkers.length; n++) {
                var markerID = cctvMarkers[n].getId();
                
                if (cctv_ID == markerID){
                    //event already on map - do not display twice
                    existingCCTVArray[existingCCTVArray.length] = markerID;
                    addCCTVFlag = false;
                    break;
                }
                else {
                    //marker does not exist - set add flag to true to notify that
                    //we have to add it to the map
                    addCCTVFlag = true;  
                }
            }        
        }
    	
    	if (addCCTVFlag) {
		    //create new markers			
		    var point = new GLatLng((lat),(lon));
		
			
		    var icon = cctvIcon;

            var CCTVmarker = new PdMarker(point, icon);
            CCTVmarker.setId(cctv_ID);			
		    CCTVmarker.tooltip = '<div class="markerTooltip" style="color:'+textColor+';">'
		    CCTVmarker.tooltip += name +'<br></div>';
		
         
	        //trim the whitespace
	        cctv_ID = cctv_ID.replace(/^\s+|\s+$/g, '');
	        //var newUrl = url + "CCTV_ID=" + cctv_ID + "&";
	        
	        //GLog.write(newUrl);
	        //function in createCrossingMarkers.js - reused code
		    createCCTVMarker(point, CCTVmarker, name, cctvDesc, reportedBy);	
		    
		    googleMap.addOverlay(CCTVmarker);
            
            cctvMarkers[cctvMarkers.length] = CCTVmarker;
            
        }//end if addCCTV flag
        
        
	}//end for loop

    //function to display markers true, make sure something is in the array first
	if (checkExistingCCTV) {
	    
		for (var n = 0; n < existingCCTVArray.length; n++) {
		    var markerToDisplay = googleMap.getMarkerById(existingCCTVArray[n]);
            markerToDisplay.display(true);
            
            //if we've reached the last element, hide please wait
            if (n == existingCCTVArray.length-1) {
	          drawingCameras = false;
	          hidePleaseWaitScreen();
            }
        }
        if (existingCCTVArray.length == 0) {
          drawingCameras = false;
          hidePleaseWaitScreen();
        }
	}
	else{
	  drawingCameras = false;
	  hidePleaseWaitScreen();
	}
    
    //now that we've gotten data, we need to set a flag to let us know to 
    //check existing next time the user updates the map
    checkExistingCCTV = true;
    existingCCTVArray = [];
   
}

function createClusteredCCTVMarkers(elem, xmlDoc) {
    //this function sets up the regional cctv markers (clustering)
    for (i = 0; i < elem.length; i++) {
        var name = xmlDoc.getElementsByTagName("DisplayName")[i].firstChild.nodeValue;
        var lon = xmlDoc.getElementsByTagName("Longitude")[i].firstChild.nodeValue;
        var lat = xmlDoc.getElementsByTagName("Latitude")[i].firstChild.nodeValue;
        var cctv_ID = xmlDoc.getElementsByTagName("CCTV_ID")[i].firstChild.nodeValue;
        var zoomTo = xmlDoc.getElementsByTagName("ZoomTo")[i].firstChild.nodeValue;
        
        name = name.replace("'","\'");
				
		if (lat > 90 || lat < -90)
		{
			lat = lat*.000001;
		}
		if (lon > 180 || lon < -180)
		{
			lon = lon*.000001;
		}
        
        var point = new GLatLng((lat),(lon));
		
			
		var icon = cctvIcon;
        var CCTVmarker = new PdMarker(point, icon);
        CCTVmarker.setId(cctv_ID);			
		CCTVmarker.tooltip = '<div class="markerTooltip" style="color:#990000;">'
		CCTVmarker.tooltip += name +'<br></div>';
		    
		googleMap.addOverlay(CCTVmarker);
        CCTVmarker.display(false);
        
        createClusteredCCTVMarker(point, CCTVmarker, name, zoomTo);
        clusteredCCTVMarkers[clusteredCCTVMarkers.length] = CCTVmarker;    
    }		
    showClusteredCCTVMarkers();
}

function showClusteredCCTVMarkers(){
    initializeEventMarkers(clusteredCCTVMarkers);
    if (document.getElementById('ctl00_ContentPlaceHolder1_traffic_cctvCheck').checked) {
        for (var n = 0; n < clusteredCCTVMarkers.length; n++) {
            clusteredCCTVMarkers[n].display(true);
        
            if(n == clusteredCCTVMarkers.length-1) {
              hidePleaseWaitScreen();
            }
        }
    }
}

function createClusteredCCTVMarker(point, marker, name, zoomTo) {
    GEvent.addListener(marker, "click", function() {
  	  //added to save the position of the map before the marker is opened.
      googleMap.savePosition();
      googleMap.setCenter(new GLatLng(point.lat(), point.lng()), parseInt(zoomTo));
    });
    GEvent.addListener(marker,"mouseover", function() {
        markerTooltipFlag=true;
        clearPopupTimer();
        showTooltip(marker);
    });        
    GEvent.addListener(marker,"mouseout", function() {
        markerTooltipFlag=false;
        markerTooltip.style.visibility="hidden";
    });
    GEvent.addListener(marker, "infowindowclose", function() {
        //return the map to its original position.
        //googleMap.returnToSavedPosition();    
    });
}

function createCCTVMarker(point, marker, name, cctvDesc, reportedBy) {
    GEvent.addListener(marker, "click", function() {
    
        //4-08-08 - minimize the overview map when the cctv popup is opened. JZ
        overview.hide(true);
        
        //may need to put back
        //if (crossingPopupDisplayed) {
        //    closeCrossingPopupWindow();
        //}
        
        //added to save the position of the map before the marker is opened.
        googleMap.savePosition();
    
        var id = marker.getId();
        var markerOffsetX = null;
        var markerOffsetY = null;
        var tempPoint = null;
      
        var zoom = googleMap.getZoom();
        var height = document.getElementById('cctvDiv').clientHeight;
        
        //calculate an offset based on the zoom level
        var offSetArray = calculatePopupOffset(zoom, height);
        tempPoint = new GLatLng(point.lat(), point.lng());
        markerOffsetY = parseFloat(tempPoint.lat()) + parseFloat(offSetArray[0]);
        markerOffsetX = parseFloat(tempPoint.lng()) + parseFloat(offSetArray[1]);
      
        var nameDiv = document.getElementById('cctvName');
        //var cctvLastUpdated = document.getElementById('cctvLastUpdated');
        var cctvDescField = document.getElementById('cctvDescription');
        var cctvImage = document.getElementById('cctvImage');        
        var cctvOwnerIcon = document.getElementById('cctvIcon');        
   
        nameDiv.innerHTML = name;
        //cctvLastUpdated.innerHTML = cctvImageInc;
        cctvDescField.innerHTML = cctvDesc;
        cctvImage.src = "./images/cctv_wait.gif";                         
        
        if (reportedBy.indexOf("NYSDOT") != -1)
        {     
         if(reportedBy.indexOf("Thruway")!=-1)
         {
            cctvOwnerIcon.src = "./images/thruway_logo1.gif"; 
            cctvOwnerIcon.alt="NYSDOT_Thruway";
         }
         else
         {           
            cctvOwnerIcon.src = "./images/NYSDOT_Logo.gif"; 
            cctvOwnerIcon.alt="NYSDOT";
            }
        }
        else if (reportedBy.indexOf("NYSTA") != -1)
        {       
            cctvOwnerIcon.src = "./images/thruway_logo.gif";
            cctvOwnerIcon.alt="THRUWAY";
        }
        else if (reportedBy.indexOf("CT DOT") != -1)
        {       
            cctvOwnerIcon.src = "./images/ctdot_logo.gif";  
            cctvOwnerIcon.alt="CTDOT";
        }
        else if (reportedBy.indexOf("NYC DOT") != -1)
        {       
            cctvOwnerIcon.src = "./images/nycdot_logo.gif"; 
            
             cctvOwnerIcon.alt="NYCDOT";
        }
        else if (reportedBy.indexOf("PA -") != -1)
        {       
            cctvOwnerIcon.src = "./images/portauth_logo.gif"; 
             cctvOwnerIcon.alt="PA";
        }
        else if (reportedBy.indexOf("MTA") != -1)
        {       
            cctvOwnerIcon.src = "./images/mta_logo.gif"; 
             cctvOwnerIcon.alt="MTA";
        }
        else if (reportedBy.indexOf("NJ DOT") != -1)
        {       
            cctvOwnerIcon.src = "./images/njdot_logo.jpg"; 
            cctvOwnerIcon.alt="NJDOT";
        }
        else if (reportedBy.indexOf("NJ Highway Auth") != -1)
        {       
            cctvOwnerIcon.src = "./images/njtp_logo.jpg"; 
            cctvOwnerIcon.alt="NJTP";
        }
        else if (reportedBy.indexOf("NJ Turnpike Auth") != -1)
        {       
            cctvOwnerIcon.src = "./images/njtp_logo.jpg"; 
             cctvOwnerIcon.alt="NJTP";
        }
        else if (reportedBy.indexOf("PennDOT") != -1)
        {       
            cctvOwnerIcon.src = "./images/20_CCTVPennDotLogo.gif"; 
            cctvOwnerIcon.alt="PennDOT";
        }
        else
        {
            cctvOwnerIcon.src = "./images/default_logo.gif";
        }
        
        
        //recenter the map to display the popup
        googleMap.setCenter(new GLatLng(markerOffsetY, markerOffsetX),zoom);
        markerTooltip.style.visibility="hidden";
        //markerTooltip.title="Hello Test";
        
        //fools server into thinking new image, so it doesn't cache.
        //Global to store image path
        //tmpImagePath = url;
        cctvImageInc = 0;
        CCTVPopupDisplayed = true;
        
        showCCTVPopup(id);
    });
    
    GEvent.addListener(marker,"mouseover", function() {
        markerTooltipFlag=true;
        clearPopupTimer();
        showTooltip(marker);
    });        
    GEvent.addListener(marker,"mouseout", function() {
        markerTooltipFlag=false;
        markerTooltip.style.visibility="hidden";
    }); 
    
    
    
}	

function showCCTVPopup(id) {
    var marker = googleMap.getMarkerById(id);
    var opacity;
      
    
    selectedCameraID = id;
    var newDiv = document.getElementById('cctvDiv');
    var imageDiv = document.getElementById('cctvImage');
   
    loadNewImageForHits("./Cameras/trafficLandWebsitehits.aspx?inc="+cctvImageInc+"&CCTV_ID="+selectedCameraID);      
    
    newDiv.style.backgroundColor = "#FFFFFF"; 
     
    googleMap.closeInfoWindow();
    
    SnapShot_Loop(id, cctvInt);
    
    positionCrossingOrCCTVPopup(marker, newDiv);
	
    zoomListener = GEvent.addListener(googleMap,"zoomend", function() {
        //create a listener to reposition the div when map is zoomed in or out
        if (CCTVPopupDisplayed) {
		    positionCrossingOrCCTVPopup(marker, newDiv);
		}
    });
}

function loadNewImageForHits(imagePath) {
	var cctvImage = document.getElementById("cctvImage");
	//GLog.write(imagePath);
	cctvImage.src = imagePath;
}


function closeCCTVPopupWindow() {
    var newDiv = document.getElementById('cctvDiv');
   // var cctvLastUpdated = document.getElementById('cctvLastUpdated');
    newDiv.style.visibility="hidden";
    tipArrow.style.visibility = "hidden";
    CCTVPopupDisplayed = false;
    tmpImagePath = "";
    selectedCameraID = "";
    cctvImageInc = 0;
    //cctvLastUpdated.innerHTML = "";
    
    //4-4-07 - set image back to default wait
    var cctvImage = document.getElementById('cctvImage');
    cctvImage.src = "./images/cctv_wait.gif";
        
    removeTimeout();
    
    //4-08-08 - redisplay overview map after closing popup. 
    //to be in  consistent with other popupus , below line is commented -- IEL COMMENT ENDS
    //overview.show(true);
    
    //GEvent.addListener(marker, "infowindowclose", function() {
        //return the map to its original position.
        //googleMap.returnToSavedPosition();    
    //});
    
}
	

function calculatePopupOffset(zoom, height) {
    //function to calculate popup window offset based on zoom level - just a best guess effort
    var offSetArray = new Array();
    var index = 1;
    
    //position based on height of popup
    if (height > 200) {
        var lat = 90;
    }
    else {
        var lat = 50;
    }
    
    var lon = 76.8;
    
    for (var i = index; i < zoom; i++) {
        lat = lat/2;
        lon = lon/2;
    }
    offSetArray[0] = lat;
    offSetArray[1] = lon;
    
    return offSetArray;
}
