var COLORS = [["red", "#ff0000"], ["green","#008000"],
              ["blue", "#000080"], ["orange", "#ff8800"], ["purple", "#800080"]];
			  
var encodedPolyline = null;
var colorIndex_ = 0;
var waitForId = false; 

var polylineReadOnly = false
var isExternal = false;
var polylines = [];  

var weightPoly = 4; 
kkk=0

function BluePolyline(points4polyline, id, name, type, datetime_start, datetime_end, color) 
{
	this.id = id;
	this.name = name;
	this.color = color; 
	this.type = type;	
	
	this.datetime_start = pgDate2JsDate(datetime_start);
	this.datetime_end = pgDate2JsDate(datetime_end); 
	
	this.cells = null;
	
	this.notInit = true;
	this.refreshStatus = true;
	if(type==1)
		this.polyline = new GPolyline(points4polyline,color);
	if(type==2)
		this.polyline = points4polyline ;
	
	this.getLength = function() {
		var len = this.polyline.getLength();
    	return Math.round(len / 1.852 / 100) / 10  ;		
	}
	 
	this.getTotalMinute = function() {  
		//Get 1 minute in milliseconds
		var one_minute_ms = 1000*60  
		return Math.ceil((this.datetime_end.getTime() - this.datetime_start.getTime())/one_minute_ms )  
	}
	
	this.getDbDatetime_start = function()
	{
		year = this.datetime_start.getFullYear()
		month = this.datetime_start.getMonth() + 1
		day = this.datetime_start.getDate()
		hour = this.datetime_start.getHours()
		minute = this.datetime_start.getMinutes()   
		return month + "-" + day + "-" + year + " " + hour + ":" + minute  + ":00"; 
	}
	
	this.getDbDatetime_end = function()
	{
		year = this.datetime_end.getFullYear()
		month = this.datetime_end.getMonth() + 1
		day = this.datetime_end.getDate()
		hour = this.datetime_end.getHours()
		minute = this.datetime_end.getMinutes()   
		return month + "-" + day + "-" + year + " " + hour + ":" + minute  + ":00"; 
	} 
	
	this.getTotalTime = function() {  
		minutes = this.getTotalMinute();
		days = Math.floor(minutes/(60*24));
		minute_remain = minutes - days*60*24;
		hours = Math.floor(minute_remain/60);
		minutes = minute_remain - hours*60 ;
		var rtn = ""
		if (days>0) rtn += days + " days "
		if (hours>0) rtn += hours + " hours "
		if (minutes>0) rtn += minutes + " minutes"
		 
		return rtn;  
	}
	
	this.getAverage = function() {
		var minutes = this.getTotalMinute();
		var len = this.getLength(); 
		if (minutes>0)
	    	return Math.round(10*len /(minutes/60)) / 10  ;		
		else
			return "0";
	}
	
	this.getUpperVertexPoint = function ()
	{
		return this.polyline.getVertex(this.getUpperVertex());
	}
	
	this.getUpperVertex = function ()
	{
		var maxLat = -90;
		var currVertex = 0;
		//Math.round(polylines[polylineIndex].getVertexCount()/2+0.1)-1
		for(uu=0; uu < this.polyline.getVertexCount(); uu++)
		{
			if(this.polyline.getVertex(uu).lat() > maxLat)
			{
				maxLat = this.polyline.getVertex(uu).lat();
			 	currVertex = uu;
			}
		}
		return currVertex;
	}  
} 
 

/*
var polylineNames = [];  
var notInit = []; 
var polylineId = []; 
var polylineColor = []; 
var refreshStatus = []; 
*/ 

function getColor(named) {
  return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
}


function editablePolyline() 
{   
  refreshPolylineNumber();
  if(polylines.length==0) return;  
  //polyline = new GPolyline(pnts, colorPoly);  
  for (kk=0;kk<polylines.length;kk++)
  { 
	if( polylines[kk].polyline.getVertexCount() >0)
	{
		polylines[kk].refreshStatus = false;
 		if(polylines[kk].notInit) initPolyline(kk); 
  		map.addOverlay(polylines[kk].polyline);
    	polylines[kk].polyline.setStrokeStyle({color: polylines[kk].color  , weight: weightPoly}); 
		 
	}
  }
}

function visibleOnlyPolyline() 
{  
	refreshPolylineNumber();
	polylineReadOnly = true;
    if(polylines.length==0) return;
	for (kk=0;kk<polylines.length;kk++)
	{    
	
	  if( polylines[kk].polyline.getVertexCount() >0)
	  {
	 	polylines[kk].refreshStatus  = false;
 		if(polylines[kk].notInit) initReadOnlyPolyline(kk); 
  		map.addOverlay(polylines[kk].polyline);
    	polylines[kk].polyline.setStrokeStyle({color: polylines[kk].color , weight: weightPoly});  
	  }
	} 
} 

function initReadOnlyPolyline(polylineIndex)
{     
	 GEvent.bind(polylines[polylineIndex].polyline, "mouseout", null, function (latlng, index){
	 	  isToHideTooltip = true; 
		  setTimeout('hideTooltip()' ,2000);
	 });
	 
	 GEvent.bind(polylines[polylineIndex].polyline, "mouseover", null, function (latlng, index){
	 	if (typeof index != "number") 
  		{	
			viewTrackBubble(polylineIndex);
		} 
		 
	  });
	  		  
	  var cells = addFeatureEntry( polylineIndex ,polylines[polylineIndex].color );
	  polylines[polylineIndex].cells = cells;
	  /// cells.innerHTML = " "+ polylines[polylineIndex].getLength() + " miles ";		  
	  polylines[polylineIndex].notInit = false; 
}

function initPolyline(polylineIndex)
{     
		 GEvent.bind(polylines[polylineIndex].polyline, "mouseout", null, function (latlng, index)
		 {
			 isToHideTooltip = true;
			 //map.closeInfoWindow();
			 setTimeout('hideTooltip()' ,2000);
			 
			 if(polylines[polylineIndex].type==1)  
			 {
			 	polylines[polylineIndex].polyline.disableEditing();
				isTracking = false;   
			 }
		 });
		 
		 GEvent.bind(polylines[polylineIndex].polyline, "mouseover", null, function (latlng, index)
		 { 
      		if (typeof index != "number") 
	  		{	
				 isToHideTooltip = false;
				 viewTrackBubble(polylineIndex);
			}
			if(polylines[polylineIndex].type==1) 
			{
				isTracking = true; 
				polylines[polylineIndex].polyline.enableEditing(); 
			}
			 
		  });
		
		  /*
		polylines[polylineIndex].disableEditing({onEvent: "mouseout"});
		polylines[polylineIndex].enableEditing({onEvent: "mouseover"});
		
		  GEvent.bind(polyline, "mouseover", null, function (){
		  	refreshStatus = false;
			polyline.setStrokeStyle({color: colorPolyOver, weight: weightPoly});
		  	polyline.enableEditing(); 
			 
		  });
		  
		  GEvent.bind(polyline, "mouseout", null, function (){
		    	 refreshStatus = false;
				 polyline.setStrokeStyle({color: colorPoly , weight: weightPoly}); 
				polyline.disableEditing();  
		  });
		 if(polylineId[polylineIndex]>0)
		 {  
		 } 
		  */
	if(polylines[polylineIndex].type==1)
	{ 
		  GEvent.bind(polylines[polylineIndex].polyline, "endline", null, function (){		  
		  	select("hand_b"); 
		  }); 
		  
  		  var cells = addFeatureEntry( polylineIndex , polylines[polylineIndex].color  );
		  polylines[polylineIndex].cells = cells;
		   
		  GEvent.bind(polylines[polylineIndex].polyline, "lineupdated",  cells.lengthDesc, function (){
		   
		   var cell = this; 
		   cell.innerHTML = refreshPolylineLength(polylineIndex);
			if(polylines[polylineIndex].polyline.getVertexCount()>1 )
			{  
			  	if(! polylines[polylineIndex].refreshStatus  )
				{  
					polylines[polylineIndex].refreshStatus  = true;
					return;
				}  
		    	var len = polylines[polylineIndex].polyline.getVertexCount()||0;
				var jsonPoly = ' {"points": [';
		    	for(var i=0; i<len; i++)
				{
			  		if(i>0) jsonPoly += ',';
		      		var pnt = polylines[polylineIndex].polyline.getVertex(i);
		      		jsonPoly += '{"lng":'+pnt.lng().toFixed(12)+',"lat":'+pnt.lat().toFixed(12)+'}';			 
				}
				jsonPoly += '],"name":"'+ polylines[polylineIndex].name +'"' +
				',"datetime_start":"'+ polylines[polylineIndex].getDbDatetime_start() +'"' +
				',"datetime_end":"'+ polylines[polylineIndex].getDbDatetime_end() +		'"' +		
				',"action":"update","id":'+ polylines[polylineIndex].id +
				',"trip_id":'+tripId+'} ';
			
				var mypostrequest = new ajaxRequest()
				mypostrequest.onreadystatechange=function(){
		
					if (mypostrequest.readyState==4)
					{
						  if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1)
						  {   
					  	 	    var jsonResponse = eval("("+ mypostrequest.responseText +")");  
						  		if(!(polylines[polylineIndex].id > 0)) 
								{
									polylines[polylineIndex].id = jsonResponse["id"]; 
									isTracking = true; 
									polylines[polylineIndex].polyline.enableDrawing();
								}
								trip_total_length = jsonResponse["trip_total_length"];
								if (trip_total_length>0)
										document.getElementById("tripTotalLength").innerHTML = '<b>Track Length:</b> ' + trip_total_length + ' miles<br />'
								//alert(mypostrequest.responseText);
						  }
						  else
						  {
						   alert("An error has occured making the request")
						  } 
				    }
					
			    }
				//jsonPoly=encodeURIComponent(jsonPoly);  
				if(!(polylines[polylineIndex].id > 0)) 
				{ 
					polylines[polylineIndex].polyline.disableEditing();
					isTracking = false; 
				}
				mypostrequest.open("POST", "ajaxTrack.php", true)
				mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
				mypostrequest.send( jsonPoly) ;
			}
	  });
	  
	  GEvent.addListener(polylines[polylineIndex].polyline, "click", function(latlng, index) { 
 
	      if (typeof index == "number") {
	        polylines[polylineIndex].polyline.deleteVertex(index); 
	      }   
	  });
	  
	   //polylines[polylineIndex].notInit = false; 
	}
	else if(polylines[polylineIndex].type==2)
	{ 
	  var cells = addFeatureEntry( polylineIndex, polylines[polylineIndex].color );
	  polylines[polylineIndex].cells = cells;
	   polylines[polylineIndex].cells.lengthDesc.innerHTML = refreshPolylineLength(polylineIndex);
	  /// cells.innerHTML = " "+ polylines[polylineIndex].getLength() + " miles ";		
	}   
	polylines[polylineIndex].notInit = false; 
}

function removeTrack(polylineIndex)
{
	if (!confirm("Are you sure to remove the track '"+ polylines[polylineIndex].name  + "'?\r\n")) return false;  
	var mypostrequest = new ajaxRequest()
	mypostrequest.onreadystatechange=function(){

		if (mypostrequest.readyState==4)
		{
		  if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1)
		  {
		  		 map.closeInfoWindow();
		  		 map.removeOverlay(polylines[polylineIndex].polyline) 
			 	 featureTable_.removeChild(document.getElementById('trTrack'+polylineIndex));
				 polylines[polylineIndex].polyline =  new GPolyline( ); ;
				   //    alert(mypostrequest.responseText) ;  
			    refreshPolylineNumber(); 
		  }
		  else
		  {
		   alert("An error has occured making the request")
		  } 
	    } 
    } 
	jsonPoly = '{"action":"delete","id":'+ polylines[polylineIndex].id  +'}';
	mypostrequest.open("POST", "ajaxTrack.php", true)
	mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
	mypostrequest.send( jsonPoly) ; 
}



function viewTrackBubble(polylineIndex)
{
	if(isPlacemarkerInserting) return;
	refreshAj = false; 
 	myHtml  = ""
	var bubbleTrackPoint = polylines[polylineIndex].getUpperVertexPoint();
	if(polylineReadOnly)
	{
		myHtml += '<table  onmouseover="isToHideTooltip=false;" onmouseout="isToHideTooltip=true;setTimeout(\'hideTooltip()\' ,2000);"><tr><td nowrap style="padding:0;margin:0px;font-size:11px;">';
		myHtml  += "<u>Name</u>: "+polylines[polylineIndex].name + "<br>" ;
		myHtml  += "<u>Start date</u>: "+ dateFormat(polylines[polylineIndex].datetime_start) + "<br>" ; 
		myHtml  += "<u>End date</u>: "+ dateFormat(polylines[polylineIndex].datetime_end) + "<br>" ; 
		myHtml  += "<u>Track Time</u>: "+ polylines[polylineIndex].getTotalTime() + "<br>" ; 
		myHtml  += "<u>Length</u>: "+polylines[polylineIndex].getLength() + " miles <br>" ; 
		myHtml  += "<u>Average speed</u>: "+ polylines[polylineIndex].getAverage() + " kn <br>" ; 
		myHtml  += "<u>Track points</u>: "+ polylines[polylineIndex].polyline.getVertexCount()+"  <br>" ; 
		myHtml += '</td></tr></table>';
		
		//map.openInfoWindowHtml(bubbleTrackPoint, myHtml );
		isToHideTooltip = false; 
		showTooltip(bubbleTrackPoint,myHtml)
	}
	else 
	{
		//myHtml += '<div class="optionTrack" style="font-weight:bold;text-align:right;width:230px;"><a href="#" onclick="removeTrack('+polylineIndex+');return false;">Delete</a>&nbsp;&nbsp;<a href="#" onclick="showPopup(\'popup\',\'track\',\'edit\','+ polylineIndex +');return false;">Edit</a></div>'
		
		myHtml += '<table  onmouseover="isToHideTooltip=false;" onmouseout="isToHideTooltip=true;setTimeout(\'hideTooltip()\' ,2000);"><tr><td nowrap style="padding:0;margin:0px;">'+polylines[polylineIndex].name +'</td><td nowrap><div class="optionTrack" style="font-weight:bold;float:right;"><a href="#" onclick="isToHideTooltip=true;hideTooltip();removeTrack('+polylineIndex+');return false;">Delete</a>&nbsp;&nbsp;<a href="#" onclick="showPopup(\'popup\',\'track\',\'edit\','+ polylineIndex +');return false;">Edit</a></div></td></tr></table>' 
		isToHideTooltip = false; 
		showTooltip(bubbleTrackPoint,myHtml)
		
	}
	//map.panTo(bubbleTrackPoint); 
			
}

function refreshPolylineNumber()
{
  var cnt=0;
  for (kk=0;kk<polylines.length;kk++)
  { 
	if( polylines[kk].polyline.getVertexCount() >0) cnt++; 
  }
  if(!isExternal) document.getElementById("trackNumber").innerHTML = cnt;
}
		 
function refreshPolylineDesc(polylineIndex)
{
	  var myHtml = '<div style="font-size:11px;width:150px;padding:0px 5px 3px 5px;">'   
	  myHtml  += "<u>Name</u>: "+polylines[polylineIndex].name + "<br>" ; 
	  myHtml  += "<u>Start date</u>: "+ dateFormat(polylines[polylineIndex].datetime_start) + "<br>" ; 
	  myHtml  += "<u>End date</u>: "+ dateFormat(polylines[polylineIndex].datetime_end) + "<br>" ; 
	  myHtml +='</div>';  
	  return myHtml;
}


function refreshPolylineLength(polylineIndex)
{ 
	  var myHtml = '<div style="font-size:11px;width:200px;padding:2px 5px 2px 5px;">'   
	  myHtml  += "<u>Track Length</u>: "+ polylines[polylineIndex].getLength() + " miles<br>" ; 
	  myHtml  += "<u>Track Time</u>: "+ polylines[polylineIndex].getTotalTime() + "<br>" ; 
	  myHtml  += "<span style=\"float:left!important;margin:0px\"><u>Average speed</u>: "+ polylines[polylineIndex].getAverage() + " kn</span> " ; 
	  myHtml  += "<span style=\"float:right!important;margin:0px;color:#000000;\">"+ (polylines[polylineIndex].type==2?"GPX import":"Manually created") + "</span>" ; 
	  myHtml +='</div>';  
	  return myHtml;
} 


function addFeatureEntry(idx, color) 
{
	  if(isExternal) return; 
	  currentRow_ = document.createElement("tr");
	  currentRow_.id = "trTrack"+idx; 
	  currentRow_.style.backgroundColor='#eeeeee'; 
	  currentRow_.setAttribute('style', 'background:#eeeeee;'); 
	  var colorCell = document.createElement("td"); 
	  colorCell.style.backgroundColor = "#ffffff"; 
	  colorCell.style.verticalAlign = "top";
	  colorCell.innerHTML = '<div style="width:7px;height:45px;cursor:pointer;background:'+color+';" onclick="viewTrackBubble('+ idx +');window.scrollBy(0,-3000);window.scrollBy(0,170);" title="Click to highlight on the map">&nbsp;</div>' ;
	  currentRow_.appendChild(colorCell); 
	  var descCell = document.createElement("td");
	  currentRow_.appendChild(descCell);
	  
	  //nameCell.innerHTML = '<span onmouseover="this.style.cursor=\'pointer\';polylines['+idx+'].polyline.enableEditing();viewTrackBubble('+idx+');" onmouseout="polylines['+idx+'].polyline.disableEditing();">'+polylines[idx].name +'</span>' ;

	  
	  descCell.innerHTML =   refreshPolylineDesc(idx);  
	  
	  var lengthCell = document.createElement("td");
	  lengthCell.setAttribute('style', 'background:#eeeeee;'); 
	  
	  var editCell = document.createElement("td");
	  editCell.setAttribute('style', 'color:ff4400;width:33px;background:#eeeeee;text-align:center;'); 
	  
	  var cancelCell = document.createElement("td");
	  cancelCell.setAttribute('style', 'color:ff4400;width:38px;background:#eeeeee;text-align:center;'); 
	  
	  currentRow_.appendChild(lengthCell);   
	  
	  if(polylineReadOnly)
	  {  
	  	lengthCell.innerHTML = refreshPolylineLength(idx);
	  }
	  else
	  {
	  	cancelCell.innerHTML = '<div class="optionTrack"><a href="#" onclick="removeTrack('+idx+');return false;">Delete</a></div>';
	  	currentRow_.appendChild(cancelCell); 
		
	  	editCell.innerHTML = '<div class="optionTrack"><a href="#" onclick="showPopup(\'popup\',\'track\',\'edit\','+ idx +');return false;">Edit</a></div>';
	  	currentRow_.appendChild(editCell);  
	  }
	  
	  featureTable_.appendChild(currentRow_);
	  return {desc: descCell, lengthDesc: lengthCell, cancel: cancelCell, edit: editCell, idx_: idx, color: colorCell};
}

function popup_save_track(polylineIndex)
{  
	var mypostrequest = new ajaxRequest()
	mypostrequest.onreadystatechange=function(){
 
		if (mypostrequest.readyState==4)
		{
		  if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1)
		  {
		  		 var jsonResponse = eval("("+ mypostrequest.responseText +")");  
			 
				 polylines[polylineIndex].name = jsonResponse["name"];
				 polylines[polylineIndex].datetime_start = pgDate2JsDate(jsonResponse["datetime_start"]);
				 polylines[polylineIndex].datetime_end = pgDate2JsDate(jsonResponse["datetime_end"]); 
				 
		   		 var cells = polylines[polylineIndex].cells ; 
		   		 cells.desc.innerHTML = refreshPolylineDesc(polylineIndex);  
		   		 cells.lengthDesc.innerHTML = refreshPolylineLength(polylineIndex);  
				 
				  hidePopup('popup');
				  viewTrackBubble(polylineIndex);
				//alert(mypostrequest.responseText)
		  }
		  else
		  {
		   alert("An error has occured making the request")
		  } 
	    } 
    } 
	DoDateTrack(polylines[polylineIndex].id,"start");
	DoDateTrack(polylines[polylineIndex].id,"end");
	eval('name_form = document.formTrack'+polylines[polylineIndex].id+'.name.value;');
	eval('datetime_start_form = document.formTrack'+polylines[polylineIndex].id+'.datetime_start.value;');
	eval('datetime_end_form = document.formTrack'+polylines[polylineIndex].id+'.datetime_end.value;');
	if(pgLocalDate2JsDate(datetime_start_form).getTime()>pgLocalDate2JsDate(datetime_end_form).getTime())
	{
		alert("Error! 'Start Date' is more recent than 'End Date'.")
		return;
	}
	//alert(datetime_start_form+" - "+datetime_end_form)
	jsonPoly = '{"action":"save","id":'+ polylines[polylineIndex].id  +',"name":"'+ name_form +'","datetime_start":"'+ datetime_start_form  +'","datetime_end":"'+ datetime_end_form  +'"}';
	mypostrequest.open("POST", "ajaxTrack.php", true)
	mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
	mypostrequest.send( jsonPoly) ; 
	
	 
				    
}

