	
var map;
var gVehicles = new Array();

var ajaxRequest = null;
	
//*****************************************************************************************************************

function changeZoom( newZoom )
{
  if ( map.getZoom != newZoom )
    map.setZoom( newZoom );
}
    
function zoomLevels(min, max) 
{
  var array = this.map.getMapTypes() || [];
  for (var i=0; i<array.length; i++)
  {
    array[i].getMinimumResolution = function () {
      return min
    };
    array[i].getMaximumResolution = function () {
      return max
    };
  }
}

var tooltip;
    
//Loads the map and sets the event listeners
function loadMap( showReportOptions ) 
{
/*  if ( showReportOptions )
  {
    getReportOpotionsCookies();
    validReportOptions();
  }*/

  if (GBrowserIsCompatible())
  {
    map = new GMap2(document.getElementById("map"));
      		
    //addBlocksMap();
      		
    /*
      		var ov = new GOverviewMapControl(); 
      		map.addControl(ov);       		
				ov.hide(true); 
				*/     
						
    //map.setCenter(new GLatLng(-2, -79), 7);									//Ecuador
    map.setCenter(new GLatLng(-1.831239, -78.183406), 7);									//Ecuador

    //map.addMapType(G_PHYSICAL_MAP);
    map.addMapType(G_SATELLITE_3D_MAP);

    var mapType = getCookie( 'mapType' );
      		
    map.setMapType(G_NORMAL_MAP);
    if( mapType == 'Híbrido' )
      map.setMapType(G_HYBRID_MAP)
    else if ( mapType == 'Satélite' )
      map.setMapType(G_SATELLITE_MAP);
      				
    map.addControl(new GMapTypeControl());
    map.addControl(new GOverviewMapControl());
    map.addControl(new GSmallMapControl());
    map.addControl(new GScaleControl());
            
    //map.enableScrollWheelZoom();
                 
    map.getDragObject().setDraggableCursor( "crosshair" );
    map.getDragObject().setDraggingCursor( "move" );

    // ====== set up marker mouseover tooltip div ======
    tooltip = document.createElement("div");
    map.getPane(G_MAP_FLOAT_PANE).appendChild( tooltip );
    tooltip.style.visibility = "hidden";
      
    if ( showReportOptions )
    {
      //Set listener for "singlerightclick"
      GEvent.addListener(map, "singlerightclick", onSingleRightClick);
    }
            
    //Set listener for "zoomend"
    GEvent.addListener(map, "zoomend", OnZoomEnd);
    //Set listener for "moveend"
    GEvent.addListener(map, "moveend", function(){
      OnMoveEnd();
    });
    //Set listener for "maptypechanged"
    GEvent.addListener(map, "maptypechanged", function(){
      OnMapTypeChanged();
    });
   			
    GEvent.addListener(map, "infowindowclose", function() {
      if ( currentMarker.isInfoWindowOpen )
      {
        map.setCenter( currentMarker.getLatLng() );
        currentMarker.isInfoWindowOpen  = false;
      }
    });
   			
    zoomLevels(6, 17);
  }

  if ( showReportOptions )
  {
    getReportOpotionsCookies();
    validReportOptions();
  }
}
/* para la version 2
		function CustomGetTileUrl(a,b) 
		{
			//var z = 17 - b;
			var z = b;
			var f = "http://vts.nuestroserver.com/images/tiles/Tile_"+a.x+"_"+a.y+"_"+z+".png";
			return f;
		}
		
	var custommap = null;
	
    function addBlocksMap()
    {    	
    	if ( custommap == null )
    	{
			var copyCollection = new GCopyrightCollection('RDS');
			var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "©2009 Rastreo Directo Satelital");
			copyCollection.addCopyright(copyright);
			
			var tilelayers = [new GTileLayer(copyCollection, 5, 17)];
			tilelayers[0].getTileUrl = CustomGetTileUrl;
			
			custommap = new GMapType(tilelayers, new GMercatorProjection(17), "Rastreo Directo Satelital", {errorMessage:"No disponemos mapa para este sector"});
			custommap.getMinimumResolution = function () { return 13 };
			custommap.getMaximumResolution = function () { return 13 };
			map.addMapType(custommap);
		}
	}
	
	function delBlocksMap()
	{
		if ( custommap )
		{
			map.removeMapType( custommap );
			delete custommap;
			custommap = null;
		}
	}
*/	



//*************************************************************************************************
	
function showReportOptions()
{
  var report_options = document.getElementById('report_options');
  if( report_options )
  {
    report_options.style.visibility = "visible"; ////hidden
    report_options.style.height = "100%";
  }
		
  var symbol = document.getElementById('symbol');
  if( symbol )
    symbol.innerHTML = "<a class='linkh4' title='Ocultar opciones de los reportes' href='javascript:hideReportOptions()'><img src='../images/minus.gif' width=12px height=12px style='vertical-align: middle; border-top-width: 2px; margin-top: -3px; //margin-top: 0px;'/>&nbsp;Opciones</a>";
}
	
function hideReportOptions()
{
  validReportOptions();
		
  var report_options = document.getElementById('report_options');
  if( report_options )
  {
    report_options.style.visibility = 'hidden';
    report_options.style.height = '0px';
  }
		
  var symbol = document.getElementById('symbol');
  if( symbol )
    symbol.innerHTML = "<a class='linkh4' title='Mostrar opciones de los reportes' href='javascript:showReportOptions()'><img src='../images/plus.gif' width=12px height=12px style='vertical-align: middle; border-top-width: 2px; margin-top: -3px; //margin-top: 0px;'/>&nbsp;Opciones</a>";
		
  if (IsCalendarVisible)
  {
    hideCalendar();
  }
}
	


//***********************************************************************************************
	
function playSound()
{
  var bgSound = document.getElementById("sound");
  if ( bgSound )
    bgSound.src='../sounds/updated.wav';
}

function AXAJVehiclePos( vehicleID )
{
  Ajax.elemetMessage = 'loadingbox';
  var strParam="services/services.php?method=getVehiclePos&id="+vehicleID;
   		  	
  if ( ajaxRequest != null )
  {
    if ( ajaxRequest.readyState < 3 )
    {
      var chkObject = document.getElementById('chk' + ajaxRequest.vehicleID);
      if ( chkObject )
        chkObject.checked = false;
		  				
      ajaxRequest.abort();
      ajaxRequest = Ajax.Request(strParam, showVehiclePos);
      ajaxRequest.vehicleID = vehicleID;
    }
    else
    {
      alert("Existe una petición en curso.\nPor favor, inténtelo más tarde.");
		  			
      chkObject = document.getElementById('chk' + vehicleID);
      if ( chkObject )
        chkObject.checked = false;
    }
  }
  else
  {
    ajaxRequest = Ajax.Request(strParam, showVehiclePos);
    if ( ajaxRequest )
      ajaxRequest.vehicleID = vehicleID;
  }
}	
			
function refreshVehiclePos( vehicleID )
{
  var vehicle = findVehicle( vehicleID );
  if ( vehicle != null )		// showed Vehicle
    hideVehiclePos( vehicle, true, true );

  AXAJVehiclePos( vehicleID );
}
	
function start_stopUpdatePos( vehicleID )
{
  var updatePos = document.getElementById('updatePos');
  var vehicle = findVehicle( vehicleID );
  if ( ( vehicle != null ) && ( updatePos ) )
  {
    if ( ! updatePos.checked )
    {
      clearTimeout( vehicle.t );
      setCookie( vehicleID, '0', 365 ); 			// 0 => NOT update vehicle POS
    }
    else
    {
      if ( eval( getCookie( 'updatePos' ) ) )
        vehicle.t = setTimeout('refreshVehiclePos(' + vehicle.ID + ')', getCookie( 'updatePosTime' ) * 60000 ); // 1min = 60seg * 1000mseg
      setCookie( vehicleID, '1', 365 );		// 1 => Update vehicle POS
    }
  }
}

function showVehicle( vehicleID, chkElementID )
{
  var vehicle = findVehicle( vehicleID );
  var chkElement = document.getElementById( chkElementID );
  if ( chkElement && ( chkElement.checked ) )
  {
    if ( vehicle == null )	// load Vehicle POS
    {
      AXAJVehiclePos( vehicleID );
    }
    else	// show Vehicle
    {
      if ( document.getElementById( 'map' ) )
      {
        map.addOverlay( vehicle );
        map.setCenter( vehicle.getPoint(), map.Zoom );
        currentMarker = vehicle;
        highlightMarker();
      }
    }
  }
  else	//hide Vehicle
  {
    if ( ajaxRequest && ( ajaxRequest.vehicleID == vehicleID ) )
    {
      var chkObject = document.getElementById('chk' + ajaxRequest.vehicleID);
      if ( chkObject )
        chkObject.checked = false;
		  				
      ajaxRequest.abort();
      document.getElementById('loadingbox').innerHTML = '';
      ajaxRequest = null;
    }
   				
    if ( vehicle != null )
    {
      hideVehiclePos( vehicle, true, false );
    }
  }
}
   	
function getResponsibles( sCount, sResponsibles )
{
  var strResponsibles = '';
  var arrResponsibles = sResponsibles.split('_@_');
  for ( i = 0; i < sCount; i++ )
  {
    var arrData = arrResponsibles[i].split('_$$_');
    strResponsibles += "Nombre: " + arrData[0] + "\nDirección: " + arrData[1] + "\nTeléfono: " + arrData[2] + "\nMás: " + arrData[3] + "\n\n";
  }

  return strResponsibles;
}

function showVehiclePos()
{
  if( ( Ajax.CheckReadyState(Ajax.request) ) )
  {
    var response = Ajax.request.responseText.split('_$_');

    if ( !( ( response[3] === undefined ) && ( response[4] === undefined ) ) && 
      !( ( response[3] == '' ) && ( response[4] == '' ) ) &&
      !( ( response[3] == '0' ) && ( response[4] == '0' ) ) )
      {
      var vehicle = findVehicle( response[0] ); // response[0] = vehicleID
      if ( vehicle == null )                    // create Vehicle Marker
      {
        var vehicleName = ( response[12] == "" ) ? response[11] : response[12] + " (" + response[11] + ")";
        var icon = response[13];
        var color_tour = response[14];
        var photo = response[15];
	            	
        var vehicleIcon = new GIcon(G_DEFAULT_ICON, "images/icons/" + icon );
        vehicleIcon.printImage = defaultImgURL;
        vehicleIcon.mozPrintImage = defaultImgURL;
	
        vehicle = new GMarker( new GLatLng(response[3], response[4]), {
          icon: vehicleIcon,
          draggable: false,
          title: vehicleName
        } );
        vehicle.ID = response[0];
					
        updatePosTime = eval( getCookie( 'updatePos' ) );
        if ( updatePosTime == null )
          updatePosTime = '0';
						
        if ( updatePosTime != '0' )	// '0' => NOT update vehicle POS
        {
          updatePosTime = eval( getCookie( 'updatePosTime' ) );
          if ( ( getCookie( vehicle.ID ) == null ) || ( getCookie( vehicle.ID ) == '1' ) )
            vehicle.t = setTimeout('refreshVehiclePos(' + vehicle.ID + ')', updatePosTime * 60000 ); // 1min = 60seg * 1000mseg
        }

        sResponsibles = '...';
        if ( response[18] > 0 )
          sResponsibles = getResponsibles( response[18], response[19] );

        // Add click event function
        GEvent.addListener( vehicle, "click", function(){
          currentMarker = vehicle;
          currentMarker.isInfoWindowOpen = true;
          highlightMarker();
	            	
          strInfoHTML = createInfoHTML( response[0], vehicleName , response[1] + ' ' + response[2], response[9], response[10], response[3], response[4], response[7], response[5], response[6], response[8], true );
          var htmlTab1 = new GInfoWindowTab("Datos", strInfoHTML);
          strInfoHTML = createMoreInfoHTML( response[0], vehicleName , response[16], sResponsibles, true );
          var htmlTab2 = new GInfoWindowTab("Más...", strInfoHTML);
          strReportHTML = createReportHTML( response[0], vehicleName , response[1] + ' ' + response[2], response[17], true );
          var htmlTab3 = new GInfoWindowTab("Reportes", strReportHTML);
          strImageHTML = createImageHTML( photo );
          var htmlTab4 = new GInfoWindowTab("Imagen", strImageHTML);
											
          htmlTabs = [htmlTab1, htmlTab2, htmlTab3, htmlTab4];
          vehicle.openInfoWindowTabsHtml( htmlTabs );
        });
	            
        if ( Q1.getElementById( 'map' ) )
        {
          map.addOverlay( vehicle );
          map.setCenter( vehicle.getPoint(), map.Zoom );
          currentMarker = vehicle;
          highlightMarker();
	            	
          vehicle.Pos = gVehicles.length;
          gVehicles.push( vehicle );

          var updatePos = document.getElementById('updatePos');
          if ( ( updatePos ) && ( updatePos.checked ) )
            showTour( vehicle.ID );
        }
        else
        {
          alert( 'ERROR: Mapa no encontrado...' );
        }
      }
      else	// update Vehicle Marker
      {
        vehicle.setLatLng(  new GLatLng(response[3], response[4]) );
        map.addOverlay( vehicle );
        currentMarker = vehicle;
        highlightMarker();

        if ( ( vehicle.Tour != null ) && ( getRadioButtonChecked( document.report.options ) == 2 ) )
          showTour( vehicle.ID );
      }
      playSound();
    }
    else
    {
      alert( "ERROR: Última posición indefinida." );
      var chkObject = document.getElementById('chk' + ajaxRequest.vehicleID);
      if ( chkObject )
        chkObject.checked = false;
    }
			
    ajaxRequest = null;
  }
  else if ( Ajax.request.readyState == 4 )
  {
    chkObject = document.getElementById('chk' + ajaxRequest.vehicleID);
    if ( chkObject )
      chkObject.checked = false;
  				
    ajaxRequest = null;
  }
}
	


//**********************************************************************************************************************************************

function hideVehicleTour( vehicle )
{
  if ( !( vehicle.TourPolyline === undefined ) && !( vehicle.Tour === undefined ) &&
    !( vehicle.TourPolyline == null ) && !( vehicle.Tour == null ) )
    {
    for( i = 0; i < vehicle.Tour.length; i++ )
      map.removeOverlay( vehicle.Tour[i] );

    map.removeOverlay( vehicle.TourPolyline );	// Delete vehicle tour polyline from GMap
    delete vehicle.TourPolyline;                // Destroy vehicle tour polyline
  }
		
  deleteHighlightCircle();
}
	
function hideVehiclePos( vehicle, blnHideVehicleTour, blnDestroyVehicle )
{
  if ( blnHideVehicleTour )
    hideVehicleTour( vehicle );
		
  clearTimeout( vehicle.t );
		
  if ( currentMarker == vehicle )
    deleteHighlightCircle();
		
  map.removeOverlay( vehicle );					// Delete vehicle from GMap
  if ( blnDestroyVehicle )
  {
    gVehicles.splice( vehicle.Pos, 1 );	// Delete vehicle from array of Vehicles
    delete vehicle;                     // Destroy vehicle
  }
}
	
function centerToVehicle( vehicleID )
{
  var vehicle = findVehicle( vehicleID );
  if ( vehicle != null )
  {
    map.setCenter( vehicle.getPoint(), map.Zoom );
    currentMarker = vehicle;
    highlightMarker();
  }
}



//**********************************************************************************************

function showTour( vehicleID )
{
  validReportOptions();	// To valid report options
  var vehicle = findVehicle( vehicleID );
  if ( vehicle != null )
  {
    hideVehicleTour( vehicle );
   			
    Ajax.elemetMessage = 'loadingbox';
    var strParam="services/services.php?method=getVehicleTour&id="+vehicleID;
    Ajax.Request(strParam, showVehicleTour);
  }
}
   
function showTooltip( marker ) 
{
  tooltip.innerHTML = marker.tooltip;
  var point = map.getCurrentMapType().getProjection().fromLatLngToPixel( map.fromDivPixelToLatLng( new GPoint(0,0), true ), map.getZoom() );
  var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel( marker.getLatLng(), map.getZoom() );
  var anchor = marker.getIcon().iconAnchor;
  var width = marker.getIcon().iconSize.width;
  var height = tooltip.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));
			
  //var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x + width, offset.y - point.y));
  pos.apply( tooltip );
  tooltip.style.visibility = "visible";
}
      
function showVehicleTourPos( vehicleInfo )
{
  var tourPos = new GMarker( new GLatLng(vehicleInfo[3], vehicleInfo[4]), {
    icon: getCourseIcon( vehicleInfo[6] ),
    draggable: false
  } );
			
  tourPos.tooltip = '<div class="tooltip"><nobr>';
  tourPos.tooltip += '<table>';
  tourPos.tooltip += '<tr>';
  tourPos.tooltip += ' <td colspan="2">'
  tourPos.tooltip += '     &nbsp;Vehículo: ' + vehicleInfo[0];
  tourPos.tooltip += ' </td>'
  tourPos.tooltip += '</tr>';
  tourPos.tooltip += '<tr>';
  tourPos.tooltip += ' <td colspan="2">';
  tourPos.tooltip += '     &nbsp;Fecha y Hora: ' + vehicleInfo[1] + ' ' + vehicleInfo[2] + '<hr>';
  tourPos.tooltip += ' </td>';
  tourPos.tooltip += '</tr>';
  tourPos.tooltip += '<tr>';
  tourPos.tooltip += ' <td>';
  tourPos.tooltip += '    &nbsp;Latitud: ' + vehicleInfo[3];
  tourPos.tooltip += ' </td>';
  tourPos.tooltip += ' <td>';
  tourPos.tooltip += '    &nbsp;Velocidad: ' + vehicleInfo[5] + '<br>';
  tourPos.tooltip += ' </td>';
  tourPos.tooltip += '</tr>';
  tourPos.tooltip += '<tr>';
  tourPos.tooltip += ' <td>';
  tourPos.tooltip += '    &nbsp;Longitud: ' + vehicleInfo[4];
  tourPos.tooltip += ' </td>';
  tourPos.tooltip += ' <td>';
  //  tourPos.tooltip += '    &nbsp;Curso: ' + vehicleInfo[6] + '<br>';
  tourPos.tooltip += '    &nbsp;Curso: ' + getCourseSymb( vehicleInfo[6] ) + '<br>';
  tourPos.tooltip += ' </td>';
  tourPos.tooltip += '</tr>';
  tourPos.tooltip += '<tr>';
  tourPos.tooltip += ' <td>';
  tourPos.tooltip += '    &nbsp;Altitud: ' + vehicleInfo[7];
  tourPos.tooltip += ' </td>';
  tourPos.tooltip += ' <td>';
  tourPos.tooltip += '    &nbsp;Satélites: ' + vehicleInfo[8] + '<br>';
  tourPos.tooltip += ' </td>';
  tourPos.tooltip += '</tr>';
  tourPos.tooltip += '</table>';
  tourPos.tooltip += '<\/nobr><\/div>';

  //  ======  The new tourPos "mouseover" and "mouseout" listeners  ======
  GEvent.addListener(tourPos, "mouseover", function()
  {
    showTooltip(tourPos);
  });

  GEvent.addListener(tourPos, "mouseout", function()
  {
    tooltip.style.visibility = "hidden"
  });
        			
  if ( Q1.getElementById( 'map' ) )
    map.addOverlay( tourPos );
  else
    alert( 'ERROR: Mapa no encontrado...' );

  return tourPos;
}
   		
function showVehicleTour()
{
  if( Ajax.CheckReadyState(Ajax.request) )
  {
    vehiclesInfo = Ajax.request.responseText.split('_@_');
    vehicleTour = new Array();
    vehicleTourVertex = new Array();
			
    vehicleInfo = vehiclesInfo[vehiclesInfo.length - 1].split('_$_');
    vehicleID = vehicleInfo[0];
    vehicleColorTour = vehicleInfo[1];
            
    for( i = 0; i < vehiclesInfo.length - 1; i++ )
    {
      vehicleInfo = vehiclesInfo[i].split('_$_');
				
      if ( ( vehicleInfo[3] !== undefined ) && ( vehicleInfo[4] !== undefined ) )
      {
        newPos = showVehicleTourPos( vehicleInfo );
        vehicleTour.push( newPos );
        vehicleTourVertex.push( newPos.getLatLng() );
					
        playSound();
      }
    }
			
    vehicle = findVehicle( vehicleID );
    if ( vehiclesInfo.length == 1 )
    {
      alert( "No se dispone información del recorrido del dispositivo.\n\nPor favor, cambie las opciones de los reportes e inténtelo nuevamente." );
      if ( vehicle != null )
      {
        vehicle.TourPolyline = null;
        vehicle.Tour = null;
      }
    }
    else if ( vehicle != null )
    {
      var vehicleTourPolyline = new GPolyline( vehicleTourVertex, vehicleColorTour, 1, 1 );
      map.addOverlay( vehicleTourPolyline );
      vehicle.TourPolyline = vehicleTourPolyline;
      vehicle.Tour = vehicleTour;
    }
  }
}
	


//**********************************************************************************************
	
function findVehicle( vehicleID )
{
  var result = null;

  if ( vehicleID != "" )
  {
    var i = 0;
    while ( ( i < gVehicles.length ) && ( result == null ) )
    {
      if ( gVehicles[i].ID == vehicleID )
        result = gVehicles[i];
      i++
    }
  }
		
  return result;
}
	
function createInfoHTML( sVehicleID, sVehicleName, sDateTime, sStreet, sNearestPoint, sLat, sLng, sAltitude, sSpeed, sHeading, sSatellites, showLinks )
{
  var strHTML = "";
	    
  strHTML = strHTML + "<table class='tbInfo' border='0' width='360px' >";
  strHTML = strHTML + "	<tbody>";
  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'>Vehículo: " + sVehicleName + "</td>";
  strHTML = strHTML + "		</tr>";
	    
  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'>Fecha y Hora: " + sDateTime + "</td>";
  strHTML = strHTML + "		</tr>";
	    
  strHTML = strHTML + "		<tr height='10'>";
  strHTML = strHTML + "			<td colspan='4'><hr></td>";
  strHTML = strHTML + "		</tr>";

  (sStreet != '') ? sStreet = 'Calle ' + sStreet : sStreet += '...';
  (sNearestPoint != '') ? sNearestPoint = 'Cerca de ' + sNearestPoint : sNearestPoint = '...';
  sUbicacion = 'Ubicación: ' + "<br/>&nbsp;&nbsp;&nbsp;" + sStreet + "<br/>&nbsp;&nbsp;&nbsp;" + sNearestPoint;

  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'>" + sUbicacion + "</td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + "		<tr height='10'>";
  strHTML = strHTML + "			<td colspan='4'><hr></td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td align='left'>Latitud:</td>";

  try { 
    sLat = sLat.replace(",", ".");
  } catch( ex ) {}
  var lat = new oNumero( sLat );
  strHTML = strHTML + "			<td align='left'>" + lat.formato(8, false) + "</td>";

  strHTML = strHTML + "			<td align='left'>&nbsp;&nbsp;Velocidad: </td>";

  try { 
    sSpeed = sSpeed.replace(",", ".");
  } catch( ex ) {}
  var Speed = new oNumero( sSpeed );
  strHTML = strHTML + "			<td align='left'>" + Speed.formato(2, false) + " Km/h</td>";

  strHTML = strHTML + "		</tr>";
  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td align='left'>Longitud: </td>";

  try { 
    sLng = sLng.replace(",", ".");
  } catch( ex ) {}
  var lng = new oNumero( sLng );
  strHTML = strHTML + "			<td align='left'>" + lng.formato(8, false) + "</td>";

  strHTML = strHTML + "			<td align='left'>&nbsp;&nbsp;Orientación: </td>";
  strHTML = strHTML + "			<td align='center'>" + getCourseSymb(sHeading) + "</td>";
  strHTML = strHTML + "		</tr>";
  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td align='left'>Altitud: </td>";
  strHTML = strHTML + "			<td align='left'>" + sAltitude + " msnm</td>";
  strHTML = strHTML + "			<td align='left'>&nbsp;&nbsp;Satélites: </td>";
  strHTML = strHTML + "			<td align='center'>" + sSatellites + "</td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + "		<tr height='10'>";
  strHTML = strHTML + "			<td colspan='4'><hr></td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='2' align='left'> <a href='javascript:showTour(" + sVehicleID + ")'> Mostrar Recorrido </a> </td>";
  strHTML = strHTML + "			<td colspan='2' align='right'> <a href='javascript:refreshVehiclePos(" + sVehicleID + ")'> Actualizar Posición </a> </td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + "	</tbody>";
  strHTML = strHTML + "</table>";
	    
  return strHTML;
}

function createMoreInfoHTML( sVehicleID, sVehicleName, sVehicleMore, sResponsibles, showLinks )
{
  var strHTML = "";

  strHTML = strHTML + "<table class='tbInfo' width='360px'>";
  strHTML = strHTML + " <tbody>";

  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'>Vehículo: " + sVehicleName + "</td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'><textarea class='txInfo' rows='5' cols='48' readOnly='true'>" + sVehicleMore + "</textarea></td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'>Responsables: </td>";
  strHTML = strHTML + "		</tr>";
  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'><textarea class='txInfo' rows='6' cols='48' readOnly='true'>" + sResponsibles + "</textarea></td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + " </tbody>";
  strHTML = strHTML + "</table>";

  return strHTML;
}

function createReportHTML( sVehicleID, sVehicleName, sDateTime, sRptOptions,showLinks )
{
  var strHTML = "";

  strHTML = strHTML + "<table class='tbInfo' width='360px'>";
  strHTML = strHTML + "	<tbody>";

  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'>Vehículo: " + sVehicleName + "</td>";
  strHTML = strHTML + "		</tr>";

  strHTML = strHTML + "		<tr height='19'>";
  strHTML = strHTML + "			<td colspan='4' align='left'>Fecha y Hora: " + sDateTime + "</td>";
  strHTML = strHTML + "		</tr>";

  if ( showLinks )
  {
    var rptTravelOptions = String(sRptOptions).substr(0, 12);
    var rptStopsOptions = String(sRptOptions).substr(12, 12);
    var rptAlarmsOptions = String(sRptOptions).substr(24, 12);
    var rptEventsOptions = String(sRptOptions).substr(36, 12);

    strHTML = strHTML + "		<tr height='10'>";
    strHTML = strHTML + "			<td colspan='4'><hr></td>";
    strHTML = strHTML + "		</tr>";

    strHTML = strHTML + "		<tr height='19'>";
    strHTML = strHTML + "			<td colspan='4' align='left'> &nbsp;&nbsp;&nbsp;<a href=http://" + window.location.hostname + "/reports/vehicle_report.php?vhc_id=" + sVehicleID + "&vhc_name=" + escape( sVehicleName ) + "&rpt_options=" + escape(rptTravelOptions) + " target='_blank'>Reporte de Recorrido </a> </td>";
    strHTML = strHTML + "		</tr>";
    strHTML = strHTML + "		<tr height='19'>";
    strHTML = strHTML + "			<td colspan='4' align='left'> &nbsp;&nbsp;&nbsp;<a href=http://" + window.location.hostname + "/reports/stops_report.php?vhc_id=" + sVehicleID + "&vhc_name=" + escape( sVehicleName ) + "&rpt_options=" + escape(rptStopsOptions)  + " target='_blank'>Reporte de Paradas </a> </td>";
    strHTML = strHTML + "		</tr>";

    strHTML = strHTML + "		<tr height='19'>";
    strHTML = strHTML + "			<td colspan='4' align='left'> &nbsp;&nbsp;&nbsp;<a href=http://" + window.location.hostname + "/reports/alarm_report.php?vhc_id=" + sVehicleID + "&vhc_name=" + escape( sVehicleName ) + "&rpt_options=" + escape(rptAlarmsOptions)  + " target='_blank'>Reporte de Alarmas </a> </td>";
    strHTML = strHTML + "		</tr>";
    strHTML = strHTML + "		<tr height='19'>";
    strHTML = strHTML + "			<td colspan='4' align='left'> &nbsp;&nbsp;&nbsp;<a href=http://" + window.location.hostname + "/reports/events_report.php?vhc_id=" + sVehicleID + "&vhc_name=" + escape( sVehicleName ) + "&rpt_options=" + escape(rptEventsOptions)  + " target='_blank'>Reporte de Eventos </a> </td>";
    strHTML = strHTML + "		</tr>";

    strHTML = strHTML + "		<tr height='10'>";
    strHTML = strHTML + "			<td colspan='4'><hr></td>";
    strHTML = strHTML + "		</tr>";

    strHTML = strHTML + "		<tr height='19'>";
    if ( getCookie( sVehicleID ) == '0' )	// NO update vehicle position
      strHTML = strHTML + "			<td colspan='4' align='center'> <input type='checkbox' id='updatePos' onchange='javascript:start_stopUpdatePos(" + sVehicleID + ")'/> Actualizar posición automáticamente</td>"
    else
      strHTML = strHTML + "			<td colspan='4' align='center'> <input type='checkbox' id='updatePos' onchange='javascript:start_stopUpdatePos(" + sVehicleID + ")' checked='checked'/> Actualizar posición automáticamente</td>"
    strHTML = strHTML + "		</tr>";

  }
  strHTML = strHTML + "	</tbody>";
  strHTML = strHTML + "</table>";

  return strHTML;
}

function createImageHTML( vehiclePhoto )
{
  var strHTML = '<center><img width=180px height=180px src="/images/archs/' + vehiclePhoto + '" /></center>';

  return strHTML;
}



//**********************************************************************************************

function validReportOptions()
{
  var intTimeFrom = GetSelectedValue( document.report.timeFrom ) * 1;
  var intTimeTo = GetSelectedValue( document.report.timeTo ) * 1;
		
  var strDateFrom = document.report.dateFrom.value;
  var arrDateFrom = strDateFrom.split('-');
  var intMonth = getMonthNumber( arrDateFrom[1] );
  var objDateFrom = new Date();
  objDateFrom.setFullYear( arrDateFrom[2], intMonth, arrDateFrom[0]);
  objDateFrom.setHours(intTimeFrom, 0, 0, 0);
		
  var strDateTo = document.report.dateTo.value;
  var arrDateTo = strDateTo.split('-');
  intMonth = getMonthNumber( arrDateTo[1] );
  var objDateTo = new Date();
  objDateTo.setFullYear( arrDateTo[2], intMonth, arrDateTo[0]);
  objDateTo.setHours(intTimeTo, 0, 0, 0);
		
  if ( objDateFrom > objDateTo )
  {
    if ( strDateFrom == strDateTo )
    {
      SetValue( document.report.timeFrom, intTimeTo );
      SetValue( document.report.timeTo, intTimeFrom );
    }
    else
    {
      SetValue( document.report.dateFrom, strDateTo );
      SetValue( document.report.dateTo, strDateFrom );
    }
  }
		
  setReportOpotionsCookies();
}
	
function DateTimeSettings()
{
  document.report.options[5].checked = true;
}



//**********************************************************************************************

function enableUpdatePos()
{
  if ( document.getElementById('updatePos').checked )
  {
    //document.report.updatePosTime.disabled = false;
    document.getElementById('updatePosTime').disabled = false;
  }
  else
  {
    document.getElementById('updatePosTime').disabled = true;
  }
}
	
function setReportOpotionsCookies()
{
  setCookie( 'options', getRadioButtonChecked(document.report.options), 365 );
  setCookie( 'dateFrom', document.report.dateFrom.value, 365 );
  setCookie( 'dateTo', document.report.dateTo.value, 365 );
  setCookie( 'timeFrom', GetSelectedValue( document.report.timeFrom ), 365 );
  setCookie( 'timeTo', GetSelectedValue( document.report.timeTo ), 365 );
		
  setCookie( 'updatePos', document.getElementById('updatePos').checked, 365 );
  setCookie( 'updatePosTime', GetSelectedValue( document.report.updatePosTime ), 365 );
		
  setCookie( 'showLocations', document.getElementById('showLocations').checked, 365 );
  setCookie( 'showGeofences', document.getElementById('showGeofences').checked,365 )
}
	
function getReportOpotionsCookies()
{
  var optionSelected = getCookie('options');
  if (( !optionSelected ) || ( optionSelected == "" ) )
    optionSelected = 2;
			
  setRadioButtonChecked( document.report.options, optionSelected );
    	
  if ( optionSelected == 5 )
  {
    document.report.dateFrom.value = getCookie('dateFrom');
    document.report.dateTo.value = getCookie('dateTo');
    SetSelectedValue(document.report.timeFrom, getCookie('timeFrom') );
    SetSelectedValue(document.report.timeTo, getCookie('timeTo') );
  }
  else
  {
    switch( optionSelected )
    {
      case '0': OnQuickRangeChange('report', 'DayBeforeYesterday'); break;
      case '1': OnQuickRangeChange('report', 'Yesterday'); break;
      case '2': OnQuickRangeChange('report', 'Today'); break;
      case '3': OnQuickRangeChange('report', 'ThisWeek'); break;
      case '4': OnQuickRangeChange('report', 'LastWeek'); break;
    }
  }
    	
  document.getElementById('updatePos').checked = eval( getCookie( 'updatePos' ) );
  SetSelectedValue(document.report.updatePosTime, getCookie('updatePosTime') );
  enableUpdatePos();
    	
  document.getElementById('showLocations').checked = eval( getCookie( 'showLocations' ) );

  if ( eval( getCookie( 'showGeofences' ) ) ) {
    document.getElementById('showGeofences').checked = true;
  }
//  document.getElementById('showGeofences').checked = eval( getCookie( 'showGeofences' ) );
}
	

    
//**********************************************************************************************
    
function onSingleRightClick( point )
{
  createLocation( point );
}
    
function OnZoomEnd(oldLevel, newLevel)
{
  //alert("Zoom Level " + newLevel );
  /* para la versión 2
		if ( newLevel == 13)
			addBlocksMap();
		else
			delBlocksMap();
		*/
			
  //Remember GMap ZoomLevel
  setCookie( "zoomLevel", newLevel, 364*3 );
	    
  if ( ( newLevel >= 7 ) && ( newLevel <= 17 ) )
  {
    var rdbZoom = document.getElementsByName('rdbZoom');
    if ( rdbZoom )
      setRadioButtonChecked( rdbZoom, 17 - newLevel );
  }
	    
  highlightMarker();
}
	
function OnMoveEnd()
{
  //Remember GMap position
  setCookie( "centerLng", map.getCenter().lng(), 364*3 );
  setCookie( "centerLat", map.getCenter().lat(), 364*3 );
}
	
function OnMapTypeChanged()
{
  //Remember GMap Type
  setCookie( "mapType", map.getCurrentMapType().getName(), 364*3 );
}

