﻿/* _____________________________ ON ERROR ____________________________________________ */
function silenzia()  {return true}
window.onerror=silenzia;
/* ___________________________________________________________________________________ */

var spazioVert=0;
var docHeight=0;
var selezioneTxtPre="";

function serialize( mixed_value ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}

function unserialize(data){
    // http://kevin.vanzonneveld.net
    // +     original by: Arpad Ray (mailto:arpad@php.net)
    // +     improved by: Pedro Tainha (http://www.pedrotainha.com)
    // +     bugfixed by: dptr1988
    // +      revised by: d3x
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +        input by: Brett Zamir (http://brett-zamir.me)
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: Chris
    // +     improved by: James
    // %            note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %            note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
    // *       returns 1: ['Kevin', 'van', 'Zonneveld']
    // *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
    // *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}
 
    var error = function (type, msg, filename, line){throw new this.window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while (chr != stopchr) {
            if ((i+offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        var buf;
 
        buf = [];
        for(var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        var readdata;
        var readData;
        var chrs = 0;
        var ccount;
        var stringlength;
        var keyandchrs;
        var keys;
 
        if(!offset) {offset = 0;}
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();
 
        var dataoffset = offset + 2;
        var typeconvert = new Function('x', 'return x');
 
        switch(dtype){
            case 'i':
                typeconvert = function (x) {return parseInt(x, 10);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'b':
                typeconvert = function (x) {return parseInt(x, 10) !== 0;};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'd':
                typeconvert = function (x) {return parseFloat(x);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'n':
                readdata = null;
            break;
            case 's':
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;
 
                readData = read_chrs(data, dataoffset+1, parseInt(stringlength, 10));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if(chrs != parseInt(stringlength, 10) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }
            break;
            case 'a':
                readdata = {};
 
                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;
 
                for(var i = 0;i < parseInt(keys, 10);i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;
 
                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;
 
                    readdata[key] = value;
                }
 
                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    
    return _unserialize((data+''), 0)[2];
}

function prendiElementoDaId(id_elemento) {
	var elemento;
	if(document.getElementById)
		elemento = document.getElementById(id_elemento);
	if(parent.document.getElementById)
		elemento = parent.document.getElementById(id_elemento);
	if(top.document.getElementById)
		elemento = top.document.getElementById(id_elemento);
	else
		elemento = document.all[id_elemento];
	return elemento;
}

function debJsObj(oggetto, testoDeb, livelloObj){
	if(oggetto.length>0){
		for(var prop in oggetto){
			if(oggetto[prop] && (oggetto[prop].toString()=="[object]" || oggetto[prop].toString()=="[object Text]")){
				testoDeb+="["+prop+"] Object:<br />";
				testoDeb+=debJsObj(oggetto[prop], testoDeb, (livelloObj+1));
			} else {
				for(i=0;i<livelloObj;i++){
					testoDeb+="> ";
				}
				testoDeb+="["+prop+"]="+ oggetto[prop]+"<br />";
			}
		}
	}
	return(testoDeb);
}

function insHTML(idDiv, htmlTxt){
	// alert(htmlTxt);
	oggetto=prendiElementoDaId(idDiv);
	if(oggetto){
		try{
			oggetto.innerHTML=htmlTxt;
		}catch(err){
			alert("Err:"+err);
		}
		return(true);
	} else {
		alert("non trovato:"+idDiv);
		return(false);
	}
}

function insAjaxHTML(idDiv, url){
	$.get(url, function(data){
		insHTML(idDiv, data);
	});
}

function ritorna(valore){
	return(valore);
}

function ajaxGet(url){
	$.get(url, function(data){
		alert(data);
		// alert($(this));
		// var html=ritorna(data);
		// alert(html);
		// $(this)=html;
		// return(html);
	});
}

function insAjaxGet(){
	
	$.get(url, function(data){
		alert(data);
		return(data);
	});


	
}

////////////////////////////////////////////// INIZIO RICAVA COORDINATE DEL MOUSE
var IE = document.all?true:false;
// if (!IE) document.captureEvents(Event.MOUSEMOVE)
if (!IE) document.addEventListener('mousemove', getMouseXY, true);
document.onmousemove = getMouseXY;
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	}
	else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}  
	if (tempX < 0){tempX = 0;}
	if (tempY < 0){tempY = 0;}  
	// document.Show.MouseX.value = tempX;
	// document.Show.MouseY.value = tempY;
	return true;
}
////////////////////////////////////////////// FINE RICAVA COORDINATE DEL MOUSE

/////////////// FUNZIONE PER RIMUOVERE ELEMENTI DA UN ARRAY
Array.remove = function(array, from, to) {
  var rest = array.slice((to || from) + 1 || array.length);
  array.length = from < 0 ? array.length + from : from;
  return array.push.apply(array, rest);
};

/////////////// FUNZIONE PER CAPITALIZE
String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

//////////////////////////////// STAMPA DI UN BLOCCO DI UNA PAGINA
function stampa(idBlock) {
	var testo = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />";
	testo += "<link href=\"css/stili.css\" rel=\"stylesheet\" type=\"text/css\" />"; 
	testo += "</head><body><div style=\"height:10px;\"></div><div id=\"coldx\" class=\"floatLeft\" style=\"width:745px;\">";
	testo += document.getElementById(idBlock).innerHTML;
	testo += "</div></body></html>";
	var ident_finestra = window.open("","finestra_stampa","height=700,width=800,top=5,left=5,scrollbars=yes");
	ident_finestra.document.open();
	ident_finestra.document.write(testo);
	ident_finestra.print();
	ident_finestra.document.close();
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function linkblank(src){
	MM_openBrWindow(src,'','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function getquerystring(idFormPost) {
	var qstr = "";
	var form = prendiElementoDaId(idFormPost);
	for (keyVar in form) {
		if(form[keyVar] && form[keyVar].value!=undefined){
			qstr = qstr + keyVar + '=' + escape(form[keyVar].value) + "&";  // NOTE: no '?' before querystring
		}
	}
    return qstr;
}

var chiudiMS;
var chiudiMSArr=new Array();

function setOpacity(idDiv,value){
	if(prendiElementoDaId(idDiv)){
		oggetto=prendiElementoDaId(idDiv);
		oggetto.style.opacity = value/10;
		oggetto.style.filter = 'alpha(opacity=' + value*10 + ')';
	}
}

function setlivelli(nomediv,stato){
	if(prendiElementoDaId(nomediv)){
		oggetto=prendiElementoDaId(nomediv);
		var statoOra = 0;
		if(oggetto.style.display=='block'){
			statoOra = 1;
		}
		if(stato==1){ // && statoOra==0
			oggetto.style.display='block';
			oggetto.style.visibility='visible';
		}
		if(stato==0){ // && statoOra==1
			oggetto.style.display='none';
			oggetto.style.visibility='hidden';
		}
	}
	return(false);
}

function valId(id){
	if(prendiElementoDaId(id)){
		oggetto=prendiElementoDaId(id);
		return oggetto.value;
	} else {
		return ("err");	
	}
}


function strpos(haystack, needle, offset){
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}

function strpos_old(haystack, needle, offset){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
	if(!offset){
		offset=0;
	}
    var i = haystack.indexOf(needle, offset); // returns -1
    return i >= 0 ? i : false;
}

/* ---------------------------------------------------------------------------- */
/* ---------------- INIZIO SCRIPT PER IL SITO --------------------------------- */
/* ---------------------------------------------------------------------------- */

function loading_OLD(act, idBlock){
	if(act && act==1){
		if(idBlock && idBlock!=""){
			oggetto=prendiElementoDaId(idBlock);
			if(oggetto){
				oggetto.innerHTML = '<table border="0" height="100%" cellspacing="0" cellpadding="0" style="width:100%; height:100%;"><tr><td valign="middle"><div class="alignCenter centrato"><img src="img/loading.gif" alt="LOADING" width="47" height="50" /></div></td></tr></table>';
			}
		} else {
			setlivelli("loading",1);
		}
	} else {
		setlivelli("loading",0);
	}
}

function loading(stato){
	setlivelli("loading",((stato==1)?1:0));
}

function inviaForm(idForm,url,idDest){
	oggetto=prendiElementoDaId(idDest);
	if(oggetto){
		oggetto.innerHTML=xmlhttpPost(url, '', idForm, 0);
	}
}

function posizionaDiv(idDiv,cooX,cooY){
	oggetto=prendiElementoDaId(idDiv);
	if(cooX!=""){
		oggetto.style.marginLeft=cooX+"px";
	}
	if(cooY!=""){
		oggetto.style.marginTop=cooY+"px";
	}
}


function closeTxtPop(idDiv,closeTimeOut){
	if(!(undefined===window.chiudiMS)){
		clearTimeout(chiudiMS);
	}
	chiudiMS = setTimeout("setlivelli('"+idDiv+"',0)",closeTimeOut);
	return(false);
}

var arrMenus=new Array();

function vai(url){
	location.href=url;
}

function getElementsByClassName(classname) {
    var rl = new Array();
    var re = new RegExp('(^| )'+classname+'( |$)');
    var ael = document.getElementsByTagName('*');
    var op = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
    if (document.all && !op) ael = document.all;
    for(i=0, j=0 ; i<ael.length ; i++) {
        if(re.test(ael[i].className)) {
        	rl[j]=ael[i];
            j++;
        }
    }
    return rl;
}

function swappaVis(idBlock, classOn, classOff){
	oggetto=prendiElementoDaId(idBlock);
	if(oggetto){
		if(oggetto.style.height=="0px"){
			oggetto.style.height="auto";
			oggetto.style.overflow="visible";
			oggetto=prendiElementoDaId('tit_'+idBlock);
			oggetto.className = 'blocco categ';
		} else {
			oggetto.style.height="0px";
			oggetto.style.overflow="hidden";
			oggetto=prendiElementoDaId('tit_'+idBlock);
			oggetto.className = 'blocco categ_off';
		}
	}
}

function swappaClass(idBlock, classOn, classOff){
	oggetto=prendiElementoDaId(idBlock);
	if(oggetto){
		if(oggetto.className==classOn){
			oggetto.className = classOff;
		} else if(oggetto.className==classOff){
			oggetto.className = classOn;
		}
	}
	window.focus();
	return(false);
}

function swappaClassAll(classOld, classNew) {
	items = getElementsByClassName(classOld);

	for(var i=0; i<items.length; i++) {
		items[i].className=classNew;
	}

}

function modClassAll(idElem,classNew,classOld){
	 swappaClassAll(classNew, classOld);
	 modClass(idElem,'attiva');
}

function swappaDiv(livOn,livOff){
	setlivelli(livOn,1);
	setlivelli(livOff,0);
	if(livOff.substring(5,8)=="Off"){
		arrMenus[livOn]=setTimeout("swappaDiv('"+livOff+"','"+livOn+"');",5000);
	}
}

function modClass(nomediv,nomeclass){
	oggetto=prendiElementoDaId(nomediv);
	if(oggetto){
		oggetto.className = nomeclass;
	}
}

function modform(idCampo,valore){
	oggetto=prendiElementoDaId(idCampo);
	oggetto.value=valore;
}

function is_email(valore){
	indirizzo = valore;
	if (window.RegExp) {
		var nonvalido = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
		var valido = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		var regnv = new RegExp(nonvalido);
		var regv = new RegExp(valido);
		if (!regnv.test(indirizzo) && regv.test(indirizzo)){
			return true;
		}
		return false;
	} else {
		if(indirizzo.indexOf("@") >= 0){
			return true;
		}
		return false;
	}
}

function rand(min, max) {
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;
    } else if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randNum(){
	var data = new Date();
	data=data.getYear()+data.getMonth()+data.getDate()+data.getHours()+data.getMinutes()+data.getSeconds()+data.getMilliseconds();
	return(data);
}

function unixTime(){
	var foo = new Date; // Generic JS date object
	var unixtime_ms = foo.getTime(); // Returns milliseconds since the epoch
	// var unixtime = parseInt(unixtime_ms / 1000);
	var unixtime = parseInt(unixtime_ms);
	return(unixtime);
}

function stessa_altezza(className) {
	cols = getElementsByClassName(className);

	var max = 0;
	
	for(var i=0; i<cols.length; i++) {
		if(cols[i].clientHeight > max) max = cols[i].clientHeight;
	}
	
	for(i=0; i<cols.length; i++) {
		cols[i].style.height = max + "px";
	}

	for(i=0; i<cols.length; i++) {
		if(cols[i].clientHeight > max) {
			offset = cols[i].clientHeight - max;
			cols[i].style.minHeight = (parseInt(cols[i].style.height)) - offset + "px";
		}
	}
}

function setSpazioVert(){
	ris=getViewportSize();
	ris=ris[1];
	// oggetto=prendiElementoDaId('contenitoreAll');
	// docHeight=oggetto.clientHeight;
	// oggetto=prendiElementoDaId("cerca");
	// oggetto.value="["+ris+"]["+docHeight+"]";
	return(ris);
}

function setDocHeight(header, footer, totHeight){
		scrOfXY=getScrollXY();
		scrOfX=scrOfXY[0];
		scrOfY=scrOfXY[1];
	minHeightPag=752; // spazio occupato fino alla fine della barra tabelle
	totHeight=(totHeight>=minHeightPag || !(tipoTemplate=="colonne"))?totHeight:totHeight;
	minHeightDoc=250;
	docHeight=totHeight-header-footer;
	oggetto=prendiElementoDaId("documento");
	if(oggetto){
		if(0 && tipoTemplate=="colonne"){
			oggetto.style.height=(docHeight-16)+"px";
		} else {
			oggetto.style.height=(docHeight+scrOfY)+"px";
		}
	}
	boxColonna['y']=((docHeight-98)>minHeightDoc)? (docHeight-98) : minHeightDoc;

	// oggetto=prendiElementoDaId("cerca");
	// oggetto.value=docHeight;
	
	return(docHeight);
}

function getIEVersion(){
    var version = 999; // we assume a sane browser
    if (navigator.appVersion.indexOf("MSIE") != -1)
      // bah, IE again, lets downgrade version number
      version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    return version;
}

function funzioniResize(){
	setDocHeight(356, 34, setSpazioVert());
	setMaxDimDiv("sfPopup","contenitoreAll","xy");
	if(getIEVersion()<=6){ // IF IE6
		ris=getViewportSize();
		oggetto=prendiElementoDaId("documento");
		if(oggetto){
			dimw=ris[0]-10-10-19-30-32;
			oggetto.style.width=dimw+"px";
		}
		/*
		oggetto=prendiElementoDaId("contDocumento");
		if(oggetto){
			dimw=ris[0]-10-10;
			oggetto.style.width=dimw+"px";
		}
		*/
	}
	setPosRicerca();
}

function getViewportSize() { 
	var size = [0, 0]; 
	if (typeof window.innerWidth != "undefined") { 
		size = [window.innerWidth, window.innerHeight];
	} 
	else if (typeof document.documentElement != "undefined" && typeof document.documentElement.clientWidth != "undefined" && document.documentElement.clientWidth != 0) {
		size = [document.documentElement.clientWidth, document.documentElement.clientHeight]; 
	}
	else {
		size = [document.getElementsByTagName("body")[0].clientWidth, document.getElementsByTagName("body")[0].clientHeight]; 
	}
	return size; 
}

function setMaxDimDiv(idDiv,idRif,xy){
	livello=prendiElementoDaId(idDiv);
	if(livello){
		oggetto=prendiElementoDaId(idRif);
		if(oggetto){
			contentHeight=oggetto.clientHeight;
			contentWidth=oggetto.clientWidth;
		} else {
			contentHeight=0;
			contentWidth=0;
		}
		// alert(contentWidth+"#"+contentHeight);
		dimWindow=getViewportSize();

		maxWidth=Math.max(contentWidth,dimWindow[0]);
		maxHeight=Math.max(contentHeight,dimWindow[1]);
		if(xy=="x" || xy=="xy"){
			// livello.style.width=maxWidth+"px";
			livello.style.width="100%";
			livello.style.minWidth="962px";
		}
		if(xy=="y" || xy=="xy"){
			livello.style.height=maxHeight+"px";
			livello.style.minHeight=maxHeight+"px";
		}
	} else {
		// diDiv non trovato
	}
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

var scrOfX=-1;
var scrOfY=-1;
function apriPopup(stato, src, noOsc){
	if(scrOfX==-1 || scrOfY==-1){
		getScrollXY();
	}
	if(!noOsc){
		setlivelli("sfPopup",stato);
	}
	if(stato==0){
		window.scrollTo(scrOfX,scrOfY);
	} else {
		scrOfXY=getScrollXY();
		scrOfX=scrOfXY[0];
		scrOfY=scrOfXY[1];
		window.scrollTo(0,0);
	}
	funzioniResize();
	oggetto=prendiElementoDaId("contPopup");
	if(oggetto){
		oggetto.innerHTML="";
		if(src!="" && src!="undefined" && src!=undefined){
			// alert(src);
			ris=insAjaxHTML("contPopup", src);
		}
	}
	setlivelli("contPopup",stato);
	return(false);
}

/* ----------------- INIZIO FUNZIONI DI CARRELLO ----------------------- */

var inviabile=true;

function bloccaNum(nomeModulo, nomeCampo) { // IMPONE AL CAMPO DI ACCETTARE SOLO NUMERI
	oggetto=document.getElementById(nomeModulo);
	var textObj = eval("oggetto."+nomeCampo);
	textObj.onkeyup = function () {
		valoreIniz=textObj.value;
		valoreFin="";
		valoreLenght=valoreIniz.length;
		for (i=0; i<valoreLenght; i++){
			if(!isNaN(valoreIniz.charAt(i))){
				valoreFin+=valoreIniz.charAt(i);
			} else {
			}
		}
		textObj.value=valoreFin;
	}
}

function visAllSelect(stato){
	for (var counter=0; counter<selectLists.length; counter++){
		selectLists[counter].style.visibility=(stato==0)?'hidden':'visible';
	}
}

selectLists = document.getElementsByTagName('select');

function modQta(qta){
	oggetto=prendiElementoDaId("qta");
	var qtaAtt=parseInt(oggetto.value, 10);
	qtaAtt=qtaAtt+parseInt(qta, 10);
	qtaAtt=(qtaAtt>=1)? qtaAtt : 1;
	oggetto.value=qtaAtt;
	oggetto=prendiElementoDaId("qtaTxt");
	oggetto.innerHTML=qtaAtt;
}

/* ----------------- FINE FUNZIONI DI CARRELLO ----------------------- */

function testRegExp(stringa, espressione){
	var espressione = new RegExp(espressione);
	return espressione.test(stringa)
}

function attivaFScroll(idDiv){
	/*
	oggetto=prendiElementoDaId(idDiv);
	CSBfleXcroll(idDiv);
	oggetto.scrollUpdate();
	*/
	$(function()
	{
		$('#documento').jScrollPane();
		reinitialiseScrollPane = function()
		{
			$('#documento').jScrollPane();
		}
		$('#documento').load('lipsum.php', '', reinitialiseScrollPane);
	});
}

function zoomImg(url){
	tb_show('', url);
	return(false);
}

function boxMouse(url, idDiv, offX, offY, closeTimeOut){
	// loading(1);
	var posiziona=posizionaDiv(idDiv,tempX+offX,tempY+offY);
	ris=insHTML(idDiv, "");
	if(!(undefined===window.chiudiMS)){
		clearTimeout(chiudiMS);
	}
	var apri=$.get(url, function(data){
				// loading(0);
				ris=insHTML(idDiv, data);
				setlivelli(idDiv,1);
				closeTxtPop(idDiv,closeTimeOut);
		});
	return(false);
}

function popParola(id){
	urlPopMouse='pop_nota.php?';
	urlPopMouse=urlPopMouse+"id="+id;
	boxMouse(urlPopMouse, 'overDiv', 12, -57, 10000);
	return(false);
}

function popNota(id){
	urlPopMouse='pop_nota_doc.php?';
	urlPopMouse=urlPopMouse+"id="+id;
	boxMouse(urlPopMouse, 'overDiv', 10, -50, 10000);
	return(false);
}

function popNotaDoc(id){
	return(popNota(id));
}

function popComingSoon(rif){
	urlPopMouse='pop_comingsoon.php';
	var idDiv="overDiv";
	if(!rif){
		boxMouse(urlPopMouse, idDiv, -159, 0, 2000);
	} else {
		var idRif=$(rif).attr('id');
		// alert(idRif);
		var posXYrif=$("#"+idRif).offset();
		// alert(posXYrif.left+"---"+posXYrif.top);
		var posiziona=posizionaDiv(idDiv,posXYrif.left-160,posXYrif.top-2);
		ris=insHTML(idDiv, "");
		if(!(undefined===window.chiudiMS)){
			clearTimeout(chiudiMS);
		}
		var apri=$.get(urlPopMouse, function(data){
					// loading(0);
					ris=insHTML(idDiv, data);
					setlivelli(idDiv,1);
					closeTxtPop(idDiv,4000);
			});
	}
	
	return(false);
}

function popCommentoOld(id){
	urlPopMouse='pop_commento.php?';
	urlPopMouse=urlPopMouse+"id="+id;
	boxMouse(urlPopMouse, 'overDiv', 10, -50, 10000);
	return(false);
}


function popCommento(idComm){
	setlivelli("draggableComm",0);
	loading(1);

	var spazioSel=new Array();
	spazioSel['x1']=0;
	spazioSel['y1']=0;
	spazioSel['x2']=0;
	spazioSel['y2']=0;

	items = getElementsByClassName("h1");
	for(var i=0; i<items.length; i++) {
		if(parseInt(items[i].getAttribute('idCommento'))==idComm){
			// alert($(items[i]).position().top);
			spazioSel['x1']=($(items[i]).position().left < spazioSel['x1'] || spazioSel['x1']==0)? parseInt($(items[i]).position().left) : spazioSel['x1'];
			spazioSel['y1']=(($(items[i]).position().top < spazioSel['y1'] || spazioSel['y1']==0) && $(items[i]).position().top>300)? parseInt($(items[i]).position().top) : spazioSel['y1'];
			spazioSel['x2']=(($(items[i]).width() + spazioSel['x1']) > spazioSel['x2'] || spazioSel['x2']==0)? parseInt(($(items[i]).width() + spazioSel['x1'])) : spazioSel['x2'];
			spazioSel['y2']=(($(items[i]).height() + spazioSel['y1']) > spazioSel['y2'] || spazioSel['y2']==0)? parseInt(($(items[i]).height() + spazioSel['y1'])) : spazioSel['y2'];
		}
	}
	// alert(spazioSel['y1']);
	var spazioDisp=getViewportSize();

	if(getIEVersion()>6){
		var posYtmp=(spazioSel['y1']-92)-162;
	} else { // IE6
		var posYtmp=(spazioSel['y1']-92)-169;
	}

	var posXtmpL=(spazioSel['x1']-55)-382;
	var posXtmpR=(spazioSel['x2']-55)+400;

	if(posXtmpL<=0 && posXtmpR>=spazioDisp[0]){
		posXtmp=parseInt(((spazioDisp[0])/2)-(382/2));
	} else if(posXtmpR>=spazioDisp[0]){
		posXtmp=(spazioSel['x1']-55-382);
	} else {
		posXtmp=(spazioSel['x2']-55);
	}

	var posiziona=posizionaDiv("draggableComm",posXtmp,posYtmp);

	url='pop_commento.php';
	$.get(url,{
			id: idComm,
			time: unixTime()
		}, function(data){
			loading(0);
			ris=insHTML("draggableComm", data);
			// $('#draggableComm').draggable({ handle:'#draggerHandle', cursor: 'crosshair' });
			setlivelli("draggableComm",1);
	});

}

function popModCommento(idComm){
	loading(1);
	url='inc_pop_modcommento.php';
	$.get(url,{
			id: idComm,
			time: unixTime()
		}, function(data){
			loading(0);
			ris=insHTML("draggableComm", data);
	});
	return(false);
}

function aggPreferiti(id,stato){
	url="background.php?act=aggPreferiti&id="+id+"&stato="+stato+"&rand="+randNum();
	$.get(url, function(data){
		if(data=="dologin"){
			var apri=apriLogin();
		} else {
			ris=insAjaxHTML("pannelloSx", "background.php?act=getPannelloSx&id="+idContenutoAtt+"&tipo="+tipoPannello+"&visAltOn="+visAltOn+"&rand="+randNum());
			ris=caricaPannelloDoc(id);
		}
	});
	return(false);
}

function aggPreferitiPag(id,stato){
	setPannello('preferiti');
	aggPreferiti(id,stato);
	return(false);
}


function aggiornaCaptcha(){
	oggetto=prendiElementoDaId("imgCaptcha");
	if(oggetto){
		oggetto.src="captcha_zdr/captcha_img.php?rand="+randNum();
	}
	return(false);
}

function apriRegister(){
	apriPopup(1, "inc_pop_register.php?rand="+randNum());
	return(false);
}

function apriPopMsg(act){
	apriPopup(1, "inc_pop_msg.php?act="+act+"&rand="+randNum());
	return(false);
}

function apriLogin(){
	apriPopup(1, "inc_pop_login.php?rand="+randNum());
	return(false);
}

function apriRecuperaPwd(){
	apriPopup(1, "inc_pop_recuperapwd.php?rand="+randNum());
	return(false);
}

function apriSegnala(){
	apriPopup(1, "inc_pop_segnala.php?rand="+randNum());
	return(false);
}

function logout(){
	var apri=closeRicerca();
	var url="background.php?act=logout";
	$.get(url, function(data){
		var apri=caricaContenuto(idContenutoAtt);
	});
	return(false);
}

function setPosRicerca(){
	oggetto=prendiElementoDaId("draggable");
	if(oggetto){
		var posXYRic=$('#ricerca').offset();
		var newLeft=(0-218+parseInt(posXYRic.left));
		newLeft=newLeft+250-parseInt($('#draggable').position().left);
		var newTop=(0-103+parseInt(posXYRic.top));
		newTop=newTop+250-parseInt($('#draggable').position().top);
		oggetto.style.marginLeft=newLeft+"px";
		oggetto.style.marginTop=newTop+"px";
	}
}

function contrRicerca(){
	if($("#ricerca").val()!=""){
		if(scrOfX==-1 || scrOfY==-1){
			getScrollXY();
		}
		window.scrollTo(scrOfX,scrOfY);
		funzioniResize();
		oggetto=prendiElementoDaId("draggable");
		if(oggetto){
			url="inc_pop_ricerca.php?ricerca="+($("#ricerca").val())+"&rand="+randNum();
			oggetto.innerHTML="";
			$.get(url, function(data){
				insHTML("draggable", data);
				setlivelli("draggable",1);
				oggetto=prendiElementoDaId("ricerca");
				oggetto.value="";
				$('#draggable').draggable({ 
					handle:'#draggerHandle',
					cursor: 'crosshair',
					// Find original position of dragged image. 
					start: function(event, ui) { 
						// Show start dragged position of image. 
						// var Startpos = $(this).position(); 
						// $("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top); 
					}, 
					// Find position where image is dropped. 
					stop: function(event, ui) { 
						// Show dropped position. 
						// var Stoppos = $(this).position(); 
						// $("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top); 
					} 
				});
			});
		}
	}
	return(false);
}





function openCommenti(){
	oggetto=prendiElementoDaId("draggable");
	if(oggetto){
		url="inc_pop_commenti.php";
		oggetto.innerHTML="";
		$.get(url,{
				time: unixTime()
			}, function(data){
				if(data=="dologin"){
					var apri=apriLogin();
				} else {
					if(scrOfX==-1 || scrOfY==-1){
						getScrollXY();
					}
					window.scrollTo(scrOfX,scrOfY);
					funzioniResize();
					insHTML("draggable", data);
					setlivelli("draggable",1);
					$('#draggable').draggable({ handle:'#draggerHandle', cursor: 'crosshair' });
				}
		});
	}
	return(false);
}

function closeRicerca(){
	insHTML("draggable", "");
	setlivelli('draggable',0);
	return(false);
}

function closeCommenta(){
	insHTML("draggableComm", "");
	setlivelli('draggableComm',0);
	return(false);
}

function deleteCommento(id, onOk){
	url="background.php";
	$.get(url,{
			idCommento: id,
			act: "deleteCommento",
			time: unixTime()
		}, function(data){
			var apri=disattivaCommento(id);
			if(onOk=="reopen"){
				var apri=openCommenti();
			} else {
				var apri=closeCommenta();
			}
			ris=insAjaxHTML("pannelloSx", "background.php?act=getPannelloSx&id="+idContenutoAtt+"&tipo="+tipoPannello+"&visAltOn="+visAltOn+"&rand="+randNum());
			/*
			colonnaAttTmp=colonnaAtt;
			var apri=caricaContenuto(idContenutoAtt,0);
			if(tipoTemplate=="colonne" && visAltOn!="html"){
				var apri=vaiColonna(colonnaAttTmp, colonne.length);
			}
			*/
	});
	return(false);
}

function contrPrivacy(){
	if(scrOfX==-1 || scrOfY==-1){
		getScrollXY();
	}
	window.scrollTo(scrOfX,scrOfY);
	funzioniResize();
	oggetto=prendiElementoDaId("draggable");
	if(oggetto){
		url="inc_pop_privacy.php";
		oggetto.innerHTML="";
		$.get(url, function(data){
			insHTML("draggable", data);
			$('#draggable').draggable({ handle:'#draggerHandle', cursor: 'crosshair' });
			setlivelli("draggable",1);
		});
	}
	return(false);
}

function closePrivacy(){
	insHTML("draggable", "");
	setlivelli('draggable',0);
	return(false);
}

function inStampa(idParent,idNodo){
	var url="background.php?act=inStampa&idParent="+idParent+"&idNodo="+idNodo+"&rand="+randNum();
	$.get(url, function(data){
		ris=insAjaxHTML("pannelloSx", "background.php?act=getPannelloSx&id="+idContenutoAtt+"&tipo="+tipoPannello+"&visAltOn="+visAltOn+"&rand="+randNum());
	});
	return(false);
}

function outStampa(idParent,idNodo){
	var url="background.php?act=outStampa&idParent="+idParent+"&idNodo="+idNodo+"&rand="+randNum();
	$.get(url, function(data){
		ris=insAjaxHTML("pannelloSx", "background.php?act=getPannelloSx&id="+idContenutoAtt+"&tipo="+tipoPannello+"&visAltOn="+visAltOn+"&rand="+randNum());
	});
	return(false);
}

function inStampaP(stato){
	var url="background.php?act=inStampaP&stato="+stato+"&rand="+randNum();
	$.get(url, function(data){
		if(data=="dologin"){
			var apri=apriLogin();
		} else {
			ris=insAjaxHTML("pannelloSx", "background.php?act=getPannelloSx&id="+idContenutoAtt+"&tipo="+tipoPannello+"&visAltOn="+visAltOn+"&rand="+randNum());
		}
	});
	return(false);
}

function inStampaC(stato){
	var url="background.php?act=inStampaC&stato="+stato+"&rand="+randNum();
	$.get(url, function(data){
		if(data=="dologin"){
			var apri=apriLogin();
		} else {
			ris=insAjaxHTML("pannelloSx", "background.php?act=getPannelloSx&id="+idContenutoAtt+"&tipo="+tipoPannello+"&visAltOn="+visAltOn+"&rand="+randNum());
		}
	});
	return(false);
}


/* ---------------------------------------------------------------------------- */
/* ---------------- FINE SCRIPT PER IL SITO ----------------------------------- */
/* ---------------------------------------------------------------------------- */

/* ---------------------------------------------------------------------------- */
/* ---------------- INIZIO SCRIPT PER I FORM ---------------------------------- */
/* ---------------------------------------------------------------------------- */


function contaCharsTxtArea(maxchar){
	testo=$("#messaggio").val();
	caratteri=testo.length;
	if (caratteri > maxchar){
		$("#messaggio").val(testo.substr(0, maxchar));
	}
}

function alertCampo(oggetto, stato){
	if(stato==1){ // alert ON
		// oggetto.style.borderColor="#FF0000";
		oggetto.style.backgroundColor="#FFCCCC";
		oggetto.focus();
		oggetto.select();
	} else { // alert OFF
		// oggetto.style.borderColor="#9B9B9B";
		oggetto.style.backgroundColor="#FFFFFF";
	}
}

var chiudiAL=0;
function alertBox(messaggio){
	oggetto=prendiElementoDaId("boxAlert");
	if(oggetto){
		if(!(undefined===window.chiudiAL)){
			clearTimeout(chiudiAL);
		}
		setlivelli("boxAlert",0);
		oggetto.innerHTML=messaggio;
		setlivelli("boxAlert",1);
		chiudiAL = setTimeout("setlivelli('boxAlert',0)",5000);
	} else {
		alert(messaggio);	
	}
	
}

/* ---------------------------------------------------------------------------- */
/* ---------------- FINE SCRIPT PER I FORM ------------------------------------ */
/* ---------------------------------------------------------------------------- */
