// JavaScript Document
/*
Objeto carritoJsonSendParams definido en Carrito.js

****************** PARAMETROS o OBJETO "carritoJsonSendParams"
	
	idGrupProducte = {un ID}
	idsAtributs = {un array de IDS}
	quantitat = default [0] numérico entero
	unitat = default [0] -> numérico entero
	carretTipus = default ['resum'] -> 'llista' | 'resum' | 'buit' 
	retornaHTML = default ['true'] -> true | false

****************** 	METODOS DEL CARRITO

	afegirProducte(idGrupProducte,idsAtributs,quantitat,unitat,carretTipus,retornaHTML | [carritoJsonSendParams] )
	modificarProducte(idGrupProducte,idsAtributs,quantitat,unitat,carretTipus,retornaHTML | [carritoJsonSendParams] )
	eliminarProducte (idGrupProducte,carretTipus,retornaHTML | [carritoJsonSendParams] )
	recalcularCarret(carretTipus,retornaHTML | [carritoJsonSendParams] )
	refrescaCarret(carretTipus,retornaHTML | [carritoJsonSendParams] )
	
****************** OBJETO RESPUESTA DEL CARRITO
	this.resultat = null;
	this.idError = null;
	this.descripcionError = null;	

****************** FUNCIONES PARA ESTE VISOR
function controlCarga()
function comprarProducto(id)
function modificarProducto(id)
function borrarProducLista(id,idAttr)
function recalcularCarro()

function compruebaValor(obj(this),incremento,minValor)
sumar(id,incremento,minValor)
restar(id,incremento,minValor)
*/

function controlCarga(){
	_showLoading('carritoListado');
	var sendObjetc = new carritoJsonSendParams()
	sendObjetc.carretTipus = "llista"
	var rObj = refrescaCarret(sendObjetc);
	
	_printResult('carritoListado',rObj);
	_removeLoading('carritoListado');

	_showLoading('carritoResum');
	sendObjetc.carretTipus = "resum"
	rObj = refrescaCarret(sendObjetc);
	_printResult('carritoResum',rObj);
	_removeLoading('carritoResum');
}

function comprarProducto(id){
	if (miraObligatoris(_globalTags["attrObligJS"]) ){
		var sendObjetc = _getParamsCompra(id)
		sendObjetc.carretTipus = "llista"
		_showLoading('carritoListado');
		var rObj = afegirProducte(sendObjetc);
		//for(f=0;f<5000000;f++) g=f
		_printResult('carritoListado',rObj);
		_removeLoading('carritoListado');
		
		sendObjetc.carretTipus = "resum"
		_showLoading('carritoResum');		
		rObj = refrescaCarret(sendObjetc);
//		for(f=0;f<5000000;f++) g=f
		_printResult('carritoResum',rObj);
		_removeLoading('carritoResum');		
	}
	
}
function modificarProducto(id){
	if (miraObligatoris(_globalTags["attrObligJS"]) ){
		var sendObjetc = _getParamsCompra(id)
		sendObjetc.carretTipus = "llista"
		_showLoading('carritoListado');
		var rObj = modificarProducto(sendObjetc);
		_printResult('carritoListado',rObj);
		_removeLoading('carritoListado');
		
		sendObjetc.carretTipus = "resum"
		_showLoading('carritoResum');	
		rObj = refrescaCarret(sendObjetc);
		_printResult('carritoResum',rObj);	
		_removeLoading('carritoResum');	
	}
}

function borrarProducLista(id,idAttr){
	var sendObjetc = new carritoJsonSendParams()
	sendObjetc.idGrupProducte = id;
	sendObjetc.idsAtributs = idAttr;
	sendObjetc.carretTipus = "llista";
	_showLoading('carritoListado');
	var rObj = eliminarProducte(sendObjetc);
	_printResult('carritoListado',rObj);
	_removeLoading('carritoListado');
	
	sendObjetc.carretTipus = "resum"
	_showLoading('carritoResum');	
	rObj = refrescaCarret(sendObjetc);
	_printResult('carritoResum',rObj);
	_removeLoading('carritoResum');
}

function recalcularCarro(){
	var sendObjetc = new carritoJsonSendParams()
	sendObjetc.carretTipus = "llista"
	var rObj = recalcularCarret(sendObjetc);
}
//********************************** 	SUMAR Y RESTAR Y CONTROLAR CANTIDAD DE PRODUCTOS	*****************************************//
function controlKeyPress(e){
	if (  e.keyCode < 48 || e.keyCode > 57 ) 
		if ( e.keyCode != 44 && e.keyCode != 46 )
			e.returnValue = false;
}
function stringToInt(valor){
	var v = parseFloat(valor.replace(",","."))
	v = ( isNaN(v) ) ? 1:v;
	return v;
}
function compruebaValor(obj,incremento,minValor, avis, atencio){
	if (typeof(obj) != "object") alert("parametro obj tiene que ser el elemento sobre el que se actua [function compruebaValor]");
	var valor = stringToInt(obj.value);
	valorIni = valor;
	var inc = stringToInt(incremento);
	var minV = stringToInt(minValor);
	valor = ( valor < minV) ? minV:valor;
	var resto = valor%inc
	var result = ((valor-resto)/inc)
	result = ((result+1)*inc);
	valor = ( resto != 0 ) ?  result :valor;
	obj.value = valor;

	if(valorIni!=valor) { alertFacil(atencio, avis); }
}

function sumar(id,incremento,minValor,avis, atencio){
	var v = _getValor(id);
	valorIni = v;
	var inc = stringToInt(incremento);
	var minV = stringToInt(minValor);
	_setValor(id,v+inc)
}

function restar(id,incremento,minValor,avis, atencio){
	var v = _getValor(id);
	var inc = stringToInt(incremento);
	var minV = stringToInt(minValor);
	incremento = stringToInt(incremento);
	v = ( v-inc < minV) ? minV:v-inc;
	_setValor(id, v)
	if(v==minValor) { alertFacil(atencio, avis); }
}

function _getValor(id){
	return parseFloat($("input[id='quantitat"+ id+ "']").val().replace(",","."));
}
function _setValor(id,v){
	$("input[id='quantitat"+ id+ "']").val(v.toString())
}

//*************************************************************************************************************//
//*************************************************************************************************************//

function _showLoading(id){
	$('#'+id).prepend("<div class='loading' id='load_'"+id+"><img border='0' src='aspimagina/comu/images/ajax-loader.gif' alt='' /></div>")

}
function _removeLoading(id){
	$("#load_"+id).remove();
}
function _printResult(idDiv,rObj){
	if (rObj.idError != 0 )
			alert("err["+rObj.idError+"]: " + _errTags[parseInt(rObj.idError)]);
		else
			$('#'+idDiv).empty().html(rObj.resultat);
}
function _getParamsCompra(id){
		var sendObjetc = new carritoJsonSendParams()
		sendObjetc.idGrupProducte = id
		var tempAttr = new Array();
		var attr = $("input[name='atributsProducteId']")
		attr.each( function(){
					var value = $(this).val();
					if( value.length > 0 ) tempAttr.push(value);
					}
			)

		sendObjetc.idsAtributs = "";
		if ( tempAttr.length > 0) sendObjetc.idsAtributs = tempAttr ;
				
		sendObjetc.unitat = $("input[id='unitat"+ sendObjetc.idGrupProducte + "']").val();
		sendObjetc.quantitat = $("input[id='quantitat"+ sendObjetc.idGrupProducte + "']").val();		
//		debug("quantitat: " + tempAttr,true)
		
		return sendObjetc;
}





/* FUNCIONES CLIENTE PARA RECOGER LOS DATOS A PASAR
*
*
*
*/
function recojeIds(){
	var arrTemp = new Array
	var radios = $('input[type=radio]:checked');

	radios.each(function(){
		arrTemp.push($(this).attr("id"))				
		 })

	return arrTemp.join(',')

}
	
	
function recojeValors(){

	var arrTemp = new Array
	var radios = $('input[type=radio]:checked');

	radios.each(function(){
		arrTemp.push($(this).val())				
		})

	return arrTemp.join(',')
	}
	
	
	
function calculaPrecioTotal(){
	if(document.getElementById("precioBase")) return document.getElementById("precioBase").value;
}


function actualitzaPreu(accio, preu, moneda){

	if(!document.getElementById("precioInicial")) return false;
	
	actual = document.getElementById("precioInicial").value;

	switch(accio)
	{
		case "+":

			document.getElementById("precioBase").value = parseFloat(actual) + parseFloat(preu);
			document.getElementById("preuBase").innerHTML = document.getElementById("precioBase").value 
			
		break;
		case "=":
			document.getElementById("precioBase").value = parseFloat(preu);
			document.getElementById("preuBase").innerHTML = document.getElementById("precioBase").value
		break;
		
	}
}


function miraObligatoris(textAlert){
	
	retornem = true;
	var camps;
	var alerta = "";
	var contador = 0;
	radios = $('input[obligatori=1]')
	radios.each( function (){
				   
		if(this.value=='')
		 {
			 camps = this.id
			 camps = camps.substr(2, camps.length - 40)
			 if(textAlert!='')
				{
				if(contador==0)
					alerta = textAlert + '' + camps;
				else
					alerta = alerta + ' y ' + camps;
				}
			 retornem = false; 
		 }
		 contador++;
	})	

   if(!retornem){
	idElem = "idOblig" + Math.round(Math.random()*10);
	obj = mostraConfirm('!', alerta, idElem);
	obj.dialog('option', 'buttons',{ "ok": function() { $(this).dialog("close");$(this).dialog('destroy'); $(this).empty();} });
	obj.dialog( 'open' );
	}

	return retornem;
}
/* FIN FUNCIONES CLIENTE PARA RECOGER LOS DATOS A PASAR
*
*
*
*/
