var Product = Class.create();

Product.prototype =
{	
	AJAXSEARCH_URL: '/?-=view_productajax',
	
    initialize : function(offerProductId)
    {
    	this.form=$('productform');
    	this.offerDate=$('offer_date');
    	this.duration=$('duration');
    	this.board=$('board');
    	this.addToCart=$('addtocart');  
    	this.resztvevokszama=$('resztvevokszama');  
    	this.pcc=$('pcc_id')  ;
    	this.next=$('next_id')  ;
    	this.nextadv=$('next_adv_id')  ;
    	this.offerAgesContainer=$('offerages_container');
    	
		if (this.form)
		{
	    	this.createEvents();        	
	    	this.offerProductId=offerProductId;    
	    	this.thisref=this;
	    	
	    	fireEvent(this.offerDate,'change');			    	
		}
    },
        
    createEvents : function()
    {    	
    	Event.observe(this.offerDate,"change", this.startSearch.bindAsEventListener(this,this.offerDate));
    	Event.observe(this.duration,"change", this.startSearch.bindAsEventListener(this,this.duration));
    	if (this.next && this.nextadv)
    	{
    		Event.observe(this.next,"click", this.startSearch.bindAsEventListener(this,this.next));
    		Event.observe(this.nextadv,"click", this.startSearch.bindAsEventListener(this,this.nextadv));
    	}
    },
        
    createOfferAgeItems : function(offerages)
    {
    	if (!this.offerAgesContainer)	return;
    	var oldMaxAges=new Array();
    	var oldSelectElements=$$('#offerages_container select');
    	for (var i=0;i<oldSelectElements.length;i++)
    		if (oldSelectElements[i].value>0)
    			oldMaxAges.push({age:oldSelectElements[i].maxAge,cnt:oldSelectElements[i].value});
    	
    	this.offerAgesContainer.innerHTML='';
    	
    	for (var i=offerages.length-1;i>=0;i--)
    	//for (var i=0;i<offerages.length;i++)
    	{
	    	var item=document.createElement('div');
	    	item.className='offerage';
	    	
	    	if (i!=offerages.length-1)	    		
	    		item.appendChild(new Element('div').update(offerages[i][0]+' - '+offerages[i][1]+' év között'));
	    	else
	    	{
	    		if (offerages.length===1)
	    			item.appendChild(new Element('div').update('Résztvevő személyek száma'));
	    		else
	    			item.appendChild(new Element('div').update('felnőtt ('+offerages[i][0]+' évnél idősebb)'));
	    	}
	    	
	    	select=document.createElement('select');
	    	select.setAttribute('name','age['+((offerages[i][1]-offerages[i][0])/2+offerages[i][0])+']');
	    	select.maxAge=offerages[i][1];
	    	
	    	for (var a=0;a<6;a++)
	    	{
	    		select.options[select.options.length]=new Option(a,a);
	    	}
	    	
	    	for (var x=0;x<oldMaxAges.length;x++)
	    		if (oldMaxAges[x].age==offerages[i][1])
	    			select.value=oldMaxAges[x].cnt;
	    	
	    	Event.observe(select,"change", this.startSearch.bindAsEventListener(this,this.next));
	    	
	    	item.appendChild(select);
	    	
	    	item.appendChild(new Element('div',{'class':'fo'}).update('&nbsp;fő'));
	    	
	    	this.offerAgesContainer.appendChild(item);
	    	
	    	if ((i==offerages.length-1) && (oldMaxAges.length===0))
	    		select.value=2;	    		
    	}
    },
    
    startSearch : function(e,el)
    {    	
    	if (typeof(reservationSearcher)=='object' && (el==this.offerDate || el==this.duration))
    	{
    		reservationSearcher.clearResultContainer();
    		reservationSearcher.clearRoomsContainer();
    		reservationSearcher.resetObjects();    	
    	}
    	
    	var thisref=this;
    	
    	new Ajax.Request(this.AJAXSEARCH_URL+'&product_id='+this.offerProductId+'&el='+el.name,
	    	{
	    		method:'post',
	    		parameters:this.form.serialize(),
	    		asynchronous:false,
	    		onSuccess: function(transport)
	    		{	    			    			    		
	    			jsonObject=(transport.responseText.evalJSON());	 
	    			
	    			thisref.duration.disabled=false;
	    			thisref.board.disabled=false;
	    			thisref.offerDate.disabled=false;

	    			if (jsonObject.duration)
	    				thisref.updateOptionList(thisref.duration,jsonObject.duration); 
	    			if (jsonObject.board)
	    				thisref.updateOptionList(thisref.board,jsonObject.board); 
	    			if (jsonObject.offerages)
	    				thisref.createOfferAgeItems(jsonObject.offerages);
	    			if (jsonObject.reserv)	
	    			{	    	
   					//										automatikus legolcsobb / szobalista kiirasa	    				
    					reservationSearcher.updateJSONData(jsonObject.reserv,el.id==='next_adv_id');
    					    					    					
    					if (el.id==='next_id' && reservationSearcher.reservList.length>0)
    					{
    						var roomCntList=$$('td.roomcnt input[type=text]');    						
    						for (var i=0;i<roomCntList.length;i++)
    						{
    							roomCntList[i].value='0';
    						}
    						
    						for (var i=0;i<reservationSearcher.reservList[0].reservOffers.length;i++)
    							for (var a=0;a<roomCntList.length;a++)
    								if (roomCntList[a].parentOffer.offerId==reservationSearcher.reservList[0].reservOffers[i].parentOffer.offerId)
    								{
    									roomCntList[a].value=Number(roomCntList[a].value)+1;
    									reservationSearcher.onKeyUpRoomCount(null,roomCntList[a],reservationSearcher.reservList[0].reservOffers[i].parentOffer);
    								}
    					}
	    			}	   
	    			
	    			if (el.id!='next_adv_id' && el.id!='next_id')
	    			{
	    				if ($('next_adv_id'))
	    					fireEvent($('next_adv_id'),'click');
	    				if ($('next_id'))
	    					fireEvent($('next_id'),'click');
	    			}
	    			//alert(reservationSearcher);
	    		},
	    		onCreate: function()
	    		{
	    			for (var i=0;i<(el1=$$('.productforminput')).length;i++)
	    			{
	    				if (el1[i].id==el.id)
	    					el1[i].disabled=false;
	    				else
	    					el1[i].disabled=true;
	    			}
	    		},
				onException: function(req,exception) {
					alert("The request had a fatal exception thrown.\n\n" + exception + req );
					return true;
				}	    		
	    	}    	
    	);
    },    
    
	countAge : function(birthDayString)
	{
		now = new Date();
		bD = birthDayString.split('-');
		if(bD.length==3)
		{
			born = new Date(bD[0], bD[1]*1-1, bD[2]);
			years = new Date(now.getTime() - born.getTime());
			base = new Date(0);
			return years.getFullYear()-base.getFullYear();
		}
	},
	
	testAge : function(minage,maxage)
	{
		cnt=0;
		for (var i=0;i<Number($('resztvevokszama').value);i++)
		{
			r=countAge($('date_'+i).value);
			if (r>=minage && r<=maxage)
				cnt++;
		}
		return cnt;
	},
	
    createPCCElements : function()
    {
    	this.pcc.innerHTML='';
    	
    	offerlist=this.offerList;
    	
    	personCount=$('resztvevokszama').value;    
    	
//    	this.ages=this.getAges();
    	
    	table1=this.createTable('ppctable1');    	    	 	
    	
//    	for (var i=0;i<offerlist.length;i++)
    	for (var i=0;i<1;i++)
    	{  
	    	this.addSpecialTableRow(table1,'Részvételi díj',offerlist[i].personprice,0,personCount,1);
	    	
	    	//kotelezo dijak / fő
	    	for (var a=0;a<offerlist[i].specialrows.length;a++)
	    	{	    		
	    		if (offerlist[i].specialrows[a].required)
	    		{
	    			row=(this.addRow(table));	    			
	    			
	    			this.addSpecialTableRow(
	    					table1,
	    					offerlist[i].specialrows[a].pricename,
	    					offerlist[i].specialrows[a].price,
	    					offerlist[i].specialrows[a].unit,
	    					personCount,
	    					offerlist[i].specialrows[a].required,
	    					offerlist[i].specialrows[a].minage,
	    					offerlist[i].specialrows[a].maxage
	    					);
	    		}
	    	}	    	
    	}
    	
    	this.pcc.appendChild(table1);
    },
    
    addSpecialTableRow : function(table,priceName,price,unit,count,required,minage,maxage)
    {    	
    	row=(this.addRow(table));
    	    
    	if ((minage===undefined && maxage===undefined) || (minage!==undefined && maxage!==undefined && this.testAge(minage,maxage)>0))
    	{	    		
			td=document.createElement('td');td.appendChild(document.createTextNode(priceName));row.appendChild(td);
			td=document.createElement('td');td.appendChild(document.createTextNode(price));row.appendChild(td);
			td=document.createElement('td');td.appendChild(document.createTextNode('/'));row.appendChild(td);
			td=document.createElement('td');td.appendChild(document.createTextNode(this.convertUnitIdToString(unit)));row.appendChild(td);
			td=document.createElement('td');td.appendChild(document.createTextNode('x'));row.appendChild(td);
    		if (minage!==undefined && maxage!==undefined && this.testAge(minage,maxage)>0)
    			tmpCount=this.testAge(minage,maxage);
			else		
				tmpCount=count;
				
			
			td=document.createElement('td');td.appendChild(document.createTextNode(tmpCount));row.appendChild(td);
				
			td=document.createElement('td');td.appendChild(document.createTextNode(price*tmpCount));row.appendChild(td);
			
			if (required==0)
			{	
				requiredInput=document.createElement('input');
				requiredInput.type='checkbox';
				requiredInput.value=1;			
				td=document.createElement('td');td.appendChild(requiredInput);row.appendChild(td);    	
			}
    	}
		
		return table;
    },
    
    convertUnitIdToString : function(unitId)
    {
    	var str='';
    	switch (unitId)
    	{
    		case 0:str='fő';		break;
    		case 1:str='szoba';	break;
    		case 2:str='foglalás';break;    		
    	}
    	return str;
    },
    
    getSpecialRowsByAge : function(offerData,age)
    {
    	var result=[];
		for (var a=0;a<offerData.specialrows.length;a++)
	    {	    	
	    	if ((age>=Number(offerData.specialrows[a].minage) && age<=Number(offerData.specialrows[a].maxage)) || Number(offerData.specialrows[a].maxage)==0)
	    		result[result.length]=offerData.specialrows[a];
	    }
	    return result;
    },
    
    createTable : function (id)
    {
		table=document.createElement('table');
		table.appendChild(document.createElement('tbody'));
		table.id=id;
		return table;
    },
    
    addRow : function(table)
    {
    	return table.appendChild(document.createElement('tr'));
    },
    
    addColumn : function(tr)
    {
    	return tr.appendChild(document.createElement('td'));
    },
    
    updateOptionList : function(el,items,options)
    {
    	oldValue=el.value;
    	el.options.length=0;
    	for (var i=0;i<items.length;i++)
    		el.options[el.options.length]=new Option(items[i].text,items[i].value);    		
		if (setComboValue(el,oldValue)<0)
		{
			el.selectedIndex=0;
		}

    },
        
    debug: function(str)
    {
    	$('debug').innerHTML=str;
    }
};

function countAge(birthDayString)
{
	now = new Date();
	bD = birthDayString.split('-');
	if(bD.length==3)
	{
		born = new Date(bD[0], bD[1]*1-1, bD[2]);
		years = new Date(now.getTime() - born.getTime());
		base = new Date(0);
		return years.getFullYear()-base.getFullYear();
	}
}
