var FLY = {
	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);
	}
};
	
// --- SEARCH FORM ---	
FLY.Search = Class.create({}, {
	initialize: function(f) {
		this.f 	= f;
		var o	= this;
		
		this.initAirports('from');
		this.initAirports('to');		
		
		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.initCalendar('start');
		this.initCalendar('end');
		this.checkType();
		
		f.observe('submit', this.validate.bindAsEventListener(this));
	},
	
	initCalendar: function(type) {
		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.render();
		
		input.observe('keydown', 	function(e) { e.stop(); });
		
		['focus', 'mousedown', 'click'].each(function(name) {
			trigger.observe(name, function(e) {
				e.stop();
				cal.show();
			});
			
			input.observe(name, function(e) {
				e.stop();
				cal.show();
			});	
		});

		this['cal_' + type] = cal;
		
		trigger.show();
	},
	
	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();
	},
	
	initAirports: function(dir) {
		new AutoSuggest(dir, {
			script:"modules/flights/airports_ajax.php?",
			timeout:9999,
			minchars:1,
			cache:false,
			callback: function (obj) { $('iata_' + dir).value = obj.id; }
		});
		
		$('show_airports_' + dir).observe('click', function(e) { 
			$(dir + '_sel').hide();
			$(dir).show();
			openPopWindow2(_ABS_PATH + _INDEX + '/misc/airports?f=' + dir); 
			e.stop(); 
		});

		$(dir + '_sel').observe('change', function(e) {
			var v = $F(e.element());
			
			$('iata_' + dir).value = v;

			if (v == 'OTHER') {
				$('iata_' + dir).value = $(dir).value = ''; 
				$(dir + '_sel').hide();
				$(dir).show();
			}
		});
		
		if ($F(dir + '_sel') != $F('iata_' + dir))
		{
			$(dir + '_sel').hide();
			$(dir).show();
		}
	},
	
	getType: function() {
		return $F(this.f.select("input[name='item[fly_type]']").find(function(e) {
			return e.checked;
		}));
	},
	
	checkType: function() {
		this.getType() == 1 ? $('date_end_block').hide() : $('date_end_block').show();
	},
	
	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) {
		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);
		});
		
		$('airlines').select('input').each(function(e) {
			e.observe('click', o.filter.bindAsEventListener(o));
		});

		this.sliders = {};
		this.registerSliderFilter('slider1', 72, [0, 1, 2, '3+']);
		this.registerSliderFilter('slider2', 168, ['00:00', '09:00', '12:00', '15:00', '18:00', '21:00', '23:59']);
		this.registerSliderFilter('slider3', 168, ['00:00', '09:00', '12:00', '15:00', '18:00', '21:00', '23:59']);
		
		if (this.type == 1)
			$('slider3').hide();

		this.filter();

		new NEO.Block('filters_block').expand();
		
		$('loading').hide();
		$('results-list').show();
	},
	
	registerSliderFilter: function(name, range, values) {
		this.sliders[name] = new FLY.Slider(name, {
			values: values,
			range: range,
			onChange: this.filter.bindAsEventListener(this)
		});
	},
	
	filter: function() {
		var changes = this.sliders.slider1.value;
		
		// 3+
		if (parseInt(changes[1]) != changes[1])
			changes[1] = 10;
		
		var filters = {
			changes		: changes,
			depart		: this.sliders.slider2.value,
			back		: this.sliders.slider3.value,
			airlines	: this.getSelectedAirlines()
		};
		
		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) {
		var o 	= this;
		this.el = $(el);
		
		if (arguments[1])
			new NEO.Block(el).expand();
		else
			new NEO.Block(el).collapse();
			
		tablecloth('price_table'); // table decorations
		
		this.el.select('.tooltip').each(this.attachTooltip.bind(this));
	},
	
	attachTooltip: function(tip) {
		// some hackery to fix bug of moving pointer up in IE.
		var cell = tip.up('td')
		var tmp = tip.remove();
		this.el.insert(tmp);
		new Tooltip(cell, tmp);		
	}
});

FLY.Special = Class.create({}, {
	initialize: function(el, expanded_id){
		var o = this;
		this.blocks = el.select('.sp').collect(function(e) {
			var el = new NEO.Block(e);
			if (expanded_id)
				if (e.id == expanded_id)
					el.expand();

			o.addObservers(e);
		});
	},
	
	addObservers: function(block) {
		var o = this;
		block.select('select').each(function(select_el) {
			select_el.observe('change', o.reload.bindAsEventListener(o, block));
		});
	},
	
	reload: function(ev, block) {
		var o = this;
		var ajax_reload = block.down('.ajax_reload');
		var ajax_loader = block.down('.loader');
		ajax_loader.show();
		ajax_reload.hide();
		new Ajax.Updater(ajax_reload, _INDEX + '/ajax/special_list', {
			parameters : $(ev.element().form).serialize(),
			evalScripts : true,
			onComplete : function (transport) {
				o.addObservers(block);
				ajax_loader.hide();
				ajax_reload.show();
			}
		});
	}
});

// --- GROUP BLOCK ---
FLY.Group = Class.create({}, {
	initialize: function(el) {
		this.el 	= $(el);
		
		new NEO.Block(el);
		
		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.down('.meta').innerHTML.evalJSON();
		this.el = $(el);
		
		this.el.select('input.radio').each(function(el) {
			el.observe('click', o.select.bindAsEventListener(o));
		});
	},
	
	select: function() {
		this.el.select('input.radio').each(function(el) { el.checked = true; });
	},
	
	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() }
});

FLY.Slider = Class.create({}, {
	initialize: function(name) {
		this.options = Object.extend({
			values	: [1, 2, 3],
			range	: 72
		}, arguments[1] || {});

		this.el 	= $(name);
		this.name	= name;
		var value 	= [0, this.options.values.length - 1] 
		
		this.updateValue(value);
		
		// calculate step automatically
		this.step = Math.round(this.options.range / (this.options.values.length - 1));
    
		var Dom = YAHOO.util.Dom;

        // Create the DualSlider
        this.slider = YAHOO.widget.Slider.getHorizDualSlider(name + "_bg",
            name + "_min_thumb", name + "_max_thumb",
            this.options.range, this.step);
        
        // Decorate the DualSlider instance with some new properties and
        // methods to maintain the highlight element
        YAHOO.lang.augmentObject(this.slider, {
            _highlight : Dom.get(name + "_highlight"),

            updateHighlight : function () {
                var delta = this.maxVal - this.minVal;
				
                if (this.activeSlider === this.minSlider) {
                    // If the min thumb moved, move the highlight's left edge
                    Dom.setStyle(this._highlight,'left', (this.minVal + 23) + 'px');
                }
                // Adjust the width of the highlight to match inner boundary
                Dom.setStyle(this._highlight,'width', Math.max(delta - 0,0) + 'px');
            }
        },true);

        // Attach the highlight method to the slider's change event
        this.slider.subscribe('change', this.slider.updateHighlight,this.slider,true);
		this.slider.subscribe('change', this.onChangeInternal.bind(this));

		this.el.show();
	},
	
	onChangeInternal: function(slider) {
		this.updateValue([slider.minVal / this.step, slider.maxVal / this.step]);
		if (this.options['onChange']) this.options['onChange'](this);
	},
	
	updateValue: function(v) {
		this.value = [this.options.values[v[0]], this.options.values[v[1]]]; 		
		$(this.name + '_range').update(this.value[0] + ' - ' + this.value[1]);
	}
});

// --- 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('.price').update(FLY.formatPrice(tax));
		this.calcTotal();
	},
	
	getTax: function(type) {
		var el = $(type + '_tax');
		var tax = parseFloat(el.down('.price').innerHTML);
		tax > 0 ? el.show() : el.hide();
		return isNaN(tax) ? 0 : tax;
	}, 
	
	getPassengersPrice: function() {
		return this.el.select('.passenger .price').inject(0, function(total, el) {
			return total + parseFloat(el.innerHTML);
		});
	},
	
	getDiscount: function() {
		return $('basket_discount') ? parseFloat($('basket_discount').down('.price').innerHTML) : 0;
	},
	
	setInsurance: function(price) {
		$('basket_insurance').down('.price').update(FLY.formatPrice(price));
		this.calcTotal();
	},
	
	getInsurance: function() {
		var el 		= $('basket_insurance');
		var price 	= parseFloat(el.down('.price').innerHTML);
		price > 0 ? el.show() : el.hide();
		return isNaN(price) ? 0 : price;
	},
	
	setParking: function(price) {
		$('basket_parking').down('.price').update(FLY.formatPrice(price));
		this.calcTotal();
	},
	
	getParking: function() {
		var el 		= $('basket_parking');
		var price 	= parseFloat(el.down('.price').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('.price').update(FLY.formatPrice(tickets_total));
		
		total = tickets_total + this.getInsurance() + this.getParking() - this.getDiscount();
		
		$('total_price').down('.price').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('cart');
		
		$('payment').select('.radio').each(function(e) {
			e.observe('click', o.checkPaymentEngine.bind(o));
		});
		
		$$('.baggage_selector').each(function(e) {
			e.observe('change', 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) {
			var m = el.options[el.selectedIndex].innerHTML.match(/\(([\d\.]+) [A-Z]{3}\)/);
			return tax + parseFloat(m[1]); 
		});
		
		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;
	},
	
	setInsurance: function(price) {
		if (price > 0)
			this.el.select('.insurance_draft').each(Element.hide);
		
		$('insurance_rules').down('.price').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;
		$('step3').disable(); // disable form
		this.disabled = true;
		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);
						o.showInsuranceRules(insurance.policy_id);	
					}
				}
				else {
					o.setInsurance(0);
				}
				
				$('step3').enable(); // enable form
			} 
		});
	},
	
	showInsuranceRules: function(policy_id) {
		$('insurance_project_link').href = $('insurance_project_link').href.split('=')[0] + '=' + policy_id;
		$('insurance_rules').show();
	},
	
	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);
		}
	}
});

// --- PASSENGER  ---
FLY.AbstractPassenger = Class.create({}, {
	bindBirthday: function() {
		var b = this.el.down('.birthday');
		if (!b) return;
		var o = this;
		
		b.select('select').each(function(s){
			s.observe('change', o.updateBirthday.bindAsEventListener(o, b));
		});
	},
	
	updateBirthday: function(e, b) {
		var v = $F(b.down('select[name=Date_Year]')) + '-' + $F(b.down('select[name=Date_Month]')) + '-' + $F(b.down('select[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.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.checkEnabled();
		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('ul').show();
		else
			this.el.down('ul').hide();
	},
	
	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', 'country', 'city', '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('ul').show();
		else
			this.el.down('ul').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);
			}
		});
	}
});
