function caricaArticoliPrimoPiano(src, status) {
	if (status == 'init') {
		var ulid = src.container.first("ul").context.id;
		//if (ulid == 'nuoviarrivi') {
		$.getJSON('/'+section+'/'+cat+'/' + 'action/getPromoArticles', {"type": ulid }, loadedPromoArticles);
		//}
	}
}

function loadedPromoArticles(data) {
	//alert("loaded articles 2: type=" + data.type);
	var carousel = $('#' + data.type).data('jcarousel');
	for (var i=0; i< data.items.length; i++) {
		var itemInfo = data.items[i];
		var itemHtml = "<div class=\"box_product_mini\"><a href=\"/" + section +"/" + cat + "/schedaProdotto?sku=" + itemInfo.sku + "&color=" + itemInfo.codColore + "\" style=\"display:block;width:83px;height:125px\"><img src=\"/public/foto/" + itemInfo.imgpath +"\" border=\"0\" width=\"83\" height=\"125\" alt=\"no-photo\" /></a><h2>" + itemInfo.title +"</h2><p>" + itemInfo.descr +"</p></div>";
		carousel.add(i+1,itemHtml);
	}
	carousel.size(data.items.length);
	//carousel.startAuto(8);
}

function aggiungiFiltro() {
	//alert("Aggiungo:" + this.id);
	var fobj = $("#" + this.id+" span");
	//alert("span:" + fobj.html());
	$.getJSON('/action/aggFiltro', {"idFiltro": this.id, "descrFiltro": fobj.html() }, aggiuntoFiltro);
}

function aggiuntoFiltro(data) {
	//alert("aggiuntoFiltro!:"+data);
	if (data.result) {
		var destDiv = $("#filtri-" + data.cat +"-panel");
		destDiv.append("<a id=\"flt-" + data.id + "\" href=\"#\" class=\"filtroEl\">" + data.catdescr +": <span>" + data.descr+"</span></a>");
		$("#flt-" + data.id).bind("click",rimuoviFiltro);
		$("#filtri-nofiltri-panel").hide();
		/*var frm = $("#ricForm");
		if (frm) {
			$("#old_sort").val("");
			frm.submit();
		}*/
		document.location="/" + section + "/" + cat + "/ricerca";
	}
}

function rimuoviFiltro() {
	$.getJSON('/action/rimFiltro', {"idFiltro": this.id }, rimossoFiltro);
}

function rimossoFiltro(data) {
	if (data.result) {
		$("#" + data.id).remove();
		if (data.size == 0) {
			$("#filtri-nofiltri-panel").show();
		}
		var frm = $("#ricForm");
		if (document.getElementById("ricForm")) {
			$("#old_sort").val("");
			frm.submit();
		} else {
			document.location="ricerca";
		}
	}
}

function azzeraFiltri() {
	if (! confirm("Azzerare tutti i filtri di ricerca?")) return;
	$.getJSON('/action/azzeraFiltri', null, azzeratiFiltri);
}

function azzeratiFiltri(data) {
	//alert("azzerati filtri!");
	$(".filtroEl").remove();
	$("#filtri-nofiltri-panel").show();
	var frm = $("#ricForm");
	if (frm) {
		$("#old_sort").val("");
		frm.submit();
	}
}

function mostraSchedaEmbedded(ev) {
	//alert("source:" + ev);
	//alert("sku:" +ev.getAttribute("sku"));
	var sku = ev.getAttribute("sku");
	$("#schedaProdotto").load("/itemDetail?sku="+sku, caricataScheda);
}

function caricataScheda() {
	//alert("scrollTop:" + $(window).scrollTop()+", window height:" + $(window).height());
	var sp = $("#schedaProdotto");
	//sp.offset({top: $(window).scrollTop()});
	//sp.show();
	sp.jqmShow();
	var wh = $(window).height();
	var h = sp.height() + 40;
	//alert("h:" + h);
	var oy = Math.max(20,(wh -h ) / 2);
	var t = $(window).scrollTop() + oy;
	
	sp.offset({"top": t});
	$('#currentProductImages').jcarousel({
        // Configuration goes here
    });
	$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
	
}

function selezionaColoreArticolo(src) {
	//alert("src:" + src.id);
	var cs = "" + src.id;
	cs = cs.substring(2);
	//alert("cs:" + cs);
	if (cs == colSel) return;
	var prevBC = $("#bc" + colSel);
	if (prevBC != null) {
		prevBC.removeClass("current");
		$("#photoDiv"+colSel).removeClass("frontElement");
	}
	$("#taglie-"+colSel).hide();
	$("#prz-"+colSel).hide();
	colSel = cs;
	$("#bc"+colSel).addClass("current");
	$("#photoDiv"+colSel).addClass("frontElement");
	$("#colScelto span").html($("#bc"+colSel).attr("title"));
	//$("#colScelto span").html($("#bc"+colSel).attr("id"));
	$("#taglie-"+colSel).show();
	$("#prz-"+colSel).show();
	if (tgSel != null) {
		$("#tg"+tgSel).removeClass("current");
		tgSel = null;
	}
}

function selezionaTagliaArticolo(src) {
	//alert("src:" + src.id);
	var ts = "" + src.id;
	ts = ts.substring(2);
	//alert("cs:" + cs);
	if (ts == tgSel) return;
	if (tgSel != null) {
		$("#tg"+tgSel).removeClass("current");
	}
	tgSel = ts;
	$("#tg"+tgSel).addClass("current");
	
}

function kpric(src) {
	var elId="";
	var elQt="";
	var errors = false;
	
	var txel = $(src);
	var q = txel.val().trim();
	if (q == "") return false;
	if (isNaN(q) || q<0)  {
		errors = true;
		txel.addClass("red");
	} else {
		txel.removeClass("red");
		txel.removeClass("yellow");
		elId ="" + txel.attr("id").substr(2);
		elQt ="" + q;
	}
	
	if (errors) {
		alert("La quantità specificata non è corretta.");
		return false;
	}
	$.ajax({
		  url: "/action/setCartItems",
		  data: {"itemsId": elId, "qta":elQt},
		  success: aggiunteTaglieCarrello,
		  error: erroreCarrello
		});
	return false;
}

function rimuoviArticoloCarrello(src) {
	var itemId = (""+src.id).substring(10);
	if (! confirm("Rimuovere tutte le taglie di questo articolo dal carrello?")) return;
	/*$.ajax({
		  url: "/action/removeItems",
		  data: {"itemId": itemId},
		  success: function(){window.location.replace("/" + section+"/"+cat+"/carrello");},
		  error: function() {alert("Impossibile eliminare l'articolo."); }
		});*/
	var txfields = $("#resdiv"+itemId+" input[type='text']");
	var elId="";
	var elQt="";
	var errors = false;
	txfields.each(function(){
		var txel = $(this);
		elId +=";" + txel.attr("id").substr(2);
		elQt +=";0";
	});
	$.ajax({
		  url: "/action/setCartItems",
		  data: {"itemsId": elId.substr(1), "qta":elQt.substr(1), "groupId":itemId},
		  success: function(){window.location.replace("/" + section+"/"+cat+"/carrello");},
		  error: function() {alert("Impossibile eliminare l'articolo."); }
		});
	return false;
}

function aggTgRic() {
	var iid = this.id.substr(3);
	var txfields = $("#resdiv"+iid+" input[type='text']");
	var elId="";
	var elQt="";
	var errors = false;
	txfields.each(function(){
		var txel = $(this);
		var q = txel.val();
		if (q == "") q = 0;
		if (isNaN(q) || q<0)  {
			errors = true;
			txel.addClass("red");
		} else {
			txel.removeClass("red");
			txel.removeClass("yellow");
			elId +=";" + txel.attr("id").substr(2);
			elQt +=";" + q;
		}
	});
	if (errors) {
		alert("La quantità specificata per alcuni articoli non è corretta.");
		return false;
	}
	$.ajax({
		  url: "/action/setCartItems",
		  data: {"itemsId": elId.substr(1), "qta":elQt.substr(1), "groupId":iid},
		  success: aggiunteTaglieCarrello,
		  error: erroreCarrello
		});
	return false;
}
function aggiunteTaglieCarrello(data, status, req) {
	//alert("aggiunto:" + data);
	if (data.error) {
		alert(data.error);
	} else {
		$("div.cart-box span.msg").html('Hai <span style="color:#ffcc00; font-weight:bold">' + data.numArticoli + '</span> articoli nel carrello<br/>Valore attuale: <span style="color:#ffcc00; font-weight:bold">'+ data.valore +'&euro;</span><span style="font-size: 0.8em"><br/>(iva e costi sped. esclusi)</span>');
		$("div.cart-box-leftbar span.msg").html('Hai <span style="color:#ffcc00; font-weight:bold">' + data.numArticoli + '</span> articoli nel carrello<br/>Valore attuale: <span style="color:#ffcc00; font-weight:bold">'+ data.valore +'&euro;</span><span style="font-size: 0.8em"><br/>(iva e costi sped. esclusi)</span>');
		
		var elIds = data.id.split(";");
		var elQt = data.qta.split(";");
		var elDispo = data.dispo.split(";");
		var errors = false;
		var qta = 0;
		for (var i=0; i< elIds.length; i++) {
			var q = parseInt(elQt[i],10);
			if (q > 0) {
				$("#qc"+elIds[i]).html("" + elQt[i]+" pezzi");
				$("#tq"+elIds[i]).addClass("green");
				qta += q;
			} else if (q == 0) {
				$("#qc"+elIds[i]).html("" + elQt[i]+" pezzi");
				$("#tq"+elIds[i]).val("");
			} else {
				$("#tq"+elIds[i]).addClass("red");
				errors = true;
			}
			$("#disp"+elIds[i]).html("" + elDispo[i]+" pezzi");
			//alert("disp " + elIds[i]+"=" + elDispo[i]);
		}
		cartCreationTime = data.cartCT;
		
		if (document.getElementById("numArtCarrello")) {
			var prz = parseFloat($("#prz"+data.groupId).html(),10);
			var tot = prz * qta;
			$("#subtot"+data.groupId).html(""+tot.toFixed(2));
			$("#numArtCarrello").html(""+data.numArticoli);
			$("#valoreCarrello").html(""+data.valore);
			if (parseInt(data.numArticoli,10) <=0) {
				$("#btProcediCarrello").fadeOut(0);
			} else {
				$("#btProcediCarrello").fadeIn(0);
			}
		}
				
		
		if (errors == true) {
			alert("Alcuni articoli non possono essere aggiornati perchè le quantità richieste non sono disponibili");
		} else {
			//alert("Carrello aggiornato correttamente");
			showNotify("Carrello aggiornato correttamente",1000);
		}
	}
}

function addTgToCart() {
	var iid = this.id.substr(2);
	var tq = $("#tq"+iid);
	var qta = tq.val();
	if (qta == "") qta = 0;
	if (isNaN(qta)) {
		alert("Qta specificata non corretta");
		return false;
	}
	$("#tq"+iid).removeClass("green");
	$("#tq"+iid).removeClass("yellow");
	$.ajax({
		  url: "/action/setCartItem",
		  data: {"itemId": iid, "qta":qta},
		  success: aggiuntaTagliaCarrello,
		  error: erroreCarrello
		});
	return false;
}

function aggiuntaTagliaCarrello(data, status, req) {
	//alert("aggiunto:" + data);
	if (data.error) {
		alert(data.error);
	} else {
		$("div.cart-box span").html('Hai <span style="color:#ffcc00; font-weight:bold">' + data.numArticoli + '</span> articoli nel carrello<br/>Valore attuale: <span style="color:#ffcc00; font-weight:bold">'+ data.valore +'&euro;</span><span style="font-size: 0.8em"><br/>(iva e costi sped. esclusi)</span>');
		$("#qc"+data.id).html("" + data.qta+"pz");
		if (data.qta > 0) {
			$("#tq"+data.id).addClass("green");
		} else {
			$("#tq"+data.id).val("");
		}
		alert("Carrello aggiornato correttamente");
		
	}
}

function addItemToCart() {
	if (colSel == null || colSel == 'null') {
		alert("selezionare il colore");
		return false;
	}
	if (tgSel == null) {
		alert("Selezionare la taglia");
		return false;
	}
	$.ajax({
		  url: "/action/addItemToCart",
		  data: {"itemId": tgSel},
		  success: aggiuntoItemCarrello,
		  error: erroreCarrello
		});
	return false;
}

function erroreCarrello(req, status, err) {
	aggiuntoItemCarrello({"error":"Impossibile completare l'operazione richiesta, errore di comunicazione con il server"},status,req);
}

function aggiuntoItemCarrello(data, status, req) {
	//alert("aggiunto:" + data);
	if (data.error) {
		alert(data.error);
	} else {
		$("#infoCarrello div.info").html("Articolo aggiunto correttamente<br/>Ora il tuo carrello contiene <strong>" + data.numArticoli + "</strong> articoli");
		$("div.cart-box span").html('Hai <span style="color:#ffcc00; font-weight:bold">' + data.numArticoli + '</span> articoli nel carrello<br/>Valore attuale: <span style="color:#ffcc00; font-weight:bold">'+ data.valore +'&euro;</span><span style="font-size: 0.8em"><br/>(iva e costi sped. esclusi)</span>');
		//$("#infoCarrello div.background").stop().show(0);
		//$("#infoCarrello div.background").fadeOut(1000);
		$("#infoCarrello").stop().hide(0);
		//$("#infoCarrello").fadeOut(200);
		$("#infoCarrello").css("backgroundColor","#FFEE99");
		$("#infoCarrello").fadeIn(500);
		//$("#infoCarrello").css("backgroundColor","#FFEE99");
	}
}

function modificaQtaCarrello(src) {
	var itemId = (""+src.id).substring(3);
	var t = $(src);
	if (t.val() == t.attr("qtaOrig")) return;
	$.ajax({
		  url: "/action/changeItemQty",
		  data: {"itemId": itemId, "qta": t.val()},
		  success: modificataQtaCarrello,
		  error: function() {alert("Impossibile modificare la quatità dell'articolo.\nErrore di comunicazione con il server"); t.val(t.attr("qtaOrig")); }
		});
}

function modificataQtaCarrello(data, status, req) {
	if (data.error) {
		alert(data.error);
	} else {
		window.location.replace("/" + section+"/"+cat+"/carrello");
	}
}



function showLoginFrame() {
	$("#loginFrame").fadeIn(500);
}

function doLogin() {
	var u = $("#username").val();
	var p = $("#password").val();
	if (u == null || u.length == 0 || p == null || p.length == 0) {
		alert("specificare username e passsword");
		return false;
	}
	$("#loginButton").hide(0);
	$("#loading").show(0);
	$.ajax({
	  url: "/action/doLogin",
	  data: {"u": u, "pw": hex_md5(p)},
	  success: loginDone,
	  error: function() {$("#loginFrame").hide(0); $("#loginButton").show(0); $("#loading").hide(0); alert("Impossibile effettuare il login.\nErrore di comunicazione con il server"); }
	});
	return false;
}

function loginDone(data, status, req) {
	if (data.error) {
		$("#loginButton").show(0);
		$("#loading").hide(0);
		alert(data.error);
	} else {
		window.location.replace("/");
	}
}

function vuotaCarrello() {
	if (! confirm("Sei sicuro di voler vuotare completamente il carrello?")) return false;
	$.ajax({
		  url: "/action/emptyCart",
		  success: function(){window.location.replace("/" + section+"/"+cat+"/carrello");},
		  error: function() {alert("Impossibile azzerare il carrello.\nErrore di comunicazione con il server"); }
		});
}

function checkTgRic() {
	var iid = this.id.substr(3);
	var txfields = $("#resdiv"+iid+" input[type='text']");
	var elId="";
	var elQt="";
	var errors = false;
	txfields.each(function(){
		verificaDispArticolo(this);
	});
	return false;
}

function verificaDispArticolo(src) {
	var iid = null;
	if (this.id) {
		iid =this.id.substr(2);
	} else {
		iid = src.id.substr(2);
	}
	var spAgg = $("#disp"+iid);
	spAgg.html("verifica..");
	$.ajax({
	  url: "/action/checkDispo",
	  data: {"itemId": iid},
	  success: aggiornaDispArticolo,
	  error: function() {spAgg.html("???");}
	});
}

function aggiornaDispArticolo(data, status, req) {
	if (data.error) {
		alert(data.error);
	} else {
		$("#disp"+data.idart).html(""+data.dispo+" pezzi").fadeOut(0).fadeIn(500);
	}
}

function showNotify(msg, delay) {
	$("#notify span").html(msg);
	$("#notify").fadeIn(500).delay(delay).fadeOut(500);
}

function checkCartTimeout() {
	//alert("cart creation time:" + cartCreationTime);
	if (cartCreationTime == 0) return;
	var d = new Date();
	var h = d.getHours();
	var m = d.getMinutes();
	var t = h*60+m;
	var dd = t-cartCreationTime;
	//alert("cart creation time:" + cartCreationTime+", now:" + t+", diff:" + dd);
	if (dd >= 120) {
		alert("Attenzione!\nNon hai ancora completato l'acquisto, il carrello sarà annullato perchè è stato superato il tempo massimo a tua disposizione");
		$.ajax({
			  url: "/action/emptyCart",
			  success: function(){window.location.replace("/" + section+"/"+cat+"/carrello");},
			  error: function() {alert("Impossibile azzerare il carrello.\nErrore di comunicazione con il server"); }
			});
	} else if (dd >=60 && ((dd % 15) == 0)) {
		alert("Attenzione!\nIl tempo a tua disposizione per completare l'acquisto sta scadendo. Ti preghiamo di completare l'ordine nel più breve tempo possibile");
	}
}
