/******************/
/* CLASSE RESERVA */
/******************/

function classeReserva (idioma){
	
	this.strNomForm = 'reservaForm';
	this.strCampInici = 'recollida';
	this.strCampFinal = 'devolucio';
	this.strCampPlataformes = 'plataforma';
	this.strCampCadiresNin = 'cadiranin';
	this.strCampNumDies = 'visorDies';
	this.urlRequest = 'bo/provider.php';
		
	this.dInici = new Date();
	this.dInici.resetHour();
	
	this.dFinal = new Date();
	this.dFinal.resetHour();
	
	this.minimDies=3;
	this.numDies = 0;
	this.numCadiresNin = 0;
	this.numPlataformes = 0
	this.idioma = idioma;
	
	/*mètodes*/
	this.setInici = setInici;
	this.setFinal = setFinal;
	this.setNumDies = setNumDies;
	this.setNumPlataformes = setNumPlataformes;
	this.setNumCadiresNin = setNumCadiresNin;
	this.updateReserva = updateReserva;
	this.setData = setData;
	this.calculaDies = calculaDies;
	this.checkDates = checkDates;
	
}

function setInici(dia,mes,any){
	this.dInici = valor;
}
function setFinal(dia,mes,any){
	this.dFinal = valor;
}
function setNumDies(valor){
	this.numDies = valor;
}
function setNumCadiresNin(valor){
	this.numCadiresNin = valor;
}
function setNumPlataformes(valor){
	this.numPlataformes = valor;
}

function setData(nomCamp){
	arrAux = new Array();
	arrAux['dia'] ='';
	arrAux['mes'] ='';
	arrAux['any'] ='';
	arrAux['hor'] ='';
	arrAux['min'] ='';
	
	//obtenim els valors a partir dels selectors
	for(sufixe in arrAux){
		obj = document.getElementById(nomCamp+'_'+sufixe);
		valor = obj.options[obj.selectedIndex].value;
		arrAux[sufixe] = valor;
	}
	
	//cream la "novaData"
	var novaData = new Date(arrAux['any'],parseInt(arrAux['mes'],10)-1,arrAux['dia'],arrAux['hor'],arrAux['min'],0,0);
	
	//obtenim l'objecte al qual fixar els valors (data inici o data final)
	objData = nomCamp==this.strCampInici ? this.dInici : this.dFinal;
	objData.setDate(novaData.getDate()); 
	objData.setMonth(novaData.getMonth()); 
	objData.setFullYear(novaData.getFullYear()); 
	objData.setHours(novaData.getHours()); 
	objData.setMinutes(novaData.getMinutes()); 
	
	//tornem a fixar el valor del selector per si ens han seleccionat una data "impossible"
	marcaSelect( document.getElementById((nomCamp==this.strCampInici? this.strCampInici:this.strCampFinal)+'_dia') , objData.getDate());
	marcaSelect( document.getElementById((nomCamp==this.strCampInici? this.strCampInici:this.strCampFinal)+'_mes') , objData.getMonth()+1);
	marcaSelect( document.getElementById((nomCamp==this.strCampInici? this.strCampInici:this.strCampFinal)+'_any') , objData.getFullYear());
		
}

function checkDates(){
	
	if (this.dInici.getTime() >= this.dFinal.getTime()){
		
		/*
		this.dFinal.setDate((this.dInici.getDate()+this.minimDies));
		if (this.dInici.getMonth()>this.dFinal.getMonth()){
			this.dFinal.setMonth(this.dInici.getMonth());
		}
		if (this.dInici.getFullYear()>this.dFinal.getFullYear()){
			this.dFinal.setFullYear(this.dInici.getFullYear());
		}
		*/
		
		if ( this.dInici.getDate()>this.dFinal.getDate() && this.dInici.getMonth()==this.dFinal.getMonth() && this.dInici.getFullYear()==this.dFinal.getFullYear() ){

			this.dFinal.setMonth(this.dFinal.getMonth()+1);	
						
		}else{
			
			if (this.dInici.getMonth()>this.dFinal.getMonth()){
				this.dFinal.setMonth(this.dInici.getMonth());
			}
			if (this.dInici.getFullYear()>this.dFinal.getFullYear()){
				this.dFinal.setFullYear(this.dInici.getFullYear());
			}
			this.dFinal.setDate((this.dInici.getDate()+this.minimDies));
			
		}
			
		
		marcaSelect( document.getElementById(this.strCampFinal+'_dia') , this.dFinal.getDate());
		marcaSelect( document.getElementById(this.strCampFinal+'_mes') , this.dFinal.getMonth()+1);
		marcaSelect( document.getElementById(this.strCampFinal+'_any') , this.dFinal.getFullYear());
		
	}
	
}

function calculaDies(){
	
	/*obtenim la data inicial*/
	var ini = new Date(this.dInici.getFullYear(), this.dInici.getMonth(), this.dInici.getDate(), this.dInici.getHours(), this.dInici.getMinutes(), this.dInici.getSeconds(), this.dInici.getMilliseconds());
	
	/*inicialitzem els dies*/
	dies = 0;
	
	//comprovar abans de la iteració que la diferencia entre inici i final és major d'un dia (en milisegons)
	milisegons_dia = 3600000 * 24;
	diferencia_inicial = this.dFinal.getTime() - ini.getTime();
	if (diferencia_inicial>=milisegons_dia){
		for (tmp = ini; tmp < this.dFinal ; tmp.setDate( tmp.getDate()+1 ) ){
			dies++;
		}
	}
		
	/* controlem 2 hores de marge */
	ini.setDate(this.dFinal.getDate());
	ini.setMonth(this.dFinal.getMonth());
	ini.setFullYear(this.dFinal.getFullYear());
	dif = this.dFinal.getTime()-ini.getTime();
	if (dif>0 && dif <= 7200000 && dies>0){
		dies--;
	}
	
	this.setNumDies(dies);
	
	/* fixem el número de dies */
	document.getElementById( this.strCampNumDies ).innerHTML = dies;
	
}

function updateReserva(){
	
	//activem avís
	document.getElementById('popupAvis').style.display = 'block';
	
	this.setData('recollida');
	this.setData('devolucio');
	
	this.checkDates();
	
	numCadires = parseInt(document.getElementById(this.strCampCadiresNin).options[document.getElementById(this.strCampCadiresNin).selectedIndex].value,10);
	if (isNaN(numCadires)){
		numCadires = 0 ;
	}
	this.setNumCadiresNin(numCadires);
	
	numPlataformes = parseInt(document.getElementById(this.strCampPlataformes).options[document.getElementById(this.strCampPlataformes).selectedIndex].value,10);
	if (isNaN(numPlataformes)){
		numPlataformes = 0 ;
	}
	this.setNumPlataformes(numPlataformes);
	
	this.calculaDies();
	
	/*****************************************/
	/* feim la petició per obtenir els preus */
	/*****************************************/
	
	//Create an HttpRequest object.
	var peticio = new HttpRequest();
	
	// Assign callback functions, URL and set request headers.
	peticio.successCallback = processResponse;
	peticio.failureCallback = showError;
	peticio.url = "bo/provider.php";
	peticio.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	
	// Create the post data.
	var data = "inici="+this.dInici.toIso()+'&final='+this.dFinal.toIso()+"&diescalculats="+this.numDies+"&cadires="+this.numCadiresNin+'&plataformes='+this.numPlataformes+'&idioma='+this.idioma;
	
	peticio.post(data);
	
}

/**
 * Funció que processa la resposta xml de la petició
 */
function processResponse(httpRequest){
	
	var cap = document.getElementById('resultats');
	
	//obtenim la referencia a la taula i esborrem els tr's que hi hagi
	var oTbody = document.getElementById('contingutTaula');
	removeChildNodes(oTbody);
	
    if (httpRequest.responseText!=''){
    	
    	cotxes = new Array();
    	
    	//activem la part dels resultats
    	cap.style.display='block';
    	
    	//obj XML
		var xmlDoc = httpRequest.responseXML;
		
		// obtenim tots els tipus de cotxe retornats
	    var els = xmlDoc.getElementsByTagName("tipus");
	        	
    	for (var i = 0; i < els.length; i++){
		  	
		  	//obtenim tipus cotxe
		  	tipus = els[i];
		  	
		  	//obtenim el preu per dia (calculat), el número de dies i el total 
		  	
		  	id = tipus.getAttribute('id');
		  	nom = tipus.getElementsByTagName('nom')[0].firstChild.nodeValue.replace(/\\+/g,'');
		  	if (tipus.getElementsByTagName('descripcio')[0].firstChild){
		  		descripcio = tipus.getElementsByTagName('descripcio')[0].firstChild.nodeValue.replace(/\\+/g,'');
		  	}else{
		  		descripcio = '';
		  	}
		  	grup = tipus.getElementsByTagName('grup')[0].firstChild.nodeValue;
		  	pDia = tipus.getElementsByTagName('preuDia')[0].firstChild.nodeValue;
		  	nDies = tipus.getElementsByTagName('numDies')[0].firstChild.nodeValue;
		  	iTotal = tipus.getElementsByTagName('total')[0].firstChild.nodeValue;
		  	if (tipus.getElementsByTagName('foto1')[0].firstChild.nodeValue){
		  		foto1 = tipus.getElementsByTagName('foto1')[0].firstChild.nodeValue;
		  	}else{
		  		foto1 = '';
		  	}
		  	if (tipus.getElementsByTagName('foto2')[0].firstChild.nodeValue){
		  		foto2 = tipus.getElementsByTagName('foto2')[0].firstChild.nodeValue;
		  	}else{
		  		foto2 = '';
		  	}
		  	
		  	//anem guardant els cotxes
		  	cotxes[i] = new Object();
		  	cotxes[i].nom = nom;
		  	cotxes[i].descripcio = descripcio; 
		  	cotxes[i].foto = foto2; 
		  			  	
		  	//comencem a crear el TR
		  	oTr = document.createElement('tr');
		  	if (i==(els.length-1)){
		  		oTr.className='ultima';
		  	}
		  	
		  	//col 1
		  	oTd = document.createElement('td');
		  	oTd.className = 'col1';
		  	oTxt = document.createTextNode(grup);
		  	oTd.appendChild(oTxt);
		  	oTr.appendChild(oTd);
		  	
		  	//col 2
		  	oTd = document.createElement('td');
		  	oTd.className = 'col2';
		  	oImg = document.createElement('img');
		  	if (foto1!=''){
		  		oImg.src = foto1.split(' ')[1].substr(5,foto1.split(' ')[1].length-6);
		  	}else{
		  		oImg.src = '';
		  	}
		  	oHref = document.createElement('a');
		  	oHref.href = 'javascript:showPopup('+i+',18,-35);';
		  	oHref.appendChild(oImg);
		  	oTd.appendChild(oHref);
		  	oTr.appendChild(oTd);
		  	
		  	//col 3
		  	oTd = document.createElement('td');
		  	oTd.className = 'col3';
		  	
		  	oImg = document.createElement('img');
		  	oImg.id='lupa_'+(i);
		  	oImg.src = '/img/reserves/lupa.gif';
		  	
		  	oHref = document.createElement('a');
		  	oHref.href = 'javascript:showPopup('+i+',18,-35);';
		  	oHref.appendChild(oImg);
		  	
		  	oTd.appendChild(oHref);
		  	oTr.appendChild(oTd);
		  	
		  	//col 4
		  	oTd = document.createElement('td');
		  	oTd.className = 'col4';
		  	oTxt = document.createTextNode(nom);
		  	oTd.appendChild(oTxt);
		  	oTr.appendChild(oTd);
		  	
		  	//col 5
		  	oTd = document.createElement('td');
		  	oTd.className = 'col5';
		  	//oTxt = document.createTextNode(pDia+' €');
		  	oTxt = document.createTextNode(pDia);
		  	oTd.appendChild(oTxt);
		  	oTd.innerHTML+=' &euro;';
		  	
		  	//obtenim el detall de la reserva (número de dies i preu per dia)
		  	subdetalls = tipus.lastChild.getElementsByTagName('subdetall');
		  	if (subdetalls.length>1){
			  	
		  		for (x=0;x<subdetalls.length;x++){
			  		
		  			pDiaDet = subdetalls[x].firstChild.firstChild.nodeValue;
			  		nDiesDet = subdetalls[x].lastChild.firstChild.nodeValue;
			  		
			  		oSpa = document.createElement('span');
			  		//oDet = document.createTextNode(nDiesDet+' '+locale['dies_a']+' '+pDiaDet+'€');
			  		oDet = document.createTextNode(nDiesDet+' '+locale['dies_a']+' '+pDiaDet);
			  		oSpa.appendChild(oDet);
			  		oSpa.innerHTML+=' &euro;';
			  		oTd.appendChild(oSpa);
			  		
			  	}
		  	
		  	}
		  	
		  	oTr.appendChild(oTd);
		  	
		  	//col 6
		  	oTd = document.createElement('td');
		  	oTd.className = 'col6';
		  	//oTxt = document.createTextNode(iTotal+' €');
		  	oTxt = document.createTextNode(iTotal);
		  	oTd.appendChild(oTxt);
		  	oTd.innerHTML+=' &euro;';
		  	oTr.appendChild(oTd);
		  	
		  	//col 7
		  	oTd = document.createElement('td');
		  	oTd.className = 'col7';
		  	//això es culpa del puto explorer que te un bug amb els radio buttons dins els formularis generats i s'ha de fer amb la propietat innerHTML
		  	oTd.innerHTML = '<input onclick="javascript:checkForm(true)" name="grup" type="radio" value="'+grup+'||'+iTotal+'||'+id+'" />';
		  	oTr.appendChild(oTd);
		  	
		  	//afegim tr al tbody
		  	oTbody.appendChild(oTr);
		  	
			/*
		  	<tr>
				<td class="col1">B</td>
				<td class="col2">foto</td>
				<td class="col3"><img src="/img/reserves/lupa.gif" width="17" height="15" alt="" /></td>
				<td class="col4">ford k o similar</td>
				<td class="col5">19,90 &euro;</td>
				<td class="col6">89,90 &euro;</td>
				<td class="col7"><input name="grup" type="radio" value="a" /></td>
			</tr>
		  	*/
			
			//desactivem avís
			document.getElementById('popupAvis').style.display = 'none';
			  	
	    }
    
    }else{
    	
    	//ocultem la part dels resultats
    	cap.style.display='none';
    	
    }
    
    
}

/**
 * Ens retorna la descripció de l'error
 */
function showError(httpRequest){
	var strError = "Lookup failed, HTTP " + httpRequest.status  + " " + httpRequest.statusText + ".";
	alert(strError);
}
