var localCistell;
					
function carret(idUsuari, incrementable, IVAinclos, descompte, idTarifa, sinIVA)
{

	var id, quantitat, preu, iva, nom, incrementable;
	
	this.idUsuari = idUsuari; //Propietari del carret (valor imprescindible al construi el objecte)
	this.incrementable = incrementable; //Si la botiga permet tenir quantitat d'elements al carret
	this.descompte = descompte; //Número percentual de descompte
	this.IVAinclos = IVAinclos; //Si el preu te el inva inclòs o no
	this.sinIVA = sinIVA;
	this.idTarifa = idTarifa;

	this.mostraProductes = mostrarP; //Mostra o amaga els productes (rep true o false)
	this.mostraTotals = mostrarT; // Mostra o amaga els totals (rep true o false)
	this.mostra = mostrarC; //Mostra o amaga tot el carret
	this.moneda = "€";
	this.ImgCesta = "aspimagina/cataleg/lib/ico/carrito.gif";
	this.ImgCestaLlena = this.ImgCesta;
	this.addToHTML = afegirHTML; //afegirHTML(id, quantitat, preu, iva, nom, incrementable)
	this.addSinIva = afegirSinIva;
	this.addButton = generaBoto;
	this.controlaT = controlaTotals;
	this.controlaR = controlaResum;
	this.recalcularQty = recalcularQty;
	
	this.addToBD = afegirBD; //afegirBD(id, quantitat, preu, iva, nom, incrementable)
	this.idPedido;
	this.total = recalcula; //Recaulca els preus dels totals
	this.Init = init; //Inicialitza el carret i consulta la BD

}


	/* Ens carrega la informació de la Base de Dades */
	/* Rep un paràmetre, true si el carret està actiu, false si sols es per mostrar */
	function init(actiu, idTarifa, IVAinclos,desplegat)
	{

		localCistell = this;
		var myConn = new XHConn();		
		if (!myConn) alert("Try a newer/better browser.");
		var fnWhenDone = function (oXML) 
		 { 
		  retorn = oXML.responseText;
	//var win = window.open("aspimagina/blank.htm","","");
	//win.document.write(oXML.responseText);

		  var linies = retorn.split("\r");
		  
		  
		  for(x=0;x<linies.length-1;x++)
		  {
			
			  var valors = linies[x].split("/*/");
			
			  if(valors.length>=7)
			  { 
				idProducto = valors[0]
				idPedido = valors[1]
				quantitat = valors[2]
				preu = replase(valors[3], ",", ".")
				iva = valors[4]
				titol = valors[5]
				referencia = valors[6]
				atributs = valors[7]
				atributsValors = valors[8]
				
				//Ja guardem els preus sense IVA, si els guardema amb IVA a la linea descomentem això.
				/*if(IVAinclos)
				{ 
					pris = Math.round( (preu / (1+(iva/100)))*100 )
					preu = pris / 100 
				}*/
				
			  	afegirHTML(idPedido, quantitat, preu, iva, titol, referencia, atributs, atributsValors, localCistell.incrementable, actiu);
			  }
		  }
		  

		  var tot = cercaCistella("totCarret");

		  
		  /* Si no es actiu amaguem la botonera */

		  if(idTarifa == "") 
		  	tot.style.display = "none"
          else
		  	tot.style.display = "block"
		  //mostrarP(getCookie("mostrarP"))

		// if(actiu==0) { //Si no està actiu amaguem la botonera i mostrem productes.
		    var bot = cercaCistella("botonera");
		    bot.style.display = "none" 
			mostrarP(desplegat)
			
		//  }



		 };
	
		myConn.connect(rutaAbsoluta + "aspimagina/cataleg/mod/carret/carga.asp", "POST", "accio=carga&actiu=" + actiu+"&idUsuari=" + this.idUsuari , fnWhenDone);	
		
	
	}


	function getCookie(name)
	
	{
		var dc = document.cookie;
		var prefix = name + "=";
		var begin = dc.indexOf("; " + prefix);
		if (begin == -1)
		 {
			begin = dc.indexOf(prefix);
			if (begin != 0) return null;
		 }
		else
		 {
			begin += 2;
		 }
		var end = document.cookie.indexOf(";", begin);
		if (end == -1)
		{
			end = dc.length;
		}
		return unescape(dc.substring(begin + prefix.length, end));		
	}

	function mostrarC(mostrem)
	{
		mostrarP(mostrem);
		mostrarT(mostrem);
	}


	function mostrarP(mostrar)
	{
		document.cookie = "mostrarP = " + mostrar;
		var cesta = cercaCistella("cistella");	
		var sumes = cercaCistella("sumes");
		var resum = cercaCistella("ResumSumes");

		if(mostrar==0 )
			{		
			cesta.style.display = "none";
			sumes.style.display = "none";
			resum.style.display = "";

			}
		else
			{ 
				cesta.style.display = "";
/*				resum.style.display = "none";*/
				sumes.style.display = "";
			}
			
		//HolaIsma	
		//cesta.style.display = "none";
		//sumes.style.display = "none";
		//resum.style.display = "none";
		//HolaIsma

	}
	

	function mostrarT(mostrar)
	{
		var totals = cercaCistella("sumes");
		if(!mostrar)
			totals.style.display = "none";
		else
			totals.style.display = "block";
		//HolaIsma	
		//totals.style.display = "none";
		//HolaIsma	
	}
	
	
	
	function replase(text, subs, per)
	{
		var temp = "" + text
		while (temp.indexOf(subs)>-1) 
		{
			
			pos= temp.indexOf(subs);
			temp = "" + (temp.substring(0, pos) + per + temp.substring((pos + subs.length), temp.length));
		}		
		return temp;
	}


	function recalcula()
	{
		var cesta = cercaCistella("cistella");
		
		if(cesta)
		{
			total = 0;
			totalSin = 0;
			IVA = 0;
			totalDto = 0;
			cImport = 0;
			
			if(!this.descompte)
			{
				if(!localCistell.descompte)
				 descompte = 0
				else
				 descompte = localCistell.descompte
			}

			for(a=1; a<cesta.rows.length; a++)
			{
				var fila = cesta.rows[a];
				for(i=0; i<fila.cells.length; i++)
				{
					switch(fila.cells[i].id)
					{
						case "preu":
							Cpreu = pasarFloat(fila.cells[i].innerHTML);
							break;
						case "iva":
							Civa = pasarFloat(fila.cells[i].innerHTML);
							break;						
						case "quantitat":
							Cquantitat = pasarFloat(fila.cells[i].title);
							break;				
						case "import":
							Cimport = pasarFloat(fila.cells[i].innerHTML);
					}

				}
					//Icrementem valors

					if(this.IVAinclos)
						{ valorSenseIVA = (Cpreu / ((Civa/100)+1) * Cquantitat); }
					else
						{ valorSenseIVA = Cpreu*Cquantitat }
					
					totalSin += valorSenseIVA;					
					
					descompteP = valorSenseIVA * (pasarFloat(this.descompte)/100);
					totalDto += descompteP;
					
					totalF = (valorSenseIVA - descompteP)*((Civa/100)+1);
		
					total += totalF;

			}
			
			this.controlaT(total, totalSin, IVA, totalDto)
			this.controlaR(total, cesta.rows.length-1)
		}
	}

	function controlaResum(total, conta)
	{
		var resu = cercaCistella("ResumSumes")

		for(b=0; b<resu.rows.length; b++)
		{
		
			for(a=0; a<resu.rows[b].cells.length;a++)
			{
				switch(resu.rows[b].cells[a].id)
				{
					case "iconoCarrito":
						var hijos =	resu.rows[b].cells[a].childNodes;
						for (var i = 0; i < hijos.length; i++) 
						{
							var node = hijos[i].firstChild;
							if (node!=null && node.id == "imgCarrito")
							{
								node.src = this.ImgCestaLlena;
								break;
							}
						}
						break;
					case "nProducte":
						resu.rows[b].cells[a].innerHTML = conta.toString();
						break;
					case "totalR":
						resu.rows[b].cells[a].innerHTML = redondejar(total, 2).ponerDecimales() + " " + this.moneda;
						break;
				}
			}
		}
	}
	
	
	
	
	function controlaTotals(total, totalSin, IVA, totalDto)
	{
		var totals = cercaCistella("sumes");
		if(totals)
		{
			for(a=0; a<totals.rows.length;a++)
			{
				switch(totals.rows[a].id)
				{
				case "dtoTOTAL":
					if(totalDto != 0 )			
						{ 
						totals.rows[a].cells[1].innerHTML = redondejar(totalDto, 2).ponerDecimales();
						  totals.rows[a].style.display = ""; 	
						 }
					else
						totals.rows[a].style.display = "none";
						
					break;
				case "sinIVA":
					totals.rows[a].cells[1].innerHTML = redondejar(totalSin, 2).ponerDecimales();
					break;
				case "TOTALconIVA":
					totals.rows[a].cells[1].innerHTML = redondejar(total, 2).ponerDecimales();
					totals.rows[a].cells[2].innerHTML = this.moneda;
					break;
				}
			}
		}
	}
	
	function calcularSinIva(preu, iva)
	{
		var ivaP = redondejar(preu - (preu / (1 + (iva/100))), 2);
		return preu - ivaP;		
	}
	
	
	// Si volem que el carret es mostri sense el IVA inclòs
	function afegirSinIva(id, quantitat, preu, iva, nom, referencia, atributs, atributsValor, incrementable)
	{
		if(preu.indexOf("€",0)>-1)
			preu = preu.substring(0, preu.indexOf(" ",0) )
		if(this.sinIVA) iva = 0
		
		//preu = calcularSinIva(preu, iva)
/*		alert('\nid: ' + id + '\n quantitat: ' + quantitat + '\n preu: ' + preu + '\n iva: ' + iva + '\nnom: ' + escape(nom) + ' referencia: ' + referencia + '\n atributs: ' + atributs + '\n incmentable: ' + incrementable)
	*/	
		
		this.addToBD(id, quantitat, preu, iva,escape(nom), referencia, atributs, atributsValor, incrementable, false, this.idTarifa);
	}


	function afegirBD(id, quantitat, preu, iva, nom, referencia, atributs, atributsValor, incrementable, IVAinclos, idTarifa)
	{
		
		var myConn = new XHConn();	
		if (!myConn) alert("Try a newer/better browser.");

		var fnWhenDone = function (oXML) 
		{
	//var win = window.open("aspimagina/blank.htm","","");
//win.document.write(oXML.responseText);
			retorna = String(oXML.responseText);
			
//alert('error:\n' + retorna + '\n incrementable ' + incrementable)
	
			if (retorna=="0")
				afegirHTML(id, quantitat, preu, iva, nom, referencia, atributs, atributsValor, incrementable, true)
			else
			{
				var win = window.open("aspimagina/blank.htm","","");
				win.document.write("Error:<br><b>Valor devuelto</b><br>");
				win.document.write(oXML.responseText);
				win.document.write("<br><b>Mirar en página funCarrito.asp</b>");				
			}
			
		}

		myConn.connect( rutaAbsoluta + "aspimagina/cataleg/mod/carret/carga.asp", "POST", "accio=afegir&idProducto=" + id + "&iva=" + iva + "&idTarifa=" + idTarifa + "&titol=" + nom + "&atributs=" + atributs + "&incrementable=" + incrementable + "&quantitat=" + quantitat + "&IVAinclos=" + this.IVAinclos, fnWhenDone);
	}
	
	// Ens afegeix x elements a la cistella
function afegirHTML(id, quantitat, preu, iva, nom, referencia, atributs, atributsValor, incrementable, actiu)
	{
		var cesta = cercaCistella("cistella");
		nom = escape(nom)
		if(cesta && !isNaN(quantitat) )
		{
			existeix = false; 
			//Per mirar si existeix el registre
			//Ens pategem les files
			
			for(a=0; a < cesta.rows.length; a++)
			{
				//Si es la fila que estem cercant...
				if(cesta.rows[a].id == id+atributs)
				{
					/* Actualitzem els valors */ 
					var fila = cesta.rows[a];
					
					//Si la quantitat es 0 eliminem la fila
					
					switch(quantitat)
					{
					case 0:
						cesta.deleteRow(a);
						break;
					default:
						
						//si la quantitat es més de 0 i es incrementable...
						//if(incrementable!="0")
						//{

							// Ens pategem tota les celes per trobar la cela quantitat
							for(i=0; i < fila.cells.length; i++)
							{
								//Actualitzem la quantitat
								if(fila.cells[i].id == "quantitat")
								 { 
								 	if(incrementable!="0")
										fila.cells[i].title = pasarFloat(fila.cells[i].title) + pasarFloat(quantitat);
									else
										fila.cells[i].title = pasarFloat(quantitat);
									
									
									params = "'" + id + "', this.value, '" + preu + "', '" + iva + "', '" + nom + "', '" + referencia + "', '" + atributs + "', '" + atributsValor + "', false, false, '" + localCistell.idTarifa + "'"

									fila.cells[i].innerHTML = "<input maxlength=3 id=tb" + id + atributs + " class=iqty type=text onKeyDown='controlaIntroQuantitat(event);' onChange=\"localCistell.recalcularQty(" + params + ");\" value=\"" + fila.cells[i].title  + "\">";
									
								  	var qtyTotal = pasarFloat(fila.cells[i].title)
								}
								//Actualitzem el import
								 if(fila.cells[i].id == "import")
								  {	
										if(qtyTotal)
										{
										fila.cells[i].innerHTML = redondejar(qtyTotal * preu).toString().ponerDecimales();
										}
										else
										{
										fila.cells[i].innerHTML = redondejar( pasarFloat(fila.cells[i].innerHTML) + (quantitat*preu) , 2).toString().ponerDecimales();
										}
								  }
							}
						//}
						break;
					}
					//Amb això diem que no cal crear-la
					existeix = true;
					}
			}
			//Si no existeix l'afegim!
			if(!existeix)
			{
				//Creem una fila amb el id del producte
				var trr = cesta.insertRow(cesta.rows.length);
				trr.setAttribute("id", id+atributs)
				//Creem les celes amb els valors


				var tdd = trr.insertCell(0);
				tdd.setAttribute("id", "nom")
				tdd.innerHTML = AlZarqaui( unescape(nom ) + ' ' + atributsValor);
				if(localCistell.idTarifa != "") {			
					var tdd = trr.insertCell(1);
					tdd.setAttribute("id", "preu")
					
					tdd.innerHTML = redondejar(pasarFloat(preu), 2).ponerDecimales();		
					tdd.setAttribute("align", "char");
					tdd.setAttribute("char", ".");
					tdd.setAttribute("charoff", "2");
					
					var tdd = trr.insertCell(2);

					
					params = "'" + id + "', this.value, '" + preu + "', '" + iva + "', '" + nom + "', '" + referencia + "', '" + atributs + "', '" + atributsValor + "', false, false, '" + localCistell.idTarifa + "'"
					if(actiu)
						tdd.innerHTML = "<input maxlength=3 id=tb" + id + atributs + " class=iqty type=text onKeyDown='controlaIntroQuantitat(event);' onChange=\"localCistell.recalcularQty(" + params + ", quantitat, this);\"  value=\"" + quantitat  + "\">";
					else
						tdd.innerHTML = quantitat
						
					tdd.setAttribute("title", quantitat);
					tdd.setAttribute("id", "quantitat");	
	
	
					var tdd = trr.insertCell(3);
					tdd.setAttribute("id", "eliminar")	

					
					if(actiu) tdd.innerHTML = localCistell.addButton(id, quantitat, preu, iva, nom, referencia, atributs, incrementable);
					

					var tdd = trr.insertCell(4);
					tdd.innerHTML = iva;
					tdd.setAttribute("id", "iva")

					
					var tdd = trr.insertCell(5);
					tdd.setAttribute("id", "import")
					tdd.innerHTML = redondejar(pasarFloat(preu)*pasarFloat(quantitat),2).ponerDecimales();
					tdd.setAttribute("align", "char");
					tdd.setAttribute("char", ".");		
					tdd.setAttribute("charoff", "2");

					
					var tdd = trr.insertCell(6);
					tdd.setAttribute("id", "monedaListado");
					tdd.setAttribute("align", "left");
					
					tdd.innerHTML = localCistell.moneda;
				
				}
	
			}

			if(localCistell.idTarifa != "") localCistell.total();
		}
		else
		{
			if(!cesta) alert("Cart not FOUND!");
		}
	}
function pasarFloat(num)
{
		if ( num == undefined ) return;
		var re = /\,+/g
		var nFloat = parseFloat(num.toString().replace(re,"."))
		return nFloat;
}
function controlaIntroQuantitat(e)
{
	// <- cod 37
	// -> cod 39
	// retroceso cod 8
	// tabulador cod 9
	// suprimir cod 46
	var keyCode = null;
	
	if( !document.all )
		keyCode = e.which;
	else
		keyCode = event.keyCode;
	
	//alert( "event.keyCode: "+ keyCode )
	
	var codes = "37,39,9,8,46"
	
	if ( ( codes.indexOf(keyCode) != -1 ) || (keyCode >= 49 && keyCode <= 57 ) || (keyCode >= 96 && keyCode <= 105 )  )
		return true;
	
	if( !document.all )
	{
		e.preventDefault();
	}
	else
		event.returnValue = false;
		
	return  false;
}

function recalcularQty(id, quantitat, preu, iva, nom, referencia, atributs, atributsValor, incrementable, IVAinclos, idTarifa, oldQty, obj)
{
	if( isNaN(quantitat) || quantitat <= 0 )
	{
			if(obj) obj.value = 1;
			//alert(jsTAG_EliminarPerZero) */
			window.location.reload( false );			
	}
	else
		afegirBD(id, quantitat, preu, iva, nom, referencia, atributs, atributsValor, incrementable, IVAinclos, idTarifa)
}


//Separem el generar el boto de treure element del carret
function generaBoto(id, quantitat, preu, iva, nom, referencia, atributs, atributsValor, incrementable)
{

	 boto = "<a onClick=\"localCistell.addToBD('" + id + "'" 
	 boto += ", 0, '" + preu + "','" + iva + "', '" + nom + ' ' + atributsValor + "','" + referencia + "','" + atributs + "', " + incrementable + ", false, 0);\">"
	 boto += "<img border='0' src='aspimagina/cataleg/lib/ico/basurillaT.gif'></a>"
	 return boto

}


//Ens retorna el element cistella (es el que conté el carret)
function cercaCistella (nom) {
	var cistella = document.getElementById(nom)
	if(!cistella)
	{
		/*  Mirem si tenim frames */ 
		for(a=0; a<document.frames.length;a++)
		{
			if (!cistella) cistella = document.frames[a].getElementById(nom);
		}

		/* Mirem si el parent te frames */
		if(!cistella)
		{
			for(a=0; a<parent.frames.length;a++)
			{
				if (!cistella) cistella = parent.frames[a].document.getElementById(nom);
			}
		}
	}
	if(cistella)
		return cistella;
	else
		return null;
}


function redondejar(num, dec)
 { 
	re = /\,+/g
	num = pasarFloat(num);
	dec = pasarFloat(dec); 
	dec = (!dec ? 2 : dec); 
	var valor = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
	return  valor.toString();
 } 

function AlZarqaui(text)
{
	var re = new RegExp("<", "ig");
	sinYankis = text.replace(re,"&lt;");
	re = new RegExp(">", "ig");
	sinGringos = sinYankis.replace(re,"&gt;");
	return sinGringos
}


//Finalitzar la compra
function finalitzar(registrat, mod, idArea, sec, lang, frame)
{
	
	if (registrat == "False")
	{
		alert(jsTAG_noRegistrador)
		document.getElementById("login").focus();
		return;
	}
	
	//Controlem el carret
	if(document.getElementById("eliminar"))
	{
		var ruta = "web.asp?mod=" + mod + "&idAreaWeb=" + idArea + "&sec=" + sec + "&lang=" + lang
		
		switch(frame)
		{
			case "top":
				top.location = ruta;
				break
			case "blank":
				window.open(ruta)
				break
			case "this":
				window.location.href = ruta;
				break
			default:
				window.location.href = ruta;
				break
			
		}
	}
}


function veureCarret(sec, mod)
{
	var nP = document.getElementById("nProducte");

	if(nP.innerHTML!="0" && mod.indexOf("mod") == -1 )
		window.location = "web.asp?mod=" + mod + "&sec=" + sec

}


function afegirFavorit(ruta, nom, idioma)
{
	
	if(ruta.indexOf("lang="+idioma)==-1)
		ruta += "&lang="+idioma
		
	window.external.AddFavorite(ruta, nom);
}


