﻿$(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 && $.browser.version < 7)) {
		$("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");
			}
		});
	}

	$("div[align]").each(function() {
		if ($(this).attr("align") != -1) {
			var attrValue = $(this).attr("align");
			if (attrValue.toLowerCase() == "center")
				$(this).css("text-align", "center");
		}
	});

	$("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");
	});

	$(".rollover").mouseover(function() {
		this.src = this.src.replace(".jpg", "-hover.jpg");
		this.src = this.src.replace(".gif", "-hover.gif");
		if (!($.browser.msie && $.browser.version < 7))
			this.src = this.src.replace(".png", "-hover.png");
	});
	$(".rollover").mouseout(function() {
		this.src = this.src.replace("-hover.jpg", ".jpg");
		this.src = this.src.replace("-hover.gif", ".gif");
		if (!($.browser.msie && $.browser.version < 7))
			this.src = this.src.replace("-hover.png", ".png");
	});
	/* --- rollover per elenco prodotti interno --- */
	$("div#pgElencoProdotti.colsx div.immagineElenco").mouseover(function() {
		if (!$(this).hasClass("sel")) {
			if (($.browser.msie && $.browser.version < 7))
				$(this).css("filter", "alpha(opacity=100)");
			else
				$(this).css("opacity", "1");
		}
	});
	$("div#pgElencoProdotti.colsx div.immagineElenco").mouseout(function() {
		if (!$(this).hasClass("sel")) {
			if (($.browser.msie && $.browser.version < 7))
				$(this).css("filter", "alpha(opacity=50)");
			else
				$(this).css("opacity", "0.5");
		}
	});

	/* --- ........................ --- */
	//if (!$.browser.msie || ($.browser.msie && $.browser.version > 7)) {
	//}

	/* funzione per il menu principale */
	$('div#header div.mainmenu ul li span a').FontEffect({
		outline: true,
		shadow: true,
		shadowOffsetTop: 1,
		shadowOffsetLeft: 2
	});
	$("div#header div.mainmenu ul li").mouseover(function() {
		if (!$(this).hasClass("noroll"))
			$(this).addClass("hover");
	});
	$("div#header div.mainmenu ul li").mouseout(function() {
		if (!$(this).hasClass("noroll"))
			$(this).removeClass("hover");
	});
	/* -------------------------------- */

	/* permette di utilizzare il tasto "invio" anche se il focus non è sul pulsante */
	$("input#textToSearch").keypress(function(event) {
		if (event.keyCode == 13) {
			$("a#btnAutoClickSrc").click();
			return false;
		}
	});
});

/* per fare il preload delle immagini passate */
var imgToCache = [];
function needPreloadImages() {
	if (arguments != null) {
		var args_len = arguments.length;
		for (var i = args_len; i--; ) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			imgToCache.push(cacheImage);
		}
	}
}

/* controllo validazione email */
function isEmail(string) {
	if (string == "")
		return false;
	return (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
};
/* rimozione tag html */
function removeHTMLTags(contentText) {
	var returnValue = contentText;
	/*  This line is optional, it replaces escaped brackets with real ones,  i.e. < is replaced with < and > is replaced with > */
	returnValue = returnValue.replace(/&(lt|gt);/g, function(strMatch, p1) {
		return (p1 == "lt") ? "<" : ">";
	});
	returnValue = returnValue.replace(/<\/?[^>]+(>|$)/g, "");
	// alert("Input code:\n" + contentText + "\n\nOutput text:\n" + returnValue);
	return returnValue;
};

/* funzione ricerca */
function siteSearch(section) {
	var userTxt = $.trim($("#textToSearch").val());
	var srcUrl = "/searchresults/" + escape(userTxt);

	alert("Funzione da implementare.");
	//window.location.href = srcUrl;
	return false;
};

/* funzioni di login e log out */
function submitLogIn(redirPG) {
	var sUsername = $.trim($("#Username").val());
	var sPassword = $.trim($("#Password").val());
	sPassword = sPassword.split(' ').join('');
	var loginErr = "";
	if (!isEmail(sUsername)) {
		loginErr += "- Inserire uno username valido;\n";
		$("#Username").addClass("inputError");
	} else {
		$("#Username").removeClass("inputError");
	}
	if (sPassword == "") {
		loginErr += "- Inserire una password;\n";
		$("#Password").addClass("inputError");
	} else {
		$("#Password").removeClass("inputError");
	}

	if (loginErr != "") {
		alert(loginErr);
	}
	else {
		var htmlOverlay = '<div id="popuplogin" class="loaderPopUpOverlay">' +
			'<br />Operzione in corso<br /><img src="/common/images/loader.gif" alt="operazione in corso" />' +
			'</div>';
		jOverlay(htmlOverlay, 250, 70, false);

		$.ajax({
			type: "POST",
			url: "/iscrizioniopt.ashx?type=login",
			dataType: "json",
			cache: false,
			data: ({
				lgUsr: sUsername,
				lgPsw: sPassword
			}),
			success: function(data) {
				var _error = data.error;
				var _success = data.success;

				if (_error != "") {
					$("#btn_close").click();
					switch (_error) {
						case "ERROR":
							htmlOverlay = 'Username e/o Password errati.';
							break;
						default:
							htmlOverlay = _error;
							break;
					}
					jOverlay('<div id="popupsoverlay" class="errorPopUpOverlay"><br />' + htmlOverlay + '<br /></div>',
						300,
						250,
						true);
				} else {
					if (_success == "OK") {
						window.location.href = redirPG;
					}
				}
			},
			error: function(XMLHttpRequestErr) {
				$("#btn_close").click();
				alert("Attenzione si sono verificati alcuni errori vi preghiamo di riprovare o di ricaricare la pagina!");
			}
		});
	}

	return false;
}
function confirmLogOut() {
	return confirm("Vuoi effettuare il logout?");
}
/* recupero Password */
function viewRecuperoPassword() {
	var htmlOverlay = '<div id="popupRecupero" class="pswRecFrmPopUpOverlay">' +
		'<br />Recupero Password<br /><br />' +
		'Inserisci il tuo indirizzo email e premi il tasto richiedi.<br /><br />' +
		'<input type="text" id="passwordRecovery" name="passwordRecovery" /><br />' +
		'<input type="button" id="recPsw" name="recPsw" value="richiedi" onclick="recuperoPassword();" />' +
		'</div>';
	jOverlay(htmlOverlay, 300, 300, true);
	return false;
}
function recuperoPassword() {
	var sUsername = $.trim($("#passwordRecovery").val());
	var recErr = "";
	if (!isEmail(sUsername)) {
		recErr += "- Inserire uno username valido;\n";
		$("#passwordRecovery").addClass("inputError");
	} else {
		$("#passwordRecovery").removeClass("inputError");
	}

	if (recErr != "") {
		alert(recErr);
	} else {
		var htmlOverlay = '<div id="popupRecupero" class="loaderPopUpOverlay">' +
			'<br />Operzione in corso<br /><img src="/common/images/loader.gif" alt="operazione in corso" />' +
			'</div>';
		jOverlay(htmlOverlay, 250, 70, false);

		$.ajax({
			type: "POST",
			url: "/iscrizioniopt.ashx?type=pswrec",
			dataType: "json",
			cache: false,
			data: ({
				pswUsr: sUsername
			}),
			success: function(data) {
				$("#btn_close").click();

				var _error = data.error;
				var _success = data.success;

				if (_error != "") {
					switch (_error) {
						case "ERROR":
							htmlOverlay = "Attenzione!! Impossibile completare l'operazione.";
							break;
						case "NOUSR":
							htmlOverlay = 'Attenzione!! Lo username inserito non è presente nel nostro database';
							break;
						default:
							htmlOverlay = _error;
							break;
					}
					jOverlay('<div id="popupRecupero" class="errorPopUpOverlay"><br />' + htmlOverlay + '<br /></div>',
						300,
						250,
						true);
				} else {
					switch (_success) {
						case "OK":
							htmlOverlay = "La password è stata inviata al tuo indirizzo e-mail.";
							break;
						default:
							htmlOverlay = _success;
							break;
					}
					jOverlay('<div id="popupRecupero" class="successMsgPopUpOverlay"><br />' + htmlOverlay + '<br /></div>',
						300,
						250,
						true);
				}
			},
			error: function(XMLHttpRequestErr) {
				$("#btn_close").click();
				alert("Attenzione si sono verificati alcuni errori vi preghiamo di riprovare o di ricaricare la pagina!");
			}
		});
	}

	return false;
}
/* Contatti */
function checkAndSendContact() {
	var msgError = "";
	var vfrmNome = $.trim($("input#frmNome").val());
	var vfrmCognome = $.trim($("input#frmCognome").val());
	var vfrmEmail = $.trim($("input#frmEmail").val());
	var vfrmTelefono = $.trim($("input#frmTelefono").val());
	var vfrmMessaggio = $.trim(removeHTMLTags($.trim($("textarea#frmMessaggio").val())));

	if (vfrmNome == "") {
		msgError += "-Inserire il nome;\n";
		$("input#frmNome").addClass("inputError");
	}
	else {
		$("input#frmNome").removeClass("inputError");
	}
	if (vfrmCognome == "") {
		msgError += "-Inserire il cognome;\n";
		$("input#frmCognome").addClass("inputError");
	}
	else {
		$("input#frmCognome").removeClass("inputError");
	}
	if (!isEmail(vfrmEmail)) {
		msgError += "-Inserire un indirizzo e-mail valido;\n";
		$("input#frmEmail").addClass("inputError");
	}
	else {
		$("input#frmEmail").removeClass("inputError");
	}
	if (vfrmTelefono == "") {
		msgError += "-Inserire il telefono;\n";
		$("input#frmTelefono").addClass("inputError");
	}
	else {
		$("input#frmTelefono").removeClass("inputError");
	}
	if (vfrmMessaggio == "") {
		msgError += "-Inserire il messaggio;\n";
		$("textarea#frmMessaggio").addClass("inputError");
	}
	else {
		$("textarea#frmMessaggio").removeClass("inputError");
		$("textarea#frmMessaggio").val(vfrmMessaggio);
	}

	if (msgError != "") {
		alert(msgError);
	} else {
		var msgConfermaInvio = confirm("Vuoi inviare il messaggio?");
		if (!msgConfermaInvio)
			return false;

		var htmlOverlay = '<div id="popupRecupero" class="loaderPopUpOverlay">' +
			'<br />Operzione in corso<br /><img src="/common/images/loader.gif" alt="operazione in corso" />' +
			'</div>';
		jOverlay(htmlOverlay, 250, 70, false);

		$.ajax({
			type: "POST",
			url: "/invioformcontatti.ashx",
			dataType: "json",
			cache: false,
			data: ({
				frmNome: vfrmNome,
				frmCognome: vfrmCognome,
				frmEmail: vfrmEmail,
				frmTelefono: vfrmTelefono,
				frmMessaggio: vfrmMessaggio
			}),
			success: function(data) {
				$("#btn_close").click();

				var _error = data.error;
				var _success = data.success;

				if (_error != "") {
					switch (_error) {
						case "ERROR":
							htmlOverlay = "Attenzione!! Impossibile completare l'operazione. Vi preghiamo di riprovare.";
							break;
						case "KOMSG":
							htmlOverlay = "Attenzione!! Si sono verificati alcuni problemi durante l'invio del messaggio. Vi preghiamo di riprovare più tardi.";
							break;
						default:
							htmlOverlay = _error;
							break;
					}
					jOverlay('<div id="popupFrmContact" class="errorPopUpOverlay"><br />' + htmlOverlay + '<br /></div>',
						300,
						250,
						true);
				} else {
					var viewButtonOverlay = true;
					switch (_success) {
						case "OK":
							htmlOverlay = 'Il tuo messaggio è stato correttamente inviato.<br /><br />' +
								'<a href="/contatti.html" style="color:#000;">chiudi</a>';
							viewButtonOverlay = false;
							break;
						default:
							htmlOverlay = _success;
							break;
					}
					jOverlay('<div id="popupFrmContact" class="successMsgPopUpOverlay"><br />' + htmlOverlay + '<br /></div>',
						300,
						250,
						viewButtonOverlay);
				}
			},
			error: function(XMLHttpRequestErr) {
				$("#btn_close").click();
				alert("Attenzione si sono verificati alcuni errori vi preghiamo di riprovare o di ricaricare la pagina!");
			}
		});
	}
	return false;
}

/* funzioni per il carrello */
/* ##Aggiunta di una promozione al carrello## */
function addThisPromoToCart(_idPromo) {
	if (_idPromo == null || _idPromo == "") {
		alert("Promozione NON disponibile");
	} else {
		var confMessage = confirm("Vuoi aggiungere la promozione al carrello?");
		if (confMessage) {
			var htmlOverlay = '<div id="popupPromoAdd" class="loaderPopUpOverlay">' +
				'<br />Operzione in corso<br /><img src="/common/images/loader.gif" alt="operazione in corso" />' +
				'</div>';
			jOverlay(htmlOverlay, 250, 70, false);
			$.ajax({
				type: "POST",
				url: "/carrelloaddpromo.ashx",
				dataType: "json",
				cache: false,
				data: ({
					idPromo: _idPromo
				}),
				success: function(data) {
					var error = data.error;
					var _okmessage = data.okmessage;
					var _redirCarrello = data.redirCarrello;

					if (error != "") {
						alert(error);
					} else {
						if (_redirCarrello == "true")
							window.location.href = "/carrello/";
					}
					$("#btn_close").click();
				},
				error: function(XMLHttpRequestErr) {
					$("#btn_close").click();
					alert("Attenzione si sono verificati alcuni errori vi preghiamo di riprovare o di ricaricare la pagina!");
				}
			});
		}
	}
	return false;
}
/* ##Visualizza/Nascondi Descrizione prodotto Riga## */
function hideShowCartDesc(idOption) {
	var riga = $("div#riga" + idOption);
	if ($("span#sp" + idOption + " a").html() == "+") {
		riga.css("height", "100%");
		$("span#sp" + idOption + " a").html("-");
	} else {
		riga.css("height", "13px");
		$("span#sp" + idOption + " a").html("+");
	}
	return false;
}
/* ##Cancellazione Riga## */
function deleteToCart(idRiga) {
	var confMessage = confirm("Vuoi togliere questo prodotto dal tuo carrello?");
	if (confMessage) {
		$.ajax({
			type: "POST",
			url: "/carrellodeleterow.ashx",
			dataType: "json",
			cache: false,
			data: ({
				idOrdineRiga: idRiga
			}),
			success: function(data) {
				var error = data.error;
				var _redirCarrello = data.redirCarrello;

				if (error != "") {
					alert(error);
				} else {
					if (_redirCarrello == "true")
						window.location.href = "/carrello/";
				}
			}
		});
	}
	return false;
}


