/* 
  	FUNCIONS DE SELECCIO DE PRODUCTE
	----------------------------------------------------------------------------------------- 
*/	
	var step = 1;
	
	function roundNumber(rnum, rlength) { 
		// Arguments: number to round, number of decimal places
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
		return newnumber; // Output the result to the form field (change for your purposes)
	}
	function checkIncrement(value, inc) {
		inc = parseInt(inc);
		value = parseInt(value);
		var aint = 0;
		if (inc==1){
				rvalue = value;
		}
		else{
				aint = value / inc;
				if (aint==0) {
						rvalue = value;
				}
				else{
						rvalue = Math.ceil(value/inc)*inc; 
				}
		}		
		return rvalue;
	}	

	function updateTableCart(id) {
		
		var cvalue 	= 0;
		var cinc 	= 1;
		
		var iAux = 0;
		
		cinc = parseInt($('incrementn'+id).value);		
		
		if ($('n'+id).value < 0) {
		    $('n'+id).value = 0;
		}
		$('n'+id).value = checkIncrement($('n'+id).value,cinc);

		// experimental : comprovar unitats maximes??		
		
		$('text_n'+id).innerHTML = $('n'+id).value;
  		
		 // Update subprice
	 	old_subprice = HTML2Number($('st'+id).innerHTML);

	 	new_subprice = $('n'+id).value * $('price'+id).value;
		$('st'+id).innerHTML = number2HTML(roundNumber(new_subprice,2));
				
		// Update total
		new_total= (HTML2Number($('total').innerHTML) - old_subprice) + (new_subprice);
		$('total').innerHTML =  number2HTML(roundNumber(new_total,2));
		$('totalv').value =  roundNumber(new_total,2);
	}

	function number2HTML(value) {
		var num = new NumberFormat();
		num.setInputDecimal('.');
		num.setNumber(value); // obj.value is '-1000.247'
		num.setPlaces('2', false);
		//num.setCurrencyValue('€');
		num.setCurrency(false);
		//num.setCurrencyPosition(num.LEFT_OUTSIDE);
		num.setNegativeFormat(num.LEFT_DASH);
		num.setNegativeRed(false);
		num.setSeparators(true, '.', ',');
		value = num.toFormatted();
		return value;
	}
	function HTML2Number(value) {
		var num = new NumberFormat();
		num.setInputDecimal(',');
		num.setNumber(value); // obj.value is '-1000.247'
		num.setPlaces('2', false);
		//num.setCurrencyValue('€');
		num.setCurrency(false);
		//num.setCurrencyPosition(num.LEFT_OUTSIDE);
		num.setNegativeFormat(num.LEFT_DASH);
		num.setNegativeRed(false);
		num.setSeparators(true, ',', '.');
		value = num.toFormatted();
		return value;
	}	
	function updateUnits (id, action){
		var increment=$('incrementn'+id).value;
		
		if (action=='+') {	 		
	 		$('n'+id).value=parseInt($('n'+id).value)+parseInt(increment);
	 	}
	 	else if (action=='-'){	 		
	 		$('n'+id).value=parseInt($('n'+id).value)-parseInt(increment);
	 	}
	 	updateTableCart(id);	
	}
	function getDateObject(fecha) {
		data = fecha.split('-');
		d = data[0]*1;
		m = data[1]*1 - 1;
		y = data[2]*1;
		return new Date(y, m, d);
	}	
	function checkDate(){
		if (step==1){
			step=2;
		};
		if (calendar.dateClicked) {
			ok=true;
			// verificar data seleccionada
			dateMin = new Date();
			dateMin.dateAdd("d",1);
			dateSelected = getDateObject($('date').value);
			
			if (dateSelected<=dateMin) {
				alert (shopcart_msg_date_noOK);
				ok=false;
			}
			if (ok) {
				checkDateSelected();	
			}	
		}	
		return false;	
	}
	function selectDate(){
		if (step==1){
			step=2;
		};
		if ($('date').value!='') {
			ok=true;
			// verificar data seleccionada
			dateMin = new Date();
			dateMin.dateAdd("d",1);
			dateSelected = getDateObject($('date').value);
			
			if (dateSelected<=dateMin) {
				alert (shopcart_msg_date_noOK);
				ok=false;
			}
			if (ok) {
				checkDateSelected();	
			}	
		}	
		return false;	
	}	
	function checkDateSelected(){
		$('bt_nextDate').hide();
		$('step_2').hide();			
		$('product_loader').show();
		$('frm_command').action.value = "getDateOptions";
		new Ajax.Request('/ajax/'+idioma+'/productos/', { method: 'get',
			parameters: $('frm_command').serialize(true),		
	  		onSuccess: function(transport) {  	
	  			var res = transport.responseText;
	  			$('step_1_info').hide();
				$('product_loader').hide();
	  			$('step_2').innerHTML=res;
			  	$('step_2').show();
				$('step_2_info').show();
			  					  	
				if (step==2) {
					
					$('bt_start').value=shc_button_addProduct;
				}
				$('bt_start').show(); 
				
		
	  		}					
		});			
	}
	function setSelectedProduct(){		
		ok = true;
		// pendent realitzar validació selecció mínima
		valueIds = $$('input.cvalue');
		qtt=0;
		if (valueIds.length>0){
				check = true;
		}
		else{
				check = false;
		}
		var itemqtt;
		for (i = 0; i < valueIds.length; i++) {
				itemqtt=parseInt($(valueIds[i].id).value);
			qtt=qtt+itemqtt;
		}
		if (qtt==0 && check) {
			ok=false;
			alert (shc_msg_minSelection);
		}
		// check items amb num mínim o max de persones
		if (ok) {
				valueIds = $$('input.checkPax');
				qtt=0;
				if (valueIds.length>0){
						checkPax=true;
				}
				else{
						checkPax = false;
				}
				var minp = 0;
				var maxp = 0;
				var npax = 0;
				for (i = 0; i < valueIds.length; i++) {
						npax	= parseInt($(valueIds[i].id).value);
						minp	= parseInt($("minpax"+valueIds[i].id).value);
						maxp	= parseInt($("maxpax"+valueIds[i].id).value);
						
						
						if (minp > npax || npax > maxp) {
								cdesc	= $("cdesc"+valueIds[i].id).value;
								alert (shc_msg_concept_pre + cdesc + shc_msg_concept_post + shc_msg_concept_sel_pre + minp + shc_msg_concept_sel_mid + maxp + shc_msg_concept_sel_post);
								$(valueIds[i].id).focus();
								ok = false;								
						}
						//alert("item:"+valueIds[i].id+",valor:"+$(valueIds[i].id).value);
						
					//qtt=qtt+$(valueIds[i].id).value;
				}
				/*
				if (qtt==0 && check) {
					ok=false;
					alert (shc_msg_minSelection);
				}*/
		}
		
		
		if (ok ) {
			$('product_loader').show();	
			modifiyIds = $$('input.modify');
			for (i = 0; i < modifiyIds.length; i++) {
				$(modifiyIds[i].id).hide();
			}
			readonlyIds = $$('span.readonly');
			for (i = 0; i < readonlyIds.length; i++) {
				$(readonlyIds[i].id).show();			
			}	
			$('bt_start').hide();
			$('bt_modify').show();	
			$('choose_product').hide();	
			$('product_loader').show();	
			$('frm_command').action.value = "setProduct";
			new Ajax.Request('/ajax/'+idioma+'/productos/', { method: 'get',
				parameters: $('frm_command').serialize(true),		
		  		onSuccess: function(transport) {  	
		  			var res = transport.responseText;
		  			$('product_loader').hide();
					$('confirm_product').innerHTML=res;
				  	updateShopcartBlock();
			  		$('confirm_product').show();
				  	
					  
					// caldra modificar aquesta funcio per tenir en compte que s'actualitzi el block amb els detalls de la cistella... 					   			
		  		}					
			});	
			step=3;		
		}
		return false;	
	}	
	function modifyOptions() {		
		$('bt_modify').hide();
		$('bt_start').show();
		modifiyIds = $$('input.modify');
		for (i = 0; i < modifiyIds.length; i++) {
			$(modifiyIds[i].id).show();
		}
		readonlyIds = $$('span.readonly');
		for (i = 0; i < readonlyIds.length; i++) {
			$(readonlyIds[i].id).hide();			
		}		
	}	

	function reModifyOptions() {		
		$('confirm_product').toggle();
		$('choose_product').toggle();
		$('frm_command').action.value = "cleanProduct";
		new Ajax.Request('/ajax/'+idioma+'/productos/', { method: 'get',
			parameters: $('frm_command').serialize(true),		
	  		onSuccess: function(transport) {  	
	  			var res = transport.responseText;	  			
				// caldra modificar aquesta funcio per tenir en compte que s'actualitzi el block amb els detalls de la cistella... 					   			
	  		}					
		});			
		modifyOptions();		 		
	}	
	function checkout() {
		$('frm_command').action.value = "proceedToCheckout";
		new Ajax.Request('/ajax/'+idioma+'/productos/', { method: 'get',
			parameters: $('frm_command').serialize(true),
	  		onSuccess: function(transport) {
	  			var result = transport.responseText;//.evalJSON();
	  			top.location.href=result;	  			
	  		}
		});		
	}	
		
/* 
  	FUNCIONS DE VALIDACIó FORMULARIO DADES PERSONALS
	----------------------------------------------------------------------------------------- 
*/	

	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	}
	
	function isEmpty(s) {
		s = s.trim();		
		return ((s == null) || (s.length == 0));
	}
	function checkEmail(s) {
		var email = s;
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!filter.test(email)) {
				return false;
		}
		else{
				return true;
		}
    }
	
	function checkUserData(){		
		if (isEmpty($('nom').value)) {
			alert(msg_check_name);
			$('nom').activate();
			return false;
		}
		if (isEmpty($('pais').value)) {
			alert(msg_check_pais);
			$('pais').activate();
			return false;
		}
		if (isEmpty($('email').value)) {
			alert(msg_check_email);
			$('email').activate();
			return false;	
		}
		if (!checkEmail($('email').value)) {
			alert(msg_check_email_invalid);
			$('email').activate();
			return false;	
		}
		if (($('conditions').checked==false)) {
			alert(msg_check_conditions);		
			return false;	
		}
		return true;
		
	}

	function changePais() {
		
		if ($('pais').getValue() != 11) {
			$('provincia').disable();
		}
		else {
			$('provincia').enable();
		}
	}
/* 
  	FUNCIONS D'ACTUALITACIO BLOCK CISTELLA
	----------------------------------------------------------------------------------------- 
*/	
	function updateShopcartBlock(){			
		new Ajax.Request('/ajax/'+idioma+'/shopcart/?action=getNumProducts', 
			{ 							
	  			onSuccess: function(transport) {  	
	  				var res = transport.responseText;
					$('shopcart_numProducts').innerHTML = res;
					if (res==0){
						$('shopcart_block').hide();
					}
	  		}					
		});		
	}
	
/* 
  	FUNCIONS DE GESTIÓ DE LA CISTELLA
	----------------------------------------------------------------------------------------- 
*/		
	function deleteProduct(CodProducto,fecha) {
		if (confirm(shc_msg_confirmDelete)) {
			$('frm_shopcart').action.value = "deleteProduct";
			$('frm_shopcart').CodProducto.value = CodProducto;
			$('frm_shopcart').date.value = fecha;
			new Ajax.Request('/ajax/'+idioma+'/shopcart/', { method: 'get',
				parameters: $('frm_shopcart').serialize(true),		
		  		onSuccess: function(transport) {  	
		  			var res = transport.responseText;			  			
		  			$('shopcart_detail').hide();			  			
					$('shopcart_detail').innerHTML=res;
				  	$('shopcart_detail').show();  
		  			updateShopcartBlock();			
		  		}					
			});				
		}	
	}
		
	function startCheckOut() {		
		$('frm_shopcart').action.value = "startCheckOut";
		new Ajax.Request('/ajax/'+idioma+'/shopcart/', { method: 'get',
			parameters: $('frm_shopcart').serialize(true),		
	  		onSuccess: function(transport) {  	
	  			var res = transport.responseText;		  			
	  			$('shopcart_detail').hide();			  			
				$('shopcart_userdata').innerHTML=res;
			  	$('shopcart_userdata').show(); 
		  		$('shopcart_steps').show();
   				$('sc_step1').addClassName('sel');
				$('shopcart_help').hide();
				$('userdata_help').show();
	  		}					
		});				
	}
		
	function finishCheckOut() {
		if (checkUserData()) {
			$('frm_shopcart').action.value = "finishCheckOut";
			new Ajax.Request('/ajax/'+idioma+'/shopcart/', { method: 'get',
				parameters: $('frm_shopcart').serialize(true),		
		  		onSuccess: function(transport) {  	
		  			var res = transport.responseText;
		  			//$('product_loader').hide();
		  			$('shopcart_steps').show();
		  			$('shopcart').hide();
					$('confirm_shopcart').innerHTML=res;
				  	$('confirm_shopcart').show();
				  	$('sc_step1').removeClassName('sel');
			  		$('sc_step2').addClassName('sel');
					$('userdata_help').hide();
					$('pay_help').show();
		  		}					
			});	
		}	
	}		
	function modifyShopcartData() {	
		$('confirm_shopcart').toggle();
		$('shopcart').toggle();
		
		$('sc_step1').addClassName('sel');
		$('sc_step2').removeClassName('sel');
		
		$('shopcart_steps').show();
		
		$('bt_continue').hide();
		$('bt_getUserData').hide();
		$('pay_help').hide();
		$('userdata_help').show();
	}	
	function pay() {
		$('confirm_shopcart').hide();
		$('tpv_shopcart').show();
	  	$('sc_step2').removeClassName('sel');
  		$('sc_step3').addClassName('sel'); 			
		$('frm_shopcart').action.value = "getTPV";
		new Ajax.Request('/ajax/'+idioma+'/shopcart/', { method: 'get',
			parameters: $('frm_shopcart').serialize(true),
	  		onSuccess: function(transport) {
	  			var result = transport.responseText.evalJSON();
	  			if (result.RESULT == 0) {
	  				setTPVVAlues(result);
	  				calctpv();
  				}
  				else{
  					showFinalStep(result);
  				}
	  		}
		});		
	}	
	function showFinalStep (aVals){
		top.location.href=aVals["URL"];			
	}
/* 
  	FUNCIONS DE GESTIÓ DEL TPV
	----------------------------------------------------------------------------------------- 
*/		
	/**
	 * crida tpv Caixa Catalunya
	 */
	function calctpv() {			
		vent=window.open('','tpv','width=725,height=600,scrollbars=no,resizable=yes,status=yes,menubar=no,location=no');
		if (vent) {
			$('compratpv').submit();
		}else{
			alert(shc_msg_popup_blocked);
			$('bt_retry').show();
		}
	}
	function recalctpv(){
		$('bt_retry').hide();
		calctpv();
	}	
	/* seteja els valors del tpv de Caixa Catalunya provinents del ajax
	*
	*/
	function setTPVVAlues(aVals) {
		//alert("setTPVValues");
		$('Ds_Merchant_Amount').value = aVals['tpv_amount'];
		$('Ds_Merchant_Currency').value = aVals['tpv_currency'];
		$('Ds_Merchant_Order').value = aVals['tpv_order'];
					
		$('Ds_Merchant_MerchantCode').value = aVals['tpv_mechcode'];
		
		$('Ds_Merchant_MerchantURL').value = aVals['tpv_urlresult'];
		
		$('Ds_Merchant_MerchantSignature').value = aVals['tpv_signature'];
		
		$('Ds_Merchant_Terminal').value = aVals['tpv_terminal'];			
		
		$('Ds_Merchant_TransactionType').value = aVals['tpv_transtype'];
		
		$('Ds_Merchant_ConsumerLanguage').value = aVals['tpv_language'];
		
		$('Ds_Merchant_UrlOK').value = aVals['tpv_urlok'];
		$('Ds_Merchant_UrlKO').value = aVals['tpv_urlko'];
		$('compratpv').action = aVals['tpv_server'];
	}		