var tagImmagine = "";
var nomeProdotto = "";


function selezioneNonDisponibile() {
	var divToCart = document.getElementById("toCart");
	var divCodice = document.getElementById("divCodice");
	var divTraduzione = document.getElementById("divTraduzione");
	var divIva = document.getElementById("divIva");
	var divPeso = document.getElementById("divPeso");
	var divPrezzo = document.getElementById("divPrezzo");
	
	divCodice.innerHTML = "-";
	divIva.innerHTML = "-";
	divPeso.innerHTML = "-";
	divPrezzo.innerHTML = "-";

	divToCart.style.display = "none";
}

function showVariante(idRaggruppamento) {
	// alert(idRaggruppamento);
	var idLingua = document.getElementById("idLingua");
	var txtRaggruppamento = document.getElementById("rifRaggruppamento");
	var divToCart = document.getElementById("toCart");
	var divCodice = document.getElementById("divCodice");
	var divTraduzione = document.getElementById("divTraduzione");
	var divIva = document.getElementById("divIva");
	var divPeso = document.getElementById("divPeso");
	var divPrezzo = document.getElementById("divPrezzo");
	var strPrezzo = "";
	
	divResults = document.getElementById("divResults");

	if (idRaggruppamento > 0) {

		url = baseUrl + "ajax/showVariante.php"; // The server-side script
		variabili =  "ts=" + timestamp + "&idr=" + idRaggruppamento + "&idl=" + idLingua.value;
		// url = url + "?" + variabili; // per il GET
		
		//alert(url);
		
		http.open("POST", url, false); 
	  http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		http.send(variabili); 
	
		if (http.readyState == 4) { 
			if(http.status == 200) { 
				var results = http.responseText;

				// alert(results);

				var XMLResponse = http.responseXML;
				var error = XMLResponse.getElementsByTagName("error")[0].childNodes[0].nodeValue;
				
				if (error == 0) {
					txtRaggruppamento.value = idRaggruppamento;
					var codice = XMLResponse.getElementsByTagName("codice")[0].childNodes[0].nodeValue;
					var traduzione = XMLResponse.getElementsByTagName("traduzione")[0].childNodes[0].nodeValue;
					var iva = XMLResponse.getElementsByTagName("iva")[0].childNodes[0].nodeValue;
					var peso = XMLResponse.getElementsByTagName("peso")[0].childNodes[0].nodeValue;
					var prezzo = XMLResponse.getElementsByTagName("prezzo")[0].childNodes[0].nodeValue;
					var prezzoApplicato = XMLResponse.getElementsByTagName("prezzoApplicato")[0].childNodes[0].nodeValue;
					var quantitaDisponibile = XMLResponse.getElementsByTagName("quantitaDisponibile")[0].childNodes[0].nodeValue;
					var numCaratteristiche = XMLResponse.getElementsByTagName("numCaratteristiche")[0].childNodes[0].nodeValue;
					var caratteristiche = XMLResponse.getElementsByTagName("caratteristiche")[0].childNodes[0];
										
					if (prezzoApplicato != prezzo) {
						strPrezzo = "<div class=\"prezzoBarrato\">" + prezzo + " " + _EURO + "</div>\n";
						strPrezzo += "<div class=\"prezzoBig\">" + prezzoApplicato + " " + _EURO + "</div>\n";
					} else {
						strPrezzo = "<div class=\"prezzoBig\">" + prezzo + " " + _EURO + "</div>\n";
					}
					
					nomeProdotto = traduzione;
					
					divTraduzione.innerHTML = traduzione;
					divCodice.innerHTML = codice;
					divIva.innerHTML = iva + " %";
					divPeso.innerHTML = peso + " g";
					divPrezzo.innerHTML = strPrezzo;
					
					if (quantitaDisponibile > 0) {
						divToCart.style.display = "block";
						divResults.innerHTML = "";
					} else {
						divToCart.style.display = "none";
						divResults.innerHTML = _PRODOTTO_ESAURITO;
					}

					// alert(numCaratteristiche);
					
					if (numCaratteristiche > 0) {
						// alert("CARATTERISTICHE: " + caratteristiche.length);
						
						var caratteristica;
						var valore;
						
						for (var i=0; i < numCaratteristiche; i++) {
							caratteristica = XMLResponse.getElementsByTagName("caratteristica")[i].childNodes[0].nodeValue;
							valore = XMLResponse.getElementsByTagName("valore")[i].childNodes[0].nodeValue;
							
							/*-------------*/
							coloraStessaCaratteristica(caratteristica, "");
							nomeDiv = "car_" + caratteristica + "_" + valore;
							arraySelezionati[caratteristica] = valore;
							divToPaint = document.getElementById(nomeDiv);
							divToPaint.style.background = coloreSelezionati;
							/*-------------*/

/* TOLTO PERCHE' RELATIVO AI RADIOBUTTON CHE NON CI SONO PIU'
							// alert (caratteristica + " = " + valore);
							eval("var contaElementi = document.formAcquisto.elementi_" + caratteristica + ".length;");
							// alert("contaElementi[" + caratteristica + "] = " + contaElementi);
							
							for(var j=0; j<contaElementi; j++) {
								if (eval("document.formAcquisto.elementi_" + caratteristica + "[j].value") == valore) {
									eval("document.formAcquisto.elementi_" + caratteristica + "[j].checked = true;")
								} else {
									// nessuna modifica
								}
							}
*/
						}
						
						reimpostaSelezionati(nomeDiv);
					} else {
						// alert("NESSUNA CARATTERISTICA");
					}
				} else {
					alert("ERRORE: " + error);
				}
			}
		}
	} else {
		// alert("PRODOTTO O COMBINAZIONE NON DISPONIBILE");
		selezioneNonDisponibile();
		divResults.innerHTML = _COMBINAZIONE_NON_DISPONIBILE;
	}
}

function checkRaggruppamento(idProdotto, strVarianti) {
	url = baseUrl + "ajax/showVariante.php"; // The server-side script
	variabili =  "ts=" + timestamp + "&idp=" + idProdotto + "&strCar=" + escape(strVarianti);
	// url = url + "?" + variabili; // per il GET
	
	http.open("POST", url, false);
  http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	// http.send(""); // send con il GET
	http.send(variabili); // send con il POST
		
	if (http.readyState == 4) { 
		if(http.status == 200) { 
			var results = http.responseText;
			
			// alert(results);

			var XMLResponse = http.responseXML;
			var idRaggruppamento = XMLResponse.getElementsByTagName("idRaggruppamento")[0].childNodes[0].nodeValue;
			var error = XMLResponse.getElementsByTagName("error")[0].childNodes[0].nodeValue;
			
			showVariante(idRaggruppamento);
		} else {
		}
	} else {
	}
}

function checkVarianti() {
	var idProdotto = document.getElementById("idProdotto");
	
	var i, y;
	var arrayCaratteristiche = Array(5, 6, 7);
	var currentValue;
	var currentChecked;
	var caratteristica;
	var strRisultato = "";
	var numElementi;
	
	/* --- DA TOGLIERE QUANDO SI USERANNO SOLO I DIV --- */
/*
	for (i=0; i < arrayCaratteristiche.length; i++) {
		caratteristica = arrayCaratteristiche[i];
		// alert(caratteristica);
		
		eval ("numElementi = document.formAcquisto.elementi_" + caratteristica + ".length;");
		// alert("elementi_" + i + "[].length = " + numElementi);
		
		for (y=0; y < numElementi; y++) {
			eval("currentValue = document.formAcquisto.elementi_" + caratteristica + "[y].value");
			eval("currentChecked = document.formAcquisto.elementi_" + caratteristica + "[y].checked");

			// strRisultato = "CARATTERISTICA: " + caratteristica + "\nVALORE: " + currentValue + "\n\n";
			
			if (currentChecked) {
				strRisultato += caratteristica + "@" + currentValue + "|";
			} else {
				// strRisultato += "KO";
			}
			
		}
	}
*/
	/* ### DA TOGLIERE QUANDO SI USERANNO SOLO I DIV ### */
	
	/*----------*/
	var carAttuale;
	var valAttuale;
	var checkCombinazione = true;
	
	strRisultato = "";
	
	for(y=0; y<arrayCaratteristiche.length; y++) {
		carAttuale = arrayCaratteristiche[y];
		strRisultato += carAttuale + "@";
		valAttuale = arraySelezionati[carAttuale];
		
		if (valAttuale != "") {
			strRisultato += valAttuale;
		} else {
			strRisultato += "-1";
			checkCombinazione = false;
			y = arrayCaratteristiche.length;
		}
		
		strRisultato += "|";
	}
	/*----------*/
	
	if (strRisultato != "") {
		strRisultato = strRisultato.substr(0, (strRisultato.length-1));
		// alert(strRisultato);
	}
	
	if (checkCombinazione) {
		checkRaggruppamento(idProdotto.value, strRisultato);
	} else {
		// reimpostare a null tutti i prezzi/pesi/ecc... nella pagina perche' la combinazione non e' possibile
		selezioneNonDisponibile();
	}
}

function checkDatiProdotto() {
	var retValue;
	var quantita = document.getElementById("quantita");
	
	if (quantita.value > 0) {
		retValue = "OK";
	} else {
		retValue = _QUANTITA_NON_VALIDA;
	}
	
	return retValue;
}

function aggiungiProdottoDaLista(idProdotto, rifRaggruppamento, quantita, nome, pathImmagine) {
	var formAcquisto = document.getElementById("formAcquisto");
	
	formAcquisto.idProdotto.value = idProdotto;
	formAcquisto.rifRaggruppamento.value = rifRaggruppamento;
	formAcquisto.quantita.value = quantita;
	
	nomeProdotto = nome;
	tagImmagine = pathImmagine;

	aggiungiProdotto();
	
	eval("qta = \"quantita_" + idProdotto + "\"");
	var valoreQuantita = document.getElementById(qta);
	valoreQuantita.value = "";
}

function aggiungiProdotto() {
	var check = checkDatiProdotto();
	
	if (check == "OK") {
		var sid = document.getElementById("sid");
		var idProd = document.formAcquisto.idProdotto.value;
		var rifRaggruppamento = document.formAcquisto.rifRaggruppamento.value;
		var qta = document.formAcquisto.quantita.value;

		divResults = document.getElementById('divResults');
		url = baseUrl + "ajax/aggiungiProdotto.php?ts=" + timestamp; // The server-side script
		url = url + "&sid=" + escape(sid.value) + "&idProd=" + escape(idProd) + "&rifRaggruppamento=" + escape(rifRaggruppamento) + "&qta=" + escape(qta);
		// prompt("aggiungiProdotto", url);
		http.open("GET", url, false); 
		http.send("");
	
		if (http.readyState == 4) { 
			if(http.status == 200) { 
				var results = http.responseText;
				
				if (results == "true") {
					addProd(true);
				} else if (results == "low") {
					//divResults.innerHTML = _QUANTITA_NON_DISPONIBILE;
					var layerErroreInserimento = document.getElementById("layerInserimento");
					layerErroreInserimento.innerHTML = _QUANTITA_NON_DISPONIBILE;
					layerErroreInserimento.style.background = "#fff";			
					animatedcollapse.show('layerInserimento','fade=1,height=auto');
					setTimeout("animatedcollapse.hide('layerInserimento');", 5000);			
				} else {
					addProd(false);
					
					if (results != "false") {
						// nel caso non sia uno dei valori di ritorno previsti
						// visualizzo il messaggio di errore (o altro) restituito
						divResults.innerHTML = "OTHER_ERROR: " + results;
					}
				}
			} else {
				divResults.innerHTML = "[readyState != 200] (" + http.status + ")";
			}
		} else {
			// divResults.innerHTML = "Loading... (" + http.readyState + ")";
		}
	} else {		
		var layerErroreInserimento = document.getElementById("layerInserimento");
		
		layerErroreInserimento.innerHTML = check;
		layerErroreInserimento.style.background = "#fff";
			
		animatedcollapse.show('layerInserimento','fade=1,height=auto');		
		setTimeout("animatedcollapse.hide('layerInserimento');", 2000); // nasconde il layer dopo 3 sec (3000 ms)
	}
}

function aggiornaNumProdottiCarrello(articoli) {
	var sid = document.getElementById("sid");

	url = baseUrl + "ajax/aggiornaNumProdottiCarrello.php?ts=" + timestamp; // The server-side script
	url = url + "&sid=" + escape(sid.value) + "&articoli=" + articoli;
	// prompt("aggiornaNumProdottiCarrello", url);
	http.open("GET", url, false); 
	http.send("");
	
	var divNumProdottiCarrello = document.getElementById("numProdottiCarrello");	
	var risultato = http.responseText;
	
	// alert(divNumProdottiCarrello.innerHTML + "\n\n" + "***" + risultato + "***" + http.responseText + "***");
	
	if (risultato != "") {
		divNumProdottiCarrello.innerHTML = risultato;
	} else {
		divNumProdottiCarrello.innerHTML = "-";
	}
}
function aggiornaSommaCarrello(articoli) {
	var sid = document.getElementById("sid");

	url = baseUrl + "ajax/aggiornaSommaCarrello.php?ts=" + timestamp; // The server-side script
	url = url + "&sid=" + escape(sid.value) + "&articoli=" + articoli;
	http.open("GET", url, false); 
	http.send("");
	
	var divSommaCarrello = document.getElementById("sommaCarrello");	
	var risultato = http.responseText;
	
	//alert(divNumProdottiCarrello.innerHTML + "\n\n" + "***" + risultato + "***" + http.responseText + "***");
	
	if (risultato != "") {
		divSommaCarrello.innerHTML = risultato;
	} else {
		divSommaCarrello.innerHTML = "-";
	}
}
animatedcollapse.addDiv('layerInserimento','fade=1,height=auto,hide=1')
animatedcollapse.addDiv('layerErroreInserimento','fade=1,height=auto,hide=1')
animatedcollapse.init()





// --------------------------------------------------------






/* var x;

function chiudiLayer() {
	alert("chiudiLayer");
	x.style.visibility = "hidden";				
	// document.formAcquisto.submit(); // spostare prima del messaggio di inserimento nel carrello sostituendolo con una chiamata AJAX
} */
		
function addProd(risultato) {
	var x = document.getElementById("layerInserimento");
	
	if (risultato) {
		x.innerHTML = "<img  src=\"" + prefixPath + commonsDir + "/functions/thumbOnTheFly.php?imagePath=" +  tagImmagine + "&width=60/><br />";
		/*x.innerHTML = "<img class=\"floatLeft\" src=\"" + prefixPath + tagImmagine + "\" width=\"60\" /><br /><br />";*/
		x.innerHTML += document.formAcquisto.quantita.value + " " + _QUANTITA + "<br />";
		x.innerHTML += "\"" + nomeProdotto + "\"<br />";
		x.innerHTML += _IN_CARRELLO + "<br /><br />";
		x.innerHTML += "<a href=\"" + creaLinkCarrello + "\"><img src=\"" + prefixPath + "images/btnCheckOut.jpg\"><!-- _CARRELLO --></a>";			
		x.style.background = "#fff";
		document.formAcquisto.quantita.value = "";

		aggiornaNumProdottiCarrello(true);
		aggiornaSommaCarrello(true);		
	} else {
		x.innerHTML = _ERRORE_INS_CARRELLO;
	}
	
	//x.style.visibility = "visible";
	animatedcollapse.show('layerInserimento','fade=5,height=400px');		
	setTimeout("animatedcollapse.hide('layerInserimento');", 5000); // nasconde il layer dopo 3 sec (3000 ms)
}

function test_change(formID, categoria, valore) {
	alert('test_change(' + formID + ', ' + categoria + ', ' + valore + ')');
	checkaVarianti();
}

function test_add(formID, categoria, valore) {
	// alert('test_add(' + formID + ', ' + categoria + ', ' + valore + ')');
	checkVarianti();
}
