var incMarkers = new Array();
var constMarkers = new Array();
var specevtMarkers = new Array();
var busMarkers = new Array();

var eventMarkers = new Array();
var existingArray = new Array();
var addFlag = true;
var checkExisting = false; //flag to check existing array - only changes if we've already gotten data

var incVisible = false;
var constVisible = false;
var specevtVisible = false;
var busVisible = false;

//3-29-07 added to fix events that overlap
var previousLat = 0;
var previousLon = 0;
var appendDesc = false;
var lastIndex = 0;
var htmlDescs = new Array();
var idArray = new Array();
//end 3-29-07

function createPopups(elem, xmlDoc) {
	//create popups from XML data
	
	//initialize markers to display false - send type to display false
	initializeEventMarkers(eventMarkers);
	
	var incChecked = document.main.incCheck.checked;
	var constChecked = document.main.constCheck.checked;
	var specevtChecked = document.main.specevtCheck.checked;
	
	//3-29-07 
	//keep track of new markers added
	var addCount = 0;
	//end 3-29-07
	
	for (var i = 0; i < elem.length; i++) {

	//loop through and create markers	
		
		//since we have layer checkboxes, we wont want to display the marker if the
		//checkbox is unchecked, or layer is toggled off - we can store the marker 
		//for later use - just don't add the overlay
		var displayMarker = true;
		
		var incType = xmlDoc.getElementsByTagName("IncType")[i].firstChild.nodeValue;
		var eventMode = xmlDoc.getElementsByTagName("Event_Mode")[i].firstChild.nodeValue.toLowerCase();
		var facility = xmlDoc.getElementsByTagName("Facility")[i].firstChild.nodeValue;
		var incDescLong = xmlDoc.getElementsByTagName("IncDescLong")[i].firstChild.nodeValue;
		var lat = parseFloat(xmlDoc.getElementsByTagName("Event_Lat")[i].firstChild.nodeValue);
		var lon = parseFloat(xmlDoc.getElementsByTagName("Event_Lon")[i].firstChild.nodeValue);
		var lastActionUpdate = xmlDoc.getElementsByTagName("LastActionUpdate")[i].firstChild.nodeValue;
		var reportOrgName = xmlDoc.getElementsByTagName("Report_Org_Name")[i].firstChild.nodeValue;
		var startDate = xmlDoc.getElementsByTagName("IncVerifiedDateTime")[i].firstChild.nodeValue;
		var endDate = xmlDoc.getElementsByTagName("IncExpDateTime")[i].firstChild.nodeValue;
		var incID = xmlDoc.getElementsByTagName("IncID")[i].firstChild.nodeValue;
		var estDuration = xmlDoc.getElementsByTagName("Est_Duration")[i].firstChild.nodeValue;
		
		var textColor = "";
		var pointType = eventMode;
			
		if (checkExisting) {
			var addToExistingArray = false;
			//we already have data in the array, now check to see if we need to remove markers
			for (var n = 0; n < eventMarkers.length; n++) {
				var markerID = eventMarkers[n].getId();
				if (incID == markerID){
					appendDesc = false;
					//event already on map - do not display twice
	                
					//now set display flag based on checkbox status --- ugghh
					if ((pointType == "1") || (pointType == "2")) {
						if (incChecked) {
							addToExistingArray = true;
						}
					}
					else if ((pointType == "3") || (pointType == "4") || (pointType == "5") || (pointType == "6")) {
						if (constChecked) {
							addToExistingArray = true;
						}
					}
					else if ((pointType == "7") || (pointType == "14") || (pointType == "16") || (pointType == "17")) {    
						if (specevtChecked) {
							addToExistingArray = true;
						}
					}
					else if (pointType == "buses") {
						if (busChecked) {
							addToExistingArray = true;
						}
					}
	                
					if (addToExistingArray) {
						existingArray[existingArray.length] = markerID;
					}
					
					addFlag = false;
					break;
				}
				else {
					//marker does not exist - set add flag to true to notify that
					//we have to add it to the map
					addFlag = true;  
				}
			}        
		}
		
		//3-29-07 now check lat/lon to find out if we need to append description or create a new marker
	    //if addFlag is true, means we have a new event.
		//find difference between last point passed and current point, lat and long. Since the precision
		//is .001 degrees = about 278ft., check the difference to the nearest thousandth. If the abs. value of the difference of
		//lat and long is less than .002 or roughly 600ft., then combine the incident descriptions, and don't create a new marker. 
		//don't do first iteration
		if (addFlag) {
			var dLat = Math.abs(previousLat - lat)*1000;
			var dLon = Math.abs(previousLon - lon)*1000;
			if ((dLat < 2) && (dLon < 2)) {
				//append to previous desc
				appendDesc = true;
				addFlag = false;
			}	
			else{
				appendDesc = false;
			}
			//end 3-29-07	
		}
    
	    if ((addFlag) && (!appendDesc)) {
        //create new markers
    			
    		var point = new GLatLng(lat,lon);	
    			
    		if ((pointType == "1") || (pointType == "2")) {
    			
    			icon = incIcon;
    			textColor = "#990000";
    			incVisible = true;
      		
    			var incMarker = new PdMarker(point, icon);
    			tmpMarker = incMarker;
    			incMarkers.push(incMarker);
    			
    			
    			if (!document.main.incCheck.checked) {
    			    displayMarker = false;
    			}
    		}
    		
    		else if ((pointType == "3") || (pointType == "4") || (pointType == "5") || (pointType == "6")) {
    			
    			icon = constIcon; 
    			textColor = "#009900";
    			constVisible = true;
    		  		
    			var constMarker = new PdMarker(point, icon);
    			tmpMarker = constMarker;
    			constMarkers.push(constMarker);
    			
    			if (!document.main.constCheck.checked) {
    			    displayMarker = false;
    			}
    		}
    		
    		else if ((pointType == "7") || (pointType == "14") || (pointType == "16") || (pointType == "17")) {
    			
    			icon = specEvtIcon; 
    			textColor = "#000099";
    			specevtVisible = true;	
      		
    			var specevtMarker = new PdMarker(point, icon);
    			tmpMarker = specevtMarker;
    			specevtMarkers.push(specevtMarker);
    			
    			if (!document.main.specevtCheck.checked) {
    			    displayMarker = false;
    			}
    		}
    			
    		var length = eventMarkers.length;
    			
    		var hours = 0;
    		var minutes = 0;
    			
    		//calculate estDuration
    		estDuration = parseFloat(estDuration);
    		//convert to hours
    		//hours = estDuration*(1/60);
    		estDuration = durationString(estDuration);
    		
    		//GLog.write(hours);
    		//convert to days
    		//estDuration = estDuration*(1/24);
    		//truncate to two decimal places
    		//estDuration = estDuration.toFixed(2);
    			
    		incDescLong = '<b><font style="color: ' + textColor + ';">' + incDescLong + '</font></b><br />';
    		//startDate = '<b><font style="color: #000066;">Start Date: ' + startDate + '</font></b><br />';
    		//endDate = '<b><font style="color: #000066;">End Date: ' + endDate + '</font></b><br />';
	    	var estDurationString = '<b><font style="color: #000066;">Estimated Duration: ' + estDuration + '</font></b><br />';
	    									
    		var infoHtmls = '<div align="left" class="markerinfo" style="font-size: 10px; width: 375px;">';
    		infoHtmls += '<b><font style="color: #000066;">Reported By: ' + reportOrgName + '</font></b>';	
    		infoHtmls += '<br /><br />';		
    		infoHtmls += incDescLong;
            //infoHtmls += '<br />';
            //infoHtmls += estDurationString;
            infoHtmls += '</div>';
            	
    		//incDescLong = '<b><font style="color: ' + textColor + ';">' + incDescLong + '</font></b><br />';
    		//var estDurationString = '<b><font style="color: #000066;">Estimated Duration: ' + estDuration + ' Days</font></b><br />';
    		//startDate = '<b><font style="color: #000066;">Start Date: ' + startDate + '</font></b><br />';
    		//endDate = '<b><font style="color: #000066;">End Date: ' + endDate + '</font></b><br />';
    										
    		// BUILD HTML MARKUP for info window
            //var infoHtmls = '<div class="markerinfo" style="width:260px; font-size: 11px;">';
    		//infoHtmls += '<b><font style="color: #000066;">Reported By: ' + reportOrgName + '</font></b><br />';	
    		//infoHtmls += '<br />';		
    		//infoHtmls += incDescLong;
            //infoHtmls += '<br />';
         	//infoHtmls += estDurationString;
            //infoHtmls += startDate;
            //infoHtmls += endDate;
            //infoHtmls += '</div>';		
    				
    		//now store html and index of last marker created in case we have to append the desc 
	    	//in the next iteration
            htmlDescs[length] = infoHtmls;
            		
    		tmpMarker.tooltip = '<div class="markerTooltip" style="color:'+textColor+'; font-weight:bold;">'
    		tmpMarker.tooltip = tmpMarker.tooltip + incType +'<br>'+facility+'</div>';
    
    		createMarker(point, tmpMarker, '', length);
    		
            
    		
    		eventMarkers[length] = tmpMarker;
            eventMarkers[length].setId(incID); // over-ride internal id
            googleMap.addOverlay(eventMarkers[length]);
            
            if (displayMarker) {
                //only display the marker if the particular layer checkbox is checked
                eventMarkers[length].display(true);
            }
            else {
			    eventMarkers[length].display(false);
            }
            tmpMarker = null;
            
            //3-29-07 store current lat/lon in previous to compare next iteration
			//also store ID in idArray to compare later
			idArray[idArray.length] = incID;	
			previousLat = lat;
			previousLon = lon; 
			latDiff = 0;
			lonDiff = 0;
			appendDesc = false;
			lastIndex = length;
			addCount++; //keep track of how many new markers added
    		//end 3-29-07
    		
        } 
        //added 3-27-07 for appending descriptions - here we did not add a marker, rather appended the desc to the existing
   		else if((appendDesc) && (!addFlag)) {
   		    if ((pointType == "buses")) {
	            textColor = "#000000";
	        }
	        else if ((pointType == "1") || (pointType == "2")) {
	            textColor = "#990000";
	        }
	        else if ((pointType == "3") || (pointType == "4") || (pointType == "5") || (pointType == "6")) {
	            textColor = "#009900";
	        }
	        else if ((pointType == "7") || (pointType == "14") || (pointType == "16") || (pointType == "17")) {
	            textColor = "#000099";
	        }
	    
   		    // BUILD HTML MARKUP for info window
   		    incDescLong = '<b><font style="color: ' + textColor + ';">' + incDescLong + '</font></b>';
    		//startDate = '<b><font style="color: #000066;">Start Date: ' + startDate + '</font></b><br />';
    		//endDate = '<b><font style="color: #000066;">End Date: ' + endDate + '</font></b>';
    		
    		var newTooltip = '<div class="markerTooltip" style="color:'+textColor+'; font-weight:bold;">'
    		newTooltip += newTooltip + incType +'<br>'+facility+'</div>';
    		
    		//include existing
            var infoHtmls = htmlDescs[lastIndex];
            
            //append new desc
            infoHtmls += '<hr>';
            infoHtmls += '<div align="left" class="markerinfo" style="font-size: 10px; width: 375px;">';
    		infoHtmls += '<b><font style="color: #000066;">Reported By: ' + reportOrgName + '</font></b>';	
    		infoHtmls += '<br /><br />';		
    		infoHtmls += incDescLong;
            infoHtmls += '<br /><br />';
            //4-18-07 - removed start and end date from description
            //infoHtmls += startDate;
            //infoHtmls += endDate;
            infoHtmls += '</div>';
            
            htmlDescs[lastIndex] = infoHtmls;
           
            //store ID regardless of whether marker was created or not
            idArray[idArray.length] = incID;
            
            //set tooltip
            var tmpId = eventMarkers[lastIndex].getId();
            var markerToAppend = googleMap.getMarkerById(tmpId);
            var tmpTooltip = markerToAppend.tooltip;
            
            //append new tooltip to existing tooltip
            markerToAppend.tooltip = tmpTooltip + newTooltip
   		}
		
	}//end for loop looping through XML elements      
        
    
	//function to display markers true, make sure something is in the array first
	if (checkExisting) {
	    for (var n = 0; n < existingArray.length; n++) {
            var markerToDisplay = googleMap.getMarkerById(existingArray[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
    checkExisting = true;

    //append scrolling function to markers
	appendScrollbars(addCount);	
    	
	//hide please wait screen
	//functions are in javascript/showHidePleaseWaitScreen.js
	hidePleaseWaitScreen();
	
    //reset existing marker array
    existingArray = [];
    
    lastIndex = null;
	appendDesc = false;
	previousLat = 0;
	previousLon = 0;
}

//3-29-07  - added to append div style to complete HTML text string that may have been appended to
//for scrolling purposes
function appendScrollbars(addCount) {
    var tmpLength = parseInt(htmlDescs.length);
    var tmpAddCount = parseInt(addCount);
    
    var divString = '<div align="left" style="width:400px; overflow: auto; max-height: 200px;">';
    for (var j = tmpLength-tmpAddCount; j < tmpLength; j++) {
		htmlDescs[j] = divString + htmlDescs[j] +  '</div>';
    } 
    
}

function initializeEventMarkers(markerValue) {
    //first thing we do is set all markers to display false
    //we pass the marker type so we can use this to display any type of marker
    //false like cctvs, construction, spec events, incidents, etc...
    if (markerValue.length > 0) {
        for (var i = markerValue.length-1; i >=0; i--) { 
		    //we can now set display false because of nice PdMarker extension
		    //sooo much faster!
		    markerValue[i].display(false); 
	    }
    }
    
}

function toggleMarkerCheckBox(checkBox, markerValue, isChecked) {
    //user clicked on words next to checkbox instead of clicking on 
    //checkbox itself. Toggle checkbox on or off and call function to 
    //display or hide events
    
    var checkBoxToToggle = new getObj(checkBox);
    
    if (isChecked) {
        document.main.elements[checkBox].checked = false;
        isChecked = false;
    }
    else {
       document.main.elements[checkBox].checked = true;
       isChecked = true;
    }
    toggleMarkers(markerValue, isChecked)
}

function toggleMarkers(markerValue, isChecked) {
	//clearDataRefreshInterval();
	//either set display true or false depending on state of checkbox
	//if checkbox is checked, turn on, if unchecked, turn off.
	var skipMarkerToggle = false;
	var arrayToToggle = new Array();
	//is there another way to do this,rather than hardcode?
	if (markerValue == "incMarkers") {
	    arrayToToggle = incMarkers;
	}
	else if (markerValue == "constMarkers") {
	    arrayToToggle = constMarkers;
	}
	else if (markerValue == "specevtMarkers") {
	    arrayToToggle = specevtMarkers;
	}
	else if (markerValue == "speedMarkers") {
	    skipMarkerToggle = true;
	    var myCanvas = document.getElementById("myCanvas");
	}
	else if (markerValue == "cctvMarkers") {
	    arrayToToggle = cctvMarkers;
	}
	else if (markerValue == "vmsMarkers") {
	    arrayToToggle = vmsMarkers;
	}
	
	
	if (isChecked) {
		if (skipMarkerToggle) {
		    //turn links on
		    //show please wait screen while updating map
		    //function is in javascript/showHidePleaseWaitScreen.js
		    showPleaseWaitScreen("Updating map. Please wait.");
		    
		    //added 6/28/07
		    //wait for 1/10 of second before calling draw links so 
			//we can properly display please wait box.
			setTimeout("drawLinksAfterWait()",100);
		}
        else {
		    if (markerValue == "cctvMarkers") {
		         if (!cctvsExist) {
		            //grab data and display
		            createXML('cctvs', 'cctvs', '');
		            var dontToggle = true;
		        }
		    }
		    else if (markerValue == "crossingMarkers") {
		         if (!crossingsExist) {
		            //grab data and display
		            createXML('crossings', 'crossings', '');
		            var dontToggle = true;
		        }
		    }
		    else if (markerValue == "vmsMarkers") {
		         if (!vmsExist) {
		            //grab data and display
		            createXML('VMS', 'VMS', '');
		            var dontToggle = true;
		        }
		    }
		    if (!dontToggle) {
		        //not links, toggle markers on 
			    for (var n = 0; n < arrayToToggle.length; n++) {
                    arrayToToggle[n].display(true);
                }
            }
        }
    } //end if (isChecked)
    else {
	    if (skipMarkerToggle) {
		    //turn links off
		    if (browser == "Netscape") {
		        //netscape does not use the custom overlay - remove polylines
		        if (ffPolylineArray.length > 0) {
				    for (j=ffPolylineArray.length-1; j>=0; j--) {
					    googleMap.removeOverlay(ffPolylineArray[j]);
				    }
				}
			}
			else {
			    if (useSpecialJSDrawing) {
			        //hide custom overlay
			        myCanvas.style.display = "none";
			    }
			    else {
			        //not using custom overlay - fast enough using Google
			        if (ffPolylineArray.length > 0) {
				        for (j=ffPolylineArray.length-1; j>=0; j--) {
					        googleMap.removeOverlay(ffPolylineArray[j]);
					    } 
				    }
			    }
			}
        }
        else {
	        //turn markers off
	        //function above
	        initializeEventMarkers(arrayToToggle);
	    }
	}//end else if !isChecked
	
	//now set to update every 30 seconds
	//dataRefreshInterval = setInterval("updateMapInfo()", 120000);
			
}

//added 6/28/07
function drawLinksAfterWait() {
		    
	//netscape does not use the custom overlay - remove polylines
	if (browser == "Netscape") {
	    if (ffPolylineArray.length > 0) {
		    for (j=ffPolylineArray.length-1; j>=0; j--) {
			    googleMap.removeOverlay(ffPolylineArray[j]);
		    }
		}
	}
	else {
	    if (useSpecialJSDrawing) {
		    myCanvas.style.display = "block";
		}
		else {
		    //clear polylines for IE without special jsDrawing
		    if (ffPolylineArray.length > 0) {
		        for (j=ffPolylineArray.length-1; j>=0; j--) {
		            googleMap.removeOverlay(ffPolylineArray[j]);
		        }
		    }
		}
	}
	
	//now draw the links on the map
	createCustomOverlayAndDrawLinks();
}

function createMarker(point, marker, html, length) {

  	GEvent.addListener(marker, "click", function() {
  	 // if (CCTVPopupDisplayed) {
     //     closeCCTVPopupWindow();
     // }
      //3-29-07 - only use if html is empty and length is passed in - modified for appending desc
      if ((length != '')  || (parseInt(length) == 0)){
		marker.openInfoWindowHtml(htmlDescs[length]);
      }
      else {
          //this is existing - put back if code breaks
           marker.openInfoWindowHtml(html);
      }
  	});

    GEvent.addListener(marker,"mouseover", function() {
    	showTooltip(marker);
    });        
    GEvent.addListener(marker,"mouseout", function() {
		markerTooltip.style.visibility="hidden"
    });        
}

function showTooltip(marker) {
    markerTooltip.innerHTML = marker.tooltip;
    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;
	var height=markerTooltip.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(markerTooltip);
	markerTooltip.style.visibility="visible";
	markerTooltip.style.width="150px";
	markerTooltip.style.border="1px solid #000033";
}

function durationString(theSeconds) {
	
    	var iHours = 0;
    	var iMinutes = 0;
    	var iSeconds = 0; 
    	var minuteString = "";
    	var hourString = "";
    	var theDuration = "";
    	
    	
		iHours = theSeconds / 3600;
		
		if (iHours > 0) {
			theSeconds = theSeconds - (3600*iHours);
		}
		
		//GLog.write("theSeconds: " + theSeconds);
		
		iMinutes = theSeconds / 60; 
    	if (theSeconds % 60 >= 30) {
		//round up 1 minute for seconds 30 or over
			iMinutes = iMinutes + 1;
		}
		
		if (iHours == 0) {
			iHours = "0"; 
		}
		if (iMinutes == 0) {	
			iMinutes = "0";
	    }
		
		if (iHours.length == 1) {
			iHours = "0" + iHours; 
		}
		if (iMinutes.length == 1) { 
			iMinutes = "0" + iMinutes; 
		}
		
		
		theDuration = iHours + ":" + iMinutes
		return theDuration; 
}