/*
#
#
# +-----+	Copyright 2006, Telvent Farradyne Inc.
# | TFI |					All Rights Reserved
# +-----+--------------------------------------------------------------
# This file is property of Telvent Farradyne. Any unauthorized user or
# duplication of this file, or removal of the header, constitutes
# theft or intellectual property.
#
# File Name: createCrossingPopups.js
#
# Component Name:
# 
# Prepared By: Telvent Farradyne
#
# Environmental Constraints: None
# 
# Description: used to create Crossing 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: 10/13/06 Created. JZ
#          05/09/07 added valid crossings variable to deal with same name crossing with diff id
#
# $Log$
#
*/

var crossingMarkers = new Array();

var existingCrossingArray = new Array();
var addCrossingFlag = true;
var checkExistingCrossing = false; //flag to check existing array - only changes if we've already gotten data

var crossingsExist = false;
var crossingPopupDisplayed = false;

var tableString;

function createCrossingPopups(elem, xmlDoc) {

   //function is in createPopups.js - used to clear all markers of this type
   initializeEventMarkers(crossingMarkers);
   
   var url = "crossings/rivercrossingdiv.asp?";
   var item = "crossing";
   
   for (i = 0; i < elem.length; i++) {	

    var crossingID = xmlDoc.getElementsByTagName("CrossingID")[i].firstChild.nodeValue;	
		var lat = xmlDoc.getElementsByTagName("Latitude")[i].firstChild.nodeValue;
		var lon = xmlDoc.getElementsByTagName("Longitude")[i].firstChild.nodeValue;
		var name = xmlDoc.getElementsByTagName("Name")[i].firstChild.nodeValue;
		var river = xmlDoc.getElementsByTagName("River")[i].firstChild.nodeValue;
		var direction = xmlDoc.getElementsByTagName("Direction")[i].firstChild.nodeValue;
		var level = xmlDoc.getElementsByTagName("Level")[i].firstChild.nodeValue;	
		var tube = xmlDoc.getElementsByTagName("Tube")[i].firstChild.nodeValue;	
		var validCrossings = xmlDoc.getElementsByTagName("validCrossings")[i].firstChild.nodeValue;	
		
				
		if (lat > 90 || lat < -90)
		{
			lat = lat*.000001;
		}
		if (lon > 180 || lon < -180)
		{
			lon = lon*.000001;
		}
			
		var textColor = "#990000";		
			
		if (checkExistingCrossing) {
		    //we already have data in the array, now check to see if we need to remove markers
            for (var n = 0; n < crossingMarkers.length; n++) {
                var markerID = crossingMarkers[n].getId();
                
                if (crossingID == markerID){
                    //event already on map - do not display twice
                    existingCrossingArray[existingCrossingArray.length] = markerID;
                    addCrossingFlag = false;
                    break;
                }
                else {
                    //marker does not exist - set add flag to true to notify that
                    //we have to add it to the map
                    addCrossingFlag = true;  
                }
            }        
        }
    	
    	if (addCrossingFlag) {
		    //create new markers			
		    var point = new GLatLng((lat),(lon));
		
			
		    var icon = crossingIcon;

        var Crossingmarker = new PdMarker(point, icon);
        Crossingmarker.setId(crossingID);			
		    Crossingmarker.tooltip = '<div class="markerTooltip" style="color:'+textColor+'; font-weight:bold;">'
		    Crossingmarker.tooltip += name +'<br></div>';
		
		    var divID = "crossingDiv"+crossingID;
		    
		    infoHtmls = '<div class="markerinfo" style="width:220px; font-size: 11px;">';
		    infoHtmls += '<b><font style="color: ' + textColor + ';">' + name + '</font></b><br />';				
		    infoHtmls += '<b><font style="color: ' + textColor + ';"></b><br />';
		    infoHtmls += '<br />';
		    infoHtmls += '<br />';
	        infoHtmls += '</div>';	
	     
	        //var newUrl = url + "?XID=" + crossingID;
	        
			createCrossingMarker(point, Crossingmarker, name, url, item, validCrossings);	
		    
		    googleMap.addOverlay(Crossingmarker);
            
            crossingMarkers[crossingMarkers.length] = Crossingmarker;
           
	    }//end if addCrossing flag
	}//end for loop
	
	//function to display markers true, make sure something is in the array first
	if (checkExistingCrossing) {
		for (var n = 0; n < existingCrossingArray.length; n++) {
            var markerToDisplay = googleMap.getMarkerById(existingCrossingArray[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
    checkExistingCrossing = true;
    existingCrossingArray = [];
    hidePleaseWaitScreen();
}

function createCrossingMarker(point, marker, name, url, item, validCrossings) {
    GEvent.addListener(marker, "click", function() {
        if (CCTVPopupDisplayed) {
            closeCCTVPopupWindow();
        }
        
        var id = marker.getId();
        var frameName = item + "Frame";
      
		var newUrl = url + "Title="+name+"&objID="+id+"&validCrossings="+validCrossings;
        
        
        window.frames[frameName].location.href = newUrl; 
       
        newUrl = "";
        var markerOffsetX = null;
        var markerOffsetY = null;
        markerOffsetY = point.lat() + .04;
        markerOffsetX = parseFloat(point.lng()) + .08;
        
        //recenter the map to display the popup
        googleMap.setCenter(new GLatLng(markerOffsetY, markerOffsetX),12);
        crossingPopupDisplayed = true;
        markerTooltip.style.visibility="hidden";
    });
    
    GEvent.addListener(marker,"mouseover", function() {
    	  showTooltip(marker);
    	  var id = marker.getId();
    });        
    GEvent.addListener(marker,"mouseout", function() {
		    markerTooltip.style.visibility="hidden";
    }); 
    
}	

function showCrossingPopup(id, item) {
 
    var text = window.frames[item+'Frame'].document.getElementById(item+'Display').innerHTML;
    var marker = googleMap.getMarkerById(id);
    var newDiv = document.getElementById(item+'Div');
   
    newDiv.style.backgroundColor = "#FFFFFF";
    newDiv.innerHTML = '<table width="450px" cellpadding="0" cellspacing="0" border="0"><tr><td width="450px" align="right"><img src="./images/closeX.gif" border="0" onclick="closeCrossingPopupWindow()" style="cursor:pointer; padding: 2px;"/></td></tr></table>';
	newDiv.innerHTML += text;
    
    googleMap.closeInfoWindow();
    
    positionCrossingOrCCTVPopup(marker, newDiv);

    zoomListener = GEvent.addListener(googleMap,"zoomend", function() {
        //create a listener to reposition the div when map is zoomed in or out
        if (crossingPopupDisplayed) {
		    positionCrossingOrCCTVPopup(marker, newDiv);
		}
    });
    

}

function positionCrossingOrCCTVPopup(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 closeCrossingPopupWindow() {
    var newDiv = document.getElementById('crossingDiv');
    newDiv.style.visibility="hidden";
    tipArrow.style.visibility = "hidden";
    crossingPopupDisplayed = false;
}

