//Clase TMapa que comunica con la interfaz de google maps.

//array global necesario para mantener los eventos de las marcas de los trayectos.
var t = new Array();

var TMapa = function ()
{
    //atributos publicos
    this.base_url = base;
    this.mapa = null;
}

TMapa.prototype.crearMapa = function(idmapa,posX,posY,zoom)
{
    if (GBrowserIsCompatible())
    {
        this.mapa = new GMap2(document.getElementById(idmapa));
        this.mapa.setCenter(new GLatLng(posY,posX),zoom);

        this.mapa.setUIToDefault();
    }
}

TMapa.prototype.pintarPuntos = function(data,bocadillo,centrado)
{
    this.mapa.clearOverlays();

    var cuantos = data.length;
    for(i=0;i<cuantos;i++)
    {
        var latlng = new GLatLng(data[i].lat,data[i].lon);

        marca = this.crearMarca(latlng, 1, this.base_url + icons_folder + data[i].icono, 30, 30, 15, 15);
        this.mapa.addOverlay(marca);
		
        if(bocadillo)
            this.crearBocadillo(latlng,data[i]);

        if(centrado)
            this.centrarPunto(data);
    }
}

TMapa.prototype.pintarTrayecto = function(data)
{
    this.mapa.clearOverlays();
    var poli = new Array();
    var marca;

    for ( i=0 ; i < data.length ; i++ )
    {
        var tr = data[i].trayecto;

        for ( j=0 ; j < tr.length ; j++ )
        {
            t[j] = tr[j];
            punto = new GLatLng(tr[j].lat,tr[j].lon);
            if ( j != 0  && j != tr.length-1)
            {
                if(tr[j].kmh > 0)
                {
                    marca = this.crearMarca(punto,j,base + 'application/views/client/static/images/maps/marker_green.png',10,17,5,17)
                }
                else if(tr[j].status <= 0)
                {
                    marca = this.crearMarca(punto,j,base + 'application/views/client/static/images/maps/marker.png',10,17,5,17)
                }
                else
                {
                    marca = this.crearMarca(punto,j,base + 'application/views/client/static/images/maps/marker_grey.png',10,17,5,17)
                }
                //obtengo el siguiente punto
                //obtener el punto medio
                //dibujar la flecha segun la direccion
            }
            else if ( j == tr.length-1 )
            {
                marca = this.crearMarca(punto,j,base + 'application/views/client/static/images/maps/red_flag.png',24,20,0,20)
                this.mapa.addOverlay(marca);
            }
            else if( j == 0 )
            {
                marca = this.crearMarca(punto,j,base + 'application/views/client/static/images/maps/green_flag2.png',24,20,0,20)
                this.mapa.addOverlay(marca);

                //obtener el siguiente punto
                //obtener el punto medio
                //dibujar la flecha segun la direccion
            }

            //evento de bocadillo
            
            poli[j] = punto;
        }

        polyline = new GPolyline(poli,data[i].color, 5, 0.8);
        this.mapa.addOverlay(polyline);
    }
}

TMapa.prototype.crearMarca = function(latlng,numero,img,tx,ty,ax,ay)
{
    var icono = new GIcon(G_DEFAULT_ICON);
    var tam = new GSize(tx,ty);
    icono.iconSize = tam;

    if(img != '')
    {
        icono.image = img;
        icono.iconAnchor = new GPoint(ax, ay);
        icono.shadow = null;
    }

    markerOptions = { icon:icono };
    var marca = new GMarker(latlng,markerOptions);
    marca.value = numero;

    GEvent.addListener(marca,"click",function(){
        geo = new GClientGeocoder(false);
        geo.getLocations(latlng,
            function(response)
            {
                if (!response || response.Status.code != 200)
                {
                    direccion = "error: "+ response.Status.code;
                }
                else
                {
                     place = response.Placemark[0];
                     direccion = place.address;
                     if(!direccion || direccion.length == 0)
                     {
                         direccion = "direccion desconocida."
                     }
                }
				
                //utiliza la libreria date.js del directorio 'js/public

                fecha_formateada = Date.parse(t[numero].fechahora).toString('d / M / yyyy, HH : mm : ss');
				
                var mensaje = "Fecha y Hora: "+ fecha_formateada +"<br/>";
                mensaje+= "Latitud: "+ t[numero].lat +"  ";
                mensaje+= "Longitud: "+ t[numero].lon +"<br/>";
                mensaje+= "Direccion: "+ direccion +"<br/>";
                //mensaje+= "Rubmo: "+ t[numero].dir +"<br/>";
                mensaje+= "Velocidad: "+ t[numero].kmh +" km/h<br/>";
                //mensaje+= "Io: "+ t[numero].io +"<br/>";
                var myHtml = mensaje;
                mapaObj.mapa.openInfoWindowHtml(latlng,myHtml);
            }
        );
    });

    this.mapa.addOverlay(marca);

    return marca;
}

TMapa.prototype.crearBocadillo = function(latlng,datos)
{
    geo = new GClientGeocoder(false);
    geo.getLocations(latlng,
        function(response)
        {
            if (!response || response.Status.code != 200)
            {
                direccion = "error: "+ response.Status.code;
            }
            else
            {
                 place = response.Placemark[0];
                 direccion = place.address;
                 if(!direccion || direccion.length == 0)
                 {
                     direccion = "direccion desconocida."
                 }
            }

            //utiliza la libreria date.js del directorio 'js/public
				
            fecha_formateada = Date.parse(datos.fechahora).toString('d / M / yyyy, HH : mm : ss');

            var mensaje = "Fecha y Hora: "+ fecha_formateada +"<br/>";
            mensaje+= "Latitud: "+ datos.lat +"  ";
            mensaje+= "Longitud: "+ datos.lon +"<br/>";
            mensaje+= "Direccion: "+ direccion +"<br/>";
            //mensaje+= "Sentido: "+ datos.dir +"<br/>";
            mensaje+= "Velocidad: "+ datos.kmh +" km/h<br/>";
            //mensaje+= "Io: "+ datos.io +"<br/>";
            var myHtml = mensaje;
            mapaObj.mapa.openInfoWindowHtml(latlng,myHtml);
        }
    );
}

TMapa.prototype.centrarPunto = function(datos)
{
    var latMax=-1000,latMin=1000,lngMax=-1000,lngMin=1000;
    var cuantos = datos.length;
    for(i=0;i<cuantos;i++)
    {
        if(datos[i].lat >= latMax)
        {
                latMax = datos[i].lat;
        }
        if(datos[i].lat <= latMin)
        {
                latMin = datos[i].lat;
        }
        if(datos[i].lon >= lngMax)
        {
                lngMax = datos[i].lon;
        }
        if(datos[i].lon <= lngMin)
        {
                lngMin = datos[i].lon;
        }
    }

    sw = new GLatLng(latMin,lngMin);
    ne = new GLatLng(latMax,lngMax);
    bounds = new GLatLngBounds(sw,ne);
    this.mapa.setCenter(bounds.getCenter(),this.mapa.getZoom());
}

