// JavaScript Document

var map;
var batch = [];
var geocoder = new GClientGeocoder();
var center = new GLatLng( 39.570810, 2.651221 );
var info;

var icons = new Array();
icons[1] = new GIcon();
icons[1].image = "http://www.perpiso.com/templates/default/images/icon1.png";
icons[1].iconAnchor = new GPoint(6, 31);
icons[1].infoWindowAnchor = new GPoint(17, 0);
icons[1].iconSize = new GSize(24, 31);
icons[1].shadow = "http://www.perpiso.com/templates/default/images/icon-shadow1.png";
icons[1].shadowSize = new GSize(38, 31);
icons[2] = new GIcon();
icons[2].image = "http://www.perpiso.com/templates/default/images/icon2.png";
icons[2].iconAnchor = new GPoint(6, 31);
icons[2].infoWindowAnchor = new GPoint(17, 0);
icons[2].iconSize = new GSize(24, 31);
icons[2].shadow = "http://www.perpiso.com/templates/default/images/icon-shadow2.png";
icons[2].shadowSize = new GSize(40, 31);
icons[0] = new GIcon();
icons[0].image = "http://www.perpiso.com/templates/default/images/icon0.png";
icons[0].iconAnchor = new GPoint(6, 30);
icons[0].infoWindowAnchor = new GPoint(17, 0);
icons[0].iconSize = new GSize(23, 30);
icons[0].shadow = "http://www.perpiso.com/templates/default/images/icon-shadow0.png";
icons[0].shadowSize = new GSize(34, 31);
icons[4] = new GIcon();
icons[4].image = "http://www.perpiso.com/templates/default/images/icon4.png";
icons[4].iconAnchor = new GPoint(6, 30);
icons[4].infoWindowAnchor = new GPoint(17, 0);
icons[4].iconSize = new GSize(23, 30);
icons[4].shadow = "http://www.perpiso.com/templates/default/images/icon-shadow4.png";
icons[4].shadowSize = new GSize(34, 31);
icons[5] = new GIcon();
icons[5].image = "http://www.perpiso.com/templates/default/images/icon5.png";
icons[5].iconAnchor = new GPoint(6, 30);
icons[5].infoWindowAnchor = new GPoint(17, 0);
icons[5].iconSize = new GSize(23, 30);
icons[5].shadow = "http://www.perpiso.com/templates/default/images/icon-shadow5.png";
icons[5].shadowSize = new GSize(34, 31);
icons[3] = new GIcon();
icons[3].image = "http://www.perpiso.com/templates/default/images/icon3.png";
icons[3].iconAnchor = new GPoint(6, 30);
icons[3].infoWindowAnchor = new GPoint(17, 0);
icons[3].iconSize = new GSize(23, 30);
icons[3].shadow = "http://www.perpiso.com/templates/default/images/icon-shadow3.png";
icons[3].shadowSize = new GSize(34, 31);

window.addEvents({
    'domready' : function() {
        // Inicializamos el mapa
        LoadMap();
        
        var searchFocused = 1;
        $('address').addEvent('focus',function(){
            if( searchFocused == 1 ){
                $('address').value = '';
            }
            searchFocused = 2;
        });
    },
    
    'unload' : function() {
        GUnload();
    }
});

function LoadMap()
{
    if ( GBrowserIsCompatible() ) {
        map = new GMap2(document.getElementById("body"));
        map.setCenter( center, 16);
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GOverviewMapControl());
        map.enableScrollWheelZoom();
        map.setMapType(G_SATELLITE_MAP);
        
        geocoder = new GClientGeocoder();
        updateMap();
        
        //GEvent.addListener( map, "moveend", updateMap );
        GEvent.addListener( map, "zoomend", updateMap );
        GEvent.addListener( map, "dragend", updateMap );
    }
}
    
function updateMap()
{
    map.clearOverlays();
	var flashmsg = $$('.flashMessenger');
	if ( flashmsg.length > 0 ) {
		$('flashMessenger').remove();
    }
    
    doMarkers();
    
    if ( $('partner_id').value != 0 ) {
        showCurrentPartner();
    }
}
    
function doMarkers()
{
    var bounds = map.getBounds();
    var swBound = bounds.getSouthWest();
    var neBound = bounds.getNorthEast();

    var namedBounds = {
        neLat: neBound.lat(),
        neLng: neBound.lng(),
        swLat: swBound.lat(),
        swLng: swBound.lng(),
        filterCost: $('filter_costs').value,
        filterType: $('filter_type').value,
        filterZone: $('filter_zones').value,
        pid: $('partner_id').value
    };

    var url = 'http://www.perpiso.com/xml/marker/';

    new Ajax( url, {
        data: Object.toQueryString( namedBounds ),
        method: 'get',
        onComplete: function(t) { processMarkers( t ); }
    }).request();
}
    
function processMarkers( t )
{
    var xml = Json.evaluate( t );
    batch = [];
    xml.each(function(item, i){
        var point = new GLatLng( parseFloat(item.lat), parseFloat(item.lng) );
        var type = item.type;
        var iconMarker = icons[type];
        var html = item.html;
        var marker = loadMarkers( point, iconMarker, html);
        batch.include( [ type, marker ] );
        map.addOverlay( marker );
    });

	if ( batch.length == 0 ) {
            var flashMessenger = new Element('div',{
                'class': 'flashMessenger',
				'id': 'flashMessenger'
            });
            var fx = new Fx.Style( flashMessenger, 'opacity' );
            fx.hide();

            flashMessenger.setHTML( 'No se han encontrado propiedades con los filtros especificados.' );
            $('body').adopt(flashMessenger);
            fx.start(0.7);
            (function(){ flashMessenger.remove() }).delay(2000);
	}
}

function loadMarkers( point, icons, html )
{
    var marker = new GMarker(point, {icon: icons} );
                
    GEvent.addListener( marker, "click", function() {
       
        marker.openInfoWindowHtml( html, { 'maxWidth': '350' } );
        
    });
    
    return marker;
}

function showAddress(address) {
    geocoder.getLatLng(
        address,
        function(point) {
            if (!point) {
                // Agregar mensaje en mapa
                var flashMessenger = new Element('div',{
                    'class': 'flashMessenger'
                });
                var fx = new Fx.Style( flashMessenger, 'opacity' );
                fx.hide();
        
                flashMessenger.setHTML( 'No hemos podido localizar en el mapa la direcci&oacute;n:<br />' + address );
                $('body').adopt(flashMessenger);
                fx.start(0.7);
                (function(){ flashMessenger.remove() }).delay(4000);
            } else {
                map.setCenter(point, 16);
                updateMap();
            }
        }
    );
    return false;
}

function updateMapZones()
{
    var zone = { zone: $('filter_zones').value };
    var url = 'http://www.perpiso.com/xml/centerzone/';

    new Ajax( url, {
        data: Object.toQueryString( zone ),
        method: 'get',
        onComplete: function(t) {
            var xml = Json.evaluate( t );
            $('filter_zones').value = 0;
            map.setCenter( new GLatLng( parseFloat( xml.lat ), parseFloat( xml.lng ) ), 16 );
            
            updateMap();
            
            // Agregar mensaje en mapa
            var flashMessenger = new Element('div',{
                'class': 'flashMessenger'
            });
            var fx = new Fx.Style( flashMessenger, 'opacity' );
            fx.hide();
        
            flashMessenger.setHTML( 'Mostrando Zona: ' + xml.zone );
            $('body').adopt(flashMessenger);
            fx.start(0.7);
            (function(){ flashMessenger.remove() }).delay(4000);
        }
    }).request();
}

function showCurrentPartner()
{
    var partner = { pid: $('partner_id').value };
    var url = 'http://www.perpiso.com/xml/partnerdata/';

    new Ajax( url, {
        data: Object.toQueryString( partner ),
        method: 'get',
        onComplete: function(t) {
            var xml = Json.evaluate( t );
            // Agregar mensaje en mapa
            var flashMessenger = new Element('div',{
                'class': 'flashMessengerSmall'
            });
            var fx = new Fx.Style( flashMessenger, 'opacity' );
            fx.hide();
        
            flashMessenger.setHTML( 'Mostrando propiedades publicadas por: ' + xml.name );
            $('body').adopt(flashMessenger);
            fx.start(0.7);
            (function(){ flashMessenger.remove() }).delay(4000);
        }
    }).request();
}