ReservationSearcher = Class.create();

ReservationSearcher.prototype =
{
	initialize : function(reservresultcontainer,resultField,roomsContainer,onlyCalc)
    {    	
    	this.readonlyPersons;
    	this.readonlyOffers;    	
		this.reservList=[];
		this.persons=[];
		this.calcTimeout=4;
		this.userOfferIds=[]; //ebbe gyujtom a user altal kivalasztott offeridket!
		this.reservResultContainer=reservresultcontainer;
		this.resultField=resultField;
		this.roomsContainer=roomsContainer;
		this.currency=null;
		this.onlyCalc=onlyCalc; //nem ir a container divekbe.
    },
    
    updateJSONData : function(jsonResponse,mode)
    {	
   		this.resetObjects();
    	
    	this.clearResultContainer();
    	//this.clearRoomsContainer();    	

    	if (jsonResponse.error)   	
			alert('A Teljes név, vagy a születési dátum mező érvénytelen!\r\nA dátumot év-hó-nap formátumban adja meg, pl. 1984-január-17\r\n\r\nKérem ellenőrizze az adatokat, és próbálja újra, köszönjük!');
		else
		{
	    	this.readonlyOffers=(jsonResponse.offerlist);    	    
	    	
	    	this.readonlyPersons=jsonResponse.ages;	    	
	    	
	    	this.currency=jsonResponse.currency;
	    	
	    	for (var i=0;i<this.readonlyPersons.length;i++)
	    		this.persons.push(new Person(this.readonlyPersons[i],i));
	    	

			if (this.onlyCalc)
				return this.execute(mode);
			else	
				this.execute(mode);
		}
    },
    
    getJSONObject : function(reservIndex,resultField)
    {
    	result=[];
		if (this.reservList && this.reservList[reservIndex])
		{
			var reservOfferObj=this.reservList[reservIndex].getReservOfferObjects();
			for (var i=0;i < reservOfferObj.length;i++)
			{
				var sumPriceObj=reservOfferObj[i].getSumPriceObj();
				sumPriceObj.offerid=reservOfferObj[i].parentOffer.offerId;
				result.push(sumPriceObj);
			}
			
			if (resultField)	resultField.innerHTML=result.toJSON();
			else this.resultField.value=result.toJSON();
				
			return result.toJSON();
		}
		return false;
    },
    
    resetObjects : function()
    {
    	this.userOfferIds=[];
    	this.reservList=[];
    	this.persons=[];
    	this.reservList=[];
    },
    
    clearResultContainer : function()
    {
		if (this.onlyCalc)	return;
    	this.reservResultContainer.innerHTML='';//regi tartalom torlese
    	$('submit_addtocart_id').hide();
    	$('submit_addtocart_id_force').hide();
    	$('reserverror_container_id').hide();
    	$('reserverror_timeout_id').hide();
    },
      
    clearRoomsContainer : function()
    {
		if (this.onlyCalc)	return;
    	this.roomsContainer.innerHTML='';//regi tartalom torlese
    },
      
    execute : function(mode)
    {
    	this.clearResultContainer();    	
   		//this.clearRoomsContainer();
    	
    	persons=this.persons;    	
    	//automatikusan a legolcsobbat dobja ki
    	if (!mode)
    	{
    		offers=this.readonlyOffers;
    		return this.start(persons,offers); 
    	}
    	else
    	{
    		//ez majd azokat az offereket gyujti ki, amibol a user valasztott!
    		//szoba tipusok kiirasa
   			this.renderRooms();
    	}
    },
    
    renderRooms : function()
    {   
    	var roomsContainer=this.roomsContainer;    	
    	var lastServiceTypeId=null;
    	
    	if (this.readonlyOffers.length>0)
    	{
    		//roomsContainer.appendChild(infoMsgDiv=document.createElement('div'));
			if ($('infomessagecontainer'))
			{
	    		$('infomessagecontainer').innerHTML='';
    			$('infomessagecontainer').appendChild(infoMsgDiv=document.createElement('div'));
    			infoMsgDiv.className='messages';
    			infoMsgDiv.innerHTML='Kérem jelölje meg, hogy melyik típusú szobából hány darabra kér ajánlatot!';
			}
    	}
    	for (var i=0;i<this.readonlyOffers.length;i++)
    	{   
    		//tipus kiirasa
    		if (lastServiceTypeId===null || lastServiceTypeId!=this.readonlyOffers[i].servicetypeid) 		
    		{
	    		roomsContainer.appendChild(serviceTypeDiv=document.createElement('div'));
	    		serviceTypeDiv.className='servicetype';
	    		//csak ha van szobatipus
	    		if (this.readonlyOffers[i].servicetypeid>0)
	    			serviceTypeDiv.innerHTML='<div class="servicename">Típus:'+this.readonlyOffers[i].servicetypeid+'</div>';
	    		
	    		if (this.readonlyOffers[i].arrivalrows || this.readonlyOffers[i].departurerows)
	    		{
	    			var departureArrival='<div class="departurearrival_container">';
	    			
	    			if (this.readonlyOffers[i].departurerows && this.readonlyOffers[i].departurerows[0]['name'])	
	    				departureArrival+='<div class="departure"><span class="label">Indulás:</span><span class="departure_name">'+this.readonlyOffers[i].departurerows[0]['name']+'</span><span class="departure_datetime">'+((this.readonlyOffers[i].departurerows[0]['datetime'])?this.readonlyOffers[i].departurerows[0]['datetime']:'')+'</span></div>';
	    			
	    			if (this.readonlyOffers[i].arrivalrows && this.readonlyOffers[i].arrivalrows[0]['name'])	
	    				departureArrival+='<div class="arrival"><span class="label">Érkezés:</span><span class="arrival_name">'+this.readonlyOffers[i].arrivalrows[0]['name']+'</span><span class="arrival_datetime">'+((this.readonlyOffers[i].arrivalrows[0]['datetime'])?this.readonlyOffers[i].arrivalrows[0]['datetime']:'')+'</span></div>';
	    			
	    			departureArrival+='</div>';
	    			
	    			serviceTypeDiv.innerHTML+=departureArrival;
	    		}
	    		
	    		
	    		serviceTypeDiv.innerHTML+=((this.readonlyOffers[i].servicetypedesc)?this.readonlyOffers[i].servicetypedesc:'');
				
    			lastServiceTypeId=this.readonlyOffers[i].servicetypeid;
    			var firstLiElement=serviceTypeDiv.getElementsByTagName('li');
    			if (firstLiElement.length>0)
    			{
    				firstLiElement[0].className='first' ;
    			}
    		}
    		roomsContainer.appendChild(roomContainerDiv=document.createElement('div'));
    		roomContainerDiv.className='roomcontainer';
    		
    		//roomContainerDiv.appendChild(leftDiv=document.createElement('div'));
    		//roomContainerDiv.appendChild(rightDiv=document.createElement('div'));
    		//roomContainerDiv.appendChild(clearDiv=document.createElement('div'));
    		//clearDiv.style.height='0px';clearDiv.style.clear='both';clearDiv.style.width='100%';
    		
    		roomContainerDiv.appendChild(table=document.createElement('table'));
    		table.className='roomtable';
    		table.appendChild(tbody=document.createElement('tbody'));
    		
    		//uj sor
    		tbody.appendChild(tr=document.createElement('tr'));    		
    		//1.cella
    		cell=document.createElement('td');    		
    		var str=this.readonlyOffers[i].normalbed+' normál ágy '+(((eb=this.readonlyOffers[i].totalbedcount-this.readonlyOffers[i].normalbed)>0)?', '+eb+' pót ágy':'');    		
        	cell.appendChild(document.createTextNode(str));        	
        	tr.appendChild(cell);    		
    		firstTr=tr;
    		var epr=this.readonlyOffers[i].extrabedpricerows;
        	for (var a=0;a < epr.length;a++)
    		{
    			if (epr[a].extrabedpricetype !=2 )
    			{
	        		//uj sor
	        		tbody.appendChild(tr=document.createElement('tr'));    		
	        		//1.cella
	        		cell=document.createElement('td');    		
	
	        		var str=epr[a].extrabedindex+'. pótágy, típus: '+
	        			((epr[a].extrabedpricetype==0)?'felnőtt':'gyerek')+', kor:'+epr[a].minage+'-'+epr[a].maxage;
	        		
	            	cell.appendChild(document.createTextNode(str));
	            	
	            	tr.appendChild(cell);
	            	
	            	cell=document.createElement('td');
	            	cell.appendChild(document.createTextNode(numberFormat.formatMoneyJsInput(epr[a].price)+' '+this.currency));
	            	
	            	tr.appendChild(cell);
	            	
	            	cell=document.createElement('td');
	            	cell.appendChild(document.createTextNode(' '));	            	
	            	tr.appendChild(cell);
    			}
    		}        	
    		
        	cell=document.createElement('td');
        	cell.appendChild(document.createTextNode(numberFormat.formatMoneyJsInput(this.readonlyOffers[i].personcurrencyprice)+' '+this.currency+'/fő'));	            	
        	firstTr.appendChild(cell);
        	
    		cell=document.createElement('td');
    		cell.className='roomcnt';
    		cell.appendChild(input=new Element('input',{type:'text',value:'0',size:'1'}));
    		input.parentOffer=this.readonlyOffers[i];
    		Event.observe(input,"keyup", this.onKeyUpRoomCount.bindAsEventListener(this,input,this.readonlyOffers[i]));
    		firstTr.appendChild(cell);
    		
/*   		
    		var str=this.readonlyOffers[i].normalbed+' normál ágy '+(((eb=this.readonlyOffers[i].totalbedcount-this.readonlyOffers[i].normalbed)>0)?', '+eb+' pót ágy':'');
    		
    		leftDiv.appendChild(document.createTextNode(str));
    		
    		for (var a=0;a<(epr=this.readonlyOffers[i].extrabedpricerows).length;a++)
    		{
    			leftDiv.appendChild(document.createElement('br'));
    			
    			if (epr[a].extrabedpricetype !=2 )
    				leftDiv.appendChild(document.createTextNode(epr[a].extrabedindex+'. pótágy,'+'típus: '+((epr[a].extrabedpricetype==0)?'felnőtt':'gyerek')+', kor:'+epr[a].minage+'-'+epr[a].maxage+', ár:'+epr[a].price));
    		}
    		//vezerlok
    		rightDiv.appendChild(input=new Element('input',{type:'text',value:'0',size:'1'}));
    		input.parentOffer=this.readonlyOffers[i];
    		Event.observe(input,"keyup", this.onKeyUpRoomCount.bindAsEventListener(this,input,this.readonlyOffers[i]));
*/
    	}
    	
    	//tovabb gomb
    	roomsContainer.appendChild(div=document.createElement('div'));    	
    	div.className='more';div.appendChild(a=document.createElement('a'));    	
    	a.className='button';a.appendChild(document.createTextNode('Kalkuláció indítása'));
    	Event.observe(a,"click", this.test.bindAsEventListener(this));    	
    },
    
    test : function()
    {
    	var persons=this.persons; 
    	var offers=[];
    	for (var i=0;i<this.userOfferIds.length;i++)
    		for (var a=0;a<this.readonlyOffers.length;a++)
    			if (this.readonlyOffers[a].offerId==this.userOfferIds[i])
    				offers.push(this.readonlyOffers[a]);
    	
    	this.clearResultContainer();	
    	
    	this.start(persons,offers,true);
    },
    
    onKeyUpRoomCount : function(e,inputElement,offer)
    {
    	offerId=offer.offerId;
    	offerCnt=Number(inputElement.value);
    	//regi offerek eltavolitasa
    	var newOfferIds=[];
    	for (var i=0;i<this.userOfferIds.length;i++)
    		if (this.userOfferIds[i]!=offerId)
    			newOfferIds.push(this.userOfferIds[i]);
//    			this.userOfferIds=removeKey(this.userOfferIds,i);
    			
    	//ujak hozzarendelese
    	for (var i=0;i<offerCnt;i++)
    		newOfferIds.push(offerId);
    	
    	
    	this.userOfferIds=newOfferIds;    		
    },
	
	start : function(persons,offers,mode,print)
	{
		//minden szobatipusba minden lehetseges modon megprolom behelyezni az embereket, ezt a fv-t a reserv-re irom!
		//meghivom potagy , es potagy kizarassal is. ha az elso osszeallitasban nem hsznalt fel potagyat, akkor normal aggyal nem hivom!
		//ha nem sikerult az osszeallitas akkor torlom
		//a logika mely elso gyerek eseten kivesz egy felnottet masik szobabol nem kell.
		//eltarolom a sumpricet es hogy hasznalt e potagyat a reserv objektumon.


    	
		var permutationPersons=new Permutation(persons,persons.length).getResults();		
		
		this.reservList=[];
		
		var timerStart=new Date();
		
		var timeout=false;
		
		//legolcsobb gomb
		if (!mode)
		{	
			var lastOffer=offers[offers.length-1];
			
			var radix=offers.length;
	
			var usedOfferMax=0;
			
			if (radix==1)
			{
				
				var permutationOffers = [];
				
				for (var i=0;i<persons.length;i++)
					permutationOffers.push(offers[0]);
				
				for (var a=0;a<permutationPersons.length;a++)
				{
									
					var test1=new Reserv(permutationOffers,permutationPersons[a],true,this);
						
					if (test1.success)
					{
						
						if (usedOfferMax<test1.getReservOfferObjects().length)
							usedOfferMax=test1.getReservOfferObjects().length;
							
						this.reservList.push(test1);
						
					}
					
					if (test1.extraBedCnt>0)						
					{
						
						var test2=new Reserv(permutationOffers,permutationPersons[a],false,this);		
						
						if (test2.success)	
						{
							if (usedOfferMax<test2.getReservOfferObjects().length)
								usedOfferMax=test2.getReservOfferObjects().length;
							
							this.reservList.push(test2);
						}							
							
					}
					
					var timerEnd=new Date();
					
					if (timerEnd.getTime()-timerStart.getTime()>this.calcTimeout*1000)	
					{
						timeout=true;
						break;
					}					
				}
			}
			else if (radix>0)
			{	
						
				var readonlyOfferPlaces=[];
				
				for (var i=0;i<offers.length;i++)
				{
					readonlyOfferPlaces[i.toString(radix)]=offers[i];			
				}
				
				var counter=0;
				var counterAsString='';
				var exitCond=Math.pow(radix,persons.length);
				
				while (counter<exitCond && !timeout)
				{			

					counterAsString=counter.toString(radix);
										
					while (counterAsString.length<persons.length)
						counterAsString='0'+counterAsString;
						
					var permutationOffers=[];		
					
					for (var i=0;i<counterAsString.length;i++)
					{
						permutationOffers.push(readonlyOfferPlaces[counterAsString.substr(i,1)]);
					}
					
					var usedOfferMax=0;
					
					for (var a=0;a<permutationPersons.length;a++)
					{										
						
						var test1=new Reserv(permutationOffers,permutationPersons[a],true,this);

						
						if (test1.success)
						{
							if (usedOfferMax<test1.getReservOfferObjects().length)
								usedOfferMax=test1.getReservOfferObjects().length;
							
							this.reservList.push(test1);
						}
						
						if (test1.extraBedCnt>0)						
						{
							var test2=new Reserv(permutationOffers,permutationPersons[a],false,this);		
							
							if (test2.success)	
							{
								if (usedOfferMax<test2.getReservOfferObjects().length)
									usedOfferMax=test2.getReservOfferObjects().length;
								
								this.reservList.push(test2);
							}							
						}	
						
						var timerEnd=new Date();
						
						if (timerEnd.getTime()-timerStart.getTime()>this.calcTimeout*1000)	
						{
							timeout=true;
							break;
						}
					}
														
					counter+=(usedOfferMax>0?((increment=Math.pow(radix,persons.length-usedOfferMax))-counter%increment):1);								
				}
				
			}
		}
		else
		{
			//csak a kivalasztott szobakba probalja rakni a personokat.
			var permutationOffers=new Permutation(offers,offers.length).getResults();		
			
			for (var a=0;a<permutationPersons.length;a++)
			{
				for (var i=0;i<permutationOffers.length;i++)
				{
					var test1=new Reserv(permutationOffers[i],permutationPersons[a],true,this);
					
					if (test1.success)
					{						
						this.reservList.push(test1);
					}
					
					if (test1.extraBedCnt>0)						
					{
						var test2=new Reserv(permutationOffers[i],permutationPersons[a],false,this);		
						
						if (test2.success)	
						{
							this.reservList.push(test2);
						}							
					}
					
					var timerEnd=new Date();
					
					if (timerEnd.getTime()-timerStart.getTime()>this.calcTimeout*1000)	
					{
						timeout=true;
						break;
					}										
				}
				if (timeout) break;						
			}			
		}
		
		function sortCallBack1(o1,o2)
		{
			return o1.sumPrice-o2.sumPrice;
		}
		
		//legolcsobb

		this.reservList=this.reservList.sort(sortCallBack1);		
		
		if (this.onlyCalc)	return ((this.reservList.length>0)?this.reservList[0]:false);
		
		this.reservResultContainer.innerHTML='';
		
		$('timeout_id').value=0;
		
		if (this.reservList.length>0)	
		{
			this.reservList[0].getReservOfferSumPricesHTML(this.reservResultContainer);				
			
			$('submit_addtocart_id').show();
			
			if (timeout)
			{
				$('reserverror_timeout_id').show();
				$('timeout_id').value=1;
			}
			
			//$('roomscontainer').show();
		}
		else
		{
			$('roomscontainer').hide();
			
			$('submit_addtocart_id_force').show();
			
			$('reserverror_container_id').show();
			
			if (timeout)
			{
				$('reserverror_timeout_id').show();
				$('timeout_id').value=1;
			}
			
			$('submit_addtocart_id_force').focus();
		}
	}
};

ReservationQuickSearcher = Class.create();

ReservationQuickSearcher.prototype =
{
	AJAX_URL: '/?-=view_productquickajax',
	WAITINGSEC : 1,
	
	initialize : function(iconSrc)
    {
		this.productIds=[];
		this.iconSrc=iconSrc;
		this.pe=null;
	},
	
	add : function(productId,spanElement)
	{
		this.productIds.push({productId:productId,spanElement:spanElement});
		
		if (this.iconSrc)
			spanElement.update('<img src="'+this.iconSrc+'" border="0"/>');
	},
	
	start : function()
	{
		this.pe=new PeriodicalExecuter(this.process.bind(this));
		//this.process();
	},
	
	ajaxCallBack : function(transport)
	{
		var reservationSearcher=new ReservationSearcher(null,null,null,true,5);
		var jsonObject=(transport.responseText.evalJSON());	
		if (jsonObject.reserv)
		{
			res=reservationSearcher.updateJSONData(jsonObject.reserv,false);
			spanElement.update(numberFormat.formatMoneyJsInput(res.sumPrice));
		}
		else
			spanElement.update();
			
		reservationSearcher=null;jsonObject=null;transport=null;res=null;
		
		//this.process();
		this.pe=new PeriodicalExecuter(this.process.bind(this),this.WAITINGSEC);
	},
	
	process : function()
	{		
		this.pe.stop();
		if (this.productIds.length===0)	return;
		var productData=this.productIds.pop();
		productId=productData.productId;
		spanElement=productData.spanElement;
		new Ajax.Request(this.AJAX_URL+'&product_id='+productId,
	    {
	    	method:'post',
    		onSuccess: this.ajaxCallBack.bind(this),
			onException: function(req,exception) {
				alert("The request had a fatal exception thrown.\n\n" + exception + req );
				return true;
			}	    			
		});		
	}
};
