var IE = document.all ? true : false;
var newWindow = null;

var domainusr = "ilmercatone.com";
//onerror = handleErr;

function handleErr(msg, url, l) {
	var txt = "Si è verificato un errore in questa pagina.\n\n";
	txt += "Errore: " + msg + "\n";
	txt += "URL: " + url + "\n";
	txt += "Linea: " + l + "\n\n";
	txt += "Clicca sul taso OK per continuare.\n\n";
	alert(txt);
	return true;
}

/******************************************************/

function ChkFormIscriz() {
	RemoveDefaultString($("FormIscriz"));
//	if (IsValidMail($("txtMail")) && IsValidMail($("txtConfMail")) && IsValidPassword($("txtPass"), 0) && IsValidPassword($("txtConfPass"), 1) && $("txtVerifica").value.length > 5) {
	if (IsValidMail($("txtMailReg")) && IsValidMail($("txtConfMailReg")) && $("txtVerifica").value.length > 5) {
		$("FormIscriz").submit();
		return true;
	} else {
		return false;
	}
}

function checkEntra() {
	if ($("ModLoginUtente")) {
		RemoveDefaultString($("ModLoginUtente"));
	}
	if (!IsValidMail($("txtMail"))) {
		alert("Digita un indirizzo mail corretto.");
		return false;
	}
/*
	if (strlen(trim($("passwd").value)) <= 4) {
		alert("Digita la password corretta.");
		return false;
	}
*/
}

function IsValidMail(mail) {
	if (mail.value!="") {
		var espressione = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;	
		if (!espressione.test(mail.value)) {
			alert("Controlla l'indirizzo di e-mail inserito");
			if ($(mail.id + "_img")!=null) {
				$(mail.id + "_img").style.display="none";
			}
			mail.focus();
			return false;
		} else {
			if ($(mail.id + "_img")!=null) {
				$(mail.id + "_img").style.display="inline";
			}
			return true;
		}
	} else {
		return false;
	}
}

function IsValidPassword(obj, ctest){
	var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}$/;
	if(!re.test(obj.value)) {
		alert("Passord inserita non conforme ai criteri di sicurezza!\n\n(La Passowrd deve contenere esclusivamente caratteri alfa-numerici (lettera maiuscola e minuscole) e deve essere di almeno sei caratteri");
		return false;
	}
	if (ctest==1) {
		if ($("txtPass").value!=$("txtConfPass").value) {
			alert("Le password digitate sono diverse.")
			return false;
		}
	}
	return true;
}


/******************************************************/

function $(id) {
	return document.getElementById(id);
}

function ConfermaForm() {
	//	Function Conferma la cancellazione
	return confirm("Elimina il record ?");
}

/******************************************************/

/*
function ltrim(parola) {
	var myString = new String(parola)
	for (ind = 0; ind <= (myString.length - 1); ind++){
		if (myString.substring(ind, ind + 1)!=" "){
			parola = myString.substring(ind, (myString.length));
			ind = myString.length - 1;
		}
	}
	return parola
}
*/

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function rtrim(stringToTrim) {
	return stringToTrim.replace(/^([\w\W]*)(\b\s*)$/,$1);
}

function ltrim(stringToTrim) {
	return stringToTrim.replace(/^(\s*)(\b[\w\W]*)$/, $2);
}

function strlen(parola) {
	var myString = new String(parola)
	return myString.length
}

function IsEmpty(aTextField) {
	if ((aTextField.value.length==0) || (aTextField.value==null) || trim(aTextField.value)=="") {
		return true;
	} else {
		return false;
	}
}

function isNum(fld) {
	var numericExpression = /^[0-9]+$/;
	if(fld.value.match(numericExpression)){
		return true;
	}else{
		return false;
	}
}

function isAlphabet(elem){
	var alphaExp = /^[a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		return false;
	}
}

function isAlphanumeric(elem){
	var alphaExp = /^[0-9a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		return false;
	}
}

function emailValidator(elem){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		return false;
	}
}

/*******************************************************/

function chk_cod_fisc(codfisc, ftype) {
	var re1 = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
	var re2 = /^\d{11}$/;
	Codice = trim(codfisc.value.toUpperCase());
	if (ftype="cf") {
		return (re1.test(Codice));
	} else if (ftype="pi") {
		return (re2.test(Codice));
	} else {
		return false;
	}
}

function randomPassword(lung) {
	var valori = new String("0123456789abcdefghjiklmnopqrstuvwxyzABCDEFGHJIKLMNOPQRSTUVWXYZ");
	var str = new String("");
	while (str.length < parseInt(lung)) {
		str += valori.substr((get_random(valori) % valori.length), 1);
	}
	return str;
}

function get_random(valori) {
    var ranNum= Math.round(Math.random()*valori.length);
    return ranNum;
}

function valida_data(input) {
	var regex = new RegExp("[\.\/\-]");
	var date = input.split(regex);
	var nbJours = new Array("", 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	if ( date["2"]%4 == 0 && date["2"]%100 > 0 || date["2"]%400 == 0 ) {
		nbJours["2"] = 29;
	}

	if(isNaN(date["2"])) {
		return false;
	}
	
	if ( isNaN(date["1"]) || date["1"] > 12 || date["1"] < 1 ) {
		return false;
	}

	if ( isNaN(date["0"]) || date["0"] > nbJours[Math.round(date["1"])] || date["0"] < 1 ) {
		return false;
	}

	return true;
}

/******************************************************/

function Open_PDF(IDDocu, dataDocu, tipo, D) {
	var nome_file = "";
	var filed1 = "";
	var filed2 = "";
	if (D==1) {
		myWidth = 100;
		myHeight = 100;
	} else {
		var ARicHW = RicavaHW();
		myHeight = ARicHW[0];
		myWidth  = ARicHW[1];
	}

	var r	= Math.random();
	if (tipo == 1) {
		nome_file = "preventivo_pdf.php";
		field1 = "idprev";
		field2 = "dataprev";
	} else if (tipo == 2) {
		nome_file = "ddt_pdf.php";
		field1 = "idddt";
		field2 = "dataddt";
	} else if (tipo == 3) {
		nome_file = "fattura_acc_pdf.php";
		field1 = "idfatt";
		field2 = "datafatt";
	} else if (tipo == 4) {
		nome_file = "fattura_diff_pdf.php";
		field1 = "idfatt";
		field2 = "datafatt";
	} else if (tipo == 5) {
		nome_file = "notacredito_pdf.php";
		field1 = "idfatt";
		field2 = "datafatt";
	} else if (tipo == 6) {
		nome_file = "fattura_ord_pdf.php";
		field1 = "idfatt";
		field2 = "datafatt";
	}

	var vleft = (screen.width - myWidth) / 2;
	var vtop  = (screen.height - myHeight) / 2;

//	alert("Risoluzione\n\tLarghezza: " + screen.width + "\n\tAltezza: " + screen.height + "\n\nPDF\n\tLarghezza: " + myWidth + "\n\tAltezza: " + myHeight + "\n\nCentramento\nTop: " + vtop + "\nLeft: " + vleft);

	var URL = "./moduli/" + nome_file + "?" + field1 + "=" + escape(IDDocu) + "&" + field2 + "=" + dataDocu + "&DowL="+ escape(D);
	newWindow = window.open(URL, "_new_win_fatt_pdf_", "top=" + vtop + ", left=" + vleft + ", width=" + myWidth + ", height=" + myHeight + ", scrollbars=no, resizable=no, status=no, toolbar=no, menubar=no, location=no, fullscreen=no");

	if (!newWindow.opener) {
		newWindow.opener = window;
	}

	if (newWindow.focus) {
		newWindow.focus();
	}
}

function OpenFotoAnn(IDANN, NFOTO){
    	if(newWindow && !newWindow.closed) {
		newWindow.close();
		newWindow = null;
	}

	var newWindow = window.open("/img_annunci/popup.view." + IDANN + ".pres." + NFOTO + ".html", "_new_foto_" + IDANN + "_", "scrollbars=yes, resizable=no, top=100, left=100, width=640, height=480, toolbar=no, status=no, location=no, directories=no, menubar=no");

	if (newWindow.focus) {
		newWindow.focus();
	}
}

function OpenFotoEve(IDEVE, NFOTO){
    	if(newWindow && !newWindow.closed) {
		newWindow.close();
		newWindow = null;
	}

	var newWindow = window.open("/img_eventi/popup.view." + IDEVE + ".pres." + NFOTO + ".html", "_new_foto_" + IDEVE + "_", "scrollbars=yes, resizable=no, top=100, left=100, width=640, height=480, toolbar=no, status=no, location=no, directories=no, menubar=no");

	if (newWindow.focus) {
		newWindow.focus();
	}
}

function showzoom(IDANN, NFOTO) {
//	var ImgPath = "http://foto." + domainusr + "/view." + IDANN + ".pres." + NFOTO + ".medium.jpg";
	var ImgPath = "/img_annunci/view." + IDANN + ".pres." + NFOTO + ".medium.jpg";
	if ($("PFoto").src != ImgPath) {
		if (!IE) {
			$("WPFImage").style.width = $("PFImage").style.width + "px";
			$("WPFImage").style.height = $("PFImage").style.height + "px";
		}
		$("WPFImage").style.display = "block";
		$("PFImage").style.display   = "none";

		$("PFoto").src = ImgPath;
		$("PFoto").onload = function(){
				$("aPFoto").onclick = function(){OpenFotoAnn(IDANN, NFOTO);}
				$("WPFImage").style.display = "none";
				$("PFImage").style.display = "block";
			};
	}
}

/****************************************************/

function RicavaHW () {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight)
	{
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else {
		// Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var myWidth, myHeight;
	if (self.innerHeight) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	// for small pages with total height less then height of the viewport
	if(yScroll < myHeight){
		pageHeight = myHeight;
	} else {
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < myWidth){
		pageWidth = myWidth;
	} else {
		pageWidth = xScroll;
	}
//	return new Array(myHeight, myWidth);
	return new Array(myHeight, myWidth, pageHeight, pageWidth);
}

/****************************************************/

function bookmarksite(title, url){
	if (window.sidebar) {
		// firefox
		window.sidebar.addPanel(title, url, "");
	} else if(document.all) {
		// ie
		window.external.AddFavorite(url, title);
	} else {
		alert("Siamo spiacenti il vostro browser non supporta questa funzione. Si consiglia di usare l'inserimento manuale nei preferiti premendo la combinazione dei tasti CTRL+D.");
	}
	
}

function invia_amico(lnk) {
	//alert(escape(lnk));
	var ARicHW = RicavaHW();
	var myHeight = 300;
	var myWidth  = 640;
	var vleft = (screen.width - myWidth) / 2;
	var vtop  = (screen.height - myHeight) / 2;
	// IF BROWSER IS IE 6 LOAD IE6 STYLE
/*
	if (IE){
		centerPopUp('invia_amico.php?lnk='+escape(lnk),'invia_amico',500,300,scrl);
	} else {
		centerPopUp('invia_amico.php?lnk='+escape(lnk),'invia_amico',500,300,scrl);
	}
*/
	var URL = "/invia.amico.php?lnk=" + escape(lnk);
	newWindow = window.open(URL, "_new_win_fatt_pdf_", "top=" + vtop + ", left=" + vleft + ", width=" + myWidth + ", height=" + myHeight + ", scrollbars=no, resizable=no, status=no, toolbar=no, menubar=no, location=no, fullscreen=no");
}

function centerPopUpIE6(URL, name, width, height, scrollbars ) { 
	if( scrollbars == null ) scrollbars = "0" 
	
	str = ""; 
	str += "resizable=0,";
	str += "status=0,";
	str += "scrollbars=" + scrollbars + ","; 
	str += "width=" + width + ","; 
	str += "height=" + height + ","; 
	
	if ( window.screen ) { 
	
		var ah = screen.availHeight - 30; 
		var aw = screen.availWidth - 10; 
		
		var xc = ( aw - width ) / 2; 
		var yc = ( ah - height ) / 2; 
		
		str += ",left=" + xc + ",screenX=" + xc; 
		str += ",top=" + yc + ",screenY=" + yc; 
		} 
	
	window.open( url, name, str );
	
} 

function importScript(url){
	var tag = document.createElement("script");
	tag.type = "text/javascript";
	tag.src = url;
	document.body.appendChild(tag);
}

function DefaultString() {
	var allInputs = document.getElementsByTagName("input")
	var oblur = function() {
		if (this.value == "") {
			this.style.color = "#aaaaaa";
			this.value = this.title;
		} else {
			this.style.color = "#000000";
		}
	};

	var ofocus = function() {
		if (this.value==this.title) {
			this.style.color = "#000000";
			this.value = "";
		}
	};

	for (var i = 0; i < allInputs.length; i++) {
		if (allInputs[i].type=="text" && allInputs[i].title!=null) {
			if (allInputs[i].value == "") {
				allInputs[i].style.color = "#aaaaaa";
				allInputs[i].value = allInputs[i].title;
			}

			allInputs[i].onfocus = ofocus;
			allInputs[i].onblur = oblur;
		}
	}
}

function RemoveDefaultString(objForm) {
	for (var i = 0; i < objForm.length; i++) {
		if (objForm[i].type=="text" && objForm[i].title==objForm[i].value) {
			objForm[i].value = "";
			objForm[i].style.color = "#000000";
		}
	}
}

function checkSendMailAnn(modform) {
	if(IsValidMail($("txtemail")) && $("txtVerificaSMA").value.length > 5 && confirm("Confermi l'invio di questo messaggio all'inserzionista?")) {
		modform.submit();
	}
}

function changeDivClass(obj) {
	if (obj.id=="acq") {
		obj.className = "";
		$("DivAcqPls").style.display = "block";
		$("DivModAnn").style.display = "none";
		$("DivCanAnn").style.display = "none";
		$("mod").className = "summary-tab-inactive";
		$("can").className = "summary-tab-inactive";
		$("prcAcqPls").focus();
		if ($("ODivForm")!=null && $("DivForm")==null) {
			$("ODivForm").id = "DivForm";
		}
	} else if (obj.id=="mod") {
		obj.className = "";
		if ($("DivAcqPls")){
			$("DivAcqPls").style.display = "none";
		}
		$("DivModAnn").style.display = "block";
		$("DivCanAnn").style.display = "none";
		if ($("acq")){
			$("acq").className = "summary-tab-inactive";
		}
		$("can").className = "summary-tab-inactive";
		if ($("pann_cat_select")) {
			$("pann_cat_select").focus();
		}
		if ($("ODivForm")==null && $("DivForm")!=null) {
			$("DivForm").id = "ODivForm";
		}
	} else if (obj.id=="can") {
		obj.className = "";
		if ($("DivAcqPls")){
			$("DivAcqPls").style.display = "none";
		}
		$("DivModAnn").style.display = "none";
		$("DivCanAnn").style.display = "block";
		$("mod").className = "summary-tab-inactive";
		if ($("acq")){
			$("acq").className = "summary-tab-inactive";
		}
		$("DivCanAnn").focus();
		if ($("ODivForm")==null && $("DivForm")!=null) {
			$("DivForm").id = "ODivForm";
		}
	}
}

function opacityBackGround() {
	var objBody = document.getElementsByTagName("body").item(0);
//	var objHead = document.getElementsByTagName("head").item(0);
	var mypagesize = RicavaHW();
	if ($("div_opacity") != null) {
		removeElement($("div_opacity"));
	}
	objOverlay = document.createElement("div");
	objOverlay.setAttribute("id", "div_opacity");
	objOverlay.style.position = "absolute";
	objOverlay.style.opacity = "0.50";
	objOverlay.style.filter= "alpha(opacity=50)";
	objOverlay.style.MozOpacity = "0.50";
	objOverlay.style.backgroundColor = "#fff";
	objOverlay.style.top = "0";
	objOverlay.style.left = "0";
	objOverlay.style.zIndex = "90";
	objOverlay.style.width = "100%";
	objOverlay.style.height = mypagesize[2] +"px";
	objBody.appendChild(objOverlay);

	$("div_opacity").style.display = "block";
}

function OmbraBackGround(NameDiv, lwidth, lheight, offleft, offtop) {
	if ($(NameDiv) != null) {
		removeElement($(NameDiv));
	}
	if (offtop==undefined) {
		offtop = 0;
	}
	if (offleft==undefined) {
		offleft = 0;
	}

	var mypagesize = RicavaHW();
	var mywidth = (document.all) ? mypagesize[1] : mypagesize[1] -16;
	oggettoDivB = document.createElement("div");
	oggettoDivB.setAttribute("id", NameDiv);
	oggettoDivB.style.border = "0px none";
	oggettoDivB.style.display = "none";
	oggettoDivB.style.position = "absolute";
	oggettoDivB.style.backgroundColor= "#000"; 
	oggettoDivB.style.opacity = "0.50";
	oggettoDivB.style.filter= "alpha(opacity=50)";
	oggettoDivB.style.MozOpacity = "0.50";
	oggettoDivB.style.width = lwidth + "px";
	oggettoDivB.style.height = lheight + "px";
	oggettoDivB.style.left = (((mywidth - lwidth) / 2) + (10 + offleft)) + "px";
	oggettoDivB.style.top  = (((mypagesize[0] - lheight) / 2) + (10 + offtop)) + "px";
	oggettoDivB.style.zIndex = "90";
	return oggettoDivB;
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != "function") {
		window.onload = func;
	} else {
		window.onload = function() {
			{
				oldonload();
			}
			func();
		}
	}
}

function close_layer(MyLayer) {
	if ($("myoverlayer")) {
		$("myoverlayer").style.display  = 'none';
	} else if ($(MyLayer)) {
		$(MyLayer).style.display  = 'none';
	}
	if ($("div_opacity")) {
		$("div_opacity").style.display  = 'none';
	}
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

function removeElement(divObj) {
	objBody = document.getElementsByTagName("body").item(0);
	objBody.removeChild(divObj);
}