var Buscador = {};

if(google && google.loader && google.loader.ClientLocation) {
	Buscador.clientLocation = google.loader.ClientLocation;
}

Buscador.init = function(opt) {	
		this.opt = {
			barra : opt.barra || null,
			vuelos : opt.vuelos || null,
			trenes : opt.trenes || null,
			hoteles : opt.hoteles || null,
			vuelo_hoteles : opt.vuelo_hoteles || null,
			viajes : opt.viajes || null,
			alarmas : opt.alarmas || null,
			ofertas : opt.ofertas || null,
			defaultdiv : opt.defaultdiv || 'vuelos'
		};
		
		this.selectedDiv = this.opt[this.opt.defaultdiv];

		this.div = {};
		// Creamos los buscadores que procedan
		if (this.opt.vuelos) {					
			this.vuelos = new BuscadorVuelos(this.opt.vuelos);
			this.div.vuelos = this.opt.vuelos;
		}
			
		if (this.opt.trenes) {					
			this.trenes = new BuscadorTrenes(this.opt.trenes);
			this.div.trenes = this.opt.trenes;
		}
		
		if (this.opt.hoteles) {			
			this.hoteles = new BuscadorHoteles(this.opt.hoteles);
			this.div.hoteles = this.opt.hoteles;
		}
	
		if (this.opt.vuelo_hoteles) {			
			this.vuelo_hoteles = new BuscadorVuelo_hoteles(this.opt.vuelo_hoteles);
			this.div.vuelo_hoteles = this.opt.vuelo_hoteles;
		}
	
		if (this.opt.viajes) {			
			this.viajes = new BuscadorViajes(this.opt.viajes);
			this.div.viajes = this.opt.viajes;
		}

		if (this.opt.alarmas) {
			this.alarmas = new BuscadorAlarmas(this.opt.alarmas);
			this.div.alarmas = this.opt.alarmas;
		}

		if (this.opt.ofertas) {
			this.ofertas = new BuscadorOfertas(this.opt.ofertas);
			this.div.ofertas = this.opt.ofertas;
		}

		if (this.opt.barra) {
			this.li = this.opt.barra
					.select('li.vuelos, li.trenes, li.hoteles, li.vuelo_hoteles, li.viajes, li.alarmas, li.ofertas');
					
			this.selectedLi = this.li.reject(function(el) {
				return el.className != this.opt.defaultdiv;
			}.bind(this)).first();

			var over = function(clazz) {
				this.opt.barra.className = 'menu' + clazz.capitalize();				
			}.bind(this);

			var out = function() {
				this.opt.barra.className = 'menu' + this.selectedLi.className.capitalize();
			}.bind(this);

			var click = function(li) {							
				for (k in this.div) {					
					if (k != li.className) {
						this.div[k].hide();						
					}
				}				
				this.div[li.className].show();				
				over(li.className);
				this.selectedDiv = this.div[li.className];
				this.selectedLi = li;
				if(li.className=='viajes'){
					new Ajax.Request('/comunidad/lib/dao/estadisticas.php', {asynchronous: true, method: 'get', parameters: {'id': 54}});
				}
			}.bind(this);

			this.li.each(function(li) {
				li.on('mouseover', over.curry(li.className));				
				li.on('mouseout', out);
				li.on('click', click.curry(li));
				li.down('a').href = 'javascript:void(0)';
			}.bind(this));

			click(this.selectedLi);
		}

	};

var BuscadorSuper = Class.create( {
	divAuto: new Element('div', {'className': 'autocomplete'}),
	initialize : function(div) {
		if (div==null)return;
		this.div = div;
		if(this.div.fireEvent) {
			this.fire = function(el, event) {
				el.fireEvent('on'+event, document.createEventObject());
			};
		}		
		else {
			this.fire = function(el, event) {
				var e = document.createEvent('MouseEvents');
				e.initEvent(event, true, true);
				el.dispatchEvent(e);
			};
		}		
		this.init();		
	},
	
	getInput : function(id) {		
		var e = this.div.select('#' + id);
		return e.length > 0 ? e.first() : undefined;		
	},
	
	loadOfertas: function(div) {
		if(BuscadorSuper.ofertasContent) {
			div.update(BuscadorSuper.ofertasHTML);
		}
		else {
			if(BuscadorSuper.divOfertas) {
				BuscadorSuper.divOfertas.push(div);
				return;
			}
			
			new Ajax.Request(
				'/vuelos/ofertasVuelos.php', 
				{
					method: 'get',
					parameters:{ origen: Buscador.clientLocation ? Buscador.clientLocation.address.city : '' },
					onCreate: function() { BuscadorSuper.divOfertas = [div];},
					onSuccess: function(t) {
						BuscadorSuper.divOfertas.invoke('update', BuscadorSuper.ofertasHTML = t.responseText);
						delete BuscadorSuper.divOfertas;
					}
				}
			);
		}
	},
	setAerop: function(txt, iata, li) {
		if (li.id.blank())
			return;
		if (li.hasClassName('aeropAutocomp')) {
			var desc = li.select('*:[id=descIata]').first().innerHTML;
			var ciud = li.select('*:[id=ciudadIata]').first().innerHTML;
			var pais = li.select('*:[id=paisIata]').first().innerHTML;
			iata.value = li.id;
			txt.value = desc + ', ' + ciud + ' ' + pais;
		} else {
			txt.value = li.innerHTML;
			iata.value = li.id;
		}
	},
	
	setEstacion: function(txt, iata, li) {
		if (li.id.blank())
			return;
		if (li.hasClassName('aeropAutocomp')) {
			var nombre = li.select('*:[id=descIata]').first().innerHTML;
			iata.value = li.id;
			txt.value = nombre;
		} else {
			txt.value = li.innerHTML;
			iata.value = li.id;
		}
		
	},
	
	popup: function(url, title, h, w, x, y) {		
		var a = new Element('a', {href: 'javascript:return false'}).update('-');
		a.on('click', function () {
			var p = window.open(
					url,
					(Prototype.Browser.Gecko)?title:"_blank",
					'width='+w+',height='+h+',toolbar=1,scrollbars=1,screenX='+x+',screenY='+y+',left='+x+',top='+y+',resizable=1'
				);
		
			if (p){
				p.blur();
			}
			window.focus();
		});
		
		this.fire(a, 'click');
		delete a;
	},
	abreURL: function(url) {			
		var a = new Element('a', {href: 'javascript:return false'}).update('-');
		a.on('click', function () {
			var p =window.top.location.href=url;			
			if (p){
				p.blur();
			}
			window.focus();
		});
		
		this.fire(a, 'click');
		delete a;
	},
	estadisticas: function(id, asynch) {		
		if(Object.isUndefined(asynch)) asynch = true;
		new Ajax.Request('/comunidad/lib/dao/estadisticas.php', {asynchronous: asynch, method: 'get', parameters: {'id': id}});
	},
	
	enlaceDirecto: function(donde){
		alert(donde);
	}
});

var BuscadorVuelos = Class
		.create(
				BuscadorSuper,
				{
					init : function() {					
						this.origen = this.getInput('origen');
						this.txtOrigen = this.getInput('txtOrigen');
						this.destino = this.getInput('destino');
						this.txtDestino = this.getInput('txtDestino');
						this.soloIda = this.getInput('soloIda');
						this.idaYVuelta = this.getInput('idaYVuelta');
						this.rumbo = this.getInput('rumbo');
						this.eDreams = this.getInput('eDreams');
						this.viajar = this.getInput('viajar');
						this.buscar = this.getInput('buscar');
						this.form = this.getInput('buscaVuelos');
						this.fechaIda = this.getInput('fechaIda');
						this.fechaVuelta = this.getInput('fechaVuelta');
						this.btnFechaIda = this.getInput('btnFechaIda');
						this.btnFechaVuelta = this.getInput('btnFechaVuelta');
						this.ofertasVuelos = this.getInput('ofertasVuelos');
						this.cambioOrigen = this.origen.present();
						this.cambioDestino = this.destino.present();
						this.indicator1 = this.getInput("indicator1");
						this.indicator2 = this.getInput("indicator2");
						this.ahora = new Date();
						this.pais_nav = this.getInput("pais_nav").value;
						
						this.rumbo.on('click', function() { 
							if ((Prototype.Browser.IE)){								
								if(this.rumbo.checked){									
									if(this.eDreams.checked){
										this.eDreams.checked=false;
									}
								}	
							}
						}.bind(this));
						
						this.eDreams.on('click', function() { 
							if ((Prototype.Browser.IE)){								
								if(this.eDreams.checked){									
									if(this.rumbo.checked){
										this.rumbo.checked=false;
									}
								}	
							}
						}.bind(this));

						this.form.onsubmit = function() { return false;};
						this.calendarIda = Calendar.setup( {
							animation: false,
							trigger : this.btnFechaIda,
							inputField : this.fechaIda,
							onSelect : function(cal) {
								if(Calendar.inputToInt(this.fechaIda) > Calendar.inputToInt(this.fechaVuelta)) {
									this.fechaVuelta.value = this.fechaIda.value;
								}
								cal.hide();
							}.bind(this),
							dateFormat : '%d/%m/%Y',
							align : this.getCalendarAlign(),
							bottomBar : false,
							disabled : function(date) {
								return date.dateDiff(this.ahora) < 0;
							}.bind(this)
						});
						this.fechaIda.on('click', this.fire.curry(this.btnFechaIda, 'click'));
						
						this.calendarVuelta = Calendar
								.setup( {
									animation: false,
									trigger : this.btnFechaVuelta,
									inputField : this.fechaVuelta,
									onSelect : Calendar.prototype.hide,
									dateFormat : '%d/%m/%Y',
									align : this.getCalendarAlign(),
									bottomBar : false,
									disabled : function(date) {
										return date.dateDiff(this.calendarIda.date) < 0;
									}.bind(this)
								});
						this.fechaVuelta.on('click', this.fire.curry(this.btnFechaVuelta, 'click'));
						
						var tipoAutocomp = Object.isElement(this.getInput('cercanos')) ? 1 : 2;
						this.autoOrigen = new Autocompletado.AeroCiu(this.txtOrigen, this.divAuto, this.indicator1, this.setAerop.curry(this.txtOrigen, this.origen), tipoAutocomp);
						this.autoDestino = new Autocompletado.AeroCiu(this.txtDestino, this.divAuto, this.indicator2, this.setAerop.curry(this.txtDestino, this.destino), tipoAutocomp);

						this.txtOrigen.on('focus', function() { 
							this.txtOrigen.clear();
							this.origen.clear();
							this.cambioOrigen = true; 
						}.bind(this));
						
						this.txtDestino.on('focus', function() { 
							this.txtDestino.clear();
							this.destino.clear();
							this.cambioDestino = true; 
						}.bind(this));

						this.soloIda.on('click', function() {
							this.fechaVuelta.disable();
							this.btnFechaVuelta.disable();
						}.bind(this));

						this.idaYVuelta.on('click', function() {
							this.fechaVuelta.enable();
							this.btnFechaVuelta.enable();
						}.bind(this));

						this.buscar.on('click', this.submit.bind(this));
						
/*						this.txtOrigen.enable();
						this.txtDestino.enable();*/

						if(Object.isElement(this.ofertasVuelos)) {
							this.loadOfertas(this.ofertasVuelos);
						}
						
						if(this.origen.present() && this.destino.present() && 
								(this.origen.value.match(/\d+/) || this.destino.value.match(/\d+/))) {
							this.getCercanos({
								origen: this.origen.value, txtOrigen: this.txtOrigen.value,
								destino: this.destino.value, txtDestino: this.txtDestino.value
							});
						}
					},
				
				submit: function() {
															
						if(!this.cambioOrigen || !this.cambioDestino) {
							alert('Selecciona la ruta y las fechas, por favor.');
							return;
						}
						
						if(!this.origen.present() && !this.txtOrigen.present()) {
							alert('Selecciona un aeropuerto de origen, por favor.');
							return;
						}
						
						if(!this.destino.present() && !this.txtDestino.present()) {
							alert('Selecciona un aeropuerto de destino, por favor.');
							return;
						}
						
						if(!/^[A-Z0-9]{3,3}$/.test(this.origen.value) || !/^[A-Z0-9]{3,3}$/.test(this.destino.value)) {
							this.getCercanos({
										origen: this.origen.value, txtOrigen: this.txtOrigen.value,
										destino: this.destino.value, txtDestino: this.txtDestino.value
									});
							return;
						}
						
						var params = this.form.serialize();

						/*
						 * TODO Cuando se pueda, recoger sólo las fechas de
						 * fechaIda y fechaVuelta, en vez de diaSalida,
						 * mesSalida, anyoSalida, etc.
						 */
						/*
						var fIda = $F(this.fechaIda).split('/');
						params += '&diaSalida=' + fIda[0] + '&mesSalida='+ fIda[1] + '&anyoSalida=' + fIda[2];
						if (!this.fechaVuelta.disabled) {
							var fVuelta = $F(this.fechaVuelta).split('/');
							params += '&diaVuelta=' + fVuelta[0] + '&mesVuelta=' + fVuelta[1] + '&anyoVuelta=' + fVuelta[2];
						}
						*/
						var x = 0;
						var c = this.eDreams.checked + this.rumbo.checked;
						var w = Math.floor(screen.width/c)-5;
						var h = screen.height;
						
						//cortamos el texto del origen y del destino						
						var ciudadOrigen=this.txtOrigen.value.substring(this.txtOrigen.value.indexOf(',')+1,this.txtOrigen.value.indexOf('('));
						ciudadOrigen=ciudadOrigen.replace(/^\s*|\s*$/g,"");;
						var ciudadDestino=this.txtDestino.value.substring(this.txtDestino.value.indexOf(',')+1,this.txtDestino.value.indexOf('('));
						ciudadDestino=ciudadDestino.replace(/^\s*|\s*$/g,"");;
						
						if(this.form.action.indexOf("trenes")!=-1){
							//busqueda de trenes							
							if(this.eDreams.checked) {							
								this.estadisticas(53);
								this.popup('/vuelos/busquedasExternasTrenes.php?'+params+'&ciudadOrigen='+ciudadOrigen+'&ciudadDestino='+ciudadDestino+'&proveedor=eDreams', 'eDreams', h, w, x, 0);							
								x = w;
							}
						
							if(this.rumbo.checked) {						
								this.estadisticas(52);
								this.popup('/vuelos/busquedasExternasTrenes.php?'+params+'&ciudadOrigen='+ciudadOrigen+'&ciudadDestino='+ciudadDestino+'&proveedor=rumbo', 'rumbo', h, w, x, 0);							
							}
						}else{
							//busqueda de vuelos
							if((this.eDreams.checked) && (this.pais_nav=='ES')) {							
								this.estadisticas(53);
								this.popup('/vuelos/scrappers/busquedasExternas.php?'+params+'&proveedor=eDreams', 'eDreams', h, w, x, 0);							
								x = w;
							}
						 
							if((this.rumbo.checked) && (this.pais_nav=='ES')) {						
								this.estadisticas(52);
								this.popup('/vuelos/scrappers/busquedasExternas.php?'+params+'&proveedor=rumbo', 'rumbo', h, w, x, 0);							
							}
							
							if((this.viajar.checked) && (this.pais_nav=='ES')) {						
								this.estadisticas(55);
								this.popup('/vuelos/scrappers/busquedasExternas.php?'+params+'&proveedor=viajar', 'viajar', h, w, x, 0);							
							}
						}
						
						this.estadisticas(1);
						if (this.pais_nav=='ES'){
							this.go(this.form.action + '?' + params);
						}else{
							this.go('/arg/busquedaArgentina.php?'+params);
						}
				},
				
				go: function(url) {
					window.location = url;
				},
				getCalendarAlign: function() {
					return 'Br';
				},
				getCercanos: function(params) {
					if(!Object.isElement(this.getInput('cercanos'))) {
						this.form.action = '/index.php'; 
						this.go(this.form.action + '?' + this.form.serialize());
						return;
					}
					
					if(Object.isElement(this.indicator1)) this.indicator1.show();
					if(Object.isElement(this.indicator2)) this.indicator2.show();

					if(this.divCercanos) {
						if('origen' in params && !('destino' in params)) {
							var ul = this.divCercanos.down('ul#aeropOrigen');
							var li = ul.select('li:not(.first)');
							li.invoke('update', '&nbsp');
							li.first().update('<img src="/images/iconos/loading.gif" alt="Buscando…"/></li>');
						}
						
						if('destino' in params && !('origen' in params)) {
							var ul = this.divCercanos.down('ul#aeropDestino');
							var li = ul.select('li:not(.first)');
							li.invoke('update', '&nbsp');
							li.first().update('<img src="/images/iconos/loading.gif" alt="Buscando…"/></li>');
						}
					}
					
					new Ajax.Request(
							'/get_aerop_cercano.php',
							{
								parameters: params,
								onSuccess: function(t) {
									if(Object.isElement(this.indicator1)) this.indicator1.hide();
									if(Object.isElement(this.indicator2)) this.indicator2.hide();

									this.buildCercanos(t.responseText.evalJSON());
									return;
								}.bind(this)
							}
						);
					return;
				},				
			
				buildCercanos: function(json) {
					var parseCiudades = function(lista, ul, param) {
						if(lista.length == 0) {
							ul.insert({bottom: '<li>No hay coincidencias, prueba otro criterio de b&uacute;squeda</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'});
						}
						else
						if(lista.length == 1) {
							var c = lista.first();
							if('pais' in c) {
								ul.insert({bottom: '<li>#{nombre} (#{pais})</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'.interpolate(c)});
							}
							else {
								ul.insert({bottom: '<li>#{nombre}, #{region}</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'.interpolate(c)});
							}
						}
						else {
							var li = null;
							var input = null;
							var p = null;
							for(var i=0, l=lista.length; i<l; i++) {
								var c = lista[i];
								li = new Element('li').update('#{nombre}, #{region} (#{pais})'.interpolate(c));
								input = new Element('input', {'type': 'radio', 'name': 'ciudad'+param, 'value': c.id});
								p = {};
								p[param] = c.id;
								input.on('click', this.getCercanos.curry(p).bind(this));
								li.insert({top: input});
								ul.insert({bottom: li});
							}
							
							for(;i<5;i++) ul.insert({bottom: '<li>&nbsp;</li>'});
						}
					}.bind(this);
					
					var parseAerop= function(lista, ul, nomInput) {
						if(lista.length == 1) {
							var str = '#{iata} - #{nombre}, #{ciudad} (#{pais})'.interpolate(lista[0]);
							ul.insert({bottom: '<li title="'+str+'"><input type="hidden" name="aerop'+nomInput+'" value="'+lista[0].iata+'"/><span class="airport">'+str.truncate(57, '&hellip;')+'</span><span>&nbsp;</span></li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'});
						}
						else {
							var li = null;
							for(var i=0, l=lista.length; i<l; i++) {
								var str = '#{iata} - #{nombre}, #{ciudad} (#{pais})'.interpolate(lista[i]);
								ul.insert({bottom:('<li title="'+str+'"><input type="radio" name="aerop'+nomInput+'" value="'+lista[i].iata+'"/><span class="airport">'+str.truncate(57, '&hellip;')+'</span><span>'+lista[i].distancia+' Km</span></li>')});
							}
							for(;i<8;i++) ul.insert({bottom: '<li>&nbsp;</li>'});
						}
					}.bind(this);

					if(!Object.isElement(this.divCercanos)) {
						this.divCercanos = this.getInput('cercanos').remove();
						this.divCercanos.down('#buscarCercanos').on('click', function() {
							var origen = this.divCercanos.select('#aeropOrigen input:checked, #aeropOrigen input[type=hidden]').first();
							var destino = this.divCercanos.select('#aeropDestino input:checked, #aeropDestino input[type=hidden]').first();
							if(!origen || !destino) {
								alert('Por favor, selecciona un aeropuerto de origen y otro de destino');
								return;
							}
							this.origen.value = origen.value;
							this.destino.value = destino.value;
							this.submit();
						}.bind(this));
						this.divCercanos.down('#cancelarCercanos').on('click', function() {
							this.divCercanos.hide();
							$$('body').first().scrollTo(); 
						}.bind(this));
						this.div.insert({after: this.divCercanos});
					}
					
					var ulCiudadOrigen;
					var ulCiudadDestino;
					var ulAeropOrigen = this.divCercanos.down('ul#aeropOrigen');
					var ulAeropDestino = this.divCercanos.down('ul#aeropDestino');
					
					if(Object.isArray(json.origen.ciudades)) {
						ulCiudadOrigen = this.divCercanos.down('ul#ciudadOrigen');
						ulCiudadOrigen.select('li:not(.first)').invoke('remove');
						ulAeropOrigen.select('li:not(.first)').invoke('remove');
						ulAeropOrigen.insert({bottom: '<li>Selecciona una ciudad</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'});
						parseCiudades(json.origen.ciudades, ulCiudadOrigen, 'origen');
					}
					
					if(Object.isArray(json.destino.ciudades)) {
						ulCiudadDestino = this.divCercanos.down('ul#ciudadDestino');
						ulCiudadDestino.select('li:not(.first)').invoke('remove');
						ulAeropDestino.select('li:not(.first)').invoke('remove');
						ulAeropDestino.insert({bottom: '<li>Selecciona una ciudad</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'});
						parseCiudades(json.destino.ciudades, ulCiudadDestino, 'destino');
					}

					if(Object.isArray(json.origen.aeropuertos)) {
						ulAeropOrigen.select('li:not(.first)').invoke('remove');
						parseAerop(json.origen.aeropuertos, ulAeropOrigen, 'origen');
					}

					if(Object.isArray(json.destino.aeropuertos)) {
						ulAeropDestino = this.divCercanos.down('ul#aeropDestino');
						ulAeropDestino.select('li:not(.first)').invoke('remove');
						parseAerop(json.destino.aeropuertos, ulAeropDestino, 'destino');
					}

					this.divCercanos.show();
					this.divCercanos.down('#ancla').scrollTo();
				}
			});

var BuscadorTrenes = Class
		.create(
				BuscadorSuper,
				{
					init : function() {
						this.origen = this.getInput('origen');
						this.txtOrigen = this.getInput('txtOrigen');
						this.destino = this.getInput('destino');
						this.txtDestino = this.getInput('txtDestino');
						this.soloIda = this.getInput('soloIda');
						this.idaYVuelta = this.getInput('idaYVuelta');
						this.rumbo = this.getInput('rumbo');
						this.eDreams = this.getInput('eDreams');
						this.buscar = this.getInput('buscar');
						this.form = this.getInput('buscaTrenes');
						this.fechaIda = this.getInput('fechaIda');
						this.fechaVuelta = this.getInput('fechaVuelta');
						this.btnFechaIda = this.getInput('btnFechaIda');
						this.btnFechaVuelta = this.getInput('btnFechaVuelta');
						this.ofertasVuelos = this.getInput('ofertasVuelos');
						this.cambioOrigen = this.origen.present();
						this.cambioDestino = this.destino.present();
						this.indicator1 = this.getInput("indicator1");
						this.indicator2 = this.getInput("indicator2");
						this.ahora = new Date();
						/*
						this.rumbo.on('click', function() { 
							if ((Prototype.Browser.IE)){								
								if(this.rumbo.checked){									
									if(this.eDreams.checked){
										this.eDreams.checked=false;
									}
								}	
							}
						}.bind(this));
						*/
						
						this.eDreams.on('click', function() { 
							if ((Prototype.Browser.IE)){								
								if(this.eDreams.checked){									
									if(this.rumbo.checked){
										this.rumbo.checked=false;
									}
								}	
							}
						}.bind(this));

						this.form.onsubmit = function() { return false;};
						this.calendarIda = Calendar.setup( {
							animation: false,
							trigger : this.btnFechaIda,
							inputField : this.fechaIda,
							onSelect : function(cal) {
								if(Calendar.inputToInt(this.fechaIda) > Calendar.inputToInt(this.fechaVuelta)) {
									this.fechaVuelta.value = this.fechaIda.value;
								}
								cal.hide();
							}.bind(this),
							dateFormat : '%d/%m/%Y',
							align : this.getCalendarAlign(),
							bottomBar : false,
							disabled : function(date) {
								return date.dateDiff(this.ahora) < 0;
							}.bind(this)
						});
						this.fechaIda.on('click', this.fire.curry(this.btnFechaIda, 'click'));
						
						this.calendarVuelta = Calendar
								.setup( {
									animation: false,
									trigger : this.btnFechaVuelta,
									inputField : this.fechaVuelta,
									onSelect : Calendar.prototype.hide,
									dateFormat : '%d/%m/%Y',
									align : this.getCalendarAlign(),
									bottomBar : false,
									disabled : function(date) {
										return date.dateDiff(this.calendarIda.date) < 0;
									}.bind(this)
								});
						this.fechaVuelta.on('click', this.fire.curry(this.btnFechaVuelta, 'click'));
						
						this.autoOrigen = new Autocompletado.AeroCiu(this.txtOrigen, this.divAuto, this.indicator1, this.setEstacion.curry(this.txtOrigen, this.origen), 8);
						this.autoDestino = new Autocompletado.AeroCiu(this.txtDestino, this.divAuto, this.indicator2, this.setEstacion.curry(this.txtDestino, this.destino), 8);

						this.txtOrigen.on('focus', function() { 
							this.txtOrigen.clear();
							this.origen.clear();
							this.cambioOrigen = true; 
						}.bind(this));
						
						this.txtDestino.on('focus', function() { 
							this.txtDestino.clear();
							this.destino.clear();
							this.cambioDestino = true; 
						}.bind(this));

						this.soloIda.on('click', function() {
							this.fechaVuelta.disable();
							this.btnFechaVuelta.disable();
						}.bind(this));

						this.idaYVuelta.on('click', function() {
							this.fechaVuelta.enable();
							this.btnFechaVuelta.enable();
						}.bind(this));

						this.buscar.on('click', this.submit.bind(this));
						
/*						this.txtOrigen.enable();
						this.txtDestino.enable();*/

						if(Object.isElement(this.ofertasVuelos)) {
							this.loadOfertas(this.ofertasVuelos);
						}
						
						if(this.origen.present() && this.destino.present() && 
								(this.origen.value.match(/\d+/) || this.destino.value.match(/\d+/))) {
							this.getCercanos({
								origen: this.origen.value, txtOrigen: this.txtOrigen.value,
								destino: this.destino.value, txtDestino: this.txtDestino.value
							});
						}
					},
				
				submit: function() {
						
						if(!this.cambioOrigen || !this.cambioDestino) {
							alert('Selecciona la ruta y las fechas, por favor.');
							return;
						}
						
						if(!this.origen.present() && !this.txtOrigen.present()) {
							alert('Selecciona una estación de origen, por favor.');
							return;
						}
						
						if(!this.destino.present() && !this.txtDestino.present()) {
							alert('Selecciona una estación de destino, por favor.');
							return;
						}
						//GUARDAMOS LA COOKIE PARA EL ORIGEN
						var expiration = new Date();
						expiration.setTime(expiration.getTime() + 600000); //Caduca 600 segundos después
				        document.cookie = "viajesnet_origen_estacion_id="+this.origen.value+";expires="+expiration.toGMTString();
				        document.cookie = "viajesnet_origen_estacion="+this.txtOrigen.value+";expires="+expiration.toGMTString();
						
						/*
						if(!/^[A-Z0-9]{3,3}$/.test(this.origen.value) || !/^[A-Z0-9]{3,3}$/.test(this.destino.value)) {
							this.getCercanos({
										origen: this.origen.value, txtOrigen: this.txtOrigen.value,
										destino: this.destino.value, txtDestino: this.txtDestino.value
									});
							return;
						}*/
						
						var params = this.form.serialize();

						var x = 0;
						var c = this.eDreams.checked + this.rumbo.checked;
						var w = Math.floor(screen.width/c)-5;
						var h = screen.height;
						
						var origen_codigo_rumbo = this.origen.value.split("-")[0];
						var origen_correspondencia_edreams = this.origen.value.split("-")[1];
						var destino_codigo_rumbo = this.destino.value.split("-")[0];
						var destino_correspondencia_edreams = this.destino.value.split("-")[1];
										
						if(this.eDreams.checked) {							
							this.estadisticas(53);
							this.popup('/vuelos/busquedasExternasTrenes.php?'+params+'&ciudadOrigen='+origen_correspondencia_edreams+'&ciudadDestino='+destino_correspondencia_edreams+'&proveedor=eDreams', 'eDreams', h, w, x, 0);							
							x = w;
						}
						
						var url='/vuelos/busquedasExternasTrenes.php?'+params+'&proveedor=rumbo&origen_codigo_rumbo='+origen_codigo_rumbo+'&destino_codigo_rumbo='+destino_codigo_rumbo;
											
						this.go(url);
					
				},
				
				go: function(url) {
					window.location = url;
				},
				getCalendarAlign: function() {
					return 'Br';
				},
				getCercanos: function(params) {
					if(!Object.isElement(this.getInput('cercanos'))) {
						this.form.action = '/index.php'; 
						this.go(this.form.action + '?' + this.form.serialize());
						return;
					}
					
					if(Object.isElement(this.indicator1)) this.indicator1.show();
					if(Object.isElement(this.indicator2)) this.indicator2.show();

					if(this.divCercanos) {
						if('origen' in params && !('destino' in params)) {
							var ul = this.divCercanos.down('ul#aeropOrigen');
							var li = ul.select('li:not(.first)');
							li.invoke('update', '&nbsp');
							li.first().update('<img src="/images/iconos/loading.gif" alt="Buscando…"/></li>');
						}
						
						if('destino' in params && !('origen' in params)) {
							var ul = this.divCercanos.down('ul#aeropDestino');
							var li = ul.select('li:not(.first)');
							li.invoke('update', '&nbsp');
							li.first().update('<img src="/images/iconos/loading.gif" alt="Buscando…"/></li>');
						}
					}
					
					new Ajax.Request(
							'/get_aerop_cercano.php',
							{
								parameters: params,
								onSuccess: function(t) {
									if(Object.isElement(this.indicator1)) this.indicator1.hide();
									if(Object.isElement(this.indicator2)) this.indicator2.hide();

									this.buildCercanos(t.responseText.evalJSON());
									return;
								}.bind(this)
							}
						);
					return;
				},				
			
				buildCercanos: function(json) {
					var parseCiudades = function(lista, ul, param) {
						if(lista.length == 0) {
							ul.insert({bottom: '<li>No hay coincidencias, prueba otro criterio de b&uacute;squeda</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'});
						}
						else
						if(lista.length == 1) {
							var c = lista.first();
							if('pais' in c) {
								ul.insert({bottom: '<li>#{nombre} (#{pais})</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'.interpolate(c)});
							}
							else {
								ul.insert({bottom: '<li>#{nombre}, #{region}</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'.interpolate(c)});
							}
						}
						else {
							var li = null;
							var input = null;
							var p = null;
							for(var i=0, l=lista.length; i<l; i++) {
								var c = lista[i];
								li = new Element('li').update('#{nombre}, #{region} (#{pais})'.interpolate(c));
								input = new Element('input', {'type': 'radio', 'name': 'ciudad'+param, 'value': c.id});
								p = {};
								p[param] = c.id;
								input.on('click', this.getCercanos.curry(p).bind(this));
								li.insert({top: input});
								ul.insert({bottom: li});
							}
							
							for(;i<5;i++) ul.insert({bottom: '<li>&nbsp;</li>'});
						}
					}.bind(this);
					
					var parseAerop= function(lista, ul, nomInput) {
						if(lista.length == 1) {
							var str = '#{iata} - #{nombre}, #{ciudad} (#{pais})'.interpolate(lista[0]);
							ul.insert({bottom: '<li title="'+str+'"><input type="hidden" name="aerop'+nomInput+'" value="'+lista[0].iata+'"/><span class="airport">'+str.truncate(57, '&hellip;')+'</span><span>&nbsp;</span></li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'});
						}
						else {
							var li = null;
							for(var i=0, l=lista.length; i<l; i++) {
								var str = '#{iata} - #{nombre}, #{ciudad} (#{pais})'.interpolate(lista[i]);
								ul.insert({bottom:('<li title="'+str+'"><input type="radio" name="aerop'+nomInput+'" value="'+lista[i].iata+'"/><span class="airport">'+str.truncate(57, '&hellip;')+'</span><span>'+lista[i].distancia+' Km</span></li>')});
							}
							for(;i<8;i++) ul.insert({bottom: '<li>&nbsp;</li>'});
						}
					}.bind(this);

					if(!Object.isElement(this.divCercanos)) {
						this.divCercanos = this.getInput('cercanos').remove();
						this.divCercanos.down('#buscarCercanos').on('click', function() {
							var origen = this.divCercanos.select('#aeropOrigen input:checked, #aeropOrigen input[type=hidden]').first();
							var destino = this.divCercanos.select('#aeropDestino input:checked, #aeropDestino input[type=hidden]').first();
							if(!origen || !destino) {
								alert('Por favor, selecciona un aeropuerto de origen y otro de destino');
								return;
							}
							this.origen.value = origen.value;
							this.destino.value = destino.value;
							this.submit();
						}.bind(this));
						this.divCercanos.down('#cancelarCercanos').on('click', function() {
							this.divCercanos.hide();
							$$('body').first().scrollTo(); 
						}.bind(this));
						this.div.insert({after: this.divCercanos});
					}
					
					var ulCiudadOrigen;
					var ulCiudadDestino;
					var ulAeropOrigen = this.divCercanos.down('ul#aeropOrigen');
					var ulAeropDestino = this.divCercanos.down('ul#aeropDestino');
					
					if(Object.isArray(json.origen.ciudades)) {
						ulCiudadOrigen = this.divCercanos.down('ul#ciudadOrigen');
						ulCiudadOrigen.select('li:not(.first)').invoke('remove');
						ulAeropOrigen.select('li:not(.first)').invoke('remove');
						ulAeropOrigen.insert({bottom: '<li>Selecciona una ciudad</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'});
						parseCiudades(json.origen.ciudades, ulCiudadOrigen, 'origen');
					}
					
					if(Object.isArray(json.destino.ciudades)) {
						ulCiudadDestino = this.divCercanos.down('ul#ciudadDestino');
						ulCiudadDestino.select('li:not(.first)').invoke('remove');
						ulAeropDestino.select('li:not(.first)').invoke('remove');
						ulAeropDestino.insert({bottom: '<li>Selecciona una ciudad</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li><li>&nbsp;</li>'});
						parseCiudades(json.destino.ciudades, ulCiudadDestino, 'destino');
					}

					if(Object.isArray(json.origen.aeropuertos)) {
						ulAeropOrigen.select('li:not(.first)').invoke('remove');
						parseAerop(json.origen.aeropuertos, ulAeropOrigen, 'origen');
					}

					if(Object.isArray(json.destino.aeropuertos)) {
						ulAeropDestino = this.divCercanos.down('ul#aeropDestino');
						ulAeropDestino.select('li:not(.first)').invoke('remove');
						parseAerop(json.destino.aeropuertos, ulAeropDestino, 'destino');
					}

					this.divCercanos.show();
					this.divCercanos.down('#ancla').scrollTo();
				}
			});

var BuscadorHoteles = Class.create(BuscadorSuper, {
	init : function() {	
		this.entrada = this.getInput('entrada');
		this.salida = this.getInput('salida');
		this.destino = this.getInput('destino');
		this.btnEntrada = this.getInput('btnEntrada');
		this.btnSalida = this.getInput('btnSalida');
		this.rutaDestino = this.getInput('rutaDestino');
		this.buscar = this.getInput('buscar');
		this.ofertasVuelos = this.getInput('ofertasVuelos');
		this.form = this.getInput('formHoteles');
		this.numNoches = this.getInput('numNoches');
		
		this.form.onsubmit = function() { return false;};
		
		var setBuscaHoteles = function (li) {
			this.destino.value = li.down('span[id=nombre]').innerHTML;
			this.rutaDestino.value = li.down('input[name=ruta]').value;
			//alert(this.rutaDestino.value);
		}.bind(this);
		
		this.autoDestino = new Autocompletado.AeroCiu(this.destino, this.divAuto,
				this.getInput('indicator1'), setBuscaHoteles, 5);
		
		var fSelect = function(cal) {
			if(Calendar.inputToInt.regexp.test(this.entrada.value) && (!Calendar.inputToInt.regexp.test(this.salida.value) || Calendar.inputToInt(this.entrada) >= Calendar.inputToInt(this.salida))) {
				var d = Calendar.inputToDate(this.entrada);
				d.setDate(d.getDate()+1);
				var dia = "0".times(2-d.getDate().toString().length)+d.getDate();
				var mes = "0".times(2-(d.getMonth()+1).toString().length)+(d.getMonth()+1);
				this.salida.value = dia+'/'+mes+'/'+d.getFullYear();
			}
			this.updateNoches();
			cal.hide();
		}.bind(this);
		this.calendarEntrada = Calendar.setup( {
			animation: false,
			trigger : this.btnEntrada,
			inputField : this.entrada,
			onSelect : fSelect,
			dateFormat : '%d/%m/%Y',
			align : 'Br',
			bottomBar : false,
			disabled : function(date) {
				return date.dateDiff(new Date()) < 0;
			}.bind(this)
		});
		this.entrada.on('click', this.fire.curry(this.btnEntrada, 'click'));
		
		this.calendarSalida = Calendar
				.setup( {
					animation: false,
					trigger : this.btnSalida,
					inputField : this.salida,
					onSelect : fSelect,
					dateFormat : '%d/%m/%Y',
					align : 'Br',
					bottomBar : false,
					disabled : function(date) {
						if(Calendar.inputToInt.regexp.test(this.entrada.value)) {
							var d = Calendar.inputToDate(this.entrada);
							d.setDate(d.getDate()+1);
							return date.dateDiff(d) < 0;
						}
					}.bind(this)
				});
		this.salida.on('click', this.fire.curry(this.btnSalida, 'click'));
		
		this.destino.on('focus', this.destino.clear);
		this.buscar.on('click', function() { 
			if(!this.rutaDestino.present()) {
				alert('Debes seleccionar la ciudad u hotel de destino');
				return;
			}
			
			if(this.rutaDestino.value.indexOf('?') > -1) {
				window.location = this.rutaDestino.value;
			}
			else {
				window.location = this.rutaDestino.value+"?entrada="+this.entrada.value+"&salida="+this.salida.value;
			}
		}.bind(this));
		
		if(Object.isElement(this.ofertasVuelos)) {
			this.loadOfertas(this.ofertasVuelos);
		}
	},
	updateNoches: function() {
		var n = Math.abs(Calendar.inputToDate(this.entrada).dateDiff(Calendar.inputToDate(this.salida)));
		this.numNoches.update('Has seleccionado <strong>'+n+'</strong> '+(n > 1 ? 'noches' : 'noche'));
	}
});

var BuscadorVuelo_hoteles = Class.create(BuscadorSuper, {		
		init : function() {
			this.origenVH = this.getInput('origenVH');
			this.txtOrigenVH = this.getInput('txtOrigenVH');
			this.destinoVH = this.getInput('destinoVH');
			this.txtDestinoVH = this.getInput('txtDestinoVH');
			this.fechaIdaVH = this.getInput('fechaIdaVH');
			this.fechaVueltaVH = this.getInput('fechaVueltaVH');
			this.btnFechaIdaVH = this.getInput('btnFechaIdaVH');
			this.numHabitacionesVH =this.getInput('numHabitacionesVH');
			this.CategoriaVH =this.getInput('CategoriaVH');
			this.numAdultosVH =this.getInput('numAdultosVH');
			this.numNinyosVH =this.getInput('numNinyosVH');			
			this.btnFechaVueltaVH = this.getInput('btnFechaVueltaVH');
			this.ofertasVuelos = this.getInput('ofertasVuelos');
			this.soloVuelosDirectos = this.getInput('soloVuelosDirectos');			
			this.form = this.getInput('buscaVueloHoteles');			
			this.form.onsubmit = function() { return false;};
			this.buscar = this.getInput('buscar');
			this.buscar.on('click', this.submit.bind(this));
			this.pais_nav = this.getInput("pais_nav").value;
			this.cambioOrigen = this.origenVH.present();
			this.cambioDestino = this.destinoVH.present();
			
			/*			
			var tipoAutocomp = Object.isElement(this.getInput('cercanos')) ? 1 : 2;
			this.autoOrigenVH  = new Autocompletado.AeroCiu(this.txtOrigenVH , this.divAuto , this.indicator1, this.setAerop.curry(this.txtOrigenVH , this.origenVH ), tipoAutocomp);
			this.autoDestinoVH  = new Autocompletado.AeroCiu(this.txtDestinoVH , this.divAuto , this.indicator2, this.setAerop.curry(this.txtDestinoVH , this.destinoVH ), tipoAutocomp);
			*/
			var setBuscaHotelesOrig = function (li) {
			this.txtOrigenVH.value = li.down('span[id=nombre]').innerHTML;			
			var cadenaOrig=	this.quitarAcentos(this.txtOrigenVH.value);		
			if(cadenaOrig.indexOf(",")==-1){	
				this.origenVH.value=cadenaOrig.substring(0,cadenaOrig.indexOf("(")-1);
			}else{
				this.origenVH.value=cadenaOrig.substring(0,cadenaOrig.indexOf(",")-1);
			}
			
			}.bind(this);
		
			this.autoOrig = new Autocompletado.AeroCiu(this.txtOrigenVH, this.divAuto,
				this.getInput('indicator1'), setBuscaHotelesOrig, 5);
				
			var setBuscaHotelesDest = function (li) {
			this.txtDestinoVH.value = li.down('span[id=nombre]').innerHTML;
			var cadenaDest=	this.quitarAcentos(this.txtDestinoVH.value);
			if (cadenaDest.indexOf(",")==-1){
				this.destinoVH.value=cadenaDest.substring(0,cadenaDest.indexOf("(")-1);	
			}else{
				this.destinoVH.value=cadenaDest.substring(0,cadenaDest.indexOf(",")-1);
			}								
			}.bind(this);
		
			this.autoDest = new Autocompletado.AeroCiu(this.txtDestinoVH, this.divAuto,
				this.getInput('indicator2'), setBuscaHotelesDest, 5);
			
			this.txtOrigenVH .on('focus', function() { 
				this.txtOrigenVH.clear();
				this.origenVH.clear();
				this.cambioOrigen = true; 
			}.bind(this));
						
			this.txtDestinoVH .on('focus', function() { 
				this.txtDestinoVH.clear();
				this.destinoVH.clear();
				this.cambioDestino = true; 
			}.bind(this));

			var fSelect = function(cal) {
			if(Calendar.inputToInt.regexp.test(this.fechaIdaVH.value) && (!Calendar.inputToInt.regexp.test(this.fechaVueltaVH.value) || Calendar.inputToInt(this.fechaIdaVH) >= Calendar.inputToInt(this.fechaVueltaVH))) {
				var d = Calendar.inputToDate(this.fechaIdaVH);
				d.setDate(d.getDate()+1);
				var dia = "0".times(2-d.getDate().toString().length)+d.getDate();
				var mes = "0".times(2-(d.getMonth()+1).toString().length)+(d.getMonth()+1);
				this.fechaVueltaVH.value = dia+'/'+mes+'/'+d.getFullYear();
			}
			cal.hide();
			}.bind(this);
			this.calendarEntrada = Calendar.setup( {
				animation: false,
				trigger : this.btnFechaIdaVH,
				inputField : this.fechaIdaVH,
				onSelect : fSelect,
				dateFormat : '%d/%m/%Y',
				align : 'Br',
				bottomBar : false,
				disabled : function(date) {
					return date.dateDiff(new Date()) < 0;
				}.bind(this)
			});
			this.fechaIdaVH.on('click', this.fire.curry(this.btnFechaIdaVH, 'click'));
			
			this.calendarSalida = Calendar
				.setup( {
					animation: false,
					trigger : this.btnFechaVueltaVH,
					inputField : this.fechaVueltaVH,
					onSelect : fSelect,
					dateFormat : '%d/%m/%Y',
					align : 'Br',
					bottomBar : false,
					disabled : function(date) {
						if(Calendar.inputToInt.regexp.test(this.fechaIdaVH.value)) {
							var d = Calendar.inputToDate(this.fechaIdaVH);
							d.setDate(d.getDate()+1);
							return date.dateDiff(d) < 0;
						}
					}.bind(this)
				});
			this.fechaVueltaVH.on('click', this.fire.curry(this.btnFechaVueltaVH, 'click'));
			
			if(Object.isElement(this.ofertasVuelos)) {				
				this.loadOfertas(this.ofertasVuelos);
			}
			
		},	
		
		quitarAcentos: function(cadena){
			var cadRet=cadena.toLowerCase();
			
			cadRet=cadRet.replace("á","a");
			cadRet=cadRet.replace("é","e");
			cadRet=cadRet.replace("í","i");
			cadRet=cadRet.replace("ó","o");
			cadRet=cadRet.replace("ú","u");			
			
			return cadRet;
		},
		
		submit: function() {
						if(!this.cambioOrigen || !this.cambioDestino) {
							alert('Selecciona la ruta y las fechas, por favor.');
							return;
						}
						
						if(!this.origenVH.present() && !this.txtOrigenVH.present()) {
							alert('Selecciona un aeropuerto de origen, por favor.');
							return;
						}
						
						if(!this.destinoVH.present() && !this.txtDestinoVH.present()) {
							alert('Selecciona un aeropuerto de destino, por favor.');
							return;
						}
							
						var params = this.form.serialize();
											
						if(this.pais_nav!='ES'){
							this.abreURL('/arg/busquedaArgentinaVH.php?'+params);
						}else{
							this.abreURL('/vuelos/scrappers/busquedasExternasVH.php?'+params);
							this.estadisticas(51);
						}						
						
			},
		
		go: function(url) {
			window.location = url;
		}
		
					
});

var BuscadorViajes = Class.create(BuscadorSuper, {		
		init : function() {
			var urlRUMBO='/vuelos/busquedasExternasViajes.php?destino=';
			
			this.destino = this.getInput('destino');
			
			this.form = this.getInput('buscaViajes');
			this.form.onsubmit = function() { return false;};
								
			this.directoPuntaCana = this.getInput('directoPuntaCana');
			this.directoPuntaCana.on('click', function(){				
				window.top.location.href=urlRUMBO+'punta cana';
			});			
			this.directoRivieraMaya = this.getInput('directoRivieraMaya');
			this.directoRivieraMaya.on('click', function(){
				window.top.location.href=urlRUMBO+'riviera maya';
			});			
			this.directoBrasil = this.getInput('directoBrasil');
			this.directoBrasil.on('click', function(){
				window.top.location.href=urlRUMBO+'brasil';
			});			
			this.directoTenerife = this.getInput('directoTenerife');
			this.directoTenerife.on('click', function(){
				window.top.location.href=urlRUMBO+'tenerife';
			});			
			this.directoLanzarote = this.getInput('directoLanzarote');
			this.directoLanzarote.on('click', function(){
				window.top.location.href=urlRUMBO+'lanzarote';
			});			
			this.directoMallorca = this.getInput('directoMallorca');
			this.directoMallorca.on('click', function(){
				window.top.location.href=urlRUMBO+'mallorca';
			});			
			this.directoIbiza = this.getInput('directoIbiza');
			this.directoIbiza.on('click', function(){
				window.top.location.href=urlRUMBO+'ibiza';
			});			
			this.directoEgipto = this.getInput('directoEgipto');
			this.directoEgipto.on('click', function(){
				window.top.location.href=urlRUMBO+'egipto';
			});			
			this.directoParis = this.getInput('directoParis');
			this.directoParis.on('click', function(){
				window.top.location.href=urlRUMBO+'paris';
			});
			this.directoNuevaYork = this.getInput('directoNuevaYork');
			this.directoNuevaYork.on('click', function(){
				window.top.location.href=urlRUMBO+'nueva york';
			});
			this.directoAmsterdam = this.getInput('directoAmsterdam');
			this.directoAmsterdam.on('click', function(){
				window.top.location.href=urlRUMBO+'amsterdam';
			});
			this.directoCuba = this.getInput('directoCuba');
			this.directoCuba.on('click', function(){
				window.top.location.href=urlRUMBO+'cuba';
			});
			this.directoDisney = this.getInput('directoDisney');
			this.directoDisney.on('click', function(){
				window.top.location.href=urlRUMBO+'disney';
			});
			this.directoAlemania = this.getInput('directoAlemania');
			this.directoAlemania.on('click', function(){
				window.top.location.href=urlRUMBO+'alemania';
			});
			
			this.directoItalia = this.getInput('directoItalia');
			this.directoItalia.on('click', function(){
				window.top.location.href=urlRUMBO+'italia';
			});
			
			this.ofertasVuelos = this.getInput('ofertasVuelos');	
			
			this.buscar = this.getInput('buscar');
			this.buscar.on('click', this.submit.bind(this));
			
			if(Object.isElement(this.ofertasVuelos)) {
				this.loadOfertas(this.ofertasVuelos);
			}
			
		},		
		
		submit: function() {
			var urlRUMBO='/vuelos/busquedasExternasViajes.php?destino=';
			
			if (this.destino.value==""){
				alert("Debes elegir un destino.");
				return;
			}
			
			window.top.location.href=urlRUMBO+this.destino.value;
		
		}
});


var BuscadorAlarmas = Class.create(BuscadorSuper, {
	initialize: function($super, div, reloadOnSuccess) {
		this.reload = !!reloadOnSuccess;
		$super(div);
	},
	
	init : function() {
		this.origen = this.getInput('iataOrigen');
		this.destino = this.getInput('iataDestino');
		this.txtOrigen = this.getInput('txtOrigen');
		this.txtDestino = this.getInput('txtDestino');
		this.fechaIdaMin = this.getInput('fechaIdaMin');
		this.fechaIdaMax = this.getInput('fechaIdaMax');
		this.fechaVueltaMin = this.getInput('fechaVueltaMin');
		this.fechaVueltaMax = this.getInput('fechaVueltaMax');
		this.btnFechaIdaMin = this.getInput('btnFechaIdaMin');
		this.btnFechaIdaMax = this.getInput('btnFechaIdaMax');
		this.btnFechaVueltaMin = this.getInput('btnFechaVueltaMin');
		this.btnFechaVueltaMax = this.getInput('btnFechaVueltaMax');
		this.txtPrecioMaximo = this.getInput('txtPrecioMaximo');
		this.precioMaximo = "";
		this.email = this.getInput('email');
		this.soloIda = this.getInput('soloIda');
		this.idaYVuelta = this.getInput('idaYVuelta');
		this.buscar = this.getInput('buscar');
		this.form = this.getInput('formAlarmas');		
		this.form.onsubmit = function() { return false;};
		
		this.autoOrigen = new Autocompletado.AeroCiu(this.txtOrigen, this.divAuto, this.getInput("indicator1"), this.setAerop.curry(this.txtOrigen, this.origen));
		this.autoDestino = new Autocompletado.AeroCiu(this.txtDestino, this.divAuto, this.getInput("indicator2"), this.setAerop.curry(this.txtDestino, this.destino));

		var clear = function(txt, hid) {
			txt.clear();
			hid.clear();
		};

		this.txtOrigen.on('focus', clear.curry(this.txtOrigen, this.origen));
		this.txtDestino.on('focus', clear.curry(this.txtDestino, this.destino));
		this.txtPrecioMaximo.on('focus',this.txtPrecioMaximo.clear);
		this.txtPrecioMaximo.on('change',function() { this.precioMaximo = this.txtPrecioMaximo.value;}.bind(this));
		
		if(this.email) {
			this.email.on('focus', this.email.clear);
		}
		
		this.soloIda.on('click', function() {
			this.fechaVueltaMin.disable();
			this.fechaVueltaMax.disable();
			this.fechaVueltaMin.value = "Vuelta";
			this.fechaVueltaMax.value = "Vuelta";
			this.btnFechaVueltaMin.disable();			
			this.btnFechaVueltaMax.disable();
			
		}.bind(this));

		this.idaYVuelta.on('click', function() {
			this.fechaVueltaMin.enable();
			this.fechaVueltaMax.enable();
			this.fechaVueltaMin.value = "Vuelta";
			this.fechaVueltaMax.value = "Vuelta";
			
			//this.fechaVueltaMin.value = this.fechaIdaMin.value;
			//this.fechaVueltaMax.value = this.fechaIdaMax.value;
			
			this.btnFechaVueltaMin.enable();			
			this.btnFechaVueltaMax.enable();
			

		}.bind(this));
		
		this.calendarIdaMin = Calendar.setup( {
			animation: false,
			trigger : this.btnFechaIdaMin,
			inputField : this.fechaIdaMin,
			onSelect : function(cal) {
				if(!Calendar.inputToInt.regexp.test(this.fechaIdaMax.value)) {
					var d = Calendar.intToDate(cal.selection.get());
					d.setDate(d.getDate()+30);
					d = Calendar.printDate(d, '%d/%m/%Y');
					this.fechaIdaMax.value = d;
					
					if(this.idaYVuelta.checked) {
						this.fechaVueltaMax.value = d;
						this.fechaVueltaMin.value = this.fechaIdaMin.value;
					}
				}
				
				if(Calendar.inputToInt(this.fechaIdaMin) > Calendar.inputToInt(this.fechaIdaMax)) {
					this.fechaIdaMax.value = this.fechaIdaMin.value;
				}
				
				if(Calendar.inputToInt.regexp.test(this.fechaVueltaMax.value) && Calendar.inputToInt(this.fechaIdaMin) > Calendar.inputToInt(this.fechaVueltaMax)) {
					this.fechaVueltaMax.value = this.fechaIdaMin.value;
				}
				
				if(!this.fechaVueltaMin.disabled && Calendar.inputToInt(this.fechaIdaMin) > Calendar.inputToInt(this.fechaVueltaMin)) {
					this.fechaVueltaMin.value = this.fechaIdaMin.value;
				}
				
				cal.hide();
			}.bind(this),
			dateFormat : '%d/%m/%Y',
			align : 'Br',
			bottomBar : false,
			disabled : function(date) {
				return date.dateDiff(new Date()) < 0;
			}.bind(this)
		});
		this.fechaIdaMin.on('click', this.fire.curry(this.btnFechaIdaMin, 'click'));
		
		this.calendarIdaMax = Calendar
				.setup({
					animation: false,
					trigger : this.btnFechaIdaMax,
					inputField : this.fechaIdaMax,
					onSelect : function(cal) {
						if(Calendar.inputToInt.regexp.test(this.fechaIdaMax.value)) {							
							
							//solucion 1
							/*
							var d = Calendar.intToDate(cal.selection.get())
							d = Calendar.printDate(d, '%d/%m/%Y');	
							var f1 = Calendar.inputToInt(this.fechaIdaMax);
							var f2 = Calendar.inputToInt(this.fechaVueltaMin);											
							if(f2<f1){														
								this.fechaVueltaMin.value = this.fechaIdaMax.value;
								this.fechaVueltaMax.value = this.fechaIdaMax.value;	
								var f = Calendar.inputToInt(this.fechaIdaMax);
								this.calendarVueltaMin.selection.reset(f, false);
							 	this.calendarVueltaMax.selection.reset(f, false);								
							}*/
							
							//solucion 2
							var d = Calendar.intToDate(cal.selection.get())
							d = Calendar.printDate(d, '%d/%m/%Y');	
							var f1 = Calendar.inputToInt(this.fechaIdaMax);
							var f2 = Calendar.inputToInt(this.fechaVueltaMax);											
							if(f1>f2){
								this.fechaVueltaMax.value = this.fechaIdaMax.value;	
								var f = Calendar.inputToInt(this.fechaIdaMax);								
							 	this.calendarVueltaMax.selection.reset(f, false);								
							}
							
						}
						cal.hide();
					}.bind(this),
					dateFormat : '%d/%m/%Y',
					align : 'Br',
					bottomBar : false,
					disabled : function(date) {
						return date.dateDiff(this.calendarIdaMin.date) < 0;
					}.bind(this)
				});
		this.fechaIdaMax.on('click', this.fire.curry(this.btnFechaIdaMax, 'click'));
		
		this.calendarVueltaMin = Calendar.setup( {
			animation: false,
			trigger : this.btnFechaVueltaMin,
			inputField : this.fechaVueltaMin,
			onSelect : function(cal) {
				if(Calendar.inputToInt(this.fechaVueltaMin) > Calendar.inputToInt(this.fechaVueltaMax)) {
					this.fechaVueltaMax.value = this.fechaVueltaMin.value;
				}
				cal.hide();
			}.bind(this),
			dateFormat : '%d/%m/%Y',
			align : 'Br',
			bottomBar : false,
			disabled : function(date) {
				return (!Calendar.inputToInt.regexp.test(this.fechaIdaMin.value) || Calendar.dateToInt(date) < Calendar.inputToInt(this.fechaIdaMin));
			}.bind(this)
		});
		this.fechaVueltaMin.on('click', this.fire.curry(this.btnFechaVueltaMin, 'click'));
		
		this.calendarVueltaMax = Calendar.setup({
					animation: false,
					trigger : this.btnFechaVueltaMax,
					inputField : this.fechaVueltaMax,
					onSelect : function(cal) {
						if(Calendar.inputToInt.regexp.test(this.fechaVueltaMax.value) && !Calendar.inputToInt.regexp.test(this.fechaVueltaMin.value)) {
							this.fechaVueltaMin.value = this.fechaVueltaMax.value;
						}
						cal.hide();
					}.bind(this),
					dateFormat : '%d/%m/%Y',
					align : 'Br',
					bottomBar : false,
					disabled : function(date) {
						return (!Calendar.inputToInt.regexp.test(this.fechaIdaMin.value) || Calendar.dateToInt(date) < Calendar.inputToInt(this.fechaIdaMin))
						&& (!Calendar.inputToInt.regexp.test(this.fechaVueltaMin.value) || Calendar.dateToInt(date) < Calendar.inputToInt(this.fechaVueltaMin));
					}.bind(this)
				});
		this.fechaVueltaMax.on('click', this.fire.curry(this.btnFechaVueltaMax, 'click'));
		
		this.buscar.on('click', this.submit.bind(this));
	},
	submit: function() {
		if(!this.origen.present()) {
			alert('Selecciona un aeropuerto de origen, por favor.');
			return false;
		}
		
		if(!this.destino.present()) {
			alert('Selecciona un aeropuerto de destino, por favor.');
			return false;
		}
		
		if(this.idaYVuelta.checked) {
			if([this.fechaIdaMin.value, this.fechaIdaMax.value].grep(Calendar.inputToInt.regexp).size() <= 0) {
				alert('Por favor, introduce el rango de fechas tanto para la ida como para la vuelta.');
				return;
			}
		}
		else {
			if([this.fechaIdaMin.value, this.fechaIdaMax.value, this.fechaVueltaMin.value, this.fechaVueltaMax.value].grep(Calendar.inputToInt.regexp).size() <= 0) {
				alert('Por favor, introduce el rango de fechas para la ida.');
				return;
			}
		}
		
		if(this.email && (!this.email.present() || this.email.value.indexOf('@') <= -1)) {
			alert('Por favor, introduce tu e-mail para que podamos avisarte.');
			return;
		}
		
		
		//if((this.precioMaximo.length > 0 && !this.precioMaximo.value.match(/^([0-9]*\.)?[0-9]+$/))) {
		if((this.precioMaximo.match(/^([0-9]*\.)?[0-9]+$/)==null)) {			
			alert("El precio indicado no es válido");
			return;
		}
		else {
			this.precioMaximo = this.precioMaximo.blank() ? "-1" : ""+parseFloat(this.precioMaximo, 10);
		}
		
		var solo_ida;
		if(this.soloIda.checked==true){
			solo_ida='1';
		}else{
			solo_ida='0';
		}
		
		var pars = {'iataOrigen':this.origen.value, 
					'iataDestino':this.destino.value, 
					'fechaIdaMin':this.fechaIdaMin.value,
					'fechaIdaMax':this.fechaIdaMax.value, 
					'fechaVueltaMin':this.fechaVueltaMin.value, 
					'fechaVueltaMax':this.fechaVueltaMax.value, 
					'precioMaximo':this.precioMaximo,
					'soloIda':solo_ida,
					'email': (this.email ? this.email.value.strip() : '')};
	
		new Ajax.Request('/comunidad/php/alarmas/nuevaAlarma.php', {
			method: 'get',
			parameters: pars,
			onLoading: function(){
				this.buscar.hide();
			}.bind(this),
			onSuccess: function(t){
					if(t.responseText.indexOf("true")!=-1){
				    	alert('Alarma creada con éxito. Te avisaremos por email.');
				    	window.location.reload();
				    }else{
				    	alert('Ya existe una alarma creada anteriormente con esos datos.');
				    }
				    
					this.buscar.show();
					
					if(eval(t.responseText)) {
						this.email.remove();
						new Ajax.Request('/comunidad/lib/logic/precabecera2.php', {
							method: 'post',
							onComplete: function(t){
								$('cntlogin').update(t.responseText);
							}
						});
					}
					
					this.estadisticas(42);
					
					if(this.reload) {o
						window.location.reload();
						return;
					}
					
			}.bind(this),
			on403: function(t) {
				alert(t.statusText);
				this.buscar.show();
			}.bind(this),
			on500: function(t) {
				alert(t.statusText);
				this.buscar.show();
			}.bind(this)
		});
	}
});

var BuscadorOfertas = Class.create(BuscadorSuper, {
	init : function() {
		this.origen = this.getInput('origen');
		this.destino = this.getInput('destino');
		this.txtOrigen = this.getInput('txtOrigen');
		this.txtDestino = this.getInput('txtDestino');
		this.buscar = this.getInput('buscar');
		this.form = this.getInput('buscaOfertas');
		
		var clear = function(txt, hid) {
			txt.clear();
			hid.clear();
		};

		this.txtOrigen.on('focus', clear.curry(this.txtOrigen, this.origen));
		this.txtDestino.on('click', clear.curry(this.txtDestino, this.destino));
		
		this.autoOrigen = new Autocompletado.AeroCiu(this.txtOrigen ,this.divAuto, this.getInput("indicator1"), this.setAerop.curry(this.txtOrigen, this.origen), 2);
		this.autoDestino = new Autocompletado.AeroCiu(this.txtDestino,this.divAuto, this.getInput("indicator2"),  this.setAerop.curry(this.txtDestino, this.destino), 2);
		
		this.buscar.on('click', function() {
			if(!this.origen.present()) {
				alert('Debe introducir un origen');
				return;
			}
			this.estadisticas(41);
			this.form.submit();
		}.bind(this));
	}
});

var BuscadorDestinos = Class.create(BuscadorSuper, {
	initialize: function($super, div, guia) {
		this.guia = guia || undefined;
		$super(div);
	},
	init : function() {
		this.destino = this.getInput('destino');
		this.destino.on('focus', this.destino.clear);

		if(this.guia) {
			var setBuscadorDestino = function(li) {
				var coord = $F(li.down('#coord_'+li.id));
				coord = coord.split(',');
				var lat = parseFloat(coord[0]);
				var lng = parseFloat(coord[1]);
				var zoom = parseInt($F(li.down('#zoom_'+li.id)),10);
				var ll = new google.maps.LatLng(lat, lng);
				this.map.panTo(ll);
				this.map.setZoom(zoom);
			}.bind(this.guia);
		}
		else {
			var setBuscadorDestino = function (li){
				var url = li.down('#url_'+li.id);
				if ( url && url.value.blank() ) {
					new Ajax.Request('/comunidad/lib/utils/getruta.php', { 
						method: 'post', 
						parameters: {'item_id': li.id, 'tipo':li.down('#tipo_'+li.id).value},
						onComplete:function(t){
					        var params = {
					        	bus_item_id: li.id,
					        	bus_valor_tx: li.down('#valor_'+li.id).innerHTML,
					        	bus_tipo_tx: li.down('#tipo_'+li.id).value
					        };
	
							this.go(t.responseText+"?"+$H(params).toQueryString());
					    }
					});
				}
				else {
					this.go(url.value);
				}	
			}.bind(this);
		}
		this.autoDestino = new Autocompletado.AeroCiu(this.destino ,this.divAuto, this.getInput('indicator1'), setBuscadorDestino, 3);
	},
	go: function(url) {
		window.location = url;
	}
});

var BuscadorViajeros = Class.create(BuscadorSuper, {
	init : function() {
		this.campo = this.getInput('campo');
		this.ubicacion = this.getInput('ubicacion');
		this.nombre = this.getInput('nombre');
		this.indicator = this.getInput('indicator1'); 
		this.campo.on('focus', this.campo.clear);

		var getCiudad = function(li) {
			var coord = (li.down('#coord_'+li.id).value).split(",");
			var url = 'guiadeviajes/?lat='+coord[0]+'&lng='+coord[1]+'&zoom=13';
			window.location = url;
		};

		var getUsuario = function(li){
			var url = 'guiadeviajes/?lat='+li.down('#lat_'+li.id).value+'&lng='+li.down('#long_'+li.id).value+'&zoom=12';
			window.location = url;
		};

		this.autoCiudad = new Autocompletado.AeroCiu(this.campo, this.divAuto, this.indicator, getCiudad, 6);
		this.autoUsuario = new Autocompletado.AeroCiu(this.campo, this.divAuto, this.indicator, getUsuario, 7);
		this.autoUsuario.stop();
		
		this.ubicacion.on('click', function() {
			this.campo.value="Buscar ciudad…";
			this.autoUsuario.stop();
			this.autoCiudad.start();
		}.bind(this));
		
		this.nombre.on('click', function() {
			this.campo.value="Buscar usuario…";
			this.autoCiudad.stop();
			this.autoUsuario.start();	
		}.bind(this));
	}
});

Calendar.inputToInt = function(field) {
	return parseInt(field.value.replace(Calendar.inputToInt.regexp, "$3$2$1"), 10);
};

Calendar.inputToInt.regexp = /^(\d+)\/(\d+)\/(\d+)$/;

Calendar.inputToDate = function(field) {
	return Calendar.parseDate(field.value.replace(Calendar.inputToInt.regexp, "$2-$1-$3"));
};

Date.y2k = function(y) {
	return (y < 1000) ? y + 1900 : y;
};

Date.prototype.dateDiff = function(date) {
    return (Date.UTC(Date.y2k(this.getYear()),this.getMonth(),this.getDate(),0,0,0) - Date.UTC(Date.y2k(date.getYear()),date.getMonth(),date.getDate(),0,0,0))/86400000;
};
