var FLY = {
	filter_params: '',
	page: 0,
	checkDates: function() {
		var j_start = $('date_start').value.replace(' ', '-').replace('.', '-');
		var j_end 	= $('date_end').value.replace(' ', '-').replace('.', '-');
		var pattern = /^(\d{1,4})-(\d{1,2})-(\d{1,2})$/;

		var start 	= FLY.getMinDate().toJSON().evalJSON().split('T').first(); // some hackery
		
		if (!j_start.match(pattern) || j_start < start) {
			j_start = start;
			$('date_start').value = j_start;
		}
		
		if (!j_end.match(pattern) || j_end < j_start) {
			j_end = j_start;
			$('date_end').value = j_end;
		}
	},
	
	getMinDate: function() {
		var d_start	= new Date();
		d_start.setDate(d_start.getDate() + _FLY_DAY_OFFSET);
		return d_start;		
	},
	
	loadResults: function() {
		new Ajax.Updater("results-list", _INDEX + "/ajax/results", {
			parameters : document.location.href.toQueryParams(),
			evalScripts: true,
			onComplete: function() {
			}
		});
	},
	
	formatPrice: function(price) {
		price = parseFloat(price);
		if (isNaN(price)) price = parseFloat(0);
		return price.toFixed(2);
	},
	
	ajaxReq: function(params){
		new Ajax.Updater("grouped_list", _INDEX + "/ajax/results", {
			parameters : params.toQueryParams(),
			evalScripts: true,
			onComplete: function() {
			}
		});
	},
	
	changePage: function(page){
		FLY.page = page;
		params = document.location.href + '&page='+page;
		if (FLY.params) params+='&'+FLY.params;
		FLY.ajaxReq(params);
		$('scroll_to').scrollTo();
	},
	
	filterResults: function(params) {
		FLY.params = params;
		FLY.page = 0;
		params = document.location.href + '&' + params + '&page=' + FLY.page;
		FLY.ajaxReq(params);
	},
	
	checkSOTimes: function(offer_id) {
		$('loader_time'+offer_id).show();
		$('reserve_time'+offer_id).hide();
		new Ajax.Updater("reserve_time"+offer_id, _INDEX + "/ajax/so_times", {
			parameters : $('spform_'+offer_id).serialize(),
			evalScripts: true,
			onComplete: function() {
				$('loader_time'+offer_id).hide();
				$('reserve_time'+offer_id).show();
			},
			onFailure: function() {
				$('loader_time'+offer_id).hide();
				$('error_time'+offer_id).show();
			}
		});
	},
	
	emailFriend: function(h) {
		h.unset('act');
		h.unset('type');
		h.unset('_i[pid][1]');
		h.unset('_i[pid][2]');
		$j.fancybox({
			'padding'		: 0,
			'href'			: _ABS_PATH+_INDEX+'/misc/email?'+h.toQueryString(),
			'transitionIn'	: 'none',
			'transitionOut'	: 'none'
		});
	}

};
	
// --- SEARCH FORM ---	
FLY.Search = Class.create({}, {
	initialize: function(f) {
		this.f 	= f;
		var o	= this;
		
		this.initAirports('from');
		this.initAirports('to');
		this.initAirports('from2');
		this.initAirports('to2');
		
		f.select("input[name='item[fly_type]']").each(function(e) {
			e.observe('click', o.checkType.bindAsEventListener(o));
		});
		
		$('adult').observe('change', this.updateInfants.bind(this));
		
		this.cal_shown_start = 0;
		this.cal_shown_end = 0;
	
		this.initCalendar('start');
		this.initCalendar('end');
		this.checkType();
		
		f.observe('submit', this.validate.bindAsEventListener(this));
	},
	
	initCalendar: function(type) {
		var o = this;
		var input	= $('date_' + type);
		var trigger = $('date_' + type + '_trigger');
		var min = type == 'start' ? FLY.getMinDate() : $F('date_start');
		//del Chrome, nes jis kitaip issrusiuoja
		var months_hash = $H(_CALENDAR.MONTHS);
		months_hash.unset('');
		var options = { 
			pages:2, 
			title: _MESSAGES.SELECT_DATE,
			close: true,
			mindate: min, 
			selected: $F(input),
			DATE_FIELD_DELIMITER: '-',
			DATE_RANGE_DELIMITER: '/',
			MDY_MONTH_POSITION: 2,
			MDY_DAY_POSITION: 3,
			MDY_YEAR_POSITION: 1,
			START_WEEKDAY: 1,
			//MONTHS_LONG: $H(_CALENDAR.MONTHS).values().slice(1),
			MONTHS_LONG: months_hash.values(),
			WEEKDAYS_SHORT: $A(_CALENDAR.WEEKDAYS_ABBR)
			}
		
		var cal = new YAHOO.widget.CalendarGroup("cal-" + type, 'date_' + type + '_container', options);
		
		cal.setMonth(cal.getSelectedDates().first().getMonth());
		cal.setYear(cal.getSelectedDates().first().getFullYear());
		
		cal.selectEvent.subscribe(this.dateSelected.bind(this), cal, true);
		cal.hideEvent.subscribe(this.calendarClosed.bind(this), cal, true);
		cal.showEvent.subscribe(this.calendarShown.bind(this), cal, true);
		cal.render();
		
		this['cal_' + type] = cal;
		
		var parent = $('date_' + type + '_container').up('div.section');
		input.observe('keydown', 	function(e) { e.stop(); });
		
		['focus', 'mousedown', 'click'].each(function(name) {
			input.observe(name, function(e) {
				o.whenTriggered(e, type, parent);
			});	
		});
		
		trigger.observe('click', function(e) {
			o.whenTriggered(e, type, parent);
		});

		trigger.show();
	},
	
	whenTriggered: function (e, type, parent) {
		var o = this;
		e.stop();
		if (type=='end' && o.cal_shown_start)
			o.cal_start.hide();
		else if (o.cal_end && o.cal_shown_end)
			o.cal_end.hide();
		if (parent) parent.setStyle({'zIndex': '2'});
		o['cal_'+type].show();
		Event.observe(document, "mousedown", o['closeIfClickedOut_handler_'+type] = o.closeIfClickedOut.bindAsEventListener(o, type));
	},
	
	closeIfClickedOut: function(e, type) {
		var calendar = $('date_' + type + '_container');
		if (! $(Event.element(e)).descendantOf(calendar) ) {
			Event.stopObserving(document, "mousedown", this['closeIfClickedOut_handler_'+type]);
			if (this['cal_shown_'+type])
				this['cal_' + type].hide();
		}
	},
	
	dateSelected: function(act, args, cal) {
		var type 		= cal.id.split('-').last();
		var selected 	= args[0][0];
		var date 		= selected[0];
		date+= '-' + (selected[1] > 9 ? '' : '0') + selected[1];
		date+= '-' + (selected[2] > 9 ? '' : '0') + selected[2]; 
		
		$('date_' + type).value = date;
		
		if (type == 'start') {
			this.cal_end.cfg.setProperty('mindate', date);
			
			if (cal.getSelectedDates().first() > this.cal_end.getSelectedDates().first())
				this.cal_end.select(date);
			
			this.cal_end.render();	
		}
		
		cal.hide();
		
		cal.setMonth(selected[1] - 1);
		cal.setYear(selected[0]);
		cal.render();
	},
	
	calendarClosed: function(act, args, cal) {
		var type = cal.id.split('-').last();
		var parent = $('date_' + type + '_container').up('div.section');
		if (parent) parent.setStyle({'zIndex': '0'});
		this['cal_shown_' + type] = 0;
	},
	
	calendarShown: function(act, args, cal) {
		var type = cal.id.split('-').last();
		this['cal_shown_' + type] = 1;
	},
	
	initAirports: function(dir) {
		new AutoSuggest(dir, {
			script:"modules/flights/airports_ajax.php?ln="+_LN+'&',
			timeout:9999,
			minchars:1,
			cache:false,
			callback: function (obj) { $('iata_' + dir).value = obj.id; }
		});
		
		$('show_airports_' + dir).observe('click', function(e) { 
			openPopWindow2(_ABS_PATH + _INDEX + '/misc/airports?f=' + dir); 
			e.stop(); 
		});

	},
	
	getType: function() {
		return $F(this.f.select("input[name='item[fly_type]']").find(function(e) {
			return e.checked;
		}));
	},
	
	checkType: function() {
		var type = this.getType();
		type == 1 ? $('date_end_block').hide() : $('date_end_block').show();
		if (type == 3){
			$j('#multi_from,#multi_to').show();
			$j('#date_start_container,#date_end_container').css('top','378px');
		} else {
			$j('#multi_from,#multi_to').hide();
			$j('#date_start_container,#date_end_container').css('top','270px');
			$j('#aside #date_start_container,#aside #date_end_container').css('top','282px');
		}
	},
	
	validate: function(e) {
		var errors = $H();
		
		if ($F('iata_from').length != 3)
			errors.set('iata_from', _MESSAGES.FILL_FROM); 
		
		if ($F('iata_to').length != 3)
			errors.set('iata_from', _MESSAGES.FILL_TO);
			
		if (parseInt($F('adult')) + parseInt($F('child')) > 9)
			errors.set('adult', _MESSAGES.PASSENGERS_9);
			
		if (errors.size()) {
			alert(errors.values().join("\n"));
			e.stop();
		}
	},
	
	updateInfants: function(e) {
		var n = parseInt($F('adult'));
		var s = $('infant');
		
		while (s.options.length > n+1)
			s.remove(s.options.length-1);
	
		while (s.options.length < n+1)
			s.options.add(new Option(s.options.length, s.options.length));	
	}
});

	
// --- RESULTS  ---
FLY.Results = Class.create({}, {
	initialize: function(el, ajax) {
		var o 		= this;
		this.el 	= $(el);
		this.type	= this.el.down('.iti.type2') ? 2 : 1;

		this.groups = this.el.select('.group').collect(function(el) { 
			return new FLY.Group(el);
		});
		if (!ajax){
			$('airlines').select('input').each(function(e) {
				e.observe('click', o.filter.bindAsEventListener(o));
			});
	
			//this.filter();
			
			new NEO.Block('filters_block').expand();
			
			$('loading').hide();
			$('results-list').show();
		}
	},
	
	filter: function() {
		var filters = {
			'airlines[]'	: this.getSelectedAirlines()
		};
		FLY.filterResults(Object.toQueryString(filters));
		//this.groups.each(function(o) { o.filter(filters); });
	},
	
	getSelectedAirlines: function() {
		return $('airlines').select('input').select(function(e) { 
			return e.checked; 
		}).collect(function(e) { 
			return $F(e); 
		});
	}
});

FLY.Calendar = Class.create({}, {
	initialize: function(el, expand, load, price) {
		var o 	= this;
		this.el = $(el);
		this.load = load;
		this.price = price;
		this.loaded = 0;
		var block = new NEO.Block(el, 'calendar', o);
		if (expand)
			block.expand();
		else
			block.collapse();
			
		//this.el.select('.tooltip').each(this.attachTooltip.bind(this));
	},
	
	loadCalendar: function() {
		var o = this;
		if (!this.loaded){
			new Ajax.Updater("price-block", _INDEX + "/ajax/calendar", {
				parameters : {price: o.price, load: o.load},
				evalScripts: true,
				onComplete: function() {
					o.el.select('.tooltip').each(o.attachTooltip.bind(this, o));
				}
			});
			this.loaded = 1;
		}
	},
	
	attachTooltip: function(o, tip) {
		// some hackery to fix bug of moving pointer up in IE.
		var cell = tip.up('td');
		var tmp = tip.remove();
		o.el.insert(tmp);
		new Tooltip(cell, tmp);		
		//new Tooltip(cell, tip);
	}
});

FLY.Offers = Class.create({}, {
	initialize: function(el){
		var o = this;
		this.el = $(el);
		var extras = document.location.href.split('#');
		var type = null;
		var offer = null;
		if (extras[1]){
			var temp = new Array();
			temp =  extras[1].split('|');
			type = temp[0];
			offer = temp[1];
		}
		this.el.select('li a').collect(function(e) {
			e.observe('click', o.switcher.bindAsEventListener(o, e));
		});
		this.el.select('.sp-offer').collect(function(e) {
			op = e.down('.button-closesp');
			cl = e.down('.button-viewsp');
			if (op)
				op.observe('click', o.toggle.bindAsEventListener(o, e, 'previous'));
			if (cl)
				cl.observe('click', o.toggle.bindAsEventListener(o, e, 'next'));
		});	
		if (type && $('offers'+type))
			$('offers'+type).show();
		else {
			var first = this.el.select('div').first();
			var last = first.next();
			if (first.down('div').hasClassName('no-offers') && !last.down('div').hasClassName('no-offers'))
				last.show();
			else
				first.show();
		}

		if (offer){
			el = $('offer'+offer);
			if (el){
				el.next().show();
				el.hide();
			}
		}
	},
	
	switcher: function(ev, block) {
		ev.stop();
		cur = block.up(2);
		cur.siblings().last().show();
		cur.hide();
	},
	
	toggle: function(ev, block, type) {
		ev.stop();
		var o = this;
		block.hide();
		if (type=='next')
			block.next().show();
		else
			block.previous().show();
	}
});

FLY.SingleOffer = Class.create({}, {
	initialize: function(id, dates0, dates1){
		var o = this;
		this.id = id;
		this.dates0 = dates0;
		this.dates1 = dates1;
		this.f = $('spform_'+id);
		$('adult_'+id).observe('change', this.updateInfants.bind(this, o));
		
		this.initCalendar('start_'+id, dates0);
		this.initCalendar('end_'+id, dates1);
		
		this.f.observe('submit', this.validate.bindAsEventListener(this, o));
		
	},
	
	initCalendar: function(type, dates) {
		var o = this;
		var input	= $('date_' + type);
		if (!input) return;
		var trigger = $('date_' + type + '_trigger');
		var months_hash = $H(_CALENDAR.MONTHS);
		months_hash.unset('');
		var options = { 
			pages:2, 
			title: _MESSAGES.SELECT_DATE,
			close: true,
			mindate: dates.min,
			maxdate: dates.max,
			selected: $F(input),
			DATE_FIELD_DELIMITER: '-',
			DATE_RANGE_DELIMITER: '/',
			MDY_MONTH_POSITION: 2,
			MDY_DAY_POSITION: 3,
			MDY_YEAR_POSITION: 1,
			START_WEEKDAY: 1,
			MONTHS_LONG: months_hash.values(),
			WEEKDAYS_SHORT: $A(_CALENDAR.WEEKDAYS_ABBR)
			}
		
		var cal = new YAHOO.widget.CalendarGroup("cal-" + type, 'date_' + type + '_container', options);
		
		cal.setMonth(cal.getSelectedDates().first().getMonth());
		cal.setYear(cal.getSelectedDates().first().getFullYear());
		cal.addRenderer(dates.disabled, cal.renderBodyCellRestricted); 
		cal.selectEvent.subscribe(this.dateSelected.bind(this), cal, true);
		cal.render();
		
		input.observe('keydown', 	function(e) { e.stop(); });
		var type2 = type.split('_').first();
		var id = type.split('_').last();
		
		['focus', 'mousedown', 'click'].each(function(name) {
			trigger.observe(name, function(e) {
				e.stop();
				if (type2=='end')
					o['cal_start_'+id].hide();
				else if (o['cal_end_'+id])
					o['cal_end_'+id].hide();
				cal.show();
				Event.observe(document, "mousedown", o['closeIfClickedOut_handler_'+type] = o.closeIfClickedOut.bindAsEventListener(o, type));
			});
				
			input.observe(name, function(e) {
				e.stop();
				if (type2=='end')
					o['cal_start_'+id].hide();
				else if (o['cal_end_'+id])
					o['cal_end_'+id].hide();
				cal.show();
				Event.observe(document, "mousedown", o['closeIfClickedOut_handler_'+type] = o.closeIfClickedOut.bindAsEventListener(o, type));
			});	
		});

		this['cal_' + type] = cal;
		
		trigger.show();
	},
	
	closeIfClickedOut: function(e, type) {
		var calendar = $('date_' + type + '_container');
		if (! $(Event.element(e)).descendantOf(calendar) ) {
			Event.stopObserving(document, "mousedown", this['closeIfClickedOut_handler_'+type]);
			this['cal_' + type].hide();
		}
	},
	
	dateSelected: function(act, args, cal) {
		var type2 		= cal.id.split('-').last();
		var type		= type2.split('_').first();
		var id			= type2.split('_').last();
		var selected 	= args[0][0];
		var date 		= selected[0];
		
		date+= '-' + (selected[1] > 9 ? '' : '0') + selected[1];
		date+= '-' + (selected[2] > 9 ? '' : '0') + selected[2]; 
		
		$('date_' + type2).value = date;
		
		if (type == 'start' && this.dates1) {
			var end_date = new Date(date);
			while (this.dates1.disabled.indexOf(date)!==-1 || this.dates1.min > date){
				end_date.setDate(end_date.getDate()+1);
				Y = end_date.getFullYear();
				m = end_date.getMonth() + 1;
				if (m < 10) m = '0'+m;
				d = end_date.getDate();
				if (d < 10) d = '0'+d;
				date = Y + '-' + m + '-' + d;
			}
			this['cal_end_' + id].cfg.setProperty('mindate', date);
			if (cal.getSelectedDates().first() > this['cal_end_' + id].getSelectedDates().first())
				this['cal_end_' + id].select(date);
			
			this['cal_end_' + id].render();	
		}
		cal.hide();
		
		cal.setMonth(selected[1] - 1);
		cal.setYear(selected[0]);
		cal.render();
	},
	
	validate: function(e, o) {
		return;
		var errors = $H();
		
		if (parseInt($F('adult_'+o.id)) + parseInt($F('child')) > 9)
			errors.set('adult_'+o.id, _MESSAGES.PASSENGERS_9);
			
		if (errors.size()) {
			alert(errors.values().join("\n"));
			e.stop();
		}
	},
	
	updateInfants: function(e, o) {
		return;
		var n = parseInt($F('adult_'+o.id));
		var s = $('infant_'+o.id);
		
		while (s.options.length > n+1)
			s.remove(s.options.length-1);
	
		while (s.options.length < n+1)
			s.options.add(new Option(s.options.length, s.options.length));	
	}
	
});

// --- GROUP BLOCK ---
FLY.Group = Class.create({}, {
	initialize: function(el) {
		this.el 	= $(el);
		
		new NEO.Block(el, '2');
		
		var o = this;
		
		this.itineraries1 = this.el.select('.iti.type1').collect(function(e) {
			return new FLY.Itinerary(e);
		});
		
		this.itineraries2 = this.el.select('.iti.type2').collect(function(e) {
			return new FLY.Itinerary(e);
		});
	},
	
	filter: function(filters) {
		var i, x = true;
		
		i = this.itineraries1.select(function(o){ return o.filter(filters, 1); }).first();
		i ? i.select() : x = false;
		
		if (x && this.itineraries2.length) {
			i = this.itineraries2.select(function(o){ return o.filter(filters, 2); }).first();
			i ? i.select() : x = false;
		}
		
		x ? this.show() : this.hide();
	},
	
	hide: function() { this.el.hide() },
	show: function() { this.el.show() }
});

// --- ITINERARY BLOCK ---
FLY.Itinerary = Class.create({}, {
	initialize: function(el) {
		var o 	= this;
		this.meta = el.next('.meta').down('td').innerHTML.evalJSON();
		this.el = $(el);
		this.el_exp = this.el.next('.show_expanded');
		this.el.select('input:radio').each(function(el) {
			el.observe('click', o.select.bindAsEventListener(o));
		});
		this.el_exp.select('input:radio').each(function(el) {
			el.observe('click', o.select_exp.bindAsEventListener(o));
		});
	},
	
	select: function() {
		this.el_exp.select('input:radio').each(function(el) { el.checked = true; });
		$j.uniform.update();
	},
	
	select_exp: function() {
		this.el.select('input:radio').each(function(el) { el.checked = true; });
		$j.uniform.update();
	},
	
	filter: function(filters, type) {
		var match = true;
		
		match&= !$A(this.meta.airlines).find(function(a) {
			return !filters.airlines.include(a);
		});
		
		match&= (this.meta.changes >= filters.changes[0]) && (this.meta.changes <= filters.changes[1]);
		
		if (type == 1)
			match&= (this.meta.dep_t >= filters.depart[0]) && (this.meta.dep_t <= filters.depart[1]);
		else
			match&= (this.meta.arr_t >= filters.back[0]) && (this.meta.arr_t <= filters.back[1]);
		
		match ? this.show() : this.hide();
		return match;
	},
	
	hide: function() { this.el.hide() },
	show: function() { this.el.show() }
});

// --- BASKET ---
FLY.Basket = Class.create({}, {
	initialize: function(el) {
		var o 		= this;
		this.el 	= $(el);
		
		this.calcTotal();
		
		new NEO.Block(el);
	},
	
	setTax: function(type, tax) {
		var el  = $(type + '_tax');
		el.down('.pricespan').update(FLY.formatPrice(tax));
		this.calcTotal();
	},
	
	getTax: function(type) {
		var el = $(type + '_tax');
		var tax = parseFloat(el.down('.pricespan').innerHTML);
		tax > 0 ? el.show() : el.hide();
		return isNaN(tax) ? 0 : tax;
	}, 
	
	getPassengersPrice: function() {
//		return this.el.select('.passenger .pricespan').inject(0, function(total, el) {
//			return total + parseFloat(el.innerHTML);
//		});
		return parseFloat($('basket_ticket').down('.pricespan').innerHTML);
	},
	
	getDiscount: function() {
		return $('basket_discount') ? parseFloat($('basket_discount').down('.pricespan').innerHTML) : 0;
	},
	
	setInsurance: function(price) {
		$('basket_insurance').down('.pricespan').update(FLY.formatPrice(price));
		this.calcTotal();
	},
	
	getInsurance: function() {
		var el 		= $('basket_insurance');
		var price 	= parseFloat(el.down('.pricespan').innerHTML);
		price > 0 ? el.show() : el.hide();
		return isNaN(price) ? 0 : price;
	},
	
	setParking: function(price) {
		$('basket_parking').down('.pricespan').update(FLY.formatPrice(price));
		this.calcTotal();
	},
	
	getParking: function() {
		var el 		= $('basket_parking');
		var price 	= parseFloat(el.down('.pricespan').innerHTML);
		price > 0 ? el.show() : el.hide();
		return isNaN(price) ? 0 : price;
	},
	
	calcTotal: function() {
		var tickets_total = this.getPassengersPrice();
		
		var taxes = ['print', 'payment', 'service', 'baggage'].collect(this.getTax);
		
		tickets_total = taxes.inject(tickets_total, function(total, tax) {
			return total + tax;
		});
		
		//$('tickets_total').down('.pricespan').update(FLY.formatPrice(tickets_total));
		
		total = tickets_total + this.getInsurance() + this.getParking() - this.getDiscount();
		
		$('total_price').down('.pricespan').update(FLY.formatPrice(total));
	}
});

// --- ORDER  ---
FLY.Order = Class.create({}, {
	parking_price: false,
	initialize: function(el) {
		var o 		= this;
		this.el 	= $(el);
		
		this.passengers = this.el.select('.passenger').collect(function(e) {
			return new FLY.Passenger(e);
		});
		
		if ($('require_bill')) {
			$('require_bill').observe('click', this.checkCompany.bind(this));
			this.checkCompany();
		}
		
		this.basket = new FLY.Basket('basket');
		
		$('payment').select('.radio').each(function(e) {
			e.observe('click', o.checkPaymentEngine.bind(o));
		});
		
		$$('.baggage_selector').each(function(e) {
			e.observe('click', o.checkBaggage.bind(o));
		});
		
		$$('.iperson').each(function(e) {
			e.observe('fly:change', o.updateInsurance.bind(o));
		});
		
		$$('.pperson').each(function(e) {
			e.observe('fly:change2', o.updateParking.bind(o)); 
		});
		
		this.checkPaymentEngine();
		this.checkBaggage();
	},
	
	checkCompany: function() {
		$F('require_bill') ? $('company_data').show() : $('company_data').hide();  
	},
	
	checkBaggage: function() {
		var tax = $$('.baggage_selector').inject(0, function(tax, el) {
			if (el.checked){
				var label = el.next('label');
				if (!label)
					label = el.up('div.radio').next('label');
				var m = label.innerHTML.match(/<strong>([\d\.]+) [a-z]{3}<\/strong>/i);
				return tax + parseFloat(m[1]);
			}
			return tax; 
		});
		
		this.basket.setTax('baggage', tax);
	},
	
	checkPaymentEngine: function() {
		var code = this.getPaymentEngine();
		if (!code) return;
		
		var tax = $('payment').select('.tax_'+code).first().innerHTML; 
		
		this.basket.setTax('payment', tax);
	},
	
	getPaymentEngine: function() {
		var x = $('payment').select('.radio').select(function(e) {
			return e.checked;
		}).first();
		
		return x ? $F(x) : null;
	},
	
	setParking: function(price) {
		if (price > 0)
			$('parking_div').down('.pprice').update(FLY.formatPrice(price));
		this.basket.setParking(price);
	},
	
	updateParking: function() {
		var o 		= this;
		var params 	= this.el.serialize(true);
		params.act 	= 'flights/calc_parking'; 
		
		var enabled = this.passengers.findAll(function(p) {
			return p.parking && p.parking.isEnabled();
		});
	
		if (enabled.size() <= 0){ 
			o.setParking(0);
			return false;
		}
		//iskart rodyt krepselyje
		this.basket.setParking($('parking_div').down('.pprice').innerHTML);
	
		if (o.parking_price===false){
			$('parking_error').hide();
	
			new Ajax.Request(_INDEX, {
				parameters: params,
				onComplete: function(t) {
					if (t.status == 200 && t.responseText.isJSON()) {
						var parking = t.responseText.evalJSON();
						
						if (parking.error) {
							$('parking_error').update(parking.error);
							$('parking_error').show();
							o.setParking(0);
							o.parking_price = 0;
						} else {
							o.setParking(parking.price);
							o.parking_price = parking.price;
						}
					}
					else {
						o.setParking(0);
						o.parking_price = 0;
					}
				} 
			});
		} else {
			o.setParking(o.parking_price);
		}
	},
	
	setInsurance: function(price) {
		if (price > 0)
			this.el.select('.insurance_draft').each(Element.hide);
		
		$('insurance_rules').down('.pricespan').update(FLY.formatPrice(price));
		
		this.basket.setInsurance(price);
	},
	
	updateInsurance: function() {
		var o 		= this;
		var params 	= this.el.serialize(true);
		params.act 	= 'flights/calc_insurance'; 
		
		var invalid = this.passengers.findAll(function(p) {
			return p.insurance && p.insurance.isEnabled() && !p.insurance.calcHash();
		});
		
		if (invalid.size() > 0) 
			return false;
		
		$('insurance_rules').hide();
		$('insurance_error').hide();
		$('insurance_loader').show();
		$('agree_insurance_project').checked = false;
		//$('data-enter').disable(); // disable form  //buginasi su uniformu, isjungiau disablinima
		new Ajax.Request(_INDEX, {
			parameters: params,
			onComplete: function(t) {
				$('insurance_loader').hide();
				
				if (t.status == 200 && t.responseText.isJSON()) {
					var insurance = t.responseText.evalJSON();
					
					if (insurance.error) {
						$('insurance_error').update(insurance.error);
						$('insurance_error').show();
						o.setInsurance(0);
					} else {
						o.setInsurance(insurance.price);
						$('insurance_rules').show();	
					}
				}
				else {
					o.setInsurance(0);
				}
				
				//$('data-enter').enable(); // enable form
			} 
		});
	}

});

// --- PASSENGER  ---
FLY.AbstractPassenger = Class.create({}, {
	bindBirthday: function() {
		var b = this.el.down('.birthday');
		if (!b) return;
		var o = this;
		
		b.select('input').each(function(s){
			if (s.type == 'text')
				s.observe('change', o.updateBirthday.bindAsEventListener(o, b));
		});
	},
	
	bindPassportValidity: function() {
		var b = this.el.down('.passport_validity');
		if (!b) return;
		var o = this;
		
		b.select('input').each(function(s){
			if (s.type == 'text')
				s.observe('change', o.updatePassportValidity.bindAsEventListener(o, b));
		});
	},
	
	updateBirthday: function(e, b) {
		var v = $F(b.down('input[name=Date_Year]')) + '-' + $F(b.down('input[name=Date_Month]')) + '-' + $F(b.down('input[name=Date_Day]'));
		if (v.match(/\d{4}\-\d+\-\d+/))
			b.down('input').value = v;
	},
	
	updatePassportValidity: function(e, b) {
		var v = $F(b.down('input[name=Date_Year]')) + '-' + $F(b.down('input[name=Date_Month]')) + '-' + $F(b.down('input[name=Date_Day]'));
		if (v.match(/\d{4}\-\d+\-\d+/))
			b.down('input').value = v;
	},
	
	getBirthday: function() {
		var bday = $F('p' + this.nr + '_birthday');
		return bday.charAt(0) > 0 ? bday : '';
	},
	
	getNameSurname: function() {
		return $F('p' + this.nr + '_name') + ' ' + $F('p' + this.nr + '_surname');
	}
});

FLY.Passenger = Class.create(FLY.AbstractPassenger, {
	initialize: function(el) {
		var o 		= this;
		this.el 	= $(el);
		this.nr		= this.el.id.split('_').last();
		
		if ($('iperson_' + this.nr))
			this.insurance 	= new FLY.IPerson('iperson_' + this.nr, this);
		
		if ($('pperson_' + this.nr))
			this.parking 	= new FLY.PPerson('pperson_' + this.nr, this);

		this.bindBirthday();
		this.bindPassportValidity();
		
		this.el.select('input', 'select').each(function(e) {
			e.observe('change', function(){
				if (e.type == 'text')
					e.value = translit(trim($F(e)));
				
				o.updateDetails();				
			});
		});
	},
	
	updateDetails: function() {
		if (this.insurance)
			this.insurance.updateFromPerson(this);
		
		if (this.parking)
			this.parking.updateFromPerson(this);
	}	
});

// --- INSURANCE PERSON  ---
FLY.IPerson = Class.create(FLY.AbstractPassenger, {
	initialize: function(el, person) {
		var o		= this;
		this.el 	= $(el);
		this.nr		= this.el.id.split('_').last();
		this.el.down('.check').observe('click', this.checkEnabled.bindAsEventListener(this));
		this.el.down('.town').observe('change', this.checkTown.bindAsEventListener(this));
		
		this.checkEnabled();
		this.checkTown();
		this.bindBirthday();
		
		this.el.select('input', 'select').each(function(e) {
			var event = (e.type == 'checkbox') ? 'click' : 'change';
			
			e.observe(event, function(){
				if (e.type == 'text')
					e.value = trim($F(e));
				
				o.updateInsurance();				
			});
		});
		
		this.updateFromPerson(person);
		this.hash = this.calcHash();
		
		this.initialized = true;
	},
	
	isEnabled: function() {
		return $F(this.el.down('.check'));
	},
	
	checkEnabled: function() {
		if (this.isEnabled())
			this.el.down('.insurance').show();
		else
			this.el.down('.insurance').hide();
	},
	
	checkTown: function() {
		var village = this.el.down('.village');
		if (parseInt(this.el.down('.town').value) < 56){
			village.hide();
			village.down('input').value='-';
		} else {
			if (village.down('input').value=='-')
				village.down('input').value='';
			village.show();
		}
	},
	
	updateFromPerson: function(person) {
		this.name = trim(this.getNameSurname());
		
		if (this.name)
			this.el.down('.name').update(this.name);
		
		if (this.initialized)
			this.updateInsurance();
	},
	
	updateInsurance: function() {
		this.birthday = this.getBirthday();
		
		var hash = this.calcHash();
		
		if (this.hash != hash)
		{
			this.hash = hash;
			this.el.fire('fly:change');
		}
	},
	
	calcHash: function() {
		var o = this;
		var hash = $H();
		
		['personal_code', 'village', 'town_id', 'address'].each(function(field) {
			hash.set(field, o.getValue(field));
		});
		
		hash.set('birthday', 	this.birthday);
		hash.set('name', 		this.name);
			
		var empty = hash.values().findAll(function(v) {
			return !v;
		});
			
		hash.set('enabled', this.getValue('insurance'));
		
		return empty.size() > 0 ? '' : hash.toJSON();
	},
	
	getValue: function(field) {
		return $F('p' + this.nr + '_' + field)
	}
});

//--- PARKING PERSON  ---
FLY.PPerson = Class.create(FLY.AbstractPassenger, {
	initialize: function(el, person) {
		var o		= this;
		this.el 	= $(el);
		this.nr		= this.el.id.split('_').last();
		this.el.down('.check').observe('click', this.checkEnabled.bindAsEventListener(this));
		
		this.checkEnabled();
		
		this.el.select('input', 'select').each(function(e) {
			var event = (e.type == 'checkbox') ? 'click' : 'change';
			
			e.observe(event, function(){
				if (e.type == 'text')
					e.value = trim($F(e));
				
				o.updateParking();				
			});
		});
		
		this.updateFromPerson(person);
		this.hash = this.calcHash();
		
		this.initialized = true;
	},
	
	isEnabled: function() {
		return $F(this.el.down('.check'));
	},
	
	checkEnabled: function() {
		if (this.isEnabled())
			this.el.down('.licence-plate').show();
		else
			this.el.down('.licence-plate').hide();
	},
	
	updateFromPerson: function(person) {
		if (this.initialized)
			this.updateParking();
	},
	
	updateParking: function() {
		var hash = this.calcHash();
		
		if (this.hash != hash)
		{
			this.hash = hash;
			this.el.fire('fly:change2');
		}
	},
	
	calcHash: function() {
		var o = this;
		var hash = $H();
		hash.set('enabled', this.getValue('parking'));
		return hash.toJSON();
	},
	
	getValue: function(field) {
		return $F('p' + this.nr + '_' + field)
	}
});

// --- SCANNER  ---
FLY.Scanner = Class.create({}, {
	initialize: function(el, price) {
		this.el 	= $(el);
		this.f		= this.el.down('form');
		this.price	= price; 		

		this.f.observe('submit', this.submit.bind(this));
		
		this.el.show();	
	},
	
	submit: function(e) {
		e.stop();
		
		if (!emailCheck($F(this.f['item[email]'])))
			return alert(_MESSAGES.INVALID_EMAIL);
		
		['scanner_fill', 'scanner_loader'].each(Element.toggle);
		
		this.f.request({
			parameters: { 'item[price]': this.price },
			onComplete: function() {
				['scanner_loader', 'scanner_created'].each(Element.toggle);
			}
		});
	}
});

