// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

//if (typeof ( centerLatitud) == "undefined"){
//var centerLatitud = 37.16830555162306;//Granada
//}
//if ( typeof (centerLongitud) == "undefined"){
//var centerLongitud =  -3.5949325561523438;//Granada
//}



if ( typeof (zoom) == "undefined"){
    var zoom = 6;
}


if ( typeof (tipomarcas) == "undefined"){
    var tipomarcas = 'todoxml';

}

if ( typeof (address) == "undefined"){
    var address = null;
}

var mapa;
var geocoder;
var marca_anterior;
var localizacion =  new GLatLng(37.16830555162306,-3.5949325561523438); //Granada

function init() {
    if (GBrowserIsCompatible()) {
        mapa = new GMap2(document.getElementById("localizador"));
        mapa.addControl(new GLargeMapControl())
        mapa.addControl(new GMapTypeControl())

        

        //Buscador
        var options = {
            // Put results inline (default), can also suppress them or put them in another DOM node
            resultList: 'inline',
            // Put each result on multiple lines instead of one
            resultFormat: 'multi-line1',
            // Allow local business results, as well as KML results
            listingTypes: 'blended',
            // Only allow for 2 pages of results. (can specify 1-4)
            maxCursorPages: 2,
            zoomLimit: 16
        };
        
        mapa.addControl(new google.elements.LocalSearch(options));

        if(typeof (centerLongitud) == "undefined"){
            //------------------ Convertir direcciones en coordenadas------------------------//
            // address está definido en _registro//
            if (address != null){
                geocoder = new GClientGeocoder();
                geocoder.getLocations(address, centerInMap)
             
            }else{
                mapa.setCenter(localizacion, zoom);
            }

        }else{
            localizacion =  new GLatLng(centerLatitud,centerLongitud);
            
            mapa.setCenter(localizacion, zoom);
        }

        var geocoder;
        geocoder = new GClientGeocoder();
        //direccion = geocoder.getLocations(localizacion , showAddress);

        listMarkers(tipomarcas,zoom);


       

        // Vemos si se ha cambiado de zoom o si se ha movido el mapa
        GEvent.addListener(mapa, 'moveend', function() {
            //var center = mapa.getCenter();
            var zoom_actual = mapa.getZoom();
            if(zoom_actual != zoom){// Esto es para ver si nos hemos movido o si hemos hecho zoom
                // Se definen 3 niveles de detalle Provincias, ciudades y todas
                if((zoom_actual > 6 & zoom<7 ) ||( zoom_actual <7 & zoom>6 )) { // Provincias <--> Ciudades
                      mapa.clearOverlays();
                      listMarkers(tipomarcas,zoom_actual);
                }else if((zoom_actual > 11 & zoom < 12 ) ||(zoom_actual< 12 & zoom>11)) { // Ciudades <--> Todas
                      mapa.clearOverlays();
                      listMarkers(tipomarcas,zoom_actual);
                }else if((zoom_actual > 3 & zoom < 4 ) ||(zoom_actual< 4 & zoom>3)) { // Paises <--> provincias
                      mapa.clearOverlays();
                      listMarkers(tipomarcas,zoom_actual);
                }
               
                    
                     zoom = zoom_actual;
            }
           
        });



       
    }
}


function listMarkers(tipomarcas,zoom_actual) {
    new Ajax.Request(tipomarcas+'?zoom='+zoom_actual,{
        method: 'GET',
        onComplete: function(request){

            markers = eval("("+request.responseText+")");
           
            for (var i =0; i< markers.length; i++){
                var marca = markers[i].marker
                var mlat = marca.lat;
                var mlng = marca.lng;

                if(mlat&&mlng){
                    latlng = new GLatLng(parseFloat(mlat),parseFloat(mlng));
                           
                    // Definimos el Icono
                    var IconImage = new GIcon(G_DEFAULT_ICON);
                    if(marca.total > 20){
                        IconImage.image = "/images/iconos/32/"+ marca.tipo+"20.png";
                    }else if(marca.total > 10){
                        IconImage.image = "/images/iconos/32/"+ marca.tipo+"10.png";
                    }else  if(marca.total > 5){
                        IconImage.image = "/images/iconos/32/"+ marca.tipo+"5.png";
                    }else  if(marca.total > 1){
                        IconImage.image = "/images/iconos/32/"+ marca.tipo+marca.total+".png";
                    }else{
                        IconImage.image = "/images/iconos/32/"+ marca.tipo+".png";
                    }
                    
                    IconImage.iconSize = new GSize(32,32);
                    if(marca.imagen){
                        var foto = marca.imagen.split('/');
                        foto = foto[foto.length-1]
                    }else{
                        var foto = null;
                    }


                         
                    //marker = addMarkerToMap(latlng,html)
                    var html=""
                    if(foto){
                        html="<div style='min-height:160px; min-width:150px;'><h2>"+ marca.titulo+"</h2><br/>" +
                        "<img src='marker/imagen/"+marca.id+"/thumb/"+foto+"' width='100px' ALIGN='left'>"+
                        "<p>"+ marca.descripcion+"</p><br/>" +
                        "<p><a href='/localizador/"+marca.id+"'>Mas Información</a></p></div>";
                    }else{
                        html= "<div style='min-height:160px; min-width:150px;'><h2>"+ marca.titulo+"</h2><br/>" +
                        "<p>"+ marca.descripcion+"</p><br/>" +
                        "<p><a href='/localizador/"+marca.id+"'>"+masinfo+"</a></p></div>";
                    }


                    var marker = CrearMarca(latlng,html,IconImage);
                        
                            
                    //marker = addMarkerToMap(latlng,html)
                    mapa.addOverlay(marker);
                    mapa.closeInfoWindow();
                }
            }
           
        }
        
    })

}
function CrearMarca(latlng, html,IconImage){
    var  marker = new GMarker(latlng,IconImage)
    GEvent.addListener(marker, 'click', function(){

        marker.openInfoWindowHtml(html);

    });
    return marker;
}





window.onunload =GUnload;



// This function adds the point to the map

function addToMap(response)
{
            
    // Retrieve the object
    place = response.Placemark[0];

    // Retrieve the latitude and longitude
    point = new GLatLng(place.Point.coordinates[1],
        place.Point.coordinates[0]);

    // Center the map on this point
    mapa.setCenter(point, zoom);
      
    mapa.openInfoWindowHtml(place.address);
}

// Para centrar el mapa en una dirección dada

function centerInMap(response)
{

    // Retrieve the object
    place = response.Placemark[0];

    // Retrieve the latitude and longitude
    localizacion = new GLatLng(place.Point.coordinates[1],
        place.Point.coordinates[0]);
    //alert(localizacion)
    // Center the map on this point
    mapa.setCenter(localizacion, zoom);


}


function showAddress(response) {
    var country_name;
    var country_name_code;
    var administrative_name;
    var subadministrative_name;
    var locality_name;
    var postal_code ="";
    var dependent_locality;
    var thoroughfare = "";
    var locality;
    var info_direcc;
    var area;

    if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
    } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);



        country_name = place.AddressDetails.Country.CountryName;
        country_name_code = place.AddressDetails.Country.CountryNameCode;
        if (typeof(place.AddressDetails.Country.AdministrativeArea) != "undefined"){
            administrative_name = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
            if (typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) != "undefined"){
                subadministrative_name = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
                if (typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) != "undefined"){
                    locality = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality
                }
            }else{
                if (typeof(place.AddressDetails.Country.AdministrativeArea.Locality) != "undefined"){
                    locality = place.AddressDetails.Country.AdministrativeArea.Locality
                }
            }
        }else{
            if (typeof(place.AddressDetails.Country.Locality) != "undefined"){
                locality = place.AddressDetails.Country.Locality
            }
        }

        if(locality != null){
            locality_name = locality.LocalityName;
            if (typeof(locality.PostalCode) != "undefined"){
                postal_code = locality.PostalCode.PostalCodeNumber;
            }

            if (typeof( locality.DependentLocality) != "undefined"){
                dependent_locality= locality.DependentLocality.DependentLocalityName;
                if (typeof( locality.DependentLocality.Thoroughfare) != "undefined"){
                    thoroughfare = locality.DependentLocality.Thoroughfare.ThoroughfareName;
                }else{
                    thoroughfare = place.adderess;
                }

            }else{
                if (typeof( locality.Thoroughfare) != "undefined"){
                    thoroughfare = locality.Thoroughfare.ThoroughfareName;
                }else{
                    thoroughfare = place.adderess;
                }

            }
        }

        if(typeof( subadministrative_name) == "undefined"){
            area = administrative_name;
        }else{
            area = subadministrative_name;
        }

        //if (typeof(thoroughfare) != "undefined"){
        //   $("marker_direccion").innerHTML = thoroughfare;
        //}


        info_direcc = '' + country_name +  //' ('+country_name_code+' ) ' +
        ' &gt;&gt; ' + area +
        ' &gt;&gt; ' + locality_name;

        if(typeof( dependent_locality) != "undefined"){
            info_direcc = info_direcc + '&gt;&gt; ' + dependent_locality;
        }
        if($("direc_div") != null){
            $("direc_div").innerHTML =  info_direcc;
        }
        
        
    }
    return place;
}
