var FLY = {
	formatPrice: function(price) {
		price = parseFloat(price);
		if (isNaN(price)) price = parseFloat(0);
		return price.toFixed(2).replace(".", ",");
	},
	roundNumber: function(num, dec) {
		var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
		return result;
	},
	setPage: function(s){
		new Ajax.Updater("flights-list", _INDEX+"/ajax/list", {
			parameters: {'s': s},
			onCreate : function () { 
		 		$('flights-list').hide();
		 		Effect.Appear('loading');
		 		//$('loading').show(); 
		 	},
		 	onComplete : function () { 
		 		$('loading').hide();
		 		Effect.Appear('flights-list');
		 		//$('flights-list').show(); 
		 	}
		});
	},
	send_friend: function(){
		var fareIds = "";
		for (var i=0; i < document.forms.length; i++){
			var checkbox = document.forms[i].ch_friend;
			if (document.forms[i].ch_friend) {
				if (checkbox.checked){
					fareIds = fareIds + "|" + document.forms[i].fareId.value;
				}
			}
		}
		if (fareIds){
			win= window.open(_ABS_PATH + _INDEX + "/misc/sendfriend?fareIds="+fareIds,"new_send_win","top=40,left=40,width=510,height=440,buttons=no,scrollbars=yes,location=no,menubar=no,resizable=yes,status=no,directories=no,toolbar=no");
			win.window.focus();
		}
	}
};
//--- 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.checkType();
		
		f.observe('submit', this.validate.bindAsEventListener(this));
	},
	
	initAirports: function(dir) {
		var inside = _PATH.match(/search/) ? 1:0;
		new AutoSuggest(dir, {
			script:"modules/reservation/airports.php?ln="+_LN+'&',
			timeout:9999,
			minchars:1,
			cache:false,
			inside:inside,
			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() {
		if (this.getType() == 1){
			if ($('date_hide')) $('date_hide').hide();
			if ($('calendar-container-end')) $('calendar-container-end').hide();
			if ($('kadnesokinetu')) $('kadnesokinetu').show();
		} else {
			if ($('date_hide')) $('date_hide').show();
			if ($('calendar-container-end')) $('calendar-container-end').show();
			if ($('kadnesokinetu')) $('kadnesokinetu').hide();
		}
	},
	
	validate: function(e) {
		var errors = $H();
		
		if ($F('iata_from').length != 3)
			errors.set('iata_from', _MESSAGES.JR1); 
		
		if ($F('iata_to').length != 3)
			errors.set('iata_to', _MESSAGES.JR2);
			
		if (parseInt($F('adult')) + parseInt($F('child')) > 9)
			errors.set('adult', _MESSAGES.JR3);
			
		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));	
	}
});

//--- SEARCH FORM ---	
FLY.Special = Class.create({}, {
	initialize: function(f) {
		this.f 	= f;
		
		$('adult').observe('change', this.updateInfants.bind(this));
		f.observe('submit', this.validate.bindAsEventListener(this));
	},
	
	validate: function(e) {
		var errors = $H();
		
		if (parseInt($F('adult')) + parseInt($F('child')) > 9)
			errors.set('adult', _MESSAGES.JR3);
			
		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) {
		new Form.Observer(el, 0.5, function (f) {
			new Ajax.Updater("flights-list", _INDEX+"/ajax/list", {
				parameters : Form.serialize(f),
				onCreate : function () { 
			 		$('flights-list').hide();
			 		Effect.Appear('loading');
			 		//$('loading').show(); 
			 	},
			 	onComplete : function () { 
			 		$('loading').hide();
			 		Effect.Appear('flights-list');
			 		//$('flights-list').show(); 
			 	}
			});
		});
	}
});

//--- Details FORM ---	
FLY.Details = Class.create({}, {
	initialize: function(f) {
		this.f 	= f;
		var o	= this;
		this.skipcheck = 0;
		if ($('goBack'))
			$('goBack').observe('click', this.goBack.bind(this));
		f.observe('submit', this.validate.bindAsEventListener(this));
	},
	
	goBack: function(e){
		$('act').value = "reservation/back";
		this.skipcheck = 1;
	},
	
	validate: function(e) {
		var errors = $H();
		if ($('insurance') && $('insurance').checked && $('insurance_rules') && !$('insurance_rules').checked)
			errors.set('insurance_rules', _MESSAGES.JD0);
		
		if (!this.skipcheck && errors.size()) {
			alert(errors.values().join("\n"));
			e.stop();
		}
	}
});

//--- BASKET ---
FLY.Basket = Class.create({}, {
	initialize: function() {
		var o 		= this;
		this.calcTotal();
	},
	
	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.replace(",", "."));
		tax > 0 ? el.show() : el.hide();
		return isNaN(tax) ? 0 : tax;
	}, 
	
	getPassengersPrice: function() {
		return parseFloat($F('price_flight'));
	},
	
	getInsurance: function() {
		return parseFloat($F('price_insurance'));
	},
	
	calculateCCFee: function(cc_fee) {
		var total = this.getPassengersPrice() + this.getInsurance() + this.getTax('baggage');
		total = FLY.roundNumber(total * cc_fee, 2);
		if ($('tax_BTR_cc'))
			$('tax_BTR_cc').update(total);
		if ($('cc_fee'))
			$('cc_fee').update(FLY.formatPrice(total));
	},
	
	calcTotal: function() {
		var total = this.getPassengersPrice() + this.getTax('insurance') + this.getTax('baggage') + this.getTax('payment');
		$('total_price').down('.price').update(FLY.formatPrice(total));
	}
});

//--- FILL  ---
FLY.Order = Class.create({}, {
	initialize: function(el, departureDate) {
		var o 		= this;
		this.el 	= $(el);
		this.cc_fee = $('tax_cc') ? $('tax_cc').innerHTML : 0; 
		this.skipcheck = 0;

		this.passengers = this.el.select('.passenger').collect(function(e) {
			return new FLY.Passenger(e, departureDate);
		});
		
		if ($('require_bill')) {
			$('require_bill').observe('click', this.checkCompany.bind(this));
			this.checkCompany();
		}
		
		this.basket = new FLY.Basket();
		this.basket.setTax('insurance', this.basket.getInsurance());
		
		$('payment_types').select('.radio').each(function(e) {
			e.observe('click', o.checkPaymentEngine.bind(o));
		});
		
		$$('.baggage_opt').each(function(e) {
			e.observe('change', o.checkBaggage.bind(o));
		});
		
		this.checkBaggage();
		this.checkPaymentEngine();
		
		if ($('goBack'))
			$('goBack').observe('click', this.goBack.bind(this));
		this.el.observe('submit', this.validate.bindAsEventListener(this));
	},
	
	checkCompany: function() {
		$F('require_bill') ? 
			$('billing_data1','billing_data2','billing_data3','billing_data4','billing_data5','billing_data6','billing_data7').invoke('show') : 
			$('billing_data1','billing_data2','billing_data3','billing_data4','billing_data5','billing_data6','billing_data7').invoke('hide');  
	},
	
	checkBaggage: function() {
		var tax = $$('.baggage_opt').inject(0, function(tax, el) {
			var m = el.options[el.selectedIndex].innerHTML.match(/\(([\d\.]+) Lt\)/);
			return tax + parseFloat(m[1]); 
		});
		
		this.basket.setTax('baggage', tax);
		this.basket.calculateCCFee(this.cc_fee);
	},
	
	checkPaymentEngine: function() {
		var code = this.getPaymentEngine();
		if (!code) return;
		
		var tax = $('tax_'+code) ? $('tax_'+code).innerHTML : 0; 
		this.basket.setTax('payment', tax);
		if (code=='CAS')
			$('office_selection').show();
		else
			$('office_selection').hide();
	},
	
	getPaymentEngine: function() {
		var x = $('payment_types').select('.radio').select(function(e) {
			return e.checked;
		}).first();
		
		return x ? $F(x) : null;
	},
	
	goBack: function(e){
		$('act').value = "reservation/back";
		this.skipcheck = 1;
	},
	
	validate: function(e) {
		if (this.skipcheck) return;
		var errors = $H();
		this.passengers.each(function(p) {
			errors.update(p.validate());
		});
		if ($('require_bill').checked){
			if (!$F('billingCompanyName'))
				errors.set('billingCompanyName', _MESSAGES.JFILL17);
			if (!$F('billingCompanyCode'))
				errors.set('billingCompanyCode', _MESSAGES.JFILL18);
		}
		if (this.getPaymentEngine()=='CAS' && !$('offices').value)
			errors.set('offices', _MESSAGES.JFILL31);
		
		if (!$('agree_rules').checked)
			errors.set('agree_rules', _MESSAGES.JFILL32);
		
		if (errors.size()) {
			alert(errors.values().join("\n"));
			e.stop();
		}

	}

});

//--- PASSENGER  ---
FLY.Passenger = Class.create({}, {
	initialize: function(el, departureDate) {
		var o 		= this;
		this.el 	= $(el);
		this.nr		= this.el.id.split('_').last();
		this.departureDate = departureDate;

		this.bindBirthday();
		
		this.el.select('input').each(function(e) {
			e.observe('change', function(){
				if (e.type == 'text')
					e.value = translit(trim($F(e)));
		
			});
		});
	},
	bindBirthday: function() {
		var b = this.el.down('.birthday');
		if (!b) return;
		var o = this;
		
		b.select('select', 'input').each(function(s){
			s.observe('change', o.updateBirthday.bindAsEventListener(o, b));
		});
	},
	
	updateBirthday: function(e, b) {
		var v = $F(b.down('select[name=Date_Year]')) + '-' + zerofill($F(b.down('input[name=Date_Month]')),2) + '-' + zerofill($F(b.down('input[name=Date_Day]')),2);
		if (v.match(/\d{4}\-\d{2}\-\d{2}/))
			b.down('input').value = v;
	},
	
	getBirthday: function() {
		var bday = $F('p' + this.nr + '_birthday');
		return bday.charAt(0) > 0 ? bday : '';
	},
	
	validate: function() {
		var key = this.nr -1;
		var type = $F('type'+key);
		errors = $H();
		var name = $('firstname'+key);
		if (name && (!name.value || name.value.search(regNames) == -1))
			errors.set(name.id, _MESSAGES.JPASSENGER+this.nr+_MESSAGES.JFILL1);
		var surname = $('surname'+key);
		if (surname && (!surname.value || surname.value.search(regSurnames) == -1))
			errors.set(surname.id, _MESSAGES.JPASSENGER+this.nr+_MESSAGES.JFILL2);
		var pcode = $('pcode'+key);
		if (pcode && (!pcode.value || pcode.value.search(regpernr) == -1))
			errors.set(pcode.id, _MESSAGES.JPASSENGER+this.nr+_MESSAGES.JFILL11);
		var birthday = $('p'+this.nr+'_birthday');
		if (birthday){
			if (type =='ADT' && !checkBirthDates(this.departureDate, birthday.value, 12, 101))
				errors.set(birthday.id, _MESSAGES.JPASSENGER2+this.nr+_MESSAGES.JFILL7);
			else if (type =='CHD' && !checkBirthDates(this.departureDate, birthday.value, 2, 12))
				errors.set(birthday.id, _MESSAGES.JPASSENGER2+this.nr+_MESSAGES.JFILL8);
			else if (type =='INF' && !checkBirthDates(this.departureDate, birthday.value, 0, 2))
				errors.set(birthday.id, _MESSAGES.JPASSENGER2+this.nr+_MESSAGES.JFILL9);
		}
		if (this.nr==1){
			var phone = $('phone1');
			if (phone && (!phone.value || phone.value.search(regphone) == -1))
				errors.set(phone.id, _MESSAGES.JFILL13);
			var email = $('email');
			if (email && (!email.value || email.value.search(regemail) == -1))
				errors.set(email.id, _MESSAGES.JFILL15);
		}
		return errors;
	}
	
});

