/* ---------------------------------------------------------------------------------------------------- */
/* =fewo.search.js */
/* ---------------------------------------------------------------------------------------------------- */


/* -------------------------------------------------- */
/* =search */

FEWO.search = {
	
	options: {
		showExtendedSearch: true,
		'map': {},
		'direct': {},
		'extended': {}
	},
	
	init: function (options) {
		this.options = $merge(this.options, options);
		this.container = $('search-container');
		
		if (!this.options.showExtendedSearch) {
			this.extended.destroy();
			this.container.setStyle('overflow', 'visible');
			this.options.map.isExpandable = true;
			this.options.direct.isExpandable = true;
		}
				
		this.options.direct.DisplayRange = this.options.extended.DisplayRange = this.options.DisplayRange;
		this.options.direct.SelectRange = this.options.extended.SelectRange = this.options.SelectRange;
		 
		if (this.options.showExtendedSearch) {
			this.container.setStyle('height', 358);
		}
		 
		this.map.init(this.options.map);
		this.direct.init(this.options.direct);
		
		if (this.options.showExtendedSearch) {
			this.extended.init(this.options.extended);
		}
		
	}
    
};


/* -------------------------------------------------- */
/* =map-search */

FEWO.search.map = {
	
	options: {
		isExpandable: false,
		showIntro: false,
		flashSize: {x: 468, y: 358}
	},
	
	init: function (options) {
		this.options = $merge(this.options, options);
		this.container = $('map-search-container');
		this.map = $('map-search');
		this.wmode = 'transparent';
		
		// main app
		if (wlid == 1) {		
			// load overview
			if (this.options.regionID == 0) { 
				this.map.setStyle('top', 42);
				this.options.flashSize.y = 316;
				this.src = '/_swf/map-search.swf';
				
			// load region
			} else { 
				this.src = '/_swf/map-search-region-' + this.options.regionID + '.swf';
			}
			this.loadFlash();
		
		// whitelabeling
		} else {
			new Element('a', {
				'href': '/search/map/',
				'styles': {
					'background-image': 'url(/_whitelabel/' + wlid + '/_gfx/bg_map-search.jpg)'
				}
			}).inject(this.map);
		}
		
		if (this.options.isExpandable) {
			this.isOpen = false;
			this.fx = new Fx.Tween(this.container, {
				'property': 'height',
				'link': 'cancel',
				'transition': 'sine:out',
				'onComplete': this.checkFlash.bind(this)
			}).set(42);
			this.switcher = new Element('a', {
				'class': 'switcher',
				'events': {
					'click': this.toggle.bind(this)
				}
			}).inject(this.container);
		}
		
		
		// shim
		this.iframeShim = new IFrameShim(this.container, {zindex: 99, container: this.container});		
		
	},
	
	loadFlash: function () {
		this.swiff = new Swiff(this.src, {
			'width': this.options.flashSize.x,
			'height': this.options.flashSize.y,
			'params': {
				wMode: this.wmode
			},
			'vars': {
				'lang': lang,
				'serviceurl': '/_swf/Regions.xml',
				'regionid': this.options.regionID,
				'showintro': this.options.showIntro
			},
			'container': this.map
		});
	},
	
	checkFlash: function () {
		if (wlid == 1) {
		
			if (Browser.Engine.gecko && this.isOpen) {
				this.container.setStyle('overflow', 'none');
				this.wmode = 'window';
				this.loadFlash.delay(10, this);
			}
			
			// shim
			if (this.iframeShim.isActive) {
				if (this.isOpen) {
					this.iframeShim.show();
				} else {
					this.iframeShim.hide();
				}
			}
		}
		 
	},
	
	open: function () {
		this.isOpen = true;
		this.fx.start(358);
	},
	
	close: function () {
		if (Browser.Engine.gecko && this.isOpen && wlid == 1) {
			this.container.setStyle('overflow', 'hidden');
			this.wmode = 'transparent';
			this.loadFlash();
		}
		this.isOpen = false;
		this.fx.start(42);
	},
	
	toggle: function () {
		(this.isOpen) ? this.close() : this.open();
		this.switcher.toggleClass('collapse');
	}
	
};


/* -------------------------------------------------- */
/* =direct-search */

FEWO.search.direct = {
	
	options: {
		isExpandable: false
	},
	
	init: function (options) {
		this.options = $merge(this.options, options);
		this.container = $('direct-search-container');
		if (this.options.isExpandable) {
			this.isOpen = false;
			this.fx = new Fx.Tween(this.container, {
				'property': 'height',
				'link': 'cancel',
				'transition': 'sine:out',
				'onComplete': function () {
					this.checkShim();
					this.setFocus();
				}.bind(this)
			}).set('42');
			this.switcher = new Element('a', {
				'class': 'switcher',
				'events': {
					'click': this.toggle.bind(this)
				}
			}).inject(this.container);
		}
		
		this.form = $('direct-search-container');
		this.form.getElement('fieldset').getElements('input, select, textarea').each(function (el) {
			var event;
			switch (el.get('tag')) {
				case 'input': case 'textarea':
					event = 'blur';
					break;
				case 'select':
					event = 'change';
					break;
			}
			el.addEvent(event, this.getResultCounter.bind(this));
		}, this);
		
		this.form.set('send', {
			'url': '/_service/ResultCounter.ashx',
			'autoCancel': true,
			'onSuccess': this.displayResultCounter.bind(this)
		});
		this.resultCounterBar = $('result-counter-bar');
		this.resultCounterLabel = $('result-counter-label');
		this.getResultCounter();
		
		
		/* autocomplete */
		new MXM.Form.Autocomplete.Remote($('direct-search-city').getElement('input'), {service: '/_service/LocationFinder.ashx', keyword: 'query', minLength: 1, width: 166, scrollable: true});
	
		
		/* calendars */
		this.fields = {
			arrival: $('direct-search-arrival').getElement('select'),
			departure: $('direct-search-departure').getElement('select')
		};
		
		this.fields.arrival.addEvent('change', this.presetDate.pass(this.fields.arrival, this));
		this.fields.departure.addEvent('change', this.presetDate.pass(this.fields.departure, this));
				
		this.calendars = {
			'arrival': new MXM.Date.Calendar({
				Months: MXM.Date.Months,
				WeekDays: MXM.Date.WeekDays,
				Today: FEWO.Dict.get('TEXT-TITLE-TODAY'),
				showCW: true,
				DisplayRange: this.options.DisplayRange,
				SelectRange: this.options.SelectRange,
				onSelect: function (date) {
					this.selectDate(this.fields.arrival, date);
					if (Browser.Engine.trident && Browser.Engine.version == 4) { // slow down, not so fast for ie6
						this.presetDate.delay(10, this, this.fields.arrival);
					 } else {
						this.presetDate(this.fields.arrival);
					 }
				}.bind(this)
			}),
			'departure': new MXM.Date.Calendar({
				Months: MXM.Date.Months,
				WeekDays: MXM.Date.WeekDays,
				Today: FEWO.Dict.get('TEXT-TITLE-TODAY'),
				showCW: true,
				DisplayRange: this.options.DisplayRange,
				SelectRange: this.options.SelectRange,
				onSelect: function (date) {
					this.selectDate(this.fields.departure, date);
					if (Browser.Engine.trident && Browser.Engine.version == 4) { // slow down, not so fast for ie6
						this.presetDate.delay(10, this, this.fields.departure);
					 } else {
						this.presetDate(this.fields.departure);
					 }
				}.bind(this)
			})
		};
		
		$('btn-direct-search-arrival-calendar').addEvent('click', function (event) {
			this.calendars.arrival.load(event, { date: this.fields.arrival.get('value') });
		}.bind(this));
		$('btn-direct-search-departure-calendar').addEvent('click', function (event) {
			this.calendars.departure.load(event, { date: this.fields.departure.get('value') });
		}.bind(this));
		
		// shim
		this.iframeShim = new IFrameShim(this.container, {zindex: 99, container: this.container.getParent()});
		
		
		// set focus
		this.setFocus();
	},
	
	setFocus: function () {
		if ((this.options.isExpandable && this.isOpen) || !this.options.isExpandable) {
			$('direct-search-city').getElement('input').focus();
		}
	},
	
	selectDate: function (target, date) {
		var date = date.format('dd.MM.yyyy');
		var values = $A(target.options).map(function (option) {
			return option.value;
		}, this);
		
		if (!values.contains(date)) { // add date
			values.push(date);
			values.sort(function (a, b) {
				var a = a.split('.'); a.reverse(); a = a.join('').toInt();
				var b = b.split('.'); b.reverse(); b = b.join('').toInt();
				return a - b;
			});
			var ubound = target.options.length - 1;
			var index, where;
			if (values.indexOf(date) < ubound) { // new date injected between existing dates
				index = values.indexOf(date);
				where = 'before';
			} else { // new date in the future, injected at the end of the list
				index = ubound;
				where = 'after';
			}
			new Element('option', {
				'value': date,
				'text': date
			}).inject(target.options[index], where);
		}
		
		// select date
		if (Browser.Engine.trident && Browser.Engine.version == 4) { // ie6 needs some extratime to select the current date
			target.set.delay(10, target, ['value', date]);
		} else {
			target.set('value', date); 
		}
		
	},
	
	open: function () {
		this.isOpen = true;
		this.fx.start(358);
	},
	
	checkShim: function () {
		// shim
		if (this.iframeShim.isActive) {
			if (this.isOpen) {
				this.iframeShim.show();
			} else {
				this.iframeShim.hide();
			}
		}
	},
	
	close: function () {
		this.isOpen = false;
		this.fx.start(42);
	},
	
	toggle: function () {
		(this.isOpen) ? this.close() : this.open();
		this.switcher.toggleClass('collapse');
	},
	
	getResultCounter: function () {
		this.form.send();
	},
	
	displayResultCounter: function (text) {
		var json = JSON.decode(text, true);
		var percent = (json.Count / json.Total) * 100;
		var pixel = ((percent / 100) * 160).round();
		this.resultCounterBar.setStyle('width', pixel);
		this.resultCounterLabel.set({
			'html': json.Count + '&nbsp;' + FEWO.Dict.get('TEXT-MAPSEARCH-OBJECTS'),
			'styles': {
				'left': ((percent.toInt() <= 50) ? pixel : 0) + 5
			}
		});
	},
	
	presetDate: function (field) {
		var arrival = MXM.Date.extract(this.fields.arrival.get('value'));
		var departure = MXM.Date.extract(this.fields.departure.get('value'));
				
		if (MXM.Date.compare(arrival, departure, {accuracy: 'd', operator: '>='})) {
			
			if (field == this.fields.arrival) {
				var tmpDate = arrival;
				tmpDate.setDate(tmpDate.getDate() + 7);
				this.selectDate(this.fields.departure, tmpDate);
			} else {
				var tmpDate = departure;
				tmpDate.setDate(tmpDate.getDate() - 7);
				this.selectDate(this.fields.arrival, tmpDate);
			}
			
		}
	}
	
};


/* -------------------------------------------------- */
/* =extended-search */

FEWO.search.extended = {
	
	options: {
		showOnLoad: false
	},
	
	init: function (options) {
		this.options = $merge(this.options, options);
		this.fx = new Fx.Tween($('extended-search-container'), {
			'property': 'left',
			'link': 'cancel',
			'transition': 'sine:out',
			'onComplete': this.setFocus.bind(this)
		});
		$('btn-extended-search').addEvent('click', this.toggle.bind(this));
		this.isOpen = false;
		
		// autocomplete
		new MXM.Form.Autocomplete.Remote($('extended-search-city').getElement('input'), {service: '/_service/LocationFinder.ashx', keyword: 'query', minLength: 1, width: 166, scrollable: true});
		
		
		// calendars
		this.fields = {
			arrival: $('extended-search-arrival').getElement('select'),
			departure: $('extended-search-departure').getElement('select')
		};
		
		this.fields.arrival.addEvent('change', this.presetDate.pass(this.fields.arrival, this));
		this.fields.departure.addEvent('change', this.presetDate.pass(this.fields.departure, this));
						
		this.calendars = {
			'arrival': new MXM.Date.Calendar({
				Months: MXM.Date.Months,
				WeekDays: MXM.Date.WeekDays,
				Today: FEWO.Dict.get('TEXT-TITLE-TODAY'),
				showCW: true,
				DisplayRange: this.options.DisplayRange,
				SelectRange: this.options.SelectRange,
				onSelect: function (date) {
					this.selectDate(this.fields.arrival, date);
					if (Browser.Engine.trident && Browser.Engine.version == 4) { // slow down, not so fast for ie6
						this.presetDate.delay(10, this, this.fields.arrival);
					 } else {
						this.presetDate(this.fields.arrival);
					 }
				}.bind(this)
			}),
			'departure': new MXM.Date.Calendar({
				Months: MXM.Date.Months,
				WeekDays: MXM.Date.WeekDays,
				Today: FEWO.Dict.get('TEXT-TITLE-TODAY'),
				showCW: true,
				DisplayRange: this.options.DisplayRange,
				SelectRange: this.options.SelectRange,
				onSelect: function (date) {
					this.selectDate(this.fields.departure, date);
					if (Browser.Engine.trident && Browser.Engine.version == 4) { // slow down, not so fast for ie6
						this.presetDate.delay(10, this, this.fields.departure);
					 } else {
						this.presetDate(this.fields.departure);
					 }
				}.bind(this)
			})
		};
		
		$('btn-extended-search-arrival-calendar').addEvent('click', function (event) {
			this.calendars.arrival.load(event, { date: this.fields.arrival.get('value') });
		}.bind(this));
		$('btn-extended-search-departure-calendar').addEvent('click', function (event) {
			this.calendars.departure.load(event, { date: this.fields.departure.get('value') });
		}.bind(this));
				
		
		if (this.options.showOnLoad) this.open();		
	},
	
	setFocus: function () {
		if (this.isOpen) {
			$('extended-search-city').getElement('input').focus();
		} else {
			$('direct-search-city').getElement('input').focus();
		}
	},
	
	selectDate: function (target, date) {
		var date = date.format('dd.MM.yyyy');
		var values = $A(target.options).map(function (option) {
			return option.value;
		}, this);
		
		if (!values.contains(date)) { // add date
			values.push(date);
			values.sort(function (a, b) {
				var a = a.split('.'); a.reverse(); a = a.join('').toInt();
				var b = b.split('.'); b.reverse(); b = b.join('').toInt();
				return a - b;
			});
			var ubound = target.options.length - 1;
			var index, where;
			if (values.indexOf(date) < ubound) { // new date injected between existing dates
				index = values.indexOf(date);
				where = 'before';
			} else { // new date in the future, injected at the end of the list
				index = ubound;
				where = 'after';
			}
			new Element('option', {
				'value': date,
				'text': date
			}).inject(target.options[index], where);
		}
		
		// select date
		if (Browser.Engine.trident && Browser.Engine.version == 4) { // ie6 needs some extratime to select the current date
			target.set.delay(10, target, ['value', date]);
		} else {
			target.set('value', date); 
		}
		
	},
		
	open: function () {
		this.isOpen = true;
		this.fx.start(25);
		if (Browser.Engine.trident4) this.hideDirectSearchSelects();
	},
	
	close: function () {
		this.isOpen = false;
		this.fx.start(770);
		if (Browser.Engine.trident4) this.showDirectSearchSelects.delay(400, this);
	},
	
	toggle: function () {
		(this.isOpen) ? this.close() : this.open();
	},
	
	destroy: function () {
		$('extended-search-container').destroy();
	},
	
	showDirectSearchSelects: function () {
		FEWO.search.direct.form.getElements('select').setStyle('visibility', 'visible');
	},
	
	hideDirectSearchSelects: function () {
		FEWO.search.direct.form.getElements('select').setStyle('visibility', 'hidden');
	},
	
	presetDate: function (field) {
		var arrival = MXM.Date.extract(this.fields.arrival.get('value'));
		var departure = MXM.Date.extract(this.fields.departure.get('value'));
		
		if (MXM.Date.compare(arrival, departure, {accuracy: 'd', operator: '>='})) {
			
			if (field == this.fields.arrival) {
				var tmpDate = arrival;
				tmpDate.setDate(tmpDate.getDate() + 7);
				this.selectDate(this.fields.departure, tmpDate);
			} else {
				var tmpDate = departure;
				tmpDate.setDate(tmpDate.getDate() - 7);
				this.selectDate(this.fields.arrival, tmpDate);
			}
			
		}
	}
	
};