
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.addToHTML = afegirHTML; //afegirHTML(id, quantitat, preu, iva, nom, incrementable)
	this.addSinIva = afegirSinIva;
	this.addButton = generaBoto;
	this.controlaT = controlaTotals;
	
	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)
	{

		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("asponline/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");
		  tot.style.display = "block"; 
		
		  /* Si no es actiu amaguem la botonera */

		  if(idTarifa == "") tot.style.display = "none";
		  mostrarP(getCookie("mostrarP"))

		 if(!actiu) { //Si no està actiu amaguem la botonera i mostrem productes.
		    var bot = cercaCistella("botonera");
		    bot.style.display = "none";
			mostrarP(1)
		  }

		 }
		
		myConn.connect(rutaAbsoluta + "asponline/cataleg/mod/carret/carga.asp", "POST", "accio=carga&idUsuari=" + this.idUsuari + "&actiu=" + actiu, 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");
		if(!mostrar || mostrar == "false")
			cesta.style.display = "none";
		else
			cesta.style.display = "block";
	}
	

	function mostrarT(mostrar)
	{
		var totals = cercaCistella("sumes");
		if(!mostrar)
			totals.style.display = "none";
		else
			totals.style.display = "block";
	}
	
	
	
	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 = parseFloat(fila.cells[i].innerHTML);
							break;
						case "iva":
							Civa = parseFloat(fila.cells[i].innerHTML);
							break;						
						case "quantitat":
							Cquantitat = parseFloat(fila.cells[i].innerHTML);
							break;				
						case "import":
							Cimport = parseFloat(fila.cells[i].innerHTML);
					}

				}
					//Icrementem valors

					if(this.IVAinclos)
						{ valorSenseIVA = (Cpreu / ((Civa/100)+1) * Cquantitat); }
					else
						{ valorSenseIVA = Cpreu*Cquantitat }
					
					totalSin += valorSenseIVA; 
					
					descompteP = valorSenseIVA * (parseFloat(this.descompte)/100);
					totalDto += descompteP;
					

					if(this.sinIVA) 
					{ totalF = (valorSenseIVA - descompteP); }
					else
					{ totalF = (valorSenseIVA - descompteP)*((Civa/100)+1); }
		
					total += totalF;

			}
			
			this.controlaT(total, totalSin, IVA, totalDto)
			
		}
	}

	
	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);
						try
						{
						  document.getElementById(totals.rows[a].id).style.display = "table-row";
						}
						catch(e)
						{document.getElementById(totals.rows[a].id).style.display = "block";}
						  //totals.rows[a].style.display = "table-row"; 	
						  }
					else
						totals.rows[a].style.display = "none";
						
					break;
				case "sinIVA":
					totals.rows[a].cells[1].innerHTML = redondejar(totalSin, 2);
					break;
				case "TOTALIVA":
					totals.rows[a].cells[1].innerHTML = redondejar(total-totalSin, 2);
					break;				
				case "TOTALconIVA":
					totals.rows[a].cells[1].innerHTML = redondejar(total, 2);
					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 == 1) iva = 0
		
		//preu = calcularSinIva(preu, iva)
		//alert('id' + id + ' quantitat' + quantitat + ' preu' + preu + ' iva' + iva + ' nom' + nom + ' referencia' + referencia + ' atributs' + atributs + ' incmentable' + incrementable)
		
		this.addToBD(id, quantitat, preu, iva, 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("asponline/blank.htm","","");
//	win.document.write(oXML.responseText);
			retorna = String(oXML.responseText);
			
//alert('error:' + retorna + ' incrementable ' + incrementable)

			if (retorna=="0")
				afegirHTML(id, quantitat, preu, iva, nom, referencia, atributs, atributsValor, incrementable, true)
			else
			{
				var win = window.open("asponline/blank.htm","","");
				win.document.write(oXML.responseText);
			}
			
		}


		myConn.connect( rutaAbsoluta + "asponline/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)
	{
//alert(id + '_' + quantitat + '_' + preu + '_' + iva + '_' + nom + '_' + referencia + '_' + atributs + '_' + atributsValor + '_' + incrementable + '_' + actiu);
		var cesta = cercaCistella("cistella");
		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")
								 { fila.cells[i].innerHTML = parseFloat(fila.cells[i].innerHTML) + parseFloat(quantitat);
								  var qtyTotal = parseFloat(fila.cells[i].innerHTML) }
								
								//Actualitzem el import
								 if(fila.cells[i].id == "import")
								  {	
								   if(qtyTotal)
								   {
									
								   	fila.cells[i].innerHTML = (qtyTotal * preu)
								   }
								   else
								   	fila.cells[i].innerHTML = redondejar( parseFloat(fila.cells[i].innerHTML) + (quantitat*preu) , 2)
								   	
								  }

							}
						}
						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", "eliminar")			
				if(actiu) tdd.innerHTML = localCistell.addButton(id, quantitat, preu, iva, nom, referencia, atributs, incrementable);
				
	
				var tdd = trr.insertCell(1);
				tdd.setAttribute("id", "nom")
				tdd.innerHTML = AlZarqaui(nom + ' ' + atributsValor);


				var tdd = trr.insertCell(2);
				tdd.innerHTML = quantitat;
				tdd.setAttribute("id", "quantitat");	


				if(localCistell.idTarifa != "") {			
					var tdd = trr.insertCell(3);
					tdd.innerHTML = iva;
					tdd.setAttribute("id", "iva")
				
					var tdd = trr.insertCell(4);
					tdd.setAttribute("id", "preu")
					tdd.innerHTML = redondejar(parseFloat(preu), 2);		
					tdd.setAttribute("align", "char");
					tdd.setAttribute("char", ".");
					tdd.setAttribute("charoff", "2");
					
					var tdd = trr.insertCell(5);
					tdd.setAttribute("id", "import")
					tdd.innerHTML = redondejar(parseFloat(preu)*parseFloat(quantitat),2);
					tdd.setAttribute("align", "char");
					tdd.setAttribute("char", ".");		
					tdd.setAttribute("charoff", "2");											
				
				}
	
			}

			if(localCistell.idTarifa != "") localCistell.total();
		}
		else
		{
			if(!cesta) alert("Cart not FOUND!");
		}
	}

//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 + "', '" + escape(nom) + ' ' + atributsValor + "','" + referencia + "','" + atributs + "', " + incrementable + ", false, 0);\">"
	 boto += "<img border='0' src='asponline/cataleg/lib/ico/falso.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)
 { 
 
	num = parseFloat(num); 
	dec = parseFloat(dec); 
	dec = (!dec ? 2 : dec); 

	return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); 
 } 

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")
	{
		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 afegirFavorit(ruta, nom, idioma)
{
	
	if(ruta.indexOf("lang="+idioma)==-1)
		ruta += "&lang="+idioma
		
	window.external.AddFavorite(ruta, nom);
}


