﻿$(document).ready(function() {
	$("a").each(function() {
		if (this.href.indexOf(".pdf") > -1)
			$(this).attr("rel", "popup");
	});

	$("a[rel=popup]").click(function() {
		var sUrl = this.href;

		if (sUrl.indexOf("javascript") < 0)
			window.open(sUrl);
		else {
			setTimeout(sUrl.replace("javascript:", ""), 0);
		}

		return false;
	});

	$("a[rel=popup]").bind("onkeydown", function() {
		if (sUrl.indexOf("javascript") < 0)
			window.open(sUrl);
		else
			setTimeout(sUrl, 0);

		return false;
	});

	if ($.browser.msie != true) {
		$("img[hspace]").each(function() {
			if ($(this).attr("hspace") != -1) {
				$(this).css("margin-left", $(this).attr("hspace") + "px");
				$(this).css("margin-right", $(this).attr("hspace") + "px");
			}

			if ($(this).attr("vspace") != -1) {
				$(this).css("margin-top", $(this).attr("vspace") + "px");
				$(this).css("margin-bottom", $(this).attr("vspace") + "px");
			}
		});
	}

	$("ul.listaprodotti").supersubs({
		minWidth: 10,   // minimum width of sub-menus in em units 
		maxWidth: 27,   // maximum width of sub-menus in em units 
		extraWidth: 1     // extra width can ensure lines don't sometimes turn over 
		// due to slight rounding differences and font-family
	}).superfish({
		//animation: { height: 'show' },
		speed: 'fast',
		delay: 1200
	});

	$("img").each(function() {
		if ($(this).attr("alt") == " ") $(this).attr("alt", "");
		if ($(this).attr("align").toLowerCase() == "left") $(this).css("float", "left");
		if ($(this).attr("align").toLowerCase() == "right") $(this).css("float", "right");
	});

	/* reindirizzamento alla pagina di ricerca libera prodotti */
	$("input#ricercadiretta").click(function() {
		var srcParam = $.trim($("input#testoricerca").val());
		srcParam = srcParam.replace(/&/g, "e");

		if (srcParam != "" && srcParam.length > 2) {
			var catSubcat = $("select#categoria").val();
			var siteSection = catSubcat.substr((catSubcat.length - 1), 1);

			var sNavigateUrl = "";
			switch (siteSection) {
				case "v":
					sNavigateUrl = "/ricerca-libera/occasioni/";
					break;
				case "a":
					sNavigateUrl = "/ricerca-libera/arredo/";
					break;
				default:
					sNavigateUrl = "/ricerca-libera/elettronica/";
					break;
			}
			window.location.href = sNavigateUrl + encodeURIComponent(srcParam);
		}
		else {
			alert("Inserire un criterio di ricerca valido.\r\nMinimo 3 caratteri.");
		}

		return false;
	});

	/* caricamento delle Marche nella tendina di ricerca */
	loadDdlMarche();
	/* caricamento delle Marche nella tendina di ricerca */
	$("select#categoria").change(function() {
		loadDdlMarche();
		return false;
	});
	/* reindirizzamento alla pagina di ricerca prodotti */
	$("input#ricercamarca").click(function() {
		var urlParam = "";
		var catSubcat = $("select#categoria").val();
		var selBrand = $("select#marca").val();

		if ((catSubcat.length == 1) && (selBrand == "")) {
			alert("Sezionare la tipologia o la marca del prodotto che si desidera ricercare.");
			return false;
		}

		if (selBrand != "") {
			urlParam += "/br/" + encodeURIComponent(selBrand);
		}
		if (catSubcat.length > 1) {
			urlParam += "/ct/" + encodeURIComponent(catSubcat);
		}

		var catSubcatSubstr = catSubcat.substr((catSubcat.length - 1), 1);
		var sNavigateUrl = "";
		switch (catSubcatSubstr) {
			case "v":
				sNavigateUrl = "/ricerca-avanzata/occasioni";
				break;
			case "a":
				sNavigateUrl = "/ricerca-avanzata/arredo";
				break;
			default:
				sNavigateUrl = "/ricerca-avanzata/elettronica";
				break;
		}

		//alert(sNavigateUrl + urlParam);
		window.location.href = sNavigateUrl + urlParam;

		return false;
	});

	/* automatismo del rollover sulle immagini */
	if (!($.browser.msie && (Math.floor($.browser.version) < 7))) {
		$(".rollover").mouseover(function() {
			this.src = this.src.replace(".jpg", "-hover.jpg");
			this.src = this.src.replace(".png", "-hover.png");
			this.src = this.src.replace(".gif", "-hover.gif");
		});

		$(".rollover").mouseout(function() {
			this.src = this.src.replace("-hover.jpg", ".jpg");
			this.src = this.src.replace("-hover.png", ".png");
			this.src = this.src.replace("-hover.gif", ".gif");
		});
	}

	$("input.cssRelLogin").keypress(function(event) {
		if (event.keyCode == 13) {
			$("input.cssClickLogin").click();
			return false;
		}
	});
	$("input#testoricerca").keypress(function(event) {
		if (event.keyCode == 13) {
			$("input#ricercadiretta").click();
			return false;
		}
	});

	/* imposto il div per il confronto prodotti */
	$("div#dialogBoxCompare").dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		title: "Comparazione prodotti",
		width: 1003
	});

	$("div#friendReport").dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		width: 600
	});

});
/* caricamento delle voci nella tendina delle marche per la ricerca */
function loadDdlMarche() {
	var catSubcat = $("select#categoria").val();
//	if (catSubcat.length == 1) {
//		catSubcat = "";
//	}
	$("img#loadProdBrands")
		.ajaxStop(function() {
			$(this).hide();
			$("select#marca").show();
	});
	$.ajax({
		type: "GET",
		url: "/getProductsBrand.ashx",
		data: "cat-subcat=" + catSubcat,
		dataType: "html",
		cache: false,
		beforeSend: function() {
			$("img#loadProdBrands").show();
			$("select#marca").hide();
		},
		success: function(html) {
			$("select#marca").html(html);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Attenzione si sono verificati alcuni problemi.");
		}
	});
	return false;
}
/* salvataggio del prodotto selezionato nella lista dei desideri */
function saveWishList(PrdCode) {
	$.ajax({
		type: "GET",
		url: "/wishList.ashx",
		data: "PrdCode=" + PrdCode,
		dataType: "json",
		cache: false,
		success: function(data) {
			alert(data.msg);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			//alert(textStatus);
			alert("Attenzione si sono verificati alcuni errori durante l'inserimento.");
		}
	});
}
/* Recupero l'html della "pagina" di confronto prodotti */
function loadProductsCompareOLD() {
	var sListaProdottiId = "";
	var iCountCompare = 0;
	$("input[type=checkbox]").each(function() {
		if (this.id.indexOf("confronta-") >= 0) {
			if (this.checked) {
				if (iCountCompare > 0)
					sListaProdottiId += this.id.replace("confronta-", ",");
				else
					sListaProdottiId += this.id.replace("confronta-", "");
				iCountCompare += 1;
			}
		}
	});
	if (iCountCompare < 2) {
		alert("Selezionare almeno 2 prodotti per eseguire il confronto.");
		return;
	}
	$.ajax({
		type: "GET",
		url: "/productsCompare.ashx",
		data: "prdId=" + sListaProdottiId,
		dataType: "html",
		cache: false,
		beforeSend: function() {
			$("div#dialogBoxCompare").html('<div class="divImageLoading"><img src="/common/images/loadingAnimation.gif" alt="loading" /></div>');
			$("div#dialogBoxCompare").dialog('open');
		},
		success: function(html) {
			$("div#dialogBoxCompare").dialog('close');
			$("div#dialogBoxCompare").html(html);
			$("div#dialogBoxCompare").dialog('open');
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Attenzione si sono verificati alcuni problemi.");
		}
	});
}
function loadProductsCompare(referrerPage) {
	$.ajax({
		type: "GET",
		url: "/productsCompareSession.ashx",
		data: "rpg=" + encodeURIComponent(referrerPage) + "&id=0&op=get",
		dataType: "html",
		cache: false,
		beforeSend: function() {
		},
		success: function(html) {
			arrProducts = html.split("-");
			if (arrProducts.length < 4) {
				alert("Selezionare almeno 2 prodotti per eseguire il confronto.");
				return;
			}
			else {
				var sListaProdottiId = "";
				for (i = 1; i < (arrProducts.length - 1); i++) {
					if (i == 1)
						sListaProdottiId += arrProducts[i];
					else
						sListaProdottiId += "," + arrProducts[i];
				}
				//alert(sListaProdottiId);
				showCompareProducts(sListaProdottiId)
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Attenzione si sono verificati alcuni problemi.");
		}
	});
}
function showCompareProducts(sListaProdottiId) {
	$.ajax({
		type: "GET",
		url: "/productsCompare.ashx",
		data: "prdId=" + sListaProdottiId,
		dataType: "html",
		cache: false,
		beforeSend: function() {
			$("div#dialogBoxCompare").html('<div class="divImageLoading"><img src="/common/images/loadingAnimation.gif" alt="loading" /></div>');
			$("div#dialogBoxCompare").dialog('open');
		},
		success: function(html) {
			$("div#dialogBoxCompare").dialog('close');
			$("div#dialogBoxCompare").html(html);
			$("div#dialogBoxCompare").dialog('open');
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Attenzione si sono verificati alcuni problemi.");
		}
	});
}
/* chiamata automatica della "pagina" di confronto prodotti */
function autoStartCompare(checkElement, referrerPage) {
	var arrProducts = "";
	var productId = "-" + checkElement.value + "-";
	var operation = "del";
	if (checkElement.checked)
		operation = "add";

	$.ajax({
		type: "GET",
		url: "/productsCompareSession.ashx",
		data: "rpg=" + encodeURIComponent(referrerPage) + "&id=" + encodeURIComponent(productId) + "&op=" + encodeURIComponent(operation),
		dataType: "html",
		cache: false,
		beforeSend: function() {
		},
		success: function(html) {
			arrProducts = html.split("-");
			//alert(arrProducts);
			if (arrProducts.length > 6) {
				alert("Attezione il confronto può essere effettuato al massimo con 4 prodotti.\r\n" +
					"Potete ripartire con una nuova ricerca cliccando il pulsante Elimina a fondo pagina.");
				checkElement.checked = false;
				autoStartCompare(checkElement, referrerPage);
			}
			if (arrProducts.length == 6)
				loadProductsCompare(referrerPage);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Attenzione si sono verificati alcuni problemi.");
		}
	});

/* ### Old ###
	var iCountAutostartCompare = 0;
	$("input[type=checkbox]").each(function() {
		if (this.id.indexOf("confronta-") >= 0) {
			if (this.checked) {
				iCountAutostartCompare += 1;
			}
		}
	});
	if (iCountAutostartCompare > 4)
		checkElement.checked = false;

	if (iCountAutostartCompare == 4)
		loadProductsCompare();
*/

}
/* spegimento delle checkbox selezionate per il confronto prodotti */
function clearProductsCompare() {
	$("input[type=checkbox]").each(function() {
		if (this.id.indexOf("confronta-") >= 0) {
			if (this.checked) {
				this.checked = false;
			}
		}
	});
	$.ajax({
		type: "GET",
		url: "/productsCompareSession.ashx",
		data: "rpg=&id=0&op=remove",
		dataType: "html",
		cache: false,
		beforeSend: function() {
		},
		success: function(html) {
			arrProducts = html.split("-");
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Attenzione si sono verificati alcuni problemi.");
		}
	});
}
function openDialogFriend() {
	$("div#friendReport").dialog('open');
	$("div#tblSendMessages").show();
	return false;
}
function sendProductToFriend(httpProdUrl) {
	var sTofrMyName = $.trim($("input#tofrMyName").val());
	var sTofrMyEmail = $.trim($("input#tofrMyEmail").val());
	var sTofrFriendEmail = $.trim($("input#tofrFriendEmail").val());
	var sTofrMyMessage = $.trim($("textarea#tofrMyMessage").val());

	if (sTofrMyName == "") {
		alert("inserire il nome e il cognome.");
		return false;
	}
	if (sTofrMyEmail=="" || !isEmail(sTofrMyEmail)) {
		alert("il campo 'La Tua E-Mail' non è correttamente compilato.");
		return false;
	}
	if (sTofrFriendEmail == "" || !isEmail(sTofrFriendEmail)) {
		alert("il campo 'E-Mail Destinatario' non è correttamente compilato.");
		return false;
	}

	$.ajax({
		type: "GET",
		url: "/sendEmailProductFriend.ashx",
		data: "par1=" + encodeURIComponent(sTofrMyName) + "&par2=" + encodeURIComponent(sTofrMyEmail) +
			"&par3=" + encodeURIComponent(sTofrFriendEmail) + "&par4=" + encodeURIComponent(sTofrMyMessage) + "&par5=" + encodeURIComponent(httpProdUrl),
		dataType: "html",
		cache: false,
		beforeSend: function() {
			$("div#loadSendFrindEmail").html('<br /><br /><img src="/common/images/loadingAnimation.gif" alt="loading" /><br /><br />');
			$("div#tblSendMessages").hide();
		},
		success: function(html) {
			$("div#loadSendFrindEmail").html('<br /><br />La tua email è stata correttamente inviata.<br /><br />');
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$("div#loadSendFrindEmail").html('');
			alert("Attenzione si sono verificati alcuni problemi.");
			$("div#tblSendMessages").show();
		}
	});

	return false;
}
/* controllo validazione email */
function isEmail(string) {
	return (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}
/* controllo della correttezza del codice fiscale */
function codiceFISCALE(cfins) {
	var cf = cfins.toUpperCase();
	var cfReg = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
	if (!cfReg.test(cf))
		return false;
	var set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	var s = 0;
	for (i = 1; i <= 13; i += 2)
		s += setpari.indexOf(set2.charAt(set1.indexOf(cf.charAt(i))));
	for (i = 0; i <= 14; i += 2)
		s += setdisp.indexOf(set2.charAt(set1.indexOf(cf.charAt(i))));
	if (s % 26 != cf.charCodeAt(15) - 'A'.charCodeAt(0))
		return false;
	return true;
}
function changeFotoScheda(objImg, photoShedaId) {
	var options = {};
	$("img#" + photoShedaId).effect("slide", options, 500);
	$("img#" + photoShedaId).attr("src", objImg.src);
	return false;
}
function replaceContent(objSearch, sFind, sReplace) {
	$(objSearch).each(function() {
		var thisItem = $(this);
		var thisHtml = thisItem.html();
		var newHtml = thisHtml.replace(sFind, sReplace);
		thisItem.html(newHtml);
	});
}
