//get link data from XML

var lonArray = [];
var latArray = [];
var linkPoints = [];

//we don't need to go and grab new event data when link checkbox is clicked on
//we just need new link data
var linkDataExists = false;

//***maybe we can try to revisit this in the future, but the performance
//was worse because there was too much on the map
//store either true or false at particular point index of array to determine
//whether link point has already been drawn or not. This is so we don't redraw
//links that have already been drawn. First load may take some time, but this
//should reduce the number of points drawn as user pans/zooms. The index of the array
//is the pointID for that particular point on the link.

var ffPolylineArray = []; //store polylines for removal on pan/zoom. Only for FireFox

var lat;
var lng;
var mapev;

var bufferValue;
var linkElement;
var linkXmlDoc;
var popupTimer;


function getLinkData(elem, xmlDoc)
{
   	var pleaseWaitScreen = new getObj('pleaseWaitScreen');

    if (linkElement !=null)
    {
        linkElement = null;
    }
	
    if (linkXmlDoc != null)
    {
        linkXmlDoc = null;
    }
	
    linkElement = elem;
    linkXmlDoc = xmlDoc;

    RemoveMapMouseMoveListner();
            
    // for Internet explorer use vector graphics to draw link polylines
    if (browser != "Netscape")
    {
        if (ffPolylineArray.length > 0)
        {
            ffPolylineArray = [];
        }
        
        //tooltip should not be displayed out side the map
		GEvent.addListener(googleMap,"mouseout",function(point){	
			clearPopupTimer();
			markerTooltip.style.visibility="hidden";
		});
		
	    mapev = GEvent.addListener(googleMap, 'mousemove', function(latlng){
	    
	    if(!markerTooltipFlag)
            setPopupTimer(latlng.lng(),latlng.lat());});
	    
	    var imageHeight = parseInt(document.getElementById("map_canvas").style.height);
	    var imageWidth = parseInt(document.getElementById("map_canvas").style.width);
	    
	    for (var i = 0; i < elem.length; i++)
	    {
	        var linkID = elem.item(i).getAttribute("ID");
		    var color = elem.item(i).getAttribute("color");
		    var speed = elem.item(i).getAttribute("speed");
		
		    var points = elem[i].getElementsByTagName("point");
      
            for (var j = 0; j < points.length; j++)
            {
			    var pointID = points[j].getAttribute("pointID");
    	    	var tempPoint = new GLatLng(parseFloat(points[j].getAttribute("Lat")), parseFloat(points[j].getAttribute("Long")));
    	    	
    	    	linkPoints.push(tempPoint); 
    	    	
		    	var tempDivXY = googleMap.fromLatLngToDivPixel(tempPoint); 
		    	
			    lonArray[j] = tempDivXY.x;
			    latArray[j] = tempDivXY.y;
			    
                iTotalRows++;			
            } //end for var j = 0
            
            jg_doc.setStroke(3);
  		    jg_doc.setColor(color);
  		    jg_doc.drawPolyline(lonArray, latArray);
  		    jg_doc.paint();
  		    
  		    ffPolylineArray[i] = new GPolyline((linkPoints), color, 3, 1);
  		    
  		    lonArray = [];
  		    latArray = [];
  		    linkPoints = [];

  		    var myCanvas = document.getElementById("myCanvas");
		    myCanvas.style.display = "block";
		    
		    if (pleaseWaitScreen.style.visibility == "hidden") {
	  		    showPleaseWaitScreen("Updating map. Please wait.");
	  		}
		
		    if (i == elem.length-1) {
		        //wait till last element to set drawingLinks to false
		        //now we can allow turn off of please wait screen
		        drawingLinks = false;
		    }
		    
	   }//end for var i = 0
    }
    else  //for FireFox and Netscape Navigator browser use Google GPolyline to draw links polyline
    {
	    mapev = GEvent.addListener(googleMap, 'mousemove', function(latlng) {
		    lat = latlng.lat();
		    lng = latlng.lng();
	    });
	    
	    if (ffPolylineArray != null)
        {
            if (ffPolylineArray.length > 0)
            {
                for (var i = 0; i < ffPolylineArray.length; i++)
                {
    		        googleMap.removeOverlay(ffPolylineArray[i]);
                }			    
            
                ffPolylineArray = [];
            }
        }
        
        for (var i = 0; i < elem.length; i++)
        {
            var color = elem.item(i).getAttribute("color");
            var points = elem[i].getElementsByTagName("point");
            
            for (var j = 0; j < points.length; j++) {
		        var pointID = points[j].getAttribute("pointID");
		        var tempPoint = new GLatLng(parseFloat(points[j].getAttribute("Lat")), parseFloat(points[j].getAttribute("Long")));

        	    linkPoints.push(tempPoint); 
                iTotalRows++;		
                
            }
        
            ffPolylineArray[i] = new GPolyline((linkPoints), color, 3, 1);
            
            googleMap.addOverlay(ffPolylineArray[i]);
            linkPoints = [];
            GEvent.addListener(ffPolylineArray[i],"mouseover", function(){showSpeedLinkTooltip();});
            
            GEvent.addListener(ffPolylineArray[i],"mouseout", function() {
            markerTooltip.style.visibility="hidden";
            });
                        
  		    if (pleaseWaitScreen.style.visibility == "hidden") {
  		        showPleaseWaitScreen("Updating map. Please wait.");
  		    }
    	
	        if (i == elem.length-1) {
	            //wait till last element to set drawingLinks to false
	            //now we can allow turn off of please wait screen
	            drawingLinks = false;
	        }
        }
    }
    
    //now display markers - we had a problem trying to display markers first
	//the xml doc was coming back incorrectly. So, putting this function after creating the links
	//seemed to have fixed the issue.
	//createXML('events', 'marker', 'tM=traffic');

    var typeString = buildEventTypeString();
    
    if (typeString != "")
    {
        //checkboxes are checked - now go get events, otherwise, don't get any thing
        createXML('events', 'trafficmarker', typeString);
    }
    else
    {
        hidePleaseWaitScreen();
    }
    
    typeString = "";
}

function RemoveMapMouseMoveListner()
{
    if(mapev!=null)
    {
        GEvent.removeListener(mapev);
        mapev = null;
    }
}
    
var markerTooltipFlag=false;
// Timer function is required so as to check for tooltip when mouse stays for sometime else
// if it is checked for every mouse move then map performance will degrade.
function setPopupTimer(x,y)
{
   markerTooltip.style.visibility="hidden";
   
   if (  (x==lng) && (y==lat) )
   {
      return; // already set at this location or we've already tried here
   }      

   clearPopupTimer();
   lng = x;
   lat = y;
   
   // Earlier logic retained, mostly giving accurate tooltip at all zoom levels.
   if(!markerTooltipFlag)
      // Uncomment to call Sergey code, tooltip display is not consistent, specially at high zoom levels tooltip does not appear.
      //popupTimer = setTimeout("getLinkLayer()", 500);
      popupTimer = setTimeout("showSpeedLinkTooltip()", 500);
}


function clearPopupTimer()
{
   if (popupTimer != null)
   {
        clearTimeout(popupTimer);
        popupTimer = null;
   }
}


// This is based on Sergey code, at high zoom levels logic is not working, low level it is inconsistent
// getting tooltip
function getLinkLayer() 
{               
    var n; 
    var dY0; 
    var dX0; 
      
    var dYy; 
    var dXx; 

    var breakOut = 0;                 
    
    var x = Math.round(lng * 1000)/1000; 
    var y = Math.round(lat * 1000)/1000; 
                                                      
    for (n = 0; n < ffPolylineArray.length; n++) 
    {
        j = 0; 
        
        var linkLine = ffPolylineArray[n];        
        var vertexCount = linkLine.getVertexCount();
        var polyBounds = linkLine.getBounds();

        for (i = 0; i < vertexCount; i++) { 
            coords1 = linkLine.getVertex(i);
            coords2 = linkLine.getVertex(j);

            var x1 = coords1.lng();
            var y1 = coords1.lat();
            
            var x2 = coords2.lng();
            var y2 = coords2.lat();
                   
            if (  (y1 < y && y2>=y || y2 < y && y1 >= y) && 
              (x1 < x && x2 >=x || x2 < x && x1 >=x))
            {                                                                         
               dY0 = (Math.round(y2*1000)/1000)-(Math.round(y1*1000)/1000);
               dX0 = (Math.round(x2*1000)/1000)-(Math.round(x1*1000)/1000);
              
               dYy = y - (Math.round(y1*1000)/1000); 
               dXx = x-(Math.round(x1*1000)/1000); 
                                                                  
              if (Math.abs(dY0/dX0) >= 1) 
              {                                                     
                  if (googleMap.getZoom() > 9)
                  { 
                      if (parseInt(dY0/dX0) ==  parseInt(dYy/dXx) || (dYy == 0 && dXx == 0)   )                                   
                      {
                        
                        GetAndDisplayTooltipInfo(n,x, y);
                        breakOut = 1; 
                        break;                                                                   
                      } 
                  } 
                  else 
                  {                                 
                    if ((parseInt(dY0/dX0) ==  parseInt(dYy/dXx)) || (dYy == 0 && dXx == 0)   )                                 
                      {                                   
                        GetAndDisplayTooltipInfo(n, x, y);
                        breakOut = 1; 
                        break;                                     
                      } 
                  }                           
              } 
              else 
              { 
                 if (  Math.round((dY0/dX0)*10)/10 ==  Math.round((dYy/dXx)*10)/10  ) 
                  {  
                    GetAndDisplayTooltipInfo(n, x, y);
                    breakOut = 1; 
                    break;                                 
                  } 
              }                                                             
            } 
            else 
                markerTooltip.style.visibility="hidden";
                      
        j = i;                 
      } 

    if (breakOut == 1) 
        break;                 
    
   }                 
} 



function showSpeedLinkTooltip()
{
    var x = lng;
    var y = lat;
    
    IdentifyTooltip(lng, lat)
}


// This logic is working at all zoom levels and quite accurate
function IdentifyTooltip(x, y)
{
    if(ffPolylineArray != null)
    {
        var coords1 = null;
        var reltaiveDistance =  null;
       
        var round_x_sw = null;
        var round_y_sw = null;
        var round_x_ne = null;
        var round_y_ne = null;
       
        UpdateConfigSettings(x, y);

        round_x_sw = x - bufferValue;
        round_y_sw = y - bufferValue;
        round_x_ne = x + bufferValue;
        round_y_ne = y + bufferValue;
        
        var southWest = new GLatLng(round_y_sw,round_x_sw);
        var northEast = new GLatLng(round_y_ne,round_x_ne);
        var mouseBounds = new GLatLngBounds(southWest,northEast);
        
        var lineCount = ffPolylineArray.length;
        
        var nearestLineIndex = -1;
        var nearestLineDistance = -1;
        
        //loop through all the links
        outer : for(var i=0;i<lineCount;i++)
        {
            var linkLine = ffPolylineArray[i];
            var polyBounds = linkLine.getBounds();
            
            // Check whether current mouse bounds intersects the bounding box of the link
            // and rule out those links for which mouse pointer is not in. This reduces filtering time  
            if(polyBounds.intersects(mouseBounds) == true)
            {                
                var vertexCount = linkLine.getVertexCount();
                
                inner : for(var k=0;k < vertexCount;k++)
                {
                   coords1 = linkLine.getVertex(k);
                    
                   var longitude = coords1.lng();
                   var latitude = coords1.lat();
                   
                   // Check whether mouse pointer lies within buffer area.
                   if(mouseBounds.containsLatLng(coords1) == true)
                   {
                       try
                       {
                            // The below logic is to get the nearest link from the mouse pointer. 
                            
                            // get first coordinate distance from mouse position
                            var d1 = coords1.distanceFrom(new GLatLng(y,x));
                            var d2 = 0;
                            var d3 = 0;
                            var coords2 = null;
                            
                            if(k + 1 < vertexCount)
                            {
                                coords2 = linkLine.getVertex(k +1);
                            }
                            else
                            {
                                coords2 = linkLine.getVertex(k -1);
                            }
                            
                            // get second coordinate distance from mouse position
                            d2 = coords2.distanceFrom(new GLatLng(y,x));
                            
                            // get the distance between the two consecutive points on the link
                            d3 = Math.abs(coords1.distanceFrom(coords2));
                            
                            // get the relative distance.
                            var relativeDistance =  (d1 + d2) - d3;
                                                  
                            // for first encountered link
                            if(nearestLineDistance == -1)
                            {
                                nearestLineDistance = relativeDistance;
                                nearestLineIndex = i;
                            }
                            else if(relativeDistance < nearestLineDistance)
                            {
                                //update the nearest link.
                                nearestLineDistance = relativeDistance;
                                nearestLineIndex = i;
                            }
                            else
                            {
                                markerTooltip.style.visibility="hidden";
                            }
                            
                            break inner;
                        }catch(err){}
                   }
                   else
                   {
                       markerTooltip.style.visibility="hidden";
                   }
                   coords1 = null;
                }
            }
        }
        
        if(nearestLineIndex != -1)
        {
            GetAndDisplayTooltipInfo(nearestLineIndex, x,y);
        }
        
        southWest = null;
        northEast = null;
        mouseBounds = null;
    }
}

function UpdateConfigSettings(x, y)
{
    //Dynamically compute the buffer area to be taken around mouse position to detect closest links
    var pointInPixel = googleMap.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(y,x),googleMap.getZoom());
    
    // add 10 pixels to the current mouse position
    pointInPixel.x = pointInPixel.x + 10;
    
    // get the buffer area in geo coordinates.
    var pointInLatLng = googleMap.getCurrentMapType().getProjection().fromPixelToLatLng(pointInPixel,googleMap.getZoom(), true);
    bufferValue = Math.abs(x - pointInLatLng.x);
}


function GetAndDisplayTooltipInfo(linkIndex, x,y)
{
    // get link information and display it as tooltip.
    var name = linkXmlDoc.getElementsByTagName("Name")[linkIndex].firstChild.nodeValue;
    var speed = linkElement.item(linkIndex).getAttribute("speed");
    var color = linkElement.item(linkIndex).getAttribute("color");
    var travelTime = linkXmlDoc.getElementsByTagName("TravelTime")[linkIndex].firstChild.nodeValue;
    showLinkTooltip(name, color,"No Data Available", speed,travelTime, x, y,"speed");   
}

function showLinkTooltip(name, color, roadCondition, speed, travelTime, x, y, layerName)
{
    if (layerName == "speed")
    {
        if (name == '' || name == "null")
        {
            name = "NA"    
        }
        
        if (parseInt(speed) == -1 || speed == "null" || color == "#666666")
        {
            speed = "NA";
        }
        else
        {
            if (speed != "NA" && speed != "At or near posted speed limit")
            {        
            speed = speed + ' mph';
            }
        }
        
        if (parseInt(travelTime) == -1 || travelTime == "null" || color == "#666666")
        {
           travelTime = "NA";
        }
        else if (parseInt(travelTime) > 59)
        {
            var min = parseInt((travelTime) / 60);
            var sec = 0;
            
            if (min != 0)
            {
                sec  = parseInt(travelTime) % 60;
                travelTime = min + ' minutes ' + sec + ' seconds';
            }
            else
            {
                travelTime = travelTime + ' seconds';
            }
        }
        else
        {
            if (travelTime != "N/A")
            travelTime = travelTime + ' seconds';
        }
        
        
   if(document.getElementById("WinterAdvVisibility").value=="true")
	    {
            var tooltip = '<div class="markerTooltip" style="color:#005600;'; 
	        tooltip += 'text-align: center; width: 230px; line-height: 18px;">'
	        tooltip += name +'<br />';
	        tooltip += 'Road Condition: ' + roadCondition + '<br />'; 
	        tooltip += 'Average Speed: ' + speed + '<br />'; 
	        tooltip += 'Travel Time: ' + travelTime + '<br />'; 
	        tooltip += '</div>';
	    }
	    else
	    {
	        var tooltip = '<div class="markerTooltip" style="color:#005600;'; 
	        tooltip += 'text-align: center; width: 230px; line-height: 18px;">'
	        tooltip += name +'<br />';
	        tooltip += 'Average Speed: ' + speed + '<br />'; 
	        tooltip += 'Travel Time: ' + travelTime + '<br />'; 
	        tooltip += '</div>';
	    }
	    
	}
	
   if (layerName == "winter")
	{
	
	    if (name == '' || name == "null")
        {
            name = "NA"    
        }
        
        if (parseInt(speed) == -1 || speed == "null" || color == "#666666")
        {
            speed = "NA";
        }
        
        if (parseInt(travelTime) == -1 || travelTime == "null" || color == "#666666")
        {
           travelTime = "NA";
        }
        else if (parseInt(travelTime) > 59)
        {
            var min = parseInt((travelTime) / 60);
            var sec = 0;
            
            if (min != 0)
            {
                sec  = parseInt(travelTime) % 60;
                travelTime = min + ' minutes ' + sec + ' seconds';
            }
            else
            {
                travelTime = travelTime + ' seconds';
            }
        }
        else
        {
            if (travelTime != "N/A")
            travelTime = travelTime + ' seconds';
        }
       
        
        
        var tooltip = '<div class="markerTooltip" style="color:#0000FF'; 
	    tooltip += 'text-align: center; width: 230px; line-height: 18px;">'
	    tooltip += name +'<br />';
	  	tooltip += 'Road Condition: ' + roadCondition + '<br />'; 
	    tooltip += 'Average Speed: ' + speed + '<br />'; 
	    tooltip += 'Travel Time: ' + travelTime + '<br />'; 
	    tooltip += '</div>';
	
	}
    markerTooltip.innerHTML = tooltip;
    var point=googleMap.getCurrentMapType().getProjection().fromLatLngToPixel(googleMap.fromDivPixelToLatLng(new GPoint(0,0),true),googleMap.getZoom());	
    var offset=googleMap.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(y,x),googleMap.getZoom());
    
	var height=markerTooltip.clientHeight;
	var width=markerTooltip.clientWidth;
	
    var center = googleMap.getCurrentMapType().getProjection().fromLatLngToPixel(googleMap.getBounds().getCenter(),googleMap.getZoom());
    
    var posY, posX;
    
    if(offset.y < center.y)
    {
        posY = offset.y - point.y; // top
    }
    else
    {
        posY = offset.y - point.y - height; // bottom
    }
    
    if(offset.x < center.x){
        posX = offset.x - point.x; // left
    }
    else{
        posX = offset.x - point.x - width; // right
    }
    	
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(posX, posY)); 
	
    pos.apply(markerTooltip);
	markerTooltip.style.visibility="visible";
	markerTooltip.style.width="230px";
	markerTooltip.style.border="1px solid #005500";
}


