/*
#
#
# +-----+	Copyright 2006, PB Farradyne
# | PBF |					All Rights Reserved
# +-----+--------------------------------------------------------------
# This file is property of PB Farradyne. 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: PB Farradyne
#
# 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: 3/30/06 - Commented - JZ
#          4/26/06 - Updated to Google API V2 - JZ
#
# $Log$
#
*/

var cctvMarkers = 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 = "";

var loopTimeout;
browserType = navigator.appName;
var CCTVPopupDisplayed = false; 
var cameraSelected = "";
var cameraFound = false;  //if camera selected from menu, we loop over recordset to find if marker was 
                          //created. bIf not, we have to create a new one.
var ranOnce = false;      //only run show popup once if user selects from left nav

//question mark fools server into thinking image is unique so it never caches
var tmpImagePath = "";

//newImage.src= imagePath;
//imagePath;
var dly = 30000; //30 seconds
var x = 0;

//11-27-07 -added to store camera id for when page is refreshed, if one is open
var cctvForURL = "";
var cctvForURLDisplayed = false;

function createCCTVPopups(elem, xmlDoc) {

   initializeEventMarkers(cctvMarkers);
	
   var url = "cctvImageDiv.asp?";
   var item = "cctv";
   	
   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 imagePath = xmlDoc.getElementsByTagName("URL")[i].firstChild.nodeValue;
		var lastUpdated = xmlDoc.getElementsByTagName("LastUpdated")[i].firstChild.nodeValue;	
		var cctv_ID = xmlDoc.getElementsByTagName("CCTV_ID")[i].firstChild.nodeValue;	
				
		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+'; font-weight:bold;">'
		    CCTVmarker.tooltip += name +'<br></div>';
		
            //infoHtmls = '<div class="markerinfo" style="width:345px; font-size: 11px;">';
		    //infoHtmls += '<b><font style="color: ' + textColor + ';">' + name + '</font></b><br />';				
		    //infoHtmls += '<b><font style="color: ' + textColor + ';"><img height=240 width=345 src=' + URL + '></font></b><br />';
		    //infoHtmls += '</div>';		
	
	        var newUrl = url + "imagePath=" + imagePath + "&";
	        
                //store image path if camera was selected 
               // GLog.write("cctv_ID: " + cctv_ID + ", cameraSelected: " + cameraSelected); 
                if ((cameraSelected != "") && (cameraSelected == cctv_ID) && (!cameraFound)) { 
                    //alert("match for " + cctv_ID); 
                        //added by Tiger 
                        var nameDiv = document.getElementById('cctvName'); 
                        nameDiv.innerHTML = name; 
    
                            tmpImagePath = imagePath; 
                            cameraFound = true; 
                        } 
	        
	        //function in createCrossingMarkers.js - reused code
			createCCTVMarker(point, CCTVmarker, name, newUrl, imagePath);	
		    
		    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);
        }
	}
    
    //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 = [];
    
    hidePleaseWaitScreen();
    
    if ((cameraSelected != "") && (cameraFound) && (!ranOnce)) {
        //camera selected from menu on left, open it in window
        //only do once, when user opens page
        ranOnce = true;
        showCCTVPopup(cameraSelected);
    }
}

function createCCTVMarker(point, marker, name, url, imagePath) {
    GEvent.addListener(marker, "click", function() {
        var id = marker.getId();
        var markerOffsetX = null;
        var markerOffsetY = null;
        markerOffsetY = point.lat() + .04;
        markerOffsetX = parseFloat(point.lng()) + .08;
        
        var nameDiv = document.getElementById('cctvName');
        //var cctvLastUpdated = document.getElementById('cctvLastUpdated');
        var cctvImage = document.getElementById('cctvImage');
        
        nameDiv.innerHTML = name;
        //cctvLastUpdated.innerHTML = cctvImageInc;
        cctvImage.src = "./images/cctv_wait.gif";
        
        //recenter the map to display the popup
        //googleMap.setCenter(new GLatLng(markerOffsetY, markerOffsetX),12);
        markerTooltip.style.visibility="hidden";
        
        //fools server into thinking new image, so it doesn't cache.
        //Global to store image path
        //tmpImagePath = imagePath + "?";
        tmpImagePath = imagePath;
        cctvImageInc = 0;
        CCTVPopupDisplayed = true;
        
        //GLog.write("CCTVPopupDisplayed: " + CCTVPopupDisplayed);
        
        if (loopTimeout != "undefined") {
		    removeTimeout();
		}
		
		
        showCCTVPopup(id);
    });
    
    GEvent.addListener(marker,"mouseover", function() {
    	  showTooltip(marker);
    });        
    GEvent.addListener(marker,"mouseout", function() {
		    markerTooltip.style.visibility="hidden";
    }); 
    
}	

function showCCTVPopup(id) {
    //11-27-07 - added to store camera id to pass during refresh if camera image is open
    cctvForURLDisplayed = true;
    cctvForURL = id;
        
        
	var marker = googleMap.getMarkerById(id);
	
	//alert("marker: " + marker);
	var tmpPoint = marker.getPoint();
	
	//alert("tmpPoint: " + tmpPoint);
	//center map at the camera
	var lat = tmpPoint.lat();
	var lon = tmpPoint.lng();
	var zoom = googleMap.getZoom();
	googleMap.setCenter(new GLatLng(lat, lon),zoom);
	
    var opacity;
  
    var newDiv = document.getElementById('cctvDiv');
    var imageDiv = document.getElementById('cctvImage');
   
    loadNewImage(tmpImagePath);
    
    //newDiv.style.backgroundColor = "#FFFFFF"; 
     
    googleMap.closeInfoWindow();
    newDiv.style.visibility="visible";
    
    //loop every 10 seconds
    SnapShot_Loop(dly);
    //positionCCTVPopup(marker, newDiv);
	
    zoomListener = GEvent.addListener(googleMap,"zoomend", function() {
        //create a listener to reposition the div when map is zoomed in or out
		//positionCrossingOrCCTVPopup(marker, newDiv);
    });
}

function positionCCTVPopup(marker, newDiv) {
  
    var myOffsetX;
    var myOffsetY;
    var height;
    
    var point=googleMap.getCurrentMapType().getProjection().fromLatLngToPixel(googleMap.fromDivPixelToLatLng(new GPoint(0,0),true),googleMap.getZoom());	
    var offset=googleMap.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),googleMap.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	
	height=tipArrow.clientHeight; 
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
    pos.apply(tipArrow);
    tipArrow.style.visibility = "visible";
        
    myOffsetX = 10;
    myOffsetY = -22;
        
    height=newDiv.clientHeight; 
    pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width + myOffsetX, offset.y - point.y -anchor.y -height + myOffsetY));
 	pos.apply(newDiv);
	newDiv.style.visibility="visible";
	newDiv.style.border="1px solid #000033";
}

function SnapShot_Loop(delay) {
    dly = delay; 
	cctvImageInc += 1;
	
	//imagePath = tmpImagePath + cctvImageInc;
	imagePath = tmpImagePath;
	
	//1-11-08 - check to see if ? exists within URL already, if not, add it.
	if (imagePath.indexOf('?') < 0){ 
	    imagePath += "?";
	}
	
	//3-6-08 - use to prevent ever caching the image - we use seconds since 1970 since it will always be unique
	//get the date
	var d = new Date();
	//get the time - but this is in minutes seconds past 1970, so it will ALWAYS be unique
    var t = d.getTime();
    
    //now just add it to the incrementor so we trick the browser into thinking we are requesting a new image, not a cached image.
    cctvImageInc += t;
    
	imagePath += "&inc=" + cctvImageInc;
	loadNewImage(imagePath);
	
	//GLog.write("imagePath: " + imagePath);
	
	
	loopTimeout = setTimeout("SnapShot_Loop(dly)",delay);
}

function loadNewImage(imagePath) { 
        var cctvImage = document.getElementById("cctvImage"); 
        var markerLoc = imagePath.indexOf("192.168."); 
        if (markerLoc > 0) {         
                markerLoc = imagePath.indexOf("/", 8); 
        } else { 
                markerLoc = 0; 
        } 
        cctvImage.src = imagePath.substring(markerLoc); 
        //var cctvLastUpdated = document.getElementById('cctvLastUpdated'); 
        //cctvLastUpdated.innerHTML = Date(); 
} 
	
function closeCCTVPopupWindow() {
    var newDiv = document.getElementById('cctvDiv');
    //var cctvLastUpdated = document.getElementById('cctvLastUpdated');
    newDiv.style.visibility="hidden";
    //tipArrow.style.visibility = "hidden";
    CCTVpopupDisplayed = false;
    cctvForURLDisplayed = false;
    cctvForURL = "";
    tmpImagePath = "";
    cctvImageInc = 0;
    //cctvLastUpdated.innerHTML = "";
    removeTimeout();
}
	
function removeTimeout() {
	clearTimeout(loopTimeout);
}


