document.on('dom:loaded', function() {
	new FiltroHoteles();
});

var FiltroHoteles = Class.create(BuscadorSuper, {
	initialize: function($super) {
		$super($$('body').first());
	},
	init: function() {
		this.gsc = new GStreetviewClient();
		this.distancia = this.getInput('distancia');
		this.txtDistancia = this.getInput('txtDistancia');
		this.precio = this.getInput('precio');
		this.txtPrecio = this.getInput('txtPrecio');
		this.cercade = this.getInput('cercade');
		this.contSliderD = this.getInput('contSlider');
		this.entrada = this.getInput('entrada_lst');
		this.salida = this.getInput('salida_lst');
		this.tipo_item = this.getInput('tipo_item');
		this.pagina = this.getInput('pagina');
		this.id_padre = this.getInput('id_padre');
		this.modo = 'd';
		this.requests = 0;
		
		(function() {
			var s = this.getInput('slider-distancia');
		
			if(s) {
				var maxDistancia = 100;
				this.sliderDistancia = new Control.Slider( 
					s.down('.slider-handle_azul'), 
					s, 
					{
						range: $R(1, maxDistancia),
						sliderValue: parseInt(this.distancia.present() ? $F(this.distancia) : 0, 10),
						onSlide: function(value) {
							this.txtDistancia.setValue('A '+Math.floor(value)+' km máx.');
						}.bind(this),
						onChange: function(value) { 
							this.distancia.setValue(Math.floor(value));
						}.bind(this)
					}
				);
				
				var limpiar = function() {
					this.contSliderD.hide();
					this.cercade.selectedIndex = 0; 
					this.sliderDistancia.setValue(0); 
					this.txtDistancia.setValue(''); 
					this.distancia.setValue('');
					this.load();
				}.bind(this);
				
				this.getInput('filtrarDistancia').on('click', function() { if(this.cercade.selectedIndex > 0) this.load(); }.bind(this));
				this.limpiarDistancia = this.getInput('limpiarDistancia');
				this.limpiarDistancia.on('click', limpiar);
				this.cercade.on('change', function() {
					if(this.cercade.selectedIndex == 0) {
						this.contSliderD.hide();
						limpiar();
					}
					else {
						this.contSliderD.show();
					}
					
				}.bind(this));
				
				(this.cercade.selectedIndex == 0) ? this.contSliderD.hide() : this.contSliderD.show();
			}
		}.bind(this))();

		(function() {
			var s = this.getInput('slider-precio');
			if(s) {
				var maxPrecio = 500;
				this.sliderPrecio = new Control.Slider( 
						s.down('.slider-handle_azul'), 
						s, 
						{
							range: $R(1, maxPrecio),
							values: $A($R(1, maxPrecio)).filter(function(x) { return x == 1 || x%5 == 0; }),
							sliderValue: parseInt(this.precio.present() ? $F(this.precio) : 0, 10),
							onSlide: function(value) {
								this.txtPrecio.setValue('Hasta '+Math.floor(value)+' €');
							}.bind(this),
							onChange: function(value) { 
								this.precio.setValue(Math.floor(value));
							}.bind(this)
						}
				);
				
				this.getInput('filtrarPrecio').on('click', this.load.bind(this));
				this.limpiarPrecio = this.getInput('limpiarPrecio');
				this.limpiarPrecio.on('click', function() {
					this.sliderPrecio.setValue(0); 
					this.txtPrecio.setValue(''); 
					this.precio.setValue('');
					this.load();
				}.bind(this));
			}
		}.bind(this))();

		this.todosTipo = this.getInput('todosTipo');
		this.borrarTipo = this.getInput('borrarTipo');
		
		this.todosEstrellas = this.getInput('todosEstrellas');
		this.borrarEstrellas = this.getInput('borrarEstrellas');

		this.stars = this.div.select('#ulEstrellas li input');
		this.tipos = this.div.select('#ulTipos li input');
		for(var i = 0, s = this.stars.size(); i<s; i++) this.stars[i].on('click', this.load.bind(this));
		for(var i = 0, s = this.tipos.size(); i<s; i++) this.tipos[i].on('click', this.load.bind(this));
		
		var f = function(checks, val) { 
			for(var i = 0, s = checks.size(); i<s; i++) checks[i].checked = val;
			this.load();
		}.bind(this);
		this.borrarEstrellas.on('click', f.curry(this.stars, false));
		this.borrarTipo.on('click', f.curry(this.tipos, false));
		this.todosEstrellas.on('click', f.curry(this.stars, true));
		this.todosTipo.on('click', f.curry(this.tipos, true));

		this.onLoadEvents();
	},
	onLoadEvents: function() {
		this.orden = this.getInput('orden');
		this.orden.on('change', this.load.bind(this));
		var d = this.getInput('listaHotelesDetalle');
		var m = this.getInput('listaHotelesMiniatura');
		var bd = this.getInput('btnDetalles');
		var bm = this.getInput('btnMiniaturas');
		var f = function(d,m,bd,bm,modo) {
			if(bd.hasClassName('activo')) return;
			d.toggle(); 
			m.toggle();
			bd.addClassName('activo');
			bm.removeClassName('activo');
			this.modo = modo;
		}.bind(this);

		bd.on('click', f.curry(d,m,bd,bm,'d'));
		bm.on('click', f.curry(m,d,bm,bd,'m'));
		
		this.paginador = this.getInput('paginador');
		if(this.paginador) {
			var li = this.paginador.select('a[rel]');

			for(var i = 0, s= li.size(); i < s; i++) {
				li[i].on('click', this.doPag.bindAsEventListener(this, parseInt(li[i].getAttribute('rel'))));
			}
		}
		
		this.spinner = this.getInput('spinner');
		
		var fV = function(a, div, latlng) {
			if(latlng == null) {
				var s = a.nextSiblings().first();
				if(s) s.remove();
				a.remove();
			}
			else {
				var pan = new GStreetviewPanorama(div, {'latlng': latlng});
				var listener = function(ev) {
					ev.stop();
					if(div.toggle().visible()) {
						pan.checkResize();
					}
					
				}.bindAsEventListener();
				
				div.down('a').on('click', listener);
				a.on('click', listener);
			}
		}.bind(this);
		
		var fM = function(map, divMapa, div, latlng, z, ev) {
			Event.stop(ev);
			var tmp = divMapa.up('div');
			if(tmp) tmp.hide();
			div.insert(divMapa.remove());
			div.show();
			divMapa.show();
			map.setCenter(latlng, z);
			map.checkResize();
		};
		
		var divMapa = new Element('div', {style: 'display: none; height: 236px; width: 100%; margin-top: 3px'});
		$$('body').first().insert(divMapa);
		var map = new GMap2(divMapa, {mapTypes: [G_HYBRID_MAP], size: new GSize(585, 236)});
		map.enableScrollWheelZoom();
		
		var sv = this.div.select('a.calleMapa[rel]');
		var icon = new GIcon();
		icon.image = '/images/markers_azul/marker_destino_alojamiento.png';
		icon.iconSize = new GSize(30, 30);
	    icon.iconAnchor = new GPoint(30 >> 1, 30 >> 1);
	    icon.infoWindowAnchor = new GPoint(24 >> 1, 34 >> 1);
		for(var i = 0, s = sv.size(); i < s; i++) {
			var a = sv[i];
			var coord = a.getAttribute('rel').split(',');
			if(coord.length == 2) {
				var ll = new GLatLng(parseFloat(coord[0]),parseFloat(coord[1]));
				var id = a.getAttribute('id');
				var div = this.getInput('mapa'+id);
				G_HYBRID_MAP.getMaxZoomAtLatLng(ll, function(div, l, a, load, status) {
					var z = status.zoom - 3;
					a.on('click', fM.curry(map, divMapa, div, l, z));
					div.down('a').on('click', function() {div.hide();});
					var g = new GMarker(l, {"icon": icon});
					map.addOverlay(g);
					if(load) {
						this.loadMarkers.bind(this, map, icon).defer();
					}
				}.bind(this, div, ll, this.getInput('vermapa'+id), i == s-1));
				this.gsc.getNearestPanoramaLatLng(ll, fV.curry(a, this.getInput('pano'+id)));
			}
		}
		

	},
	doPag: function(ev, p) {
		Event.stop(ev);
		this.load(p);
		this.getInput('cntCentro').scrollTo();
	},
	isChecked: function(c) {
		return c.checked;
	},
	loadMarkers: function(map, icon) {
		var q = '';

		if(this.entrada.present() && this.salida.present()) {
			q = '?entrada='+$F(this.entrada)+'&salida='+$F(this.salida);
		}

		var tmpl = new Template('<div class="cont_informacion_bocadillo"><p><a target="_blank" href="#{ruta}'+q+'">#{nombre}</a></p>'+
	    '<p>#{direccion}</p><p><a target="_blank" href="#{ruta}'+q+'">Desde: <b>#{precio_aprox} &euro;</b></a></p></div>');

		new Ajax.Request('/hoteles/get_mk_lista.php', 
				{
					method: 'get',
					parameters: {
									id: $F(this.id_padre), 
									t:$F(this.tipo_item), 
									'entrada': $F(this.entrada),
									'salida': $F(this.salida)
								},
					onSuccess: function(t) {
						var json = t.responseText.evalJSON();					
						for(var i = 0, si = json.size(); i < si; i++) {
							var h = json[i];
							h.ruta += q;
							h.nombre = h.nombre+(h.estrellas > 0 ? ' '+h.estrellas+'*':'');
							var g = new GMarker(new GLatLng(h.lat, h.lng), {icon: icon, title: h.nombre});
							map.addOverlay(g);
							g.bindInfoWindowHtml(tmpl.evaluate(h));
						}
					}
				});
	},
	load: function(pag) {
		if(Object.isUndefined(pag) || !Object.isNumber(pag)) {
			this.pagina.setValue(pag = 1);
		}
		else {
			this.pagina.setValue(pag);
		}
		
		var p =	{
			precio: this.precio ? $F(this.precio) : null,
			pag: $F(this.pagina),
			id_padre: $F(this.id_padre),
			'estrellas[]': this.stars.filter(this.isChecked).pluck('value'),
			orden: $F(this.orden),
			cercade: this.cercade ? $F(this.cercade) : null,
			distancia: this.distancia ? $F(this.distancia) : null,
			'tipo[]': this.tipos.filter(this.isChecked).pluck('value'),
			tipo_item: $F(this.tipo_item),
			entrada: $F(this.entrada),
			salida: $F(this.salida),
			modo: this.modo
		};
		
		new Ajax.Request('/comunidad/php/get_lista_hoteles_ajax.php',
			{
				method: 'get',
				parameters: p,
				onCreate: function() {
					this.getInput('listaHotelesDetalle').hide();
					this.getInput('listaHotelesMiniatura').hide();
					this.spinner.show();
				}.bind(this),
				onSuccess: function(r, t) {
					if(this.requests != r) return;
					this.getInput('cntCentro').update(t.responseText);
					this.onLoadEvents();
				}.bind(this, ++this.requests)
			}
		);
	}
});

