// funzioni legate al carrello degli acquisti utilizzando cookies e non database
//
// (C) Damon Bonesi, 2010
// 
// data di creazione:  30.05.2010
// ultima revisione:  30.05.2010
//
// problemi attualmente conosciuti:
//
//
// La proprietà intellettuale di questo codice è di Damon Bonesi, se non altrimenti scritto.
//
// - - Damon Bonesi - - damon@bonesi.ch
//



var shoppingBasket = new CescoShoppingBasket();





// oggetto carrello degli acquisti
function CescoShoppingBasket () {
	this.debug = false;
	this.enabled = true;
	this.basketprefix = "CescoBasket";
	this.totale = 0;
	this.lingua = 'italiano'; // lingua di default
	
	
	
	
	
	
	
	
	
// mette a schermo gli elementi del carrello degli acquisti
    this.populateWindow = function (container) {
		if (this.enabled) {
			
			var deselezionato = "#3299CD";
			var selezionato = "#F29400";
			var colore = deselezionato;
			
			if (this.debug) alert("Compilo : " + container);
			
			var myspace = document.getElementById(container);
			
			var mytext = "";
			
			var elements = this.getitemlist();		
			
			// i costi di produzione sono uguali per tutti, usi i valori del primo elemento	
			elemento = this.getitemdetails(elements[0]);
			
			mytext += "<table cellspacing='3' cellpadding='3' border='0' class='riassunto'>";
			mytext += "<tr>";
			mytext += "<td colspan='2' rowspan='2'>&nbsp;</td><td width='50' rowspan='2' valign='top'><div id='acquista_1' style='color:"+deselezionato+";'></div><br><br><div id='acquista_2' style='color:"+deselezionato+";'></div></td>";
			mytext += "<td width='150' colspan='3' valign='top'><div id='acquista_3' style='color:"+deselezionato+";'></div></td></tr>";
			mytext += "<tr><td width='50'>" + this.valuta(elemento['costiproduzione1']) + "&nbsp;CHF<br><div id='acquista_5' style='color:"+deselezionato+";'></div></td>";
			mytext += "<td width='50'>" + this.valuta(elemento['costiproduzione2']) + "&nbsp;CHF<br><div id='acquista_6' style='color:"+deselezionato+";'></div></td>";
			mytext += "<td width='50'>" + this.valuta(elemento['costiproduzione3']) + "&nbsp;CHF<br><div id='acquista_7' style='color:"+deselezionato+";'></div></td>";
			mytext += "</tr>";
			
			for (var i=0; i<elements.length; i++) {
				
				// ricavo i dettagli
				elemento = this.getitemdetails(elements[i]);
				
				mytext += "<tr>";
				mytext += "<td><img src='http://www.francescopellanda.com/immagini/ridimensiona.php?image=" + elemento['percorso'] + "/" + elemento['nome'] + "&x_max=50&y_max=50' border='0' onclick=\"window.open('http://www.francescopellanda.com/immagini/ridimensiona.php?image=" + elemento['percorso'] + "/" + elemento['nome'] + "&x_max=650&y_max=650');\" style='cursor: pointer;'>&nbsp;";
				mytext += "<td class='minitesto' style='text-align: left;' align='left'>" + this.valuta(elemento['prezzo']) + "&nbsp;CHF</td>";
				mytext += "<td rowspan='2' class='downloadtesto'>";
				
				// download : primo bit indica se è possibile scaricare o meno l'immagine
				//            secondo bit indica se attialmente è selezionato da scaricare o meno
				if ((typeof(elemento['download'])!="undefined") || (parseInt(elemento['itemid'])>=1000000)) {
				   if ((((parseInt(elemento['download']))&1)==1) || (parseInt(elemento['itemid'])>=1000000)){
					  /*mytext += "<a href='#' target='_self' onclick=\"javascript: shoppingBasket.toggledownload('" + elements[i] + "')?this.style.color = '" + selezionato + "':this.style.color = '" + deselezionato + "'; shoppingBasket.refreshDownload(); shoppingBasket.refreshBuy(); shoppingBasket.refreshTotal(); return false;\" style='text-decoration: none;";
					  (parseInt(elemento['download'])&2)==2?mytext += " color:" + selezionato + ";'":mytext += " color:" + deselezionato + ";'";
					  mytext += ">";					
					  mytext += "&bull;</a>";*/
					  // shoppingBasket.refreshDownload(); shoppingBasket.refreshBuy(); shoppingBasket.refreshTotal(); return false;
					  mytext += "<input type='checkbox' ";
					  
					  if ((parseInt(elemento['download'])&2)==2) mytext += " checked='true' ";
					  
					  mytext += " onclick=\"javascript: shoppingBasket.toggledownload('" + elements[i] + "')?this.checked = true:this.checked = false; shoppingBasket.refreshDownload(); shoppingBasket.refreshBuy(); shoppingBasket.refreshTotal();\">";
					  } else mytext += "&nbsp;";
				} else mytext += "&nbsp;";				
				mytext += "</td>";
				
				// colore di default della casella
				if (elemento['quantita1']==0) colore = deselezionato; else colore = selezionato;
				//mytext += "<td rowspan='2'><input type='text' style='color: " + colore + "' id='inputq1"+elements[i]+"' value='" + elemento['quantita1'] + "' onblur=\"javascript: shoppingBasket.setquantity('" + elements[i] + "','1',document.getElementById('inputq1"+elements[i]+"').value)!=0?this.style.color = '" + selezionato + "':this.style.color = '" + deselezionato + "'; shoppingBasket.refreshTotal(); shoppingBasket.refreshBuy(); return false;\"></td>";
				// url(http://www.francescopellanda.com/immagini/generali/sfondo-1px.png) no-repeat
				// style='height:18px; width:44px; background-color: #535151; border: 1px solid " + colore + "; overflow: hidden; color: " + colore + "'
				
				if (parseInt(elemento['itemid'])<1000000) {
				   mytext += "<td rowspan='2'><select id='inputq1"+elements[i]+"' value='" + elemento['quantita1'] + "' onchange=\"javascript: shoppingBasket.setquantity('" + elements[i] + "','1',document.getElementById('inputq1"+elements[i]+"').value)!=0?this.style.color = '" + selezionato + "':this.style.color = '" + deselezionato + "'; shoppingBasket.refreshTotal(); shoppingBasket.refreshBuy(); return false;\">";
				} else {
				  mytext += "<td rowspan='2'>&nbsp;</td>";
				  }
				
				for (var numero=0; numero<=25; numero ++) {
				    mytext += "<option value='"+numero+"' ";
					if (numero == elemento['quantita1']) mytext += " selected ";
					mytext += ">"+numero+"</option>";
				    }
				
				mytext += "</td>";
				
				// colore di default della casella
				if (elemento['quantita2']==0) colore = deselezionato; else colore = selezionato;
				//mytext += "<td rowspan='2'><input type='text' style='color: " + colore + "' id='inputq2"+elements[i]+"' value='" + elemento['quantita2'] + "' onblur=\"javascript: shoppingBasket.setquantity('" + elements[i] + "','2',document.getElementById('inputq2"+elements[i]+"').value)!=0?this.style.color = '" + selezionato + "':this.style.color = '" + deselezionato + "'; shoppingBasket.refreshTotal(); shoppingBasket.refreshBuy(); return false;\"></td>";
				if (parseInt(elemento['itemid'])<1000000) {
				   mytext += "<td rowspan='2'><select id='inputq2"+elements[i]+"' value='" + elemento['quantita2'] + "' onchange=\"javascript: shoppingBasket.setquantity('" + elements[i] + "','2',document.getElementById('inputq2"+elements[i]+"').value)!=0?this.style.color = '" + selezionato + "':this.style.color = '" + deselezionato + "'; shoppingBasket.refreshTotal(); shoppingBasket.refreshBuy(); return false;\">";
				} else {
				  mytext += "<td rowspan='2'>&nbsp;</td>";
				  }
				
				for (var numero=0; numero<=25; numero ++) {
				    mytext += "<option value='"+numero+"' ";
					if (numero == elemento['quantita2']) mytext += " selected ";
					mytext += ">"+numero+"</option>";
				    }
				
				mytext += "</td>";
				
				
				// colore di default della casella
				if (elemento['quantita3']==0) colore = deselezionato; else colore = selezionato;
				//mytext += "<td rowspan='2'><input type='text' style='color: " + colore + "' id='inputq3"+elements[i]+"' value='" + elemento['quantita3'] + "' onblur=\"javascript: shoppingBasket.setquantity('" + elements[i] + "','3',document.getElementById('inputq3"+elements[i]+"').value)!=0?this.style.color = '" + selezionato + "':this.style.color = '" + deselezionato + "'; shoppingBasket.refreshTotal(); shoppingBasket.refreshBuy(); return false;\"></td>";
				if (parseInt(elemento['itemid'])<1000000) { 
				   mytext += "<td rowspan='2'><select id='inputq3"+elements[i]+"' value='" + elemento['quantita3'] + "' onchange=\"javascript: shoppingBasket.setquantity('" + elements[i] + "','3',document.getElementById('inputq3"+elements[i]+"').value)!=0?this.style.color = '" + selezionato + "':this.style.color = '" + deselezionato + "'; shoppingBasket.refreshTotal(); shoppingBasket.refreshBuy(); return false;\">";
				} else {
				  mytext += "<td rowspan='2'>&nbsp;</td>";
				  }
				for (var numero=0; numero<=25; numero ++) {
				    mytext += "<option value='"+numero+"' ";
					if (numero == elemento['quantita3']) mytext += " selected ";
					mytext += ">"+numero+"</option>";
				    }
				
				mytext += "</td>";
				
				
				mytext += "</tr>";
				
				// nome del file
				mytext += "<tr><td colspan='2' class='minitesto'>" + elemento['nome'].substr(0, elemento['nome'].length-4) + "</td></tr>";
				mytext += "<tr><td colspan='6' class='divisore'><img src='http://www.francescopellanda.com/immagini/generali/dot.gif' border='' alt='' title=''></td></tr>";				
				}						
			
			mytext += "<tr>";
			mytext += "<td colspan='6' align='right'><div style='position: relative; height: 20px; width: 350px; border:0px solid;'><div id='acquista_11' style='position:absolute; top:4px; left:170px; width:80px;'></div><div id='totale' style='position:absolute; top:4px; left:265px; width:30px;'>" + this.valuta(this.grandtotal()) + "</div><div id='acquista_10' style='position:absolute; top:4px; left:310px; width:30px;'></div></div></td></tr>";
			mytext += "<tr><td colspan='6' class='minitesto' style='text-align: center;' align='center'><div id='acquista_14'></div></td>";
			mytext += "<tr><td colspan='6' align='center'>";
			
			// metto i bottoni
			mytext += "<div style='position: relative; height: 23px; overflow: visible;'>";
			mytext += "<a href='#' class='testoscarica'><div class='scarica' value='scarica' id='scarica' onclick='shoppingBasket.multiDownload(); return false;' style='display:none;'></div></a>";
			mytext += "<a id='menuAcquista' href='infoinvio.php' target='main' class='testoacquista'><div class='acquista' value='procedi' id='procedi'></div></a>";
			mytext += "</div>";
			
			mytext += "</td></tr>";
			mytext += "</tr></table>";
			
			//alert(mytext);
			
			myspace.innerHTML = mytext;
			
			// sistemo la visibilità dei bottoni
			this.refreshDownload();
			this.refreshBuy();
			
			// eseguo le richieste di traduzione			
			xmlTxt('acquista_1', this.lingua, 'acquista_1');
			xmlTxt('acquista_2', this.lingua, 'acquista_2');
			xmlTxt('acquista_3', this.lingua, 'acquista_3');
			//xmlTxt('acquista_4', this.lingua, 'acquista_4');
			xmlTxt('acquista_5', this.lingua, 'acquista_5');
			xmlTxt('acquista_6', this.lingua, 'acquista_6');
			xmlTxt('acquista_7', this.lingua, 'acquista_7');

			xmlTxt('acquista_10', this.lingua, 'acquista_10');
			xmlTxt('acquista_11', this.lingua, 'acquista_11');
			xmlTxt('acquista_14', this.lingua, 'acquista_14');
			//xmlTxt('acquista_12', this.lingua, 'acquista_4');
			//xmlTxt('acquista_13', this.lingua, 'acquista_4');
			xmlTxt('scarica', this.lingua, 'acquista_12');
			xmlTxt('procedi', this.lingua, 'acquista_13');
			
			
		} else return false;
	}
	
	
	
	
	








// genero il testo riassuntivo per l'email dell'ordine
    this.generateEmail = function (acquista_1, acquista_2, acquista_3, acquista_5, acquista_6, acquista_7, acquista_10, acquista_11) {
		
		// visto che devo interagire tra pagine generate in javascript e codice server side php, passo i testi tradotti come parametri che facilita il task!
		
		if (this.enabled) {			
			if (this.debug) alert("Scrivo : " + container);
			
			var mytext = "";		
			var elements = this.getitemlist();		
			
			// i costi di produzione sono uguali per tutti, usi i valori del primo elemento	
			elemento = this.getitemdetails(elements[0]);
			
			mytext += "<table cellspacing='3' cellpadding='3' border='0' style='font-family: Arial;'>";
			mytext += "<tr>";
			mytext += "<td colspan='2' rowspan='2'>&nbsp;</td><td width='50' rowspan='2' valign='top'><div id='acquista_1'><i>"+acquista_1+"</i></div><br><br><font size='-1'><div id='acquista_2'>"+acquista_2+"</div></font></td>";
			mytext += "<td width='150' colspan='3' valign='top'><div id='acquista_3'><i>"+acquista_3+"</i></div></td></tr>";
			mytext += "<tr><td width='50'>" + this.valuta(elemento['costiproduzione1']) + "&nbsp;CHF<br><font size='-1'><div id='acquista_5'>"+acquista_5+"</div></font></td>";
			mytext += "<td width='50'>" + this.valuta(elemento['costiproduzione2']) + "&nbsp;CHF<br><font size='-1'><div id='acquista_6'>"+acquista_6+"</div></font></td>";
			mytext += "<td width='50'>" + this.valuta(elemento['costiproduzione3']) + "&nbsp;CHF<br><font size='-1'><div id='acquista_7'>"+acquista_7+"</div></font></td>";
			mytext += "</tr>";
			
			for (var i=0; i<elements.length; i++) {
				
				// ricavo i dettagli
				elemento = this.getitemdetails(elements[i]);
				
				mytext += "<tr>";
				mytext += "<td><img src='http://www.francescopellanda.com/immagini/ridimensiona.php?image=" + elemento['percorso'] + "/" + elemento['nome'] + "&x_max=50&y_max=50' border='0'>&nbsp;";
				mytext += "<td style='text-align: left;' align='left'><font size='-1'>" + this.valuta(elemento['prezzo']) + "&nbsp;CHF</font></td>";
				mytext += "<td rowspan='2' align='center'>";
				
				if ((typeof(elemento['download'])!="undefined") || (parseInt(elemento['itemid'])>=1000000)) {
				   if ((((parseInt(elemento['download'])&1)==1) && (parseFloat(elemento['prezzo'])!=0) || (parseInt(elemento['itemid'])>=1000000))) {					 
					  parseInt((elemento['download'])&2)==2?mytext += " &bull;":mytext += "&nbsp;";					  
					  } else mytext += "&nbsp;";
				} else mytext += "&nbsp;";				
				mytext += "</td>";
				
				// colore di default della casella
				if (parseInt(elemento['itemid'])<1000000) { mytext += "<td rowspan='2' align='center'>" + elemento['quantita1'] + "</td>"; } else { mytext += "<td rowspan='2' align='center'>&nbsp;</td>"; };
				
				// colore di default della casella
				if (parseInt(elemento['itemid'])<1000000) { mytext += "<td rowspan='2' align='center'>" + elemento['quantita2'] + "</td>"; } else { mytext += "<td rowspan='2' align='center'>&nbsp;</td>"; };
				
				// colore di default della casella
				if (parseInt(elemento['itemid'])<1000000) { mytext += "<td rowspan='2' align='center'>" + elemento['quantita3'] + "</td>"; } else { mytext += "<td rowspan='2' align='center'>&nbsp;</td>"; };
				mytext += "</tr>";
				
				// nome del file
				mytext += "<tr><td colspan='2'><font size='-1'>" + elemento['nome'].substr(0, elemento['nome'].length-4) + "</font></td></tr>";
				mytext += "<tr><td colspan='6' style='border-bottom: 1px solid #333; height: 2px;'><img src='http://www.francescopellanda.com/immagini/generali/dot.gif' border='' alt='' title=''></td></tr>";
			}
			
			
			mytext += "<tr>";
			mytext += "<td colspan='6' align='right'><div style='position: relative; height: 20px; width: 350px; border:0px solid;'><div id='acquista_11' style='position:absolute; top:4px; left:130px; width:100px;'><b>"+acquista_11+"</b></div><div id='totale' style='position:absolute; top:4px; left:220px; width:70px;'><b>" + this.valuta(this.grandtotal()) + "</b></div><div id='acquista_10' style='position:absolute; top:4px; left:310px; width:30px;'><b>"+acquista_10+"</b></div></div></td></tr></table>";			
			return mytext;
		} else return "";
	}
	
	
	
	
	
	
	// mostra il prompt di download
    this.multiDownload = function () { 
		var fileIndex = 0;
		var fileArray = [];
		var dettagli = "";
		
		fileArray = this.downloadlist();		
	
	    //alert(fileArray.length+ " " + fileArray[fileIndex]);
	 
	    for (fileIndex=0; fileIndex<fileArray.length; fileIndex++) {
		    dettagli = this.getitemdetails(fileArray[fileIndex]);
			popup = window.open("http://www.francescopellanda.com/immagini/ridimensiona.php?image="+dettagli['downloadpath'],"","height=175,width=300,scrollbars=0,status=1,toolbar=0,location=0,directories=0,menubar=0");
		    }
	}
	
	
		
	
	
	
// ricalcola e mostra il nuovo totale
	this.refreshTotal = function() {
		document.getElementById('totale').innerHTML = this.valuta(this.grandtotal());
	}
	
	
	
	

// controlla se mpstrare o meno il bottone "download"
	this.refreshDownload = function() {
		
		var downlaoditemlist = [];
		downloaditemlist = this.downloadlist();		
		if (downloaditemlist.length==0) document.getElementById('scarica').style.display = 'none'; else document.getElementById('scarica').style.display = 'block';
	}
	
	
	
	

// controlla se mostrare arancione o bianca l'icona del carrello (bianca = carrello vuoto, arancione= carrello con elementi)
	this.refreshBasketIcon = function(titolo) {		
		var itemlist = [];
		itemlist = this.getitemlist();		
		
		if (itemlist.length==0) {
		   // disabilito l'accesso alla pagina degli acquisti
		   document.getElementById('linkAcquista').href = "#";
		   document.getElementById('iconacarrello').src = '/immagini/generali/icona-carello.png';
		   document.getElementById('iconacarrello').title = '';
		   } else {
			 // riabilito l'accesso
			 document.getElementById('linkAcquista').href = "/pagine/acquista.php";
			 document.getElementById('iconacarrello').src = '/immagini/generali/icona-carello-arancione.png';
			 document.getElementById('iconacarrello').title = titolo;
		     }
	}
	
	
	
	
	
// controlla se mostrare arancione o bianca l'icona del carrello (bianca = carrello vuoto, arancione= carrello con elementi)
	this.refreshImageIcon = function(itemid) {			
		if (!this.exists(itemid)) document.getElementById('imgidfoto').src = '/immagini/generali/icona-visto.png'; else document.getElementById('imgidfoto').src = '/immagini/generali/icona-visto-arancio.png';
	}
	
	
	
	
// controlla se mpstrare o meno il bottone "download"
	this.refreshBuy = function() {		
		if (this.grandtotal()==0) document.getElementById('procedi').style.display = 'none'; else document.getElementById('procedi').style.display = 'block';
	}
	
	
	
	
// inizializza/distrugge il carrello degli acquisti
    this.init = function() {		 
	     this.totale = 0;
		 document.cookie = this.basketprefix + "=.";
		 
		 if (!document.cookie) {
			alert ("Per gli acquisti ed il download, prego attivare i cookie! Pour les achats et le téléchargement, activer les cookies! For buying and downloads, please enable cookies! Fuer online kaufen und downloaden, bitte cookie aktivieren!");
			this.enabled = false;
		    } else {
		      this.enabled = true;
			  }
		 if (this.debug) alert ("Shopping basket reinizializzato. Attualmente abilitato: " + this.enabled);
    }



// inserisce un elemento nel carrello degli acquisti
	this.add = function (itemid, percorso, nome, downloadpath, download, prezzo, costiproduzione1, costiproduzione2, costiproduzione3) {
		if (this.enabled) {
			
		   // se è già nel carrello, non lo aggiungo nuovamente
		   
		    if (this.exists(itemid)==false) {
			   var indice = document.cookie.indexOf(this.basketprefix);
			   var inizio = document.cookie.indexOf("=", indice) + 1;
			   var fine = document.cookie.indexOf(";", indice);
			   if (fine==-1) fine = document.cookie.length;
		
			   // un nuovo elemento posto nel cestino ha tutte le quantità a zero			   
			   var quantita1 = 0;
			   var quantita2 = 0;
			   var quantita3 = 0;
		
			   if (this.debug) alert("Sto per aggiungere a: "+document.cookie);
			   
			   //alert("Sto per aggiungere a: "+document.cookie);
			   
			   document.cookie = this.basketprefix + "=" + document.cookie.substring(inizio, fine) + escape("[" + itemid + '{' + percorso + '>' + nome + '<' + downloadpath + '}' + download + "%" + prezzo + "*" + costiproduzione1 + "@" + costiproduzione2 + "+" + costiproduzione3 + "?" + quantita1 + "#" + quantita2 + "$" + quantita3 + "]");
			   if (this.debug) alert("Ho aggiunto: "+document.cookie);
			   return true;
		   } else {
			 if (this.debug) alert("Già esistente, non aggiungo: "+document.cookie);
			 return false;
		     }
			
		} else return false;
	}





// inserisce un elemento nel carrello degli acquisti se non c'è, lo toglie se c'è
this.toggle = function (itemid, percorso, nome, downloadpath, download, prezzo, costiproduzione1, costiproduzione2, costiproduzione3) {
		if (this.enabled) {
		   if (!this.exists(itemid)) this.add(itemid, percorso, nome, downloadpath, download, prezzo, costiproduzione1, costiproduzione2, costiproduzione3);
		   else this.remove(itemid);
		}
    }





// imposta il linguaggio di visualizzazione
    this.lingua = function (nuovalingua) {
		if (this.enabled) {
			
		   if (typeof(nuovalingua)!="undefined") this.lingua = nuovalingua; else this.lingua = "italiano";
		   return true;
			
		} else return false;
	}
	
	
	
	
// ritorna true se il carrello è vuoto
    this.isempty = function (itemid) {
		if (this.enabled) {
			
		   var indice = document.cookie.indexOf(this.basketprefix);
	       var inizio = document.cookie.indexOf("=", indice) + 1;
           var fine = document.cookie.indexOf(";", indice);
           if (fine==-1) fine = document.cookie.length;
		   
		   //che condizione deve esserci?
		   alert(indice + " " + inizio + " " + fine);
		   
			
		} else return true;
	}
	
	
	
	
// ritorna true se un elemento è già nel carrello degli acquisti
    this.exists = function (itemid) {
		if (this.enabled) {
			
			var elemento = [];
			elemento = this.getitemdetails(itemid);
			
			if (this.debug) alert ("Elemento esistente: " + this.size(elemento));
		
			if (this.size(elemento)==0) return false; else return true;
			
		} else return false;
	}




// rimuove un elemento dal carrello degli acquisti
    this.remove = function (itemid) {
		if (this.enabled) {
			
			nuovaListaElementi = ".";
  
			indice = document.cookie.indexOf(this.basketprefix);
			inizio = document.cookie.indexOf("=", indice) + 1;
			fine = document.cookie.indexOf(";", indice);
			if (fine == -1) fine = document.cookie.length;
		   
		    //alert("Cookie prima del remove: "+document.cookie);
			
			listaCompleta = unescape(document.cookie.substring(inizio, fine));
			
			//alert("Lista completa prima del remove: "+listaCompleta);
			
			for (var i = 0; i <= listaCompleta.length; i++) {
				if (listaCompleta.substring(i,i+1) == '[') {
				  inizio = i+1;
				} else if (listaCompleta.substring(i, i+1)=='{') {
					   currentitem = listaCompleta.substring(inizio, i);
					   inizio = i + 1;			   				   
				} else if (listaCompleta.substring(i,i+1) == ']') {
						 fine = i;
						 
						 if (this.debug) alert ("Rimuovo: " + currentitem);
						 						 
						 if (this.debug) alert ("Prima della rimozione: " + nuovaListaElementi);						 	  
						 if (parseInt(currentitem) != parseInt(itemid)) nuovaListaElementi += '[' + currentitem + "{" + listaCompleta.substring(inizio, fine) + ']';
						 if (this.debug) alert ("Dopo la rimozione: " + nuovaListaElementi);
				}
           }
  
        // salvo il nuovo cestino
		//alert("Prima di rifare il cookie: "+document.cookie);
		
		document.cookie = this.basketprefix + "=" + escape(nuovaListaElementi);
		
		//alert("Dopo il cookie rifatto: "+document.cookie);
  		return true;
		
		} else return false;
	}




// cambia la quantità ordinata (formato è l'indice del tipo: 1, 2 o 3)
    this.setquantity = function (itemid, formato, quantita) {
		if (this.enabled) {
			if (this.exists(itemid)) {
			   var elemento = this.getitemdetails(itemid);			   
			   var quantitacontrollata = 0;
			   
			   // trucchetto per prendere qualsiasi tipo di errore
			   if(parseInt(quantita)>0) quantitacontrollata = quantita;
			   
			   this.remove(itemid);			   
			   
			   //alert(itemid+" "+formato+" "+quantita);
			   
			   if (formato==1) this.detailadd(elemento['itemid'],elemento['percorso'],elemento['nome'],elemento['downloadpath'],elemento['download'],elemento['prezzo'],elemento['costiproduzione1'],elemento['costiproduzione2'],elemento['costiproduzione3'],quantitacontrollata,elemento['quantita2'],elemento['quantita3']);
				  
			   if (formato==2) this.detailadd(elemento['itemid'],elemento['percorso'],elemento['nome'],elemento['downloadpath'],elemento['download'],elemento['prezzo'],elemento['costiproduzione1'],elemento['costiproduzione2'],elemento['costiproduzione3'],elemento['quantita1'],quantitacontrollata,elemento['quantita3']);
			   
			   if (formato==3) this.detailadd(elemento['itemid'],elemento['percorso'],elemento['nome'],elemento['downloadpath'],elemento['download'],elemento['prezzo'],elemento['costiproduzione1'],elemento['costiproduzione2'],elemento['costiproduzione3'],elemento['quantita1'],elemento['quantita2'],quantitacontrollata);
			   return quantitacontrollata;
			   }
		} else return 0;
	}





// marca l'elemento da scaricare o meno
    this.setdownload = function (itemid, download) {
		if (this.enabled) {
			if (this.exists(itemid)) {
			   var elemento = this.getitemdetails(itemid);
			   this.remove(itemid);
			   
			   if (download==true)
			      this.detailadd(elemento['itemid'],elemento['percorso'],elemento['nome'],elemento['downloadpath'],parseInt(elemento['download'])|2,elemento['prezzo'],elemento['costiproduzione1'],elemento['costiproduzione2'],elemento['costiproduzione3'],elemento['quantita1'],elemento['quantita2'],elemento['quantita3']);
			   else
			      this.detailadd(elemento['itemid'],elemento['percorso'],elemento['nome'],elemento['downloadpath'],parseInt(elemento['download'])&1,elemento['prezzo'],elemento['costiproduzione1'],elemento['costiproduzione2'],elemento['costiproduzione3'],elemento['quantita1'],elemento['quantita2'],elemento['quantita3']);
			   
			   return true;
			   }
			
		} else return false;
	}
	
	
	

// fa il toggle della selezione download
    this.toggledownload = function (itemid) {
		if (this.enabled) {
			
			if (this.exists(itemid)) {
			   var elemento = this.getitemdetails(itemid);
			   this.remove(itemid);

			   if ((parseInt(elemento['download'])&2)==0) {
			      this.detailadd(elemento['itemid'],elemento['percorso'],elemento['nome'],elemento['downloadpath'],parseInt(elemento['download'])|2,elemento['prezzo'],elemento['costiproduzione1'],elemento['costiproduzione2'],elemento['costiproduzione3'],elemento['quantita1'],elemento['quantita2'],elemento['quantita3']);
			      // ritorna il nuovo stato
				  return 1;
				  }
			   else {
			      this.detailadd(elemento['itemid'],elemento['percorso'],elemento['nome'],elemento['downloadpath'],parseInt(elemento['download'])&1,elemento['prezzo'],elemento['costiproduzione1'],elemento['costiproduzione2'],elemento['costiproduzione3'],elemento['quantita1'],elemento['quantita2'],elemento['quantita3']);
			      // ritorna il nuovo stato				  
				  return 0;
				  }			  
			   }
			
		} else return 0;
	}
	
	
	
	
// ritorna il costo totale per l'elemento selezionato
    this.itemtotal = function (itemid) {
		if (this.enabled) {
			var prezzoAggiunto = false;
			var elemento = this.getitemdetails(itemid);			
			var itemtotal = (parseFloat(elemento["costiproduzione1"])) * parseFloat(elemento["quantita1"])  +  (parseFloat(elemento["costiproduzione2"])) * parseFloat(elemento["quantita2"])  +  (parseFloat(elemento["costiproduzione3"])) * parseFloat(elemento["quantita3"]);
					
			// se ne è ordinato almeno uno, aggiungo il valore artistico al totale oltre ai costi di sviluppo
			if (itemtotal>0) {
			   itemtotal += parseFloat(elemento["prezzo"]);
			   prezzoAggiunto = true;
			   }
			
			if (((elemento["download"]&2)==2) &&(prezzoAggiunto==false)) itemtotal += parseFloat(elemento["prezzo"]);
			return itemtotal;
			
		} else return 0;
	}




// ritorna il totale del carrello degli acquisti
    this.grandtotal = function () {
		if (this.enabled) {
		   
		   var totale = 0;
		   var elements = this.getitemlist();
		   
		   //alert(elements.length);
		   
		   for (i=0; i<elements.length; i++) totale += this.itemtotal(elements[i]);
			
		// ritorno la lista
		return totale;
		
		} else return 0;
	}




// ritorna una stima del tempo che impiegheranno ad essere scaricate le immagini
    this.downloadtime = function () {
		if (this.enabled) {
		   
		   // per default metto una velocità media di download a 100kbyte/s
		   var downloadspeed = 100;
		   
		   // utilizzo al momento una grandezza media di file
		   var meanfilesize = 3000;
		   		   		   
		   var downlaoditemlist = this.downloadlist();
		   var downloadsize = meanfilesize * downloaditemlist.length;
		   var fulldownloadtime = downloadsize / downloadspeed;
		   
		   return fulldownloadtime;
		   
		
		} else return -1;
	}




// ritorna l'elenco dei files (id) scaricabili direttamente (presenti nel server come download gratuiti)
    this.downloadlist = function () {
		
		var itemlist = [];
		
		if (this.enabled) {
		   var elements = this.getitemlist();  
		    for (i=0; i<elements.length; i++) {
				var elemento = this.getitemdetails(elements[i]);
				
				if (((elemento['download']&2)==2) && (elemento['prezzo']==0)) {
					//alert ("Inserisco " + elemento['itemid']);
					itemlist.push(elemento['itemid']);				
				    }
			}
			
		// ritorno la lista		
		return itemlist;
			
		} else return itemlist;
	}






// funzioni interne






  		
	// ritorna un array contenente tutti i dettagli per l'elemento specificato
	this.getitemdetails = function(itemid) {
		
		var elemento = [];		
		indice = document.cookie.indexOf(this.basketprefix);
		  
		inizio = document.cookie.indexOf("=", indice) + 1;
		fine = document.cookie.indexOf(";", indice);
		if (fine == -1) fine = document.cookie.length;
 
		listaCompleta = unescape(document.cookie.substring(inizio, fine));  
		
		if (this.debug) alert(listaCompleta);
		
		for (var i=0; i<=listaCompleta.length; i++) {
			if (listaCompleta.substring(i, i+1)=='[') {
			   // vado al prossimo elemento
			   inizio = i + 1;
			} else if (listaCompleta.substring(i,i+1)==']') {
			  // sono arrivato alla fine della lettura di una stringa descrittiva di un elemento
			  fine = i;
			  
			  // prendo l'ultimo elemento
			  elemento["quantita3"] = listaCompleta.substring(inizio, fine);			 
			  
			  // se è l'elemento cercato, lo restituisco
			  if (this.debug) alert("Elemento trovato: " + parseInt(elemento["itemid"]) + ", elemento cercato: " + parseInt(itemid));
			  if (parseInt(elemento["itemid"]) == parseInt(itemid)) {
				 if (this.debug) alert("Ritorno elemento: " + parseInt(elemento["itemid"]) + ", elemento cercato: " + parseInt(itemid));
				 return elemento;
			     } else elemento = [];
						 
			} else if (listaCompleta.substring(i, i+1)=='{') {
					 elemento["itemid"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='>') {
					 elemento["percorso"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='<') {
					 elemento["nome"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='}') {
					 elemento["downloadpath"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='%') {
					 elemento["download"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='*') {
					 elemento["prezzo"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='@') {
					 elemento["costiproduzione1"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='+') {
					 elemento["costiproduzione2"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;				
			} else if (listaCompleta.substring(i, i+1)=='?') {
					 elemento["costiproduzione3"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='#') {
					 elemento["quantita1"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			} else if (listaCompleta.substring(i, i+1)=='$') {
					 elemento["quantita2"] = listaCompleta.substring(inizio, i);
					 inizio = i + 1;
			}		  
		}
		
		// se non ho trovato nulla, ritorna l'array vuoto
		return elemento;
	}
	
	
	
	
	// ritorna la lista degli itemid attualmente nel cestino
	this.getitemlist = function() {
		var itemlist = [];
		
		indice = document.cookie.indexOf(this.basketprefix);
		inizio = document.cookie.indexOf("=", indice) + 1;
		fine = document.cookie.indexOf(";", indice);
		if (fine == -1) fine = document.cookie.length;
	   
		listaCompleta = unescape(document.cookie.substring(inizio, fine));
		
		//alert("Controllo esistenza: "+listaCompleta);
		
		// tolgo xché eccessivo debug nei loop if (this.debug) alert("Leggo dalla lista: " + listaCompleta + " lunga: " + listaCompleta.length);
		
		for (var i = 0; i <= listaCompleta.length; i++) {
			if (listaCompleta.substring(i,i+1) == '[') {
			  inizio = i+1;
		  
			} else if (listaCompleta.substring(i, i+1)=='{') {
				   currentitem = listaCompleta.substring(inizio, i);
				   
				   // tolgo xché eccessivo debug nei loop if (this.debug) alert("Leggo elemento: " + currentitem);
				   
				   itemlist.push(currentitem);
				   inizio = i + 1;
			}			   
		}
		
		// ritorno la lista degli elementi
		return itemlist;
	}




	// formatta il valore per la visualizzazione in franchi svizzeri
	this.valuta = function(valore) {				
	  franchi = parseInt(valore, 10);
	  centesimi = valore - franchi;	
	  centesimi = Math.round(centesimi * 100, 10);
			
	  if (centesimi==0) centesimiStr='00'
	  else if (centesimi<10) centesimiStr='05'
		else centesimiStr = centesimi;
			
	  valoreStringa = franchi + '.' + centesimiStr;
	  return valoreStringa;
	}
	
	
	
	
	// ritorna la grandezza di un array associativo (con indici letterali). In questo caso la funzione length non va, ritorna 0
	this.size = function(myArray) {				
	  var element_count = 0;
      for(var e in myArray) if(myArray.hasOwnProperty(e)) element_count++; 
	  return element_count;
	}
	
	
	
	// inserisce un elemento con tutti i suoi dettagli
	this.detailadd = function (itemid, percorso, nome, downloadpath, download, prezzo, costiproduzione1, costiproduzione2, costiproduzione3, quantita1, quantita2, quantita3) {
		if (this.enabled) {
			
		   // se è già nel carrello, non lo aggiungo nuovamente		    
		   if (this.exists(itemid)==false) {
			   var indice = document.cookie.indexOf(this.basketprefix);
			   var inizio = document.cookie.indexOf("=", indice) + 1;
			   var fine = document.cookie.indexOf(";", indice);
			   if (fine==-1) fine = document.cookie.length;
		
			   if (this.debug) alert("Sto per aggiungere il dettaglio a: "+document.cookie);
			   document.cookie = this.basketprefix + "=" + document.cookie.substring(inizio, fine) + escape("[" + itemid + '{' + percorso + '>' + nome + '<' + downloadpath + '}' + download + "%" + prezzo + "*" + costiproduzione1 + "@" + costiproduzione2 + "+" + costiproduzione3 + "?" + quantita1 + "#" + quantita2 + "$" + quantita3 + "]");
			   if (this.debug) alert("Ho aggiunto il dettaglio a: "+document.cookie);				  		   
			   return true;
		   } else return false; 
			
		} else return false;
	}
	

	
	



// fine della function CescoShoppingBasket
}
