///////////////////////////////////////////////////////////////////////////////
//
// mapa.js
//
///////////////////////////////////////////////////////////////////////////////
//
// Este archivo es el encargado de cargar los datos y mostrarlos en el mapa
//
// 
// Autor: RB
// Fecha de Creación: 27/01/2009
// 
// Modificaciones:
// 
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// class Paginador
//  Se utiliza para el manejo de la paginacion.
///////////////////////////////////////////////////////////////////////////////
    //<![CDATA[
    //iniciacion de variables
    var iconoDefecto = new GIcon(); 
    iconoDefecto.image = 'img/mapa/azul.png';
    iconoDefecto.shadow = '';
    iconoDefecto.iconSize = new GSize(32, 40);
    iconoDefecto.shadowSize = new GSize(22, 20);
    iconoDefecto.iconAnchor = new GPoint(16, 16);
    iconoDefecto.infoWindowAnchor = new GPoint(5, 1);

    var iconoDefecto2 = new GIcon(); 
    iconoDefecto2.image = 'img/mapa/gris.png';
    iconoDefecto2.shadow = '';
    iconoDefecto2.iconSize = new GSize(32, 40);
    iconoDefecto2.shadowSize = new GSize(22, 20);
    iconoDefecto2.iconAnchor = new GPoint(16, 16);
    iconoDefecto2.infoWindowAnchor = new GPoint(5, 1);

    var customIcons = [];
    customIcons["anteriores"] = iconoDefecto2;
    customIcons["proximos"] = iconoDefecto;
    customIcons["todos"] = iconoDefecto;
    var markerGroups = { "anteriores": [], "proximos": [], "todos": [] };


    ///////////////////////////////////////////////////////////////////////////////
	// load. funcion primera en cargar 
	//               inicializa el mapa y sus variables y carga los datos de la bd 
	//
	// parameter: 
	// return: 
	// access public
	//
	// Autor: RB
	// Fecha de Creación: 27/01/2009
	//
	// Modificaciones:
	///////////////////////////////////////////////////////////////////////////////
    function load() 
    {
        if (GBrowserIsCompatible()) 
        {
            $('#eventos').attr('style','padding-bottom:1px');
            var map = new GMap2(document.getElementById("mapa"));
            map.setCenter(new GLatLng(40.463667, -3.74922), 5);
            map.disableDoubleClickZoom();
            $('#idProximo').addClass('actual');
            $('#idAnterior').removeClass('actual');
            $('#idTodos').removeClass('actual');

        
            $.ajax(
        	{
                type: "POST",
                url: "publica_generar_mapa.php",
    //             data: "contador="+contadorFoto, //Envia el país q obtuvo con el autocompletado
    //             cache: false,
    //             async: false,
                success: function(datos)
                {
                      var xml = GXml.parse(datos);
                      var markers = xml.documentElement.getElementsByTagName("marker");
                      for (var i = 0; i < markers.length; i++) 
                      {
                           var name = markers[i].getAttribute("name");
                           var label = markers[i].getAttribute("label");
                           var address = markers[i].getAttribute("address");
                           var type = markers[i].getAttribute("type");
                           var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                                parseFloat(markers[i].getAttribute("lng")));
                           var fecha = markers[i].getAttribute("fecha");
                           var hora = markers[i].getAttribute("hora");
                           hora = hora.split(":");
                           hora = hora[0]+':'+hora[1];
                           var pais = markers[i].getAttribute("pais");
                           var provincia = markers[i].getAttribute("provincia");
                           var iconoBandera = markers[i].getAttribute("icono");
                           var marker = createMarker(point, name, label, address, type,fecha, hora,pais,provincia,iconoBandera);
                           map.addOverlay(marker);
                           if (type == 'proximos')
                              marker.show();
                           else
                              marker.hide();
                      }			
        	    }           
          });
       }
    }

    ///////////////////////////////////////////////////////////////////////////////
	// createMarker. funcion para crear un marcador en el mapa 
	//               
	//
	// parameter: point,name, label, address, type, fecha, hora, pais, localidad       
	// return: marker                                   marcador
	// access public
	//
	// Autor: RB
	// Fecha de Creación: 27/01/2009
	//
	// Modificaciones:
	///////////////////////////////////////////////////////////////////////////////
    function createMarker(point, name, label, address, type,fecha, hora,pais , provincia, iconoBandera) 
    {
        if(type == 'anteriores')
        {
           var tipo = 0;
           var iconoImagen = 'anteriores';
        
        }
        
        if(type == 'proximos')
        {
           var tipo = 1;
           var iconoImagen = 'proximos';
        }
        
        if(type == 'todos')
           var tipo = 2;

        if(type == 'todos')
        {
            if(iconoBandera == '0')
                var iconoImagen = 'anteriores';
            else
                var iconoImagen = 'proximos';
        }   

        var marker = new LabeledMarker(point, {icon: customIcons[iconoImagen], labelText: label, labelOffset: new GSize(-6, -10)});
        markerGroups[type].push(marker);
                
        var html = '<div style="float:left;"><img alt="" src="img/mapa/icono_marker.png"></div>';
        html += "<b>" + name + "</b> <br/>" + address + " <strong>Fecha: </strong>"+fecha+ " <strong>Hora: </strong>"+ hora;
        GEvent.addListener(marker, 'click', function() 
        {
        
            $('#info').show();
            $.ajax(
            {
                type: "POST",
                url: "publica_generar_mapa.php",
                data: "html="+1+"&pais="+pais+"&provincia="+provincia+"&tipo="+tipo, 
                //             cache: false,
                //             async: false,
                success: function(datos)
                {
//                     alert(datos);
                    document.getElementById('info').innerHTML = datos;
                    $('#eventos').attr('style','#padding-bottom:40px; _padding-bottom:40px');
                    initPagination();
//                     $('#listaEventos').html(datos);
                    
                }           
            });        
//         marker.openInfoWindowHtml(html);
        });
        return marker;
    }

    ///////////////////////////////////////////////////////////////////////////////
	// toggleGroup. funcion para cambiar los marcadores mostrados en el mapa  
	//
	// parameter: type                 anteriores, proximos o todos
	// return: 
	// access public
	//
	// Autor: RB
	// Fecha de Creación: 27/01/2009
	//
	// Modificaciones:
	///////////////////////////////////////////////////////////////////////////////    
    function toggleGroup(type) 
    {
       $('#idProximo').removeClass('actual');
       $('#idAnterior').removeClass('actual');
       $('#idTodos').removeClass('actual');
       $('#info').hide();
       $('#info').html('');
       $('#eventos').attr('style','padding-bottom:1px');
//        $('#Pagination').removeAttr('style','padding-top:1px');
//        $('.result').hide();
//         $('.Pagination').hide();
        
        for (var i = 0; i < markerGroups['anteriores'].length; i++) 
        {   
            var marker = markerGroups['anteriores'][i];
            marker.hide();
        }
        for (var i = 0; i < markerGroups['proximos'].length; i++)
        {   
            var marker = markerGroups['proximos'][i];
            marker.hide();
        }
        for (var i = 0; i < markerGroups['todos'].length; i++)
        {   
            var marker = markerGroups['todos'][i];
            marker.hide();
        }        
                
        for (var i = 0; i < markerGroups[type].length; i++) 
        {
            var marker = markerGroups[type][i];
            if(type == 'anteriores')
                $('#idAnterior').addClass('actual');
            if(type == 'proximos')
                $('#idProximo').addClass('actual');
            if(type == 'todos')
                $('#idTodos').addClass('actual');                                
            
            marker.show();
        }
        return false; 
    }

		function pageselectCallback(page_index, jq)
    {
              var new_content = $('#hiddenresult div.result:eq('+page_index+')').clone();
              $('#Searchresult').empty().append(new_content);
              return false;
    }
         
    /** 
     * Callback function for the AJAX content loader.
     */
    function initPagination() 
    {
        var num_entries = $('#hiddenresult div.result').length;
        // Create pagination element
        $("#Pagination").pagination(num_entries, {
            num_edge_entries: 1,
            num_display_entries: 5,
            callback: pageselectCallback,
            items_per_page:1,
            prev_text: '',
            ellipse_text: '... ',
            next_text: 'siguiente >'
        });
     }
                  
    // Load HTML snippet with AJAX and insert it into the Hiddenresult element
    // When the HTML has loaded, call initPagination to paginate the elements        
//     $(document).ready(function()
//     {      
//         initPagination();
//     });

    //]]>

