/**
 * A fooldali repjegy kereso box-hoz tartozo js kodok
 */

var CCalPair = new Class ({
	mDays : [31,28,31,30,31,30,31,31,30,31,30,31],
	currDate : null,
	oOCont : null,
	oRCont : null,
	oDate : [],
	rDate : [],
	//oOCal : null,
	//oRCal : null,
	dDiff : 0,
	initialize : function (oOCont,oRCont,currDate) {
		//alert('init'+[oOCont,oRCont,currDate]);
		this.currDate = $A(currDate);
		this.oOCont = $(oOCont);
		this.oRCont = $(oRCont);
		this.oDate = this.getSelsDate(this.oOCont);
		this.rDate = this.getSelsDate(this.oRCont);
		this.oOCal = new CmooCalendar ('cal1',this.oOCont,this.oDate[0],this.oDate[1],this.oDate[2],this.onOutPickDate.bind(this),this.currDate);
		this.oRCal = new CmooCalendar ('cal2',this.oRCont,this.rDate[0],this.rDate[1],this.rDate[2],this.onRetPickDate.bind(this),this.oDate);
		this.oRCal.setMinDate(this.oDate[0],this.oDate[1],this.oDate[2]);

		// max dátum beállítása
		var maxY = currDate[1] > 1 ? currDate[0]+1 : currDate[0];
		var maxM = currDate[1] > 1 ? currDate[1]-1 : 12;
		var maxD = this.mDays[maxM-1];
		var maxD = (maxM == 2 ? (this.isLeap(maxY) ? 29 : 28) : this.mDays[maxM-1]);
		//alert ([maxY,maxM,maxD]);
		this.oOCal.setMaxDate(maxY,maxM,maxD);
		this.oRCal.setMaxDate(maxY,maxM,maxD);
		this.oOCont.getElements('select').each(function (el) {
			el.addEvent('change',this.onOutSelect.bind(this));
		},this);
		this.oRCont.getElements('select').each(function (el) {
			el.addEvent('change',this.onRetSelect.bind(this));
		},this);
		this.dDiff = this.calcDiff(this.rDate, this.oDate);
		//alert('init:'+this.dDiff);
	},
	
	calcDiff : function (aD1,aD2) {
		var d1 = new Date();
		var d2 = new Date();
		d1.setFullYear(aD1[0], aD1[1]-1, aD1[2]);
		d2.setFullYear(aD2[0], aD2[1]-1, aD2[2]);
		d1.setSeconds(0, 0);
		d2.setSeconds(0, 0);
		//alert (d1.toLocaleString()+' '+d2.toLocaleString());
		return Math.round((d1.getTime()-d2.getTime())/(60*60*24*1000));
	},
	
	fillSelects : function (oCont,aDate) {
		var y = aDate[0];
		var m = aDate[1];
		var d = aDate[2];
		var sL = null;
		if ($type(sL = oCont.getElements('select'))=='array') {
			this.mDays[1] = this.isLeap(y) ? 29 : 28;
			sL[1].empty();
			var i = m == this.currDate[1] ? this.currDate[2] : 1;
			var s = d < i ? i : (d > this.mDays[m-1] ? this.mDays[m-1] : d);
			var ld = y == this.currDate[0]+1 && m == this.currDate[1] ? ld = this.currDate[2] : this.mDays[m-1];
			var oO = null;
			for(; i <= ld; i++) {
				oO = Element('option',{value:i,html:i});
				oO.inject(sL[1]);
				if (i == s) {
					oO.set('selected',true);
				}
			}
		}
	},
	
	getSelsDate : function (oCont) {
		var sL = null;
		if ($type(sL = oCont.getElements('select'))) {
			var result = [];
			var oYm = sL[0].getSelected()[0];
			var oD = sL[1].getSelected()[0];
			result[0] = oYm.get('value').split('_')[0];
			result[1] = oYm.get('value').split('_')[1];
			result[2] = oD.get('value');
			return result;
		}
		return null;
	},
	
	shiftRDate : function (aD) {
		var y = aD[0];
		var m = aD[1];
		var d = aD[2];
		if ($chk(this.oRCal)) {
			this.oRCal.setMinDate(y,m,d);
			var arD = [this.oRCal.year,this.oRCal.month,this.oRCal.day];
			var irD = (arD[0]+(arD[1]<10?'0'+arD[1]:arD[1])+(arD[2]<10?'0'+arD[2]:arD[2])).toInt();
			//alert(irD + " " +(y+(m<10?'0'+m:m)+(d<10?'0'+d:d)).toInt());
			if (irD <= (y+(m<10?'0'+m:m)+(d<10?'0'+d:d)).toInt()) {
				var oD = new Date();
				oD.setFullYear(y, m-1, d);
				oD.setDate(oD.getDate()+this.dDiff);
				//alert(this.dDiff + ' - ' + oD.getFullYear()+ ' ' +oD.getMonth()+1+ ' ' +oD.getDate());
				this.oRCal.setDate(oD.getFullYear(),oD.getMonth()+1,oD.getDate());
				//this.oRCal.refresh();
				this.onRetPickDate(this.oRCal.year,this.oRCal.month,this.oRCal.day,true);
			}
			else {
				var diff = this.dDiff;
				this.dDiff = this.calcDiff(this.getSelsDate(this.oRCont),aD);
				//alert(diff+'  '+this.dDiff);
			}
			this.oRCal.refresh();
		}
	},
	
	onOutPickDate : function (y,m,d) {
		this.oOCont.getElement('select').getElements('option').each(function(op){
			op.selected = op.get('value') == y+'_'+m ? true : false;
		});
		this.fillSelects(this.oOCont, [y,m,d]);
		this.shiftRDate([y,m,d]);
		
	},
	
	onRetPickDate : function (y,m,d) {
		this.oRCont.getElement('select').getElements('option').each(function(op){
			op.selected = op.get('value') == y+'_'+m ? true : false;
		});
		this.fillSelects(this.oRCont, [y,m,d]);
		if (arguments.length < 4 || arguments[3] !== true) {
			//this.dDiff = this.calcDiff(this.getSelsDate(this.oRCont), this.getSelsDate(this.oOCont));
		};	
	},
	
	onOutSelect : function (oEvent) {
		this.fillSelects(this.oOCont,this.getSelsDate(this.oOCont));
		var date = this.getSelsDate(this.oOCont);
		this.oOCal.setDate(date[0],date[1],date[2]);
		this.shiftRDate(date);
	},
	
	onRetSelect : function () {
		if (this.calcDiff(this.getSelsDate(this.oRCont),this.getSelsDate(this.oOCont)) < 0) {
			var date = this.getSelsDate(this.oOCont);
			this.onRetPickDate(date[0],date[1],date[2]);
		}
		this.fillSelects(this.oRCont,this.getSelsDate(this.oRCont));
		var date = this.getSelsDate(this.oRCont);
		this.oRCal.setDate(date[0],date[1],date[2]);
		this.dDiff = this.calcDiff(date, this.getSelsDate(this.oOCont));
	},
	toggleCalendar : function (cont) {
		if ($(cont) == this.oOCont) {
			this.oOCal.toggle();
		}
		else if ($(cont) == this.oRCont) {
			this.oRCal.toggle();
		}
	},
	/**
	 * Megmondja az adott évről, hogy az szökőév-e.
	 * @param int y A vizsgált év
	 */
	isLeap : function (y) {
		if (y % 400 == 0) {
			return true;
		}
		else if (y % 100 == 0) {
			return false;
		}
		else if (y % 4 == 0) {
			return true;
		}
		return false;
	}
});

var CmooFSFormBox = new Class ({
	ac1 : null,
	ac2 : null,
	oForm : null,
	honnan : '',
	hova : '',
	eLayer : null,
	initialize : function (oForm,oRMgr,autoUrl) {
		this.oForm = $(oForm);
		// autocomplete
		this.ac1 = new CmooAutoComplete ('from',new CSuggestProvider (autoUrl, 'get', oRMgr,'command=auto_location'),'f_type');
		this.ac2 = new CmooAutoComplete ('to',new CSuggestProvider (autoUrl, 'get', oRMgr,'command=auto_location'),'t_type');
		// honnan hova felirat eltuntetese
		var oIn = this.oForm.getElement('input[name=from]');
		if ($chk(oIn)) {
			this.honnan = oIn.get('value');
			oIn.addEvent('focus',function(oe){
				var oI = oe.target;
				var oH = null;
				if($chk(oI.get('value') && $chk(oH = oI.getNext('input[name^=from_]')))) {
					if (!$chk(oH.get('value'))) {
						oI.set('value','');
					}
				}
			});
			oIn.addEvent('blur',function(oe){
				var oI = oe.target;
				var oH = null;
				if (!$chk(oI.get('value')) || oI.get('value')=='') {
					oI.set('value',this.honnan);
					if ($chk(oH = oI.getNext('input[name^=from_]'))) {
						oH.set('value','');
					}
				}
			}.bind(this));
		}
		oIn = this.oForm.getElement('input[name=to]');
		if ($chk(oIn)) {
			this.hova = oIn.get('value');
			oIn.addEvent('focus',function(oe){
				var oI = oe.target;
				var oH = null;
				if($chk(oI.get('value') && $chk(oH = oI.getNext('input[name^=to_]')))) {
					if (!$chk(oH.get('value'))) {
						oI.set('value','');
					}
				}
			});
			oIn.addEvent('blur',function(oe){
				var oI = oe.target;
				var oH = null;
				if (!$chk(oI.get('value')) || oI.get('value')=='') {
					oI.set('value',this.hova);
					if ($chk(oH = oI.getNext('input[name^=to_]'))) {
						oH.set('value','');
					}
				}
			}.bind(this));
		}
		// form ellenorzes
		this.oForm.addEvent('submit',this._submit.bind(this));
		// egyiranyu ut
		this.oForm.getElement('input[id=utazas]').addEvent('click', function(){
			var chk = this.oForm.getElement('input[id=utazas]').get('checked');
			if (chk) {
				$each($('r_date_cont').getElements('select'), function(el){el.set('disabled',true);});
				$('r_date_cont').setStyle('display','none');
				$('vido_szur').setStyle('display','none');
				$('vido_szur').set('disabled',true);
			} else {
				$each($('r_date_cont').getElements('select'), function(el){el.set('disabled',false);});
				$('r_date_cont').setStyle('display','block');
				$('vido_szur').setStyle('display','block');
				$('vido_szur').set('disabled',false);
			}
		}.bind(this));
		// naptarak
		var d = new Date();
		var aCDate = [d.getFullYear(),d.getMonth(),d.getDate()];
		this. oCalPair = new CCalPair($('o_date_cont'),$('r_date_cont'),aCDate);
		$('ocal1').addEvent('click',function(oe){oe.stop();this.oCalPair.toggleCalendar(oe.target.getParent());this.oCalPair.oRCal.hide();oe.stop();}.bind(this));
		$('rcal1').addEvent('click',function(oe){oe.stop();this.oCalPair.toggleCalendar(oe.target.getParent());this.oCalPair.oOCal.hide();oe.stop();}.bind(this));
		// tovabbi opciok
		this.oForm.getElementById('tovabbi_opc').addEvent('click',function(oe){
			oe.stop();
			this.oForm.set('action',oe.target.get('href'));
			this.oForm.submit();
		}.bind(this));
		// a tooltipek 
		var td = new CmooTooltipDisplayer(this.oForm);
		// utas valaszto
		var psh = new CmooPartsSelects (this.oForm);
	},
	_submit : function (oe) {
		
		// form ellenorzes
		msg = '';
		
		var mydate = new Date(); 
		var selectedDate = new Date();
		
		d= $('flight_omonth').value
		dd=d.split('_');


		selectedDate.setFullYear(dd[0], dd[1]-1, $('flight_oday').value);

		var newdate_ms=mydate.getTime()+(2 * 1000 * 60 * 60 * 24);
		
		mydate.setTime(newdate_ms); 
		
		
		if (selectedDate<=mydate)
			{
			msg += '<div>Az indulás napja nem lehet 48 órán belül</div>';
			}
		
	
		if (!$chk($('from_').get('value')) || $('from_').get('value').length != 3 || ($('f_type').get('value') != 'airportcode' && $('f_type').get('value') != 'citycode')) {
			// rosszul ban kitöltve az indulási reptér, vagy nincs illeszkedő találat
			if ($chk($('hibas_utvonal'))) {
				msg += '<div>'+$('hibas_utvonal').get('value')+'</div>';
			}
			else {
				msg += '<div>A kiindulási és célállomást a felajánlott listából kell kiválasztani, különben a keresés nem hoz eredményt!</div>';
			}
		}
		if (!$chk($('to_').get('value'))  || $('to_').get('value').length != 3 || ($('t_type').get('value') != 'airportcode' && $('t_type').get('value') != 'citycode')) {
			// rosszul ban kitöltve az érkezési reptér, vagy nincs illeszkedő találat
			if ($chk($('hibas_utvonal'))) {
				msg += '<div>'+$('hibas_utvonal').get('value')+'</div>';
			}
			else {
				msg += '<div>A kiindulási és célállomást a felajánlott listából kell kiválasztani, különben a keresés nem hoz eredményt!</div>';
			}
		}
		if ($('from_').get('value') == $('to_').get('value')) {
			// a két reptér megegyezik
			if ($chk($('egyezo_allomasok'))) {
				msg += '<div>'+$('egyezo_allomasok').get('value')+'</div>';
			}
			else {
				msg += '<div>A kiindulás és a cél megegyezik!</div>';
			}
		}
		if ($chk(msg)) {
			if (!$chk(this.eLayer)) {
				this.eLayer = new CmooErrorLayer();
			}
			this.eLayer.pop(msg);
			oe.stop();
			return false;
		}
	}
});


/**
 * A jobboldali keresoboxok js dolgai
 */
window.addEvent('domready',function(){
	if (typeof(oRManager) == 'undefined') {
		var oRManager = new CmooRequestManager ();
	}
	var oFSForm = new CmooFSFormBox ($('fs_form'),oRManager,flAutoUrl);
});
