var gdir;
var map;
var fotos;
var markers;
var $j=jQuery.noConflict();
var PanoramioEventHandler;
var PanoramioEventHandler2;
var mgr;
function load(map_layer) {
    initialize(map_layer);
    map.setCenter(new GLatLng(40.396764,-3.713379),6);
    $j.historyInit(historyChange);
    getAlojamientos();
    
    GEvent.addListener(map, "dragend", updateLinkToThisPage);
}
function Redimensionar(layer_name) {
    var cabecera = document.getElementById("cabecera-mapas");
    var pie = document.getElementById("pie-pagina-mapas");
    var mapa = document.getElementById(layer_name);
    var ruta = document.getElementById("Ruta");
    if (mapa) {
        var alto = 0;
        alto = cabecera.clientHeight + pie.clientHeight + 90;
        var ancho = 0;
        if (ruta)
           ancho = ruta.clientWidth + 80;
        else
            ancho = 300;
            
        //heigth = heigth + "px";
        var altoPagina;
        var anchoPagina;
        if (window.innerHeight){
            //navegadores basados en mozilla
            altoPagina = window.innerHeight;
            anchoPagina = window.innerWidth;
        }else{
            //Navegadores basados en IExplorer, es que no tengo innerheight
            altoPagina = document.body.clientHeight;
            anchoPagina = document.body.clientWidth;
        }
        //alert(altoPagina);
        alto = altoPagina - alto;
        ancho = anchoPagina - ancho;
        
        mapa.style.height = alto + "px";
        alto = alto - 45;
        if (ruta)
            ruta.style.height = alto + "px";
        mapa.style.width = ancho + "px";
    }
}
function initialize(layer_name) {
    Redimensionar(layer_name);
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById(layer_name));
        map.setCenter(new GLatLng(40.396764,-3.713379),6);
        
        var mapTypeControl = new GMapTypeControl();
        var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
        var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
        map.addControl(mapTypeControl, topRight);
        map.addControl(new GLargeMapControl());
        map.enableContinuousZoom();
        mgr = new MarkerManager(map);
        fotos = new Array();
        //map.addControl(new GOverviewMapControl());
               
    }
}

function initializeFicha(layer_name, lat, lng, pagina) {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById(layer_name));
        var point = new GLatLng(lat, lng);
        map.setCenter(point, 14);
        map.addOverlay(new GMarker(point));
        GEvent.addListener(map, "click", function(overlay, point) {
            window.location = pagina;
        });
    }
}

function setDirections(fromAddress, toAddress, locale, direccion) {
      if (gdir == null)
      {
        gdir = new GDirections(map, document.getElementById(direccion));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
      }
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }
function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
     
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    
   else alert("An unknown error occurred.");
   
}
function onGDirectionsLoad(){ 
}
function setCenter(lat, lng, zoom) {
    var point = new GLatLng(lat, lng);
    map.setCenter(new GLatLng(lat, lng), zoom);
    map.addOverlay(new GMarker(point));
}

function getPanoramio() {
    clearFotos();
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast()
    var minx = southWest.lng() + '';
    var miny = southWest.lat() + '';
    var maxx = northEast.lng() + '';
    var maxy = northEast.lat() + '';
    var op={
        'order':'popularity',
        'set':'public',
        'from':'0',
        'to':'20',
        'minx':minx,
        'miny':miny,
        'maxx':maxx,
        'maxy':maxy,
        'size':'small',
        'callback': 'addPanoramio'
    };
       
    $j.getJSON("http://www.panoramio.com/map/get_panoramas.php",op);
}
function addPanoramio(data) {
    var icon = new GIcon();
    icon.image = "http://www.panoramio.com/img/panoramio-marker.png";
    icon.shadow = "http://www.panoramio.com/img/panoramio-shadow.png";
    icon.iconSize = new GSize(18, 18);
    icon.shadowSize = new GSize(22, 22);
    icon.iconAnchor = new GPoint(9, 9);
    icon.infoWindowAnchor = new GPoint(9, 0);
    if (data.photos.length > 0)
    {
        $j.each(data.photos, function(i, photo) {
            map.addOverlay(createPanoramioMarker(photo, icon));
        });
    }
}
function createPanoramioMarker(photo, icon){
    var point = new GLatLng(photo.latitude, photo.longitude);
    var marker = new GMarker(point, icon);
    var txt = '';
    txt += "<div id='infowin' style='height:" + (photo.height + 80) + "px'>";
    txt += "<a id='photo_infowin' target='_blank' href='" + photo.photo_url + "'>";
    txt += "<img width='" + photo.width + "' height='" + photo.height + "' src='" + photo.photo_file_url + "' border='0'/><\/a>";
    txt += "<div style='overflow: hidden; '>";
    txt += "<p><a target='_blank' class='photo_title' href='" + photo.photo_url;
    txt += "'><strong>" + photo.photo_title + "<\/strong><\/a></p>";
    txt += "<p>Posted by <a target='_blank' href='" + photo.owner_url + "'>";
    txt += photo.owner_name + "<\/a></p><\/div>";
    txt += "<\/div>"
    GEvent.addListener(marker, "click", function() {
        map.openInfoWindowHtml(point, txt); 
    });
    fotos.push(marker);
    return marker;
}

function activaPanoramio() {
    getPanoramio();
    PanoramioEventHandler = GEvent.addListener(map, 'zoomend', getPanoramio);
    PanoramioEventHandler2 = GEvent.addListener(map, 'dragend', getPanoramio);
}
function desactivaPanoramio() {
    GEvent.removeListener(PanoramioEventHandler);
    GEvent.removeListener(PanoramioEventHandler2);
    clearFotos();
}

function clearFotos() {
    for (var i=0; i<fotos.length; i++){
        map.removeOverlay(fotos[i]);        
    }
    fotos = new Array();
}

function chkPanoramio_Changed(control) {
    if (control.checked)
        activaPanoramio();
    else
        desactivaPanoramio();
}

function getGeoLatLng(address, alternativa, ctrLat, ctrLng, controlDir){
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(
        address,
        function (point) {
        if (point) {
            ctrLat.value = point.lat();
            ctrLng.value = point.lng();
            controlDir.value = address;
        }
        else {
            var geo = new GClientGeocoder();
            geo.getLatLng(alternativa, function (punto) {
                if (punto) {
                    ctrLat.value = punto.lat();
                    ctrLng.value = punto.lng();
                    controlDir.value = alternativa;
                }
            });
        }
    });
}

function getAlojamientos(){
    updateLinkToThisPage();
    mgr.clearMarkers();
    var op= {
        "idPais": ctrPais.value,
        "idProvincia": ctrProvincia.value,
        "idLocalidad": document.getElementById(ctrLocalidad).value,
        "idTipoAlojamiento": document.getElementById(ctrAlojamiento).value,
        "idTipoDestino":  ctrDestino.value,
        "idTipoElemento": ctrHabitacion.value,
        "numPersonas": ctrPersonas.value,
        "precioMax": ctrPrecioMax.value,
        "fechaDesde": ctrFechaDesde.value,
        "fechaHasta": ctrFechaHasta.value,
        "ofertas": "False",
        "preciosBajos": "False",
        "tipoReserva": ctrTipoReserva.value,
        "idioma": idIdioma
    };
    //var mgr = new MarkerManager(map);
    $j.getJSON("/mapas.asmx/getAlojamientos", op, function(rs) {
        $j.each(rs.layers, function(i, layer) {
            if (layer.tipo == "cluster") {
                mgr.addMarkers(CreateCluster(layer), layer.zoom[0], layer.zoom[1]);
            }
            else {
                mgr.addMarkers(CreateHouses(layer), layer.zoom[0], layer.zoom[1]);
            }
        });
        mgr.refresh();
    });
}

function CreateCluster(layer) {
    var markers = new Array();
    var icon = new GIcon();
    icon.image = 'http://gmaps-samples.googlecode.com/svn/trunk/markers/red/blank.png';
    icon.iconSize = new GSize(20, 34);
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(25, 7);
    
    $j.each(layer.places, function(i, cluster) {
        var point = new GLatLng(cluster.lat, cluster.lng);
        var opts = { 
          "icon": icon,
          "clickable": true,
          "title": cluster.numero + " alojamientos",
          "labelText": cluster.numero,
          "labelOffset": new GSize(-10, -12)
        };
        var marker = new LabeledMarker(point, opts);
        markers.push(marker);
        GEvent.addListener(marker, "click", function() {
            map.setCenter(point);
            map.zoomIn();
            updateLinkToThisPage();
        });
    });
    return markers;
}
function CreateHouses(layer) {
    var markers = new Array();
    $j.each(layer.places, function(i, house) {
        var point = new GLatLng(house.lat, house.lng);
        var marker = new GMarker(point, {title: house.nombre});
        markers.push(marker);
        GEvent.addListener(marker, "click", function() {
//            marker.openInfoWindowHtml("<div style='height:120px;'><a href='" + house.url + "'>" + house.nombre + "<br\/>" +
//                                        "<img alt='" + house.nombre + "' src='images/ShowThumbnail.aspx?img=" + house.imagen + "&tipo=alojamientos&id=" + house.path + "'\/><\/a>" + 
//                                        "<br\/>Precio: " + house.precio + "<\/div>");
            marker.openInfoWindowHtml(house.html);
        });
    });
    return markers;
}

function historyChange(newLocation){
	var o={ln:-2.9882,lt:39.97712,z:6,k:0};
	if(newLocation)
	{
		var ar=newLocation.split("&");
		for(var i=0;i<ar.length;i++)
		{
			var a=ar[i].split("=");
			o[a[0]]=parseFloat(a[1]);
		}
	}
	var center=map.getCenter();
	var t=map.getCurrentMapType();
//	var k=t===G_MAP_TYPE?0:t===G_SATELLITE_TYPE?1:2;
//	if(!center||!isClose(o.lt,center.lat())||!isClose(o.ln,center.lng())||o.z!==map.getZoom()||o.k!==k)
//	{
//		map.setCenter(new GLatLng(o.lt,o.ln),o.z,map.getMapTypes()[o.k]);
//	}
}

function updateLinkToThisPage(){
//	var p=map.getCenter();
//	var t=map.getCurrentMapType();
//	var k=t===G_MAP_TYPE?0:t===G_SATELLITE_TYPE?1:2;
//	var z=map.getZoom();
//	var hash="lt="+p.lat()+"&ln="+p.lng()+"&z="+z+"&k="+k;
//	var currentHash=$j.historyCurrentHash.replace(/^#/,'');
//	if(hash!==currentHash)
//	{
//		$j.historyLoad(hash);
//	}
//	document.cookie="referer="+currentHash;
}

function isClose(x,y){
	return(Math.abs(x-y)<0.000001);
}