// -------------------------------------------------------------------------
//
// @file wizcommon.js
// @auth: Andrea Raggi
// @date: 17/07/2008
// @descr:
// File contenente funzioni comuni javascript, 
// per il wizard layout e non 
// -------------------------------------------------------------------------
var cm_useDebug = false;


/*
 * Funzione addCompatibleLoadListener
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di aggiungere una funzione come ascoltatore
 * dell evento onLoad della pagina web corrente, in maniera compatibile alle
 * varie tipologie di browser. La funzione viene aggiunta, mantenendo eventuali
 * listener preesistenti
 *
 * @param: 
 * - fn = parametro contenente la funzione da richiamare sull evento onLoad
 */
function addCompatibleLoadListener(fn){ 
	if (typeof window.addEventListener != "undefined"){ 
		window.addEventListener("load", fn, false); 
		} 
		else if (typeof document.addEventListener != "undefined"){ 
		document.addEventListener("load", fn, false); 
		} 
		else if (typeof window.attachEvent != "undefined"){ 
		window.attachEvent("onload", fn); 
	} 
	else { 
		var oldfn = window.onload; 
		if (typeof window.onload != "function") { 
					window.onload = fn; 
		} 
		else {
				window.onload = function(){
				oldfn(); 
				fn(); 
				}; 
			}
	}
}

/*
 * Funzione addCompatibleUnLoadListener
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di aggiungere una funzione come ascoltatore
 * dell evento onUnload della pagina web corrente, in maniera compatibile alle
 * varie tipologie di browser. La funzione viene aggiunta, mantenendo eventuali
 * listener preesistenti
 *
 * @param: 
 * - fn = parametro contenente la funzione da richiamare sull evento onUnLoad
 */
function addCompatibleUnLoadListener(fn){ 
	if (typeof window.addEventListener != "undefined"){ 
		window.addEventListener("unload", fn, false); 
		} 
		else if (typeof document.addEventListener != "undefined"){ 
		document.addEventListener("unload", fn, false); 
		} 
		else if (typeof window.attachEvent != "undefined"){ 
		window.attachEvent("onunload", fn); 
	} 
	else { 
		var oldfn = window.onunload; 
		if (typeof window.onunload != "function") { 
					window.onunload = fn; 
		} 
		else {
				window.onunload = function(){
				oldfn(); 
				fn(); 
				}; 
			}
	}
}


/*
 * Funzione addCompatibleResizeListener
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di aggiungere una funzione come ascoltatore
 * dell evento onResize della pagina web corrente, in maniera compatibile alle
 * varie tipologie di browser. La funzione viene aggiunta, mantenendo eventuali
 * listener preesistenti
 *
 * @param: 
 * - fn = parametro contenente la funzione da richiamare sull evento onResize
 */

function addCompatibleResizeListener(fn){ 
	if (typeof window.addEventListener != "undefined"){ 
		window.addEventListener("resize", fn, false); 
		} 
		else if (typeof document.addEventListener != "undefined"){ 
		document.addEventListener("resize", fn, false); 
		} 
		else if (typeof window.attachEvent != "undefined"){ 
		window.attachEvent("onresize", fn); 
	} 
	else { 
		var oldfn = window.onresize; 
		if (typeof window.onresize!= "function") { 
					window.onresize = fn; 
		} 
		else {
				window.onresize = function(){
				oldfn(); 
				fn(); 
				}; 
			}
	}
}

/*
 * Funzione addCompatibleEventListener
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di aggiungere ad un dato oggetto, una funzione
 * come listener di un dato evento.
 *
 * @param: 
 * - objID = parametro contenente l'id dell'oggetto a cui aggiungere l'ascoltatore
 *
 * - event = parametro contenente l'evento da ascoltare (senza il prefisso 'on')
 *
 * - handler = parametro contenente la funzione listener
 */
function addCompatibleEventListener(objID,event,handler) {
	try{
		if(document.getElementById(objID).addEventListener) {
			document.getElementById(objID).addEventListener(event,handler,false);
		} else if(document.getElementById(objID).attachEvent) {
			document.getElementById(objID).attachEvent('on'+event,handler,false);
		}
	}
	catch(ex){
		
	}
	return null;
}


/*
 * Funzione getEventTarget
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di recuperare l'oggetto che ha generato un dato evento passato
 *
 * @param: 
 * - e = parametro contenente l'evento
 *
 */
function getEventTarget(e){
	if(!e)e = window.event;
	if(e.currentTarget){
		return e.currentTarget;
	}
	else if(window.event.srcElement){
			return window.event.srcElement;
		 }
		 else{  
  				if(e.target)return e.target;
  				return e.srcElement;
  		 }
    return null;
}


/*
 * Funzione getFontSize
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di recuperare la proprietà fontSize di un dato 
 * oggetto. Se tale proprietà non è settata, cerca di recuperare quella di default
 *
 * @param: 
 * - obj = parametro contenente l'oggetto di cui si desidera recuperare il fontSize
 */
function getFontSize(obj) { 
	var x = obj; 
	var y = "";
	if (x.currentStyle) { 
		y = x.currentStyle['fontsize']; 
 	} else if (window.getcomputedStyle) { 
  		// FF, Opera 
  		y = document.defaultView.getComputedStyle(x,null).getPropertyValue('font-size'); 
 	}
 	y = checkValore(y);
 	if(y==""){
 		try{
 			y = (
			obj.currentStyle||
			(window.getComputedStyle&&getComputedStyle(obj,null))||
			obj.style
			).fontSize;
 		}
 		catch(ex){}
 	}
 	return y; 
} 


/*
 * Funzione getFontColor
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di recuperare la proprietà fontColor di un dato 
 * oggetto. Se tale proprietà non è settata, cerca di recuperare quella di default
 *
 * @param: 
 * - obj = parametro contenente l'oggetto di cui si desidera recuperare il getFontColor
 */
function getFontColor(obj) { 
	var x = obj; 
	var y = "";
	if (x.currentStyle) { 
		y = x.currentStyle['fontcolor']; 
 	} else if (window.getcomputedStyle) { 
  		// FF, Opera 
  		y = document.defaultView.getComputedStyle(x,null).getPropertyValue('font-color'); 
 	}
 	y = checkValore(y);
 	if(y==""){
 		try{
 			y = (
			obj.currentStyle||
			(window.getComputedStyle&&getComputedStyle(obj,null))||
			obj.style
			).fontColor;
 		}
 		catch(ex){}
 	}
 	if(checkValore(""+y)){
 		return y;
 	}
 	else {
 		return getStyleColor(obj);
 	}
 	return y; 
} 


/*
 * Funzione getStyleColor
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di recuperare la proprietà color di un dato obj
 *
 * @param: 
 * - obj = parametro contenente l'oggetto di cui si desidera recuperare il color
 */
function getStyleColor(obj) { 
	var x = obj; 
	var y = "";
	if (x.currentStyle) { 
		y = x.currentStyle['color']; 
 	} else if (window.getcomputedStyle) { 
  		// FF, Opera 
  		y = document.defaultView.getComputedStyle(x,null).getPropertyValue('color'); 
 	}
 	y = checkValore(y);
 	if(y==""){
 		try{
 			y = (
			obj.currentStyle||
			(window.getComputedStyle&&getComputedStyle(obj,null))||
			obj.style
			).color;
 		}
 		catch(ex){}
 	}
 	if(checkValore(""+y)){
		 if (y.indexOf("rgb") != -1) y = convertRGB(y);
 	}
 	return y; 
} 

/*
 * Funzione getBackColor
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di recuperare la proprietà backgroundColor di un dato 
 * oggetto. Se tale proprietà non è settata, cerca di recuperare quella di default
 *
 * @param: 
 * - obj = parametro contenente l'oggetto di cui si desidera recuperare il backgroundColor
 */
function getBackColor(obj) { 
	var x = obj; 
	var y = "";
	if (x.currentStyle) { 
		y = x.currentStyle['backgroundColor']; 
 	} else if (window.getcomputedStyle) { 
  		// FF, Opera 
  		y = document.defaultView.getComputedStyle(x,null).getPropertyValue('background-color'); 
 	}
 	y = checkValore(y);
 	if(y==""){
 		try{
 			y = (
			obj.currentStyle||
			(window.getComputedStyle&&getComputedStyle(obj,null))||
			obj.style
			).backgroundColor;
 		}
 		catch(ex){}
 	}
 	if(checkValore(""+y)){
        if (y.indexOf("rgb") != -1) y = convertRGB(y);
 		return y;
 	}
 	else {
 		return getStyleColor(obj);
 	}
 	return y; 
} 


/*
 * Funzione getBackColorNoTransparent
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * La funzione si occupa di recuperare la proprietà backgroundColor di un dato 
 * oggetto. Se tale proprietà non è settata o è a transparent, cicla per recuperare quella
 * dei parent node
 *
 * @param: 
 * - obj = parametro contenente l'oggetto di cui si desidera recuperare il backgroundColor
 */
function getBackColorNoTransparent(obj) { 
	var tmp_colore = getBackColor(obj);
	tmpObj = obj;
	while( ((tmp_colore== "transparent")||(tmp_colore== "")) && (typeof(tmpObj.parentNode)!="undefined") ){
			tmpObj = tmpObj.parentNode;
			if(tmpObj){
				tmp_colore = getBackColor(tmpObj);
			}
			else {
				tmp_colore="";
				break;
			}
	}
	return tmp_colore;
}

function convertRGB(z){
	var newfcS = "", splitter = "";
	splitter = z.split(",");
	splitter[0] = parseInt(splitter[0].substring(4, splitter[0].length));
	splitter[1] = parseInt(splitter[1]);
	splitter[2] = parseInt(splitter[2].substring(0, splitter[2].length-1));
	for (var q = 0; q < 3; q++){
		splitter[q] = splitter[q].toString(16);
		if (splitter[q].length == 1) splitter[q] = "0" + splitter[q];
		newfcS += splitter[q];
	}
	return "#" + newfcS;
}


function newRGB(f, n, d){
	var change;
	if (d == 1) change = fiBy
	else change = foBy;


	for (var g = 0; g < 3; g++)	{
		if (n[g] > f[g] && n[g] - change >= 0) n[g] -= change;
		if (n[g] < f[g] && n[g] + change <= 255) n[g] += change;
	}
	return n;
}



/*
 * Funzione imInAFrame
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione usata per conoscere se la pagina corrente, si trova 
 * all'interno di un frame oppure no.
 * Ritorna "true" se sono all'interno di un frame
 * Ritorna "false" se sono nel documento principale del browser 
 */
function imInAFrame(){
	if(parent==window)return false;
	return true;
}

/*
 * Funzione thereIsAFrame
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione usata per conoscere se all'interno della pagina corrente
 * esiste almeno un frame 
 * Ritorna "true" se è presente almeno un frame nel documento corrente
 * Ritorna "false" altrimenti
 */
function thereIsAFrame(){
	var tmp_arr_frame = document.getElementsByTagName("iframe");
	if(tmp_arr_frame.length>=1)return true;
	return false;	
}


/*
 * Funzione checkValoreNum
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione usata per controllare e restituire un valore 'pulito' da null
 * eventuali NaN e undefined. 
 * La funzione ritorna il valore stesso, o zero (trattando il valore in modo numerico)
 * in caso il valore non superi i controlli
 *
 * @param: 
 * - val = parametro contenente il valore che si desidera controllare
 */
function checkValoreNum(val){
	if(val){
		var rit = val;	
		if((""+val)=="NaN") rit = 0;
		if((""+val)=="null") rit = 0;
		if((""+val)=="undefined") rit = 0;
		return rit;
	}
	return 0;
}

/*
 * Funzione checkValore
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione usata per controllare e restituire un valore 'pulito' da null
 * eventuali NaN e undefined
 * La funzione ritorna il valore stesso, o zero (trattando il valore in modo testuale)
 * in caso il valore non superi i controlli
 *
 * @param: 
 * - val = parametro contenente il valore che si desidera controllare
 */
function checkValore(val){
	if(val){
		var rit = val;	
		if((""+val)=="NaN") rit = "";
		if((""+val)=="null") rit ="";
		if((""+val)=="undefined") rit = "";
		return rit;
	}
	return "";
}



/*
 * Funzione trimLeft
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione usata per trimmare un testo all'inizio.
 * Elimina eventuali spazi all'inizio di un testo
 *
 * @param: 
 * - txt = parametro contenente il testo che si desidera trimmare
 */
function trimLeft(txt){
  if(txt){
  	return txt.replace(/^\s*/,"");
  }
  return "";
}

/*
 * Funzione trimRight
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione usata per trimmare un testo alla fine.
 * Elimina eventuali spazi alla fine di un testo
 *
 * @param: 
 * - txt = parametro contenente il testo che si desidera trimmare
 */
function trimRight(txt){
  if(txt){
  	return txt.replace(/\s*$/,"");
  }
  return "";
}

/*
 * Funzione trim
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione usata per trimmare un testo completamente
 * Elimina eventuali spazi all'inizio e alla fine di un testo
 *
 * @param: 
 * - txt = parametro contenente il testo che si desidera trimmare
 */
function trim(txt){
  var tmp_rit = trimRight(txt)
  return trimLeft(tmp_rit);
}

function trimSpecialChars(txt){
	if(txt){
		var tmp_rit = txt.replace(new RegExp( "\\n", "g" ), " ");
		tmp_rit = tmp_rit.replace(new RegExp( "\\t", "g" ), " ");
		tmp_rit = tmp_rit.replace(new RegExp( "\\r", "g" ), " ");
		return trim(tmp_rit);
	}
	return "";
}
/*
 * Funzione startsWith
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione (java-like) per controllare se un dato testo inizia con un 
 * dato prefisso
 *
 * @param: 
 * - txt = parametro contenente il testo su cui si desidera ricercare un prefisso
 * 
 * - prefix = parametro contenente il prefisso da ricercare nel testo
 */
function startsWith(txt, prefix){
  return (txt.substr(0,prefix.length)==prefix);
}

/*
 * Funzione endsWith
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione (java-like) per controllare se un dato testo termina con un 
 * dato suffisso
 *
 * @param: 
 * - txt = parametro contenente il testo su cui si desidera ricercare un suffisso
 * 
 * - suffix = parametro contenente il suffisso da ricercare nel testo
 */
function endsWith(txt, suffix){
  return (txt.substr(txt.length -suffix.length)==suffix);
}


/*
 * Funzione containsString
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione (java-like) per controllare se un dato testo contiene una data parola
 *
 * @param: 
 * - txt = parametro contenente il testo su cui si desidera ricercare una parola
 * 
 * - parola = parametro contenente la parola da ricercare nel testo passato
 */
function containsString(txt, parola){
	return (txt.indexOf(parola)!=-1);
}



/*
 * Funzione getBrowserWidth
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione che ritorna la larghezza corrente del browser, o la variabile globale
 * fake_browserWidth se è settata
 *
 */
var fake_browserWidth = -1;
function getBrowserWidth(){
	if(fake_browserWidth!=-1)return fake_browserWidth;

	if (window.innerWidth){
		return window.innerWidth;
	} 
	else if (document.documentElement && document.documentElement.clientWidth != 0){
		return document.documentElement.clientWidth; 
	}
	else if (document.body){
		return document.body.clientWidth;
	} 
	return 0;
}

/*
 * Funzione getBrowserHeight
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione che ritorna l'altezza  corrente del browser, o la variabile globale
 * fake_browserHeight se è settata
 *
 */
var fake_browserHeight = -1;
function getBrowserHeight(){
	if(fake_browserHeight!=-1)return fake_browserHeight;

	
	if (window.innerHeight){
		return window.innerHeight;
	} 
	else if (document.documentElement && document.documentElement.clientHeight != 0){
		return document.documentElement.clientHeight; 
	}
	else if (document.body){
		return document.body.clientHeight;
	}
	return 0;
}



/*
 * Funzione randNum
 * @auth: Andrea Raggi
 * @date: 17/07/2008
 * @descr:
 * Funzione che ritorna un valore random, compreso fra un valore minimo e massimo
 *
 * @param: 
 * - min = parametro contenente il valore minimo del numero random
 *
 * - max = parametro contenente il valore massimo del numero random
 */
function randNum(min,max){
	var m=min;
	var n=max;
	var r=m+Math.round(Math.random()*n); 
	return(r); 
} 


function getEffectiveWidth(el, includePadding, includeBorder){
    var width;
    el = (typeof(el) === "string") ? document.getElementById(el) : el;	
    
    if (window.getComputedStyle) { /* FF, Safari, Opera */
        var style = document.defaultView.getComputedStyle(el, null);
        if (style.getPropertyValue("display") === "none")
            return 0;
        width = parseInt(style.getPropertyValue("width"));
        
        if (window.opera && !document.getElementsByClassName) {
            /* Opera 9.25 includes the padding and border when reporting the width/height - subtract that out */
            width -= parseInt(style.getPropertyValue("padding-left"));
            width -= parseInt(style.getPropertyValue("padding-right"));
            width -= parseInt(style.getPropertyValue("border-left-width"));
            width -= parseInt(style.getPropertyValue("border-right-width"));
        }
        
        if (includePadding) {
            width += parseInt(style.getPropertyValue("padding-left"));
            width += parseInt(style.getPropertyValue("padding-right"));
        }
        
        if (includeBorder) {
            width += parseInt(style.getPropertyValue("border-left-width"));
            width += parseInt(style.getPropertyValue("border-right-width"));
        }
    } else { /* IE */
        if (el.currentStyle["display"] === "none")
            return 0;
        var bRegex = /thin|medium|thick/; /* Regex for css border width keywords */
        width = el.offsetWidth; /* Currently the width including padding + border */
        
        if (!includeBorder) {
            var borderLeftCSS = el.currentStyle["borderLeftWidth"];
            var borderRightCSS = el.currentStyle["borderRightWidth"];
            var temp = document.createElement("DIV");
            if (el.offsetWidth > el.clientWidth && el.currentStyle["borderLeftStyle"] !== "none") {
                if (!bRegex.test(borderLeftCSS)) {
                    temp.style.width = borderLeftCSS;
                    el.parentNode.appendChild(temp);
                    width -= temp.offsetWidth;
                    el.parentNode.removeChild(temp);
                } else if (bRegex.test(borderLeftCSS)) {
                    temp.style.width = "10px";
                    temp.style.border = borderLeftCSS + " " + el.currentStyle["borderLeftStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    width -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
            if (el.offsetWidth > el.clientWidth && el.currentStyle["borderRightStyle"] !== "none") {
                if (!bRegex.test(borderRightCSS)) {
                    temp.style.width = borderRightCSS;
                    el.parentNode.appendChild(temp);
                    width -= temp.offsetWidth;
                    el.parentNode.removeChild(temp);
                } else if (bRegex.test(borderRightCSS)) {
                    temp.style.width = "10px";
                    temp.style.border = borderRightCSS + " " + el.currentStyle["borderRightStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    width -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
        }
        
        if (!includePadding) {
            var paddingLeftCSS = el.currentStyle["paddingLeft"];
            var paddingRightCSS = el.currentStyle["paddingRight"];
            var temp = document.createElement("DIV");
            temp.style.width = paddingLeftCSS;
            el.parentNode.appendChild(temp);
            width -= temp.offsetWidth;
            temp.style.width = paddingRightCSS;
            width -= temp.offsetWidth;
            el.parentNode.removeChild(temp);
        }
    }
    
    return width;
};


/*
 * Funzione preloadImmagine
 * @auth: Andrea Raggi
 * @date: 01/08/2008
 * @descr:
 * Funzione che effettua il preload di un immagine
 *
 */
function preloadImmagine(imgSrc){
	try{
		var tmpImg=new Image();
		tmpImg.src=imgSrc;				
		if(tmpImg.complete)return true;
	}
	catch(exIgn){
		return false;
	}	
	return true;
}


/*
 * Funzione getPreloadedImage
 * @auth: Andrea Raggi
 * @date: 01/08/2008
 * @descr:
 * Funzione che effettua il preload di un immagine e la ritorna
 *
 */
function getPreloadedImage(imgSrc){
	try{
		var tmpImg=new Image();
		tmpImg.src=imgSrc;				
		if(tmpImg.complete)return tmpImg;
	}
	catch(exIgn){
		return null;
	}	
	return null;
}



/*
 * Funzione isInternetExplorer
 * @auth: Andrea Raggi
 * @date: 01/08/2008
 * @descr:
 * Funzione che testa se il browser è internetExplorer 
 *
 */
function isInternetExplorer(){
	if (navigator.appName.indexOf("Microsoft") != -1)
		if (navigator.userAgent.indexOf('Opera') == -1)
			return true;
	return false;
}

var userAgent = navigator.userAgent.toLowerCase();
var wizcommon_browser = {
	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
	safari: /webkit/.test( userAgent ),
	opera: /opera/.test( userAgent ),
	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};


/*
 * Funzione fixMozPosition
 * @auth: Andrea Raggi
 * @date: 01/08/2008
 * @descr:
 * Funzione che aggiunge 2 pixel a top e left per firefox
 *
 */
function fixMozPosition(val){
	if(isInternetExplorer()){
		return val;
	}
	else return val + 2;
}


/*
 * Funzione includeJSFile
 * @auth: Andrea Raggi
 * @date: 01/08/2008
 * @descr:
 * Funzione che include dinamicamente un file javascript 
 *
 */
function includeJSFile(urlScript, doc){
	if(!doc)doc=document;
	var oNewScript = doc.createElement("script");
	oNewScript.type = "text/javascript";
	oNewScript.src = urlScript;
	doc.getElementsByTagName("head")[0].appendChild(oNewScript );

	return oNewScript;
}
/*
 * Funzione includeCSSFile
 * @auth: Andrea Raggi
 * @date: 01/08/2008
 * @descr:
 * Funzione che include dinamicamente un file css 
 *
 */
function includeCSSFile(urlScript, doc){
	if(!doc)doc=document;
	var oNewScript = doc.createElement("link");
	oNewScript.type = "text/css";
	oNewScript.rel = "stylesheet";
	oNewScript.href = urlScript;
	doc.getElementsByTagName("head")[0].appendChild(oNewScript );
	
	return oNewScript;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// USED FOR GETTING THE COMPUTED HEIGHT OF AN ELEMENT IN PIXELS
///////////////////////////////////////////////////////////////////////////////////////////////////
function getEffectiveHeight(el, includePadding, includeBorder){
    var height;
    el = (typeof(el) === "string") ? document.getElementById(el) : el;
    
    if (window.getComputedStyle) { /* FF, Safari, Opera */
        var style = document.defaultView.getComputedStyle(el, null);
        if (style.getPropertyValue("display") === "none")
            return 0;
        height = parseInt(style.getPropertyValue("height"));
        
        if (window.opera && !document.getElementsByClassName) {
            /* Opera 9.25 includes the padding and border when reporting the width/height - subtract that out */
            height -= parseInt(style.getPropertyValue("padding-top"));
            height -= parseInt(style.getPropertyValue("padding-bottom"));
            height -= parseInt(style.getPropertyValue("border-top-width"));
            height -= parseInt(style.getPropertyValue("border-bottom-width"));
        }
        
        if (includePadding) {
            height += parseInt(style.getPropertyValue("padding-top"));
            height += parseInt(style.getPropertyValue("padding-bottom"));
        }
        
        if (includeBorder) {
            height += parseInt(style.getPropertyValue("border-top-width"));
            height += parseInt(style.getPropertyValue("border-bottom-width"));
        }
    } else { /* IE */
        if (el.currentStyle["display"] === "none")
            return 0;
        var bRegex = /thin|medium|thick/; /* Regex for css border width keywords */
        height = el.offsetHeight; /* Currently the height including padding + border */
    
        if (!includeBorder) {
            var borderTopCSS = el.currentStyle["borderTopWidth"];
            var borderBottomCSS = el.currentStyle["borderBottomWidth"];
            var temp = document.createElement("DIV");
            if (el.offsetHeight > el.clientHeight && el.currentStyle["borderTopStyle"] !== "none") {
                if (!bRegex.test(borderTopCSS)) {
                    temp.style.width = borderTopCSS;
                    el.parentNode.appendChild(temp);
                    height -= temp.offsetWidth;
                    el.parentNode.removeChild(temp);
                } else if (bRegex.test(borderTopCSS)) {
                    temp.style.width = "10px";
                    temp.style.border = borderTopCSS + " " + el.currentStyle["borderTopStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    height -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
            if (el.offsetHeight > el.clientHeight && el.currentStyle["borderBottomStyle"] !== "none") {
                if (!bRegex.test(borderBottomCSS)) {
                    temp.style.width = borderBottomCSS;
                    el.parentNode.appendChild(temp);
                    height -= temp.offsetWidth;
                    el.parentNode.removeChild(temp);
                } else if (bRegex.test(borderBottomCSS)) {
                    temp.style.width = "10px";
                    temp.style.border = borderBottomCSS + " " + el.currentStyle["borderBottomStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    height -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
        }
    
        if (!includePadding) {
            var paddingTopCSS = el.currentStyle["paddingTop"];
            var paddingBottomCSS = el.currentStyle["paddingBottom"];
            var temp = document.createElement("DIV");
            temp.style.width = paddingTopCSS;
            el.parentNode.appendChild(temp);
            height -= temp.offsetWidth;
            temp.style.width = paddingBottomCSS;
            height -= temp.offsetWidth;
            el.parentNode.removeChild(temp);
        }
    }
    
    return height;
};
 
if (typeof addEvent != 'function'){

var addEvent = function(o, t, f, l){
  var d = 'addEventListener', n = 'on' + t, rO = o, rT = t, rF = f, rL = l;
  if (o[d] && !l) {
  	o[d](t, f, false);
  	return f;
  }
  if (!o._evts) o._evts = {};
  if (!o._evts[t]){
	   o._evts[t] = o[n] ? { b: o[n] } : {};
	   o[n] = new Function('e',
	    'var r = true, o = this, a = o._evts["' + t + '"], i; for (i in a) {' +
	     'o._f = a[i]; r = o._f(e||window.event) != false && r; o._f = null;' +
	     '} return r');
	   if (t != 'unload') addEvent(window, 'unload', function() {
	    removeEvent(rO, rT, rF, rL);
	   });
  }
  if (!f._i) f._i = addEvent._i++;
  
  o._evts[t][f._i] = f;
  return f;
 };
 addEvent._i = 1;
 var removeEvent = function(o, t, f, l){
  var d = 'removeEventListener';
  if (o[d] && !l) {
  	return o[d](t, f, false);
  }
  if (o._evts && o._evts[t] && f._i) {
  	delete o._evts[t][f._i];
  }
 };
 
}


function cancelEvent(e, c){
	try{
		e.returnValue = false;
	}
	catch(ex1){
		cm_debuggaTxt("errore non bloccante in cancelEvent = " + ex1.message);
	}
 	if (e.preventDefault) e.preventDefault();
 	if (c){
		e.cancelBubble = true;
  		if (e.stopPropagation) e.stopPropagation();
 	}
}


function wiz_getAbsoluteLeft(htmlObject){
    var xPos = htmlObject.offsetLeft;
    var temp = htmlObject.offsetParent;
    while (temp != null) {
    	if(temp.offsetLeft<0)xPos += 0;
        else xPos += temp.offsetLeft;
        temp = temp.offsetParent;
    }
    return xPos;
}
/**
  *     @desc: Calculate absolute position of html object
  *     @type: private
  *     @param: htmlObject - html object
  *     @topic: 0  
  */
function  wiz_getAbsoluteTop(htmlObject) {
    var yPos = htmlObject.offsetTop;
    var temp = htmlObject.offsetParent;
    while (temp != null) {
    	if(temp.offsetTop<0)yPos += 0;
        else yPos += temp.offsetTop;
        temp = temp.offsetParent;
    }
    return yPos;
}

   
   
function isDoctypeStandardMode(doc){
	if(!doc)doc=document;
	
	if(doc.compatMode){
		if(doc.compatMode=="BackCompat")return false;
		if(doc.compatMode=="QuirksMode")return false;
	}
	return true;
}



function getDocument(obj){
  	return obj.ownerDocument || obj.document;
}

function getWindow(obj){
	var doc = (obj.getElementById) ? obj :  getDocument(obj);
  	return doc.defaultView || doc.parentWindow;;
}


document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};



var cm_debugTop="650px";
var cm_useTextArea=false;

function cm_debuggaTxt(txt, top){
	if(cm_useTextArea==true){
		var tmp_new_txt = (""+txt).replace(new RegExp( "<br>", "g" ), "\n");
		txt = tmp_new_txt;
	}
	if(cm_useDebug==true){
		if(document.getElementById("DIV_DEBUG")){
			if(cm_useTextArea==true)document.getElementById("DIV_DEBUG").value = txt + "\n\n" + document.getElementById("DIV_DEBUG").value;
			else document.getElementById("DIV_DEBUG").innerHTML = txt + "<br>&nbsp;<br>" + document.getElementById("DIV_DEBUG").innerHTML;
		}
		else{
			try{
				var tmp_div_dbg = document.createElement("DIV");
				if(cm_useTextArea==true){
					tmp_div_dbg = document.createElement("TEXTAREA");
					tmp_div_dbg.setAttribute("READONLY","READONLY");
					tmp_div_dbg.readOnly = true
				}
				
				tmp_div_dbg.setAttribute("ID", "DIV_DEBUG");
				tmp_div_dbg.id = "DIV_DEBUG";
				if(document.body){
					document.body.appendChild(tmp_div_dbg);			
					tmp_div_dbg = document.getElementById("DIV_DEBUG");
					if(tmp_div_dbg){
						tmp_div_dbg.style.position = "absolute";
						var tmp_top = top;
						if(!top)tmp_top = cm_debugTop;
						tmp_div_dbg.style.top = tmp_top;
						tmp_div_dbg.style.left = "5px";
						tmp_div_dbg.style.width = "80%";
						tmp_div_dbg.style.height = "280px";
						tmp_div_dbg.style.overflow = "scroll";
						tmp_div_dbg.style.border = "1px solid black";
						if(cm_useTextArea==true)tmp_div_dbg.value=""+txt;
						else tmp_div_dbg.innerHTML = txt;
					}
				}
			}
			catch(ex){
				cm_useDebug = confirm("" + txt + "\nContinuo col debug ?");
			}
		}
	}
}


function cm_checkAndCacheUrl(tmp_url){
	var rit = ""+tmp_url;
	rit +=((rit.indexOf("?")!=-1)?"&":"?")+"tmphdata="+(new Date()).valueOf();
	return rit;
}


// -----------------------------------------------------------------------
// Funzioni per controllare i tasti premuti sugli eventi keyPress
// -----------------------------------------------------------------------
 //    8:   Backspace
 //    9:   Tab
 //    13:  Enter
 //    16:  Shift
 //    17:  Control
 //    18:  Alt
 //    19:  Pause
 //    20:  Caps-Lock
 //    27:  Escape
 //    32:  Space
 //    33:  Page-Up
 //    34:  Page-Down
 //    35:  End
 //    36:  Home
 //    37:  Left Arrow
 //    38:  Up Arrow
 //    39:  Right Arrow
 //    40:  Down Arrow
 //    45:  Insert
 //    46:  Delete
 //    91:  Left Window
 //    92:  Right Window
 //    93:  Select
 //    112: F1
 //    113: F2
 //    114: F3
 //    115: F4
 //    116: F5
 //    117: F6
 //    118: F7
 //    119: F8
 //    120: F9
 //    121: F10
 //    122: F11
 //    123: F12
 //    144: Num-Lock
 //    145: Scroll Lock
 
var isCTRL_PRESSED = false;
var isSHIFT_PRESSED = false;
var isALT_PRESSED = false;

function cm_detectKeys(evt, isKeyDown){
	var keyCode="";
	if(evt)keyCode=getCompatibleKeyCode(evt);
	else {
		if (window.event){
			var evnt = window.event;
			keyCode = getCompatibleKeyCode(evnt);
		}
	}
    if (keyCode == "16"){
		isSHIFT_PRESSED = isKeyDown;
	}
	else if (keyCode == "17"){
		isCTRL_PRESSED = isKeyDown;
	}
	else if (keyCode == "18"){
		isALT_PRESSED = isKeyDown;
	}
}

function cm_isNumericKeyCode(keyCode){
	if( (isSHIFT_PRESSED==false)&&(isCTRL_PRESSED==false)&&(isALT_PRESSED==false)) {
		if((keyCode >= 48) && (keyCode <= 57)){
			return true;
		}
	}
	if((keyCode >= 96) && (keyCode <= 105))return true;
	return false;
}

function cm_isArrowKeyCode(keyCode){

	//Questo era per il tastierino numerico 
	//(ma il tastierino numerico quando il blocknum è disabilitato ha i keycode delle frecce vere proprie)
	//if((keyCode >= 96) && (keyCode <= 105))return true;
	//frecce
	if((keyCode >= 37) && (keyCode <= 40))return true;
	return false;
}

function cm_isSpecialKeyCode(keyCode){
	// Backspace - Tab - (Page Up - Page Down - End - Home - Left Arrow - Up Arrow - Right Arrow - Down Arrow)
	if( (keyCode == 8) || (keyCode == 9)  || ((keyCode >= 33) && (keyCode <= 40)) ) return true;
	// Shift - Control - Alt - Pause -  Caps-Lock 
	if( (keyCode >= 16) && (keyCode <= 20) ) return true;
	
 	// Enter - Escape
 	if( (keyCode == 13) || (keyCode == 27) ) return true;
 	
	// Insert - Delete
 	if( (keyCode == 45) || (keyCode == 46) ) return true;

	// Left Window - Right Window - Select (key like mouse right click)
	if( (keyCode >= 91) && (keyCode <= 93) ) return true;

	// SLEEP - WAKE 
	// Nn si riescono a impedire con il cancel event, essendo eventi catturati direttamente da window!
 	if( (keyCode == 95) || (keyCode == 255) ) return true;
	
 	// Fn (F1 - F2 - .. F12)
	if( (keyCode >= 112) && (keyCode <= 123) ) return true;
	
	 // Num-Lock - Scroll Lock
 	if( (keyCode == 144) || (keyCode == 145) ) return true;

	return false;
}

function cm_isDotCommaKeyCode(keyCode){
	if( (isSHIFT_PRESSED==false)&&(isCTRL_PRESSED==false)&&(isALT_PRESSED==false)) {
		if( (keyCode==190)||(keyCode==188) ) return true;
	}
	return false;
}

function cm_isSlash(keyCode){
	if(keyCode==111)return true;
	if( (isSHIFT_PRESSED==true)&&(keyCode==55) )return true;
	return false;
}
function cm_isQuestionMark(keyCode){
	if( (isSHIFT_PRESSED==true)&&(keyCode==219) )return true;
	return false;
}
function cm_isArrowUp(keyCode){
	if(keyCode==38)return true;
	return false;
}
function cm_isArrowDown(keyCode){
	if(keyCode==40)return true;
	return false;
}
function cm_isArrowLeft(keyCode){
	if(keyCode==37)return true;
	return false;
}
function cm_isArrowRight(keyCode){
	if(keyCode==39)return true;
	return false;
}
function cm_isTab(keyCode){
	if(keyCode==9)return true;
	return false;
}
function cm_isBackspace(keyCode){
	if(keyCode==8)return true;
	return false;
}
function cm_isEnter(keyCode){
	if(keyCode==13)return true;
	return false;
}

function checkEnterOnTxt(evt){
	var characterCode;
	if(evt)keyCode=getCompatibleKeyCode(evt);
	else {
		if (window.event){
			var evnt = window.event;
			keyCode = getCompatibleKeyCode(evnt);
		}
	}
	return cm_isEnter(keyCode);
}

function getCompatibleKeyCode(e){
	var keycode;
	if(window.event){
		//IE
  		keycode = e.keyCode;
  	}
	else if(e.which) {
		// Netscape/Firefox/Opera
		keycode = e.which;
  	}
  	return keycode;
}

function getDebugKeyCodeString(evt){
	var keycode;
	if(evt)keycode=getCompatibleKeyCode(evt);
	if(keycode){
		var rit = "KeyCode = " + keycode;
		rit = rit + "  -  keyChar = " + String.fromCharCode(keycode);
		rit = rit + "  -  isArrow = " + cm_isArrowKeyCode(keycode);
		rit = rit + "  -  isSpecial = " + cm_isSpecialKeyCode(keycode);
		rit = rit + "  -  isDotComma = " + cm_isDotCommaKeyCode(keycode);
		rit = rit + "  -  isNumeric = " + cm_isNumericKeyCode(keycode);
		rit = rit + "  -  isSHIFT = " + isSHIFT_PRESSED;
		rit = rit + "  -  isCTRL = " + isCTRL_PRESSED;
		rit = rit + "  -  isALT = " + isALT_PRESSED;
		return rit;
	}
	return "Unknow!";
}




/*
 * Class jsCssParser
 * @auth: Andrea Raggi
 * @date: 17/10/2008
 * @descr:
 * Class for parse a css string into an object
 *
 * @param: 
 * - [str] cssString	= String with css style attribute value
*/
function jsCssParser(cssStringPassed) {
	this.cssProp = new Array();	
	
	if(typeof cssStringPassed!="object"){
		this.cssString = cssStringPassed;
	}
	else{		
		for(var k in cssStringPassed){
			 this.cssProp[k] = cssStringPassed[k];
		}
		this.cssString = "";
		
	}

	this.costructCssString = function(ignoreEmptyValue){
		var rit = "";
		var tmp_sep = "";
		for(var k in this.cssProp){
			if(typeof this.cssProp[k] != 'function'){
				if(ignoreEmptyValue){
					if(this.cssProp[k]!="")rit = rit +  k + ":" + this.cssProp[k] + ";";
				}
				else{
					rit = rit +  k + ":" + this.cssProp[k] + ";";
				}		
			}
		}
		return rit;
	}
	
	if(this.cssString){
		if(this.cssString!=""){
			var newStr = trim(this.cssString);
			this.cssProp = {};
			if(newStr!=""){
				var prop_arr = newStr.split(";");
				for(var i = 0; i < prop_arr.length; i++){
					var tmp_arr = 	prop_arr[i].split(":");
					if(tmp_arr.length==2){
						this.cssProp["" + tmp_arr[0] + ""] = tmp_arr[1];
					}
				}
			}
		}
	}
}

/*
 * Funzione getCSSProps
 * @auth: Andrea Raggi
 * @date: 19/12/2008
 * @descr:
 * Funzione che ritorna un oggetto di tipo jsCssParser, per un dato foglio di stile e un dato cssRules
 * di un dato document
 *
 * @param: 
 * - [str] styleSheetName	= String with css StyleSheet Id value
 * - [str] cssRuleName		= String with css Rule Name value
 * - [obj] doc				= Dom Document Object. Optional, if null, current document will be used!
 */

function getCSSProps(styleSheetId, cssRuleName, doc){
	if(!doc)doc = document;
	var rit = new jsCssParser("");
	var sth = getStyleSheetsFromId(doc,styleSheetId);
	if(sth!=null){
		var singleRls = getSingleRuleFromStyleSheets(sth, cssRuleName);
		if(singleRls)rit = new jsCssParser(""+singleRls.style.cssText);
		else{
			var rls = getRulesFromStyleSheets(sth);
			if(rls!=null){
				var tmp_cls_name = cssRuleName;
	 			if(rls[tmp_cls_name]){
	 				rit = new jsCssParser(""+rls[tmp_cls_name].style.cssText);
	 			}
	 		}
	 	}
	}
	return rit;
}


/*
 * Funzione setCSSProps
 * @auth: Andrea Raggi
 * @date: 19/12/2008
 * @descr:
 * Funzione che dato un oggetto di tipo jsCssParser, per un dato foglio di stile e un dato cssRules
 * salva o crea una cssRules
 *
 * @param: 
 * - [str] styleSheetName		= String with css StyleSheet Id value
 * - [str] cssRuleName			= String with css Rule Name value
 * - [jsCssParser] jsCssBean	= jsCssParser object with css properties in array format
 * - [obj] doc					= Dom Document Object. Optional, if null, current document will be used!
 */

function setCSSProps(styleSheetId, cssRuleName, jsCssBean, doc){
		if(!doc)doc = document;
		var sth = getStyleSheetsFromId(doc,styleSheetId);
		if(jsCssBean==null)jsCssBean = new jsCssParser("");
		if(sth!=null){
			var singleRls = getSingleRuleFromStyleSheets(sth, cssRuleName);
			if(singleRls){
				if(singleRls.style){
					try{
						singleRls.style.cssText = jsCssBean.costructCssString(true);
					}
					catch(ex2){
						cm_debuggaTxt("*********** ERRORE DURANTE setCSSProps 2 =  " + getEx(ex2));
					}
				}
			}
			else{
				try{
					var esit = insertRuleToStyleSheet(sth, cssRuleName, jsCssBean.costructCssString(true));
					if(!esit)cm_debuggaTxt("Errore in setCSSProps.insertRuleToStyleSheet ");
				}
				catch(ex4){
					cm_debuggaTxt("*********** ERRORE DURANTE setCSSProps 4 =  " + getEx(ex4));
				}
		 	}
		}
}


/*
 * Funzione setSingleCSSProps
 * @auth: Andrea Raggi
 * @date: 19/12/2008
 * @descr:
 * Funzione che dato una singola proprietà css, per un dato foglio di stile e un dato cssRules
 * salva o crea una cssRules
 *
 * @param: 
 * - [str] styleSheetName		= String with css StyleSheet Id value
 * - [str] cssRuleName			= String with css Rule Name value
 * - [str] cssKey				= String with css key 
 * - [str] cssVal				= String with css value 
 * - [obj] doc					= Dom Document Object. Optional, if null, current document will be used!
 */
function OLD_setSingleCSSProps(styleSheetId, cssRuleName, cssKey, cssVal, doc){
	var jsCssBean = getCSSProps(styleSheetId, cssRuleName, doc);
	if(jsCssBean==null){
		jsCssBean = new jsCssParser(""+cssKey + ":" + cssVal + ";");
	}
	jsCssBean.cssProp[cssKey] = cssVal;
	setCSSProps(styleSheetId, cssRuleName, jsCssBean, doc);
}

function setSingleCSSProps(styleSheetId, cssRuleName, cssKey, cssVal, doc){
	if(!doc)doc = document;
	var sth = getStyleSheetsFromId(doc,styleSheetId);
	if(sth!=null){
		var singleRls = getSingleRuleFromStyleSheets(sth, cssRuleName);
		if(singleRls){
			if(singleRls.style){
				singleRls.style[cssKey] = cssVal;
				if(typeof(singleRls.style.setProperty)!="undefined"){
					singleRls.style.setProperty(cssKey, cssVal, null);
				}
			}
		}
		else{
			var esit = insertRuleToStyleSheet(sth, cssRuleName, cssKey + ":" + cssVal + ";");
			if(!esit)cm_debuggaTxt("Errore in setSingleCSSProps.insertRuleToStyleSheet !!!");
	 	}
	}
}





/*
 * Funzione getClonedObject
 * @auth: Andrea Raggi
 * @date: 22/10/2008
 * @descr:
 * Funzione che ritorna un oggetto clone di quello passato
 *
 */
function getClonedObject(schemaVar){
	var rit = {};
	for(var p in schemaVar)rit[p] = schemaVar[p];
	return rit;
}


/*
 * Funzione getClonedArray
 * @auth: Andrea Raggi
 * @date: 02/12/2008
 * @descr:
 * Funzione che ritorna un oggetto clone di quello passato
 *
 */
function getClonedArray(tmpArr){
	var rit = new Array();
	for(var i =0; i < tmpArr.length; i++)rit[i] = tmpArr[i];
	return rit;
}

/*
 * Funzione getElementByIdFromFather
 * @auth: Andrea Raggi
 * @date: 24/10/2008
 * @descr:
 * Use getElementById from a father Object!
 *
 */
function getElementByIdFromFather(id, fatherObject){
	var parentObject = null;
	if (typeof(fatherObject)!="object"){
		parentObject=document.getElementById(fatherObject);
	}
	else{
		parentObject=fatherObject;
	}
	var rit = null;
	if(parentObject.id==id)rit = parentObject;
	else{
		if(parentObject.hasChildNodes()){
			var childs = parentObject.childNodes;
			if(childs){
				if(childs.length){
					for(var i = 0; i < childs.length; i++){
						var tmp_rit = getElementByIdFromFather(id,childs[i]);
						if(tmp_rit!=null){
							rit = tmp_rit;
							break;
						}
					}
				}
			}
		}
	}
	return rit;
}



/*
 * Funzione fatherContainsElementById
 * @auth: Andrea Raggi
 * @date: 24/10/2008
 * @descr:
 * Use getElementById from a father Object!
 *
 */
function fatherContainsElementById(id, fatherObject){
	var tmp_obj = getElementByIdFromFather(id,fatherObject);
	if(tmp_obj!=null){
		if(tmp_obj.id = id)return true;
	}
	return false;
}




function debugObjectProp(obj, ifIncludeFunction){
	var tmp_txt = "";
	for(var k in obj){
		if(!ifIncludeFunction){
			if(typeof obj[k]!="function")tmp_txt = tmp_txt + k + ":" + obj[k] + ";";
		}
		else tmp_txt = tmp_txt + k + ":" + obj[k] + ";";
	}
	cm_debuggaTxt(tmp_txt);
}


function getStyleSheetsRulesFromId(doc,tmp_id){
	var sth = getStyleSheetsFromId(doc, tmp_id);
	if(sth)return getRulesFromStyleSheets(sth);
	return null;
}

function getStyleSheetsFromId(doc,tmp_id){
	if(!doc)doc=document;	
	var theRules = new Array();
	if(doc.styleSheets){
		for(var i =0 ; i < doc.styleSheets.length; i++){
			var stsh = doc.styleSheets[i];
			if(stsh.ownerNode){
				if(stsh.ownerNode.id){
					if(stsh.ownerNode.id==tmp_id)return stsh;
				}
			}
			else{
				if(typeof(stsh.id)!="undefined"){
					if(stsh.id==tmp_id)return stsh;
				}
			}
		}
	}
	return null;
}

function insertRuleToStyleSheet(stsh, selectorKey, cssString, rulePos){
	if(!rulePos)rulePos=0;
	if(typeof(rulePos)=="undefined")rulePos=0;
	
	if(!stsh)return false;
	
	if(typeof(stsh.addRule)!="undefined"){
		stsh.addRule(selectorKey, cssString, rulePos);
		return true;
	}
	else{
		if(typeof(stsh.insertRule)!="undefined"){
			stsh.insertRule(selectorKey + "{ " + cssString + " }", rulePos);
			return true;
		}
	}
	
	return false;
}

function getRulesFromStyleSheets(stsh){
	if(stsh.cssRules)return stsh.cssRules;
	if(stsh.rules)return stsh.rules;
	return null;
}

function getSingleRuleFromStyleSheets(stsh, keyRuleName){
	var rh = getRulesFromStyleSheets(stsh);
	if(rh[keyRuleName])return rh[keyRuleName];
	for(k in rh){
		if(rh[k].selectorText==keyRuleName)return rh[k];
	}
	return null;
}




/*
 * Class jscSortableCollector
 * @auth: Andrea Raggi
 * @date: 28/10/2008
 * @descr:
 * Class for sort a collection of object
 *
 * @param: 
 * - [str] type		= String with sort type
 *							  Value:
 *									 alf
 *									 num
 *									 date
 *					  Default = "alf"
 *
 * - [str] order	= String with sort order type. "asc" or "desc" (ascending/descending)
 *					  Default = "asc"
 *
*/
var generalArrSortable = new Array();
var generalOrderSortable = "asc";
var generalKeySortable = "";

function jscSortableCollector(type, order) {
	this.type = type;
	if(!type)this.type="alf";

	this.order = order;
	if(!order)this.order="asc";
	
	this._arrObj = new Array();
	
	this.addItem = function(obj){
		this._arrObj[this._arrObj.length] = obj;
		
	};
	
	this.sortBy = function(keyProp){
		generalArrSortable = new Array();
		generalArrSortable = this._arrObj;
		generalOrderSortable = this.order;
		generalKeySortable = keyProp;
		
		if(this.type=='str'){
			generalArrSortable.sort(function(a,b){
				if(typeof a[generalKeySortable]=="undefined")return 0;
				if(typeof b[generalKeySortable]=="undefined")return 0;
				if(generalOrderSortable=="asc")
					return a[generalKeySortable]>b[generalKeySortable]?1:-1;
				else 
					return a[generalKeySortable]<b[generalKeySortable]?1:-1;
			});
		}
		else if(type=='int'){
			generalArrSortable.sort(function(a,b){
				if(typeof a[generalKeySortable]=="undefined")return 0;
				if(typeof b[generalKeySortable]=="undefined")return 0;
             	var aVal = parseFloat( a[generalKeySortable]); aVal=isNaN(aVal)?-99999999999999:aVal;
             	var bVal = parseFloat( b[generalKeySortable]); bVal=isNaN(bVal)?-99999999999999:bVal;

             	if(generalOrderSortable=="asc")
	                return aVal-bVal;
				else 
	                return bVal-aVal;
			});
		}
        else if(type=='date'){
			generalArrSortable.sort(function(a,b){
				if(typeof a[generalKeySortable]=="undefined")return 0;
				if(typeof b[generalKeySortable]=="undefined")return 0;
	            var aVal = Date.parse(a[generalKeySortable])||(Date.parse("01/01/1900"));
	            var bVal = Date.parse(b[generalKeySortable])||(Date.parse("01/01/1900"));

             	if(generalOrderSortable=="asc")
                	return aVal-bVal
				else 
	                return bVal-aVal;
			});
        }
        
        this._arrObj = generalArrSortable;
	};
	
	this.isValidIdx = function(idx){
		if(this._arrObj==null)return false;
		if(idx<0)return false;
		if(idx>=this._arrObj.length)return false;
			
		return true;
	};
	
	this.elementAt = function(idx){
		if(!this.isValidIdx(idx))return null;
		return this._arrObj[idx];
	};
	
	this.elementAtToArray = function(idx){
		var tmp_obj = this.elementAt(idx);
		var rit = new Array();
		for(var k in tmp_obj){
			rit[""+k] = tmp_obj[k];
		}
		return rit;
	};
}




/*
 * Class jscRGB
 * @auth: Andrea Raggi
 * @date: 29/10/2008
 * @descr:
 * Class for color parsering and effect
 *
 * @param: 
 * - [str] colorString	= String with color value
 *							  Value:
 *									 #xxxxxx (where x = hex )
 *									 xxxxxx  (where x = hex )
 *									 xxx	 (where x = hex )
 *									 shc	 (shortcut like red, blue, black ... )
 *
*/
function jscRGB(colorString){
	this.color_string = colorString;
    if (this.color_string.charAt(0) == '#') { // remove # if any
        this.color_string = this.color_string.substr(1,(this.color_string.length-1));
    }
    this.color_string = this.color_string.replace(/ /g,'');
    this.color_string = this.color_string.toLowerCase();

    var named_color = {aqua:'00ffff',aquamarine:'7fffd4',azure:'f0ffff',beige:'f5f5dc',black:'000000',blue:'0000ff',blueviolet:'8a2be2',
        brown:'a52a2a',burlywood:'deb887',cadetblue:'5f9ea0',chartreuse:'7fff00',chocolate:'d2691e',coral:'ff7f50',
        cornflowerblue:'6495ed',cornsilk:'fff8dc',crimson:'dc143c',cyan:'00ffff',darkblue:'00008b',darkcyan:'008b8b',
        darkgoldenrod:'b8860b',darkgray:'a9a9a9',darkgreen:'006400',darkkhaki:'bdb76b',darkmagenta:'8b008b',
        darkolivegreen:'556b2f',darkorange:'ff8c00',darkorchid:'9932cc',darkred:'8b0000',darksalmon:'e9967a',
        darkseagreen:'8fbc8f',darkslateblue:'483d8b',darkslategray:'2f4f4f',darkturquoise:'00ced1',darkviolet:'9400d3',
        deeppink:'ff1493',deepskyblue:'00bfff',dimgray:'696969',dodgerblue:'1e90ff',feldspar:'d19275',firebrick:'b22222',
        floralwhite:'fffaf0',forestgreen:'228b22',fuchsia:'ff00ff',gainsboro:'dcdcdc',ghostwhite:'f8f8ff',gold:'ffd700',
        goldenrod:'daa520',gray:'808080',green:'008000',greenyellow:'adff2f',honeydew:'f0fff0',hotpink:'ff69b4',
        indianred :'cd5c5c',indigo :'4b0082',ivory:'fffff0',khaki:'f0e68c',lavender:'e6e6fa',lavenderblush:'fff0f5',
        lawngreen:'7cfc00',lemonchiffon:'fffacd',lightblue:'add8e6',lightcoral:'f08080',lightcyan:'e0ffff',
        lightgoldenrodyellow:'fafad2',lightgrey:'d3d3d3',lightgreen:'90ee90',lightpink:'ffb6c1',lightsalmon:'ffa07a',
        lightseagreen:'20b2aa',lightskyblue:'87cefa',lightslateblue:'8470ff',lightslategray:'778899',
        lightsteelblue:'b0c4de',lightyellow:'ffffe0',lime:'00ff00',limegreen:'32cd32',linen:'faf0e6',magenta:'ff00ff',
        maroon:'800000',mediumaquamarine:'66cdaa',mediumblue:'0000cd',mediumorchid:'ba55d3',mediumpurple:'9370d8',
        mediumseagreen:'3cb371',mediumslateblue:'7b68ee',mediumspringgreen:'00fa9a',mediumturquoise:'48d1cc',
        mediumvioletred:'c71585',midnightblue:'191970',mintcream:'f5fffa',mistyrose:'ffe4e1',moccasin:'ffe4b5',
        navajowhite:'ffdead',navy:'000080',oldlace:'fdf5e6',olive:'808000',olivedrab:'6b8e23',orange:'ffa500',
        orangered:'ff4500',orchid:'da70d6',palegoldenrod:'eee8aa',palegreen:'98fb98',paleturquoise:'afeeee',
        palevioletred:'d87093',papayawhip:'ffefd5',peachpuff:'ffdab9',peru:'cd853f',pink:'ffc0cb',plum:'dda0dd',
        powderblue:'b0e0e6',purple:'800080',red:'ff0000',rosybrown:'bc8f8f',royalblue:'4169e1',saddlebrown:'8b4513',
        salmon:'fa8072',sandybrown:'f4a460',seagreen:'2e8b57',seashell:'fff5ee',sienna:'a0522d',silver:'c0c0c0',
        skyblue:'87ceeb',slateblue:'6a5acd',slategray:'708090',snow:'fffafa',springgreen:'00ff7f',steelblue:'4682b4',
        tan:'d2b48c',teal:'008080',thistle:'d8bfd8',tomato:'ff6347',turquoise:'40e0d0',violet:'ee82ee',
        violetred:'d02090',wheat:'f5deb3',white:'ffffff',whitesmoke:'f5f5f5',yellow:'ffff00',yellowgreen:'9acd32'
    };
    
    for(var k in named_color){
        if(this.color_string==k){
            this.color_string = named_color[k];
        }
    }
	var tmp_arr = searchAndReturnColor(this.color_string);
	if(tmp_arr==null){
		this.error = true;
		return;
	}
	
	this.r = tmp_arr[0];
	this.g = tmp_arr[1];
	this.b = tmp_arr[2];
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
    
    this.toRGBString = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    };
    this.toHSVString = function () {
        return 'hsv(' + this.h + ', ' + this.s + ', ' + this.v + ')';
    };
    
    this.toHexString = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }
    this.old_RGB_toHSV = function(){
		var max = Math.max(this.r, this.g, this.b);
		var min = Math.min(this.r, this.g, this.b);

		var delta = (max - min) / max;

		switch(max){
			case this.r:
				this.h = 60 * (this.g - this.b) / (max - min);
				this.s = delta;
				this.v = max;
				break;
			case this.g: 
				this.h = 60 * (this.b - this.r) / (max - min) + 120;
				this.s = delta;
				this.v = max;
				break;
			case this.b: 
				this.h = 60 * (this.r - this.g) / (max - min) + 240;
				this.s = delta;
				this.v = max;
				break;
		}
	    this.h = (isNaN(this.h)) ? 0 : this.h;
    	this.s = (isNaN(this.s)) ? 0 : this.s;
    	this.v = (isNaN(this.v)) ? 0 : this.v;
	};
    this.RGB_toHSV = function(){
		var max = Math.max(this.r, this.g, this.b);
		var min = Math.min(this.r, this.g, this.b);

		this.h = 0;
		this.s = 0;
		this.v = 0;
		
		var delta = (max - min);
		this.v   = (max + min) / 2.0;
		if(delta <= 1e-5){
			this.h=0;
			this.s=0;
		}
		else{
			if( (this.v- 0.5) <= 1e-5 ){
				this.s = delta / (max + min);
			} else {
				this.s = delta / (2 - max - min);
			}
			switch(max){
				case this.r:
					this.h = (this.g - this.b) / delta;
					break;
				case this.g: 
					this.h = (2.0 + this.b - this.r) / delta;
					break;
				case this.b: 
					this.h = (4.0 + this.r - this.g) / delta;
				break;
			}
			this.h /= 6.0;
			
			if(this.h<0)this.h+=1;
			if(this.h>1)this.h-=1;
		}
		
	    this.h = (isNaN(this.h)) ? 0 : this.h;
    	this.s = (isNaN(this.s)) ? 0 : this.s;
    	this.v = (isNaN(this.v)) ? 0 : this.v;
	};

		
	this.HSV_toRGB = function(){
		var sextant = Math.floor(this.h / 60) % 6;

		var f = this.h / 60 - sextant;
		var p = this.v * (1 - this.s);
		q = this.v * (1 - f * this.s);
		t = this.v * (1 - (1 - f) * this.s);

		switch (sextant) {
			case 0: 
				this.r = this.v;
				this.g = t;
				this.b = p;
				break;
			case 1: 
				this.r = q;
				this.g = this.v;
				this.b = p;
				break;
			case 2:
				this.r = p;
				this.g = this.v;
				this.b = t;
				break;
			case 3:
				this.r = p;
				this.g = q;
				this.b = this.v;
				break;
			case 4:
				this.r = t;
				this.g = p;
				this.b = this.v;
				break;
			case 5:
				this.r = this.v;
				this.g = p;
				this.b = q;
				break;
		}
		
	    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
	    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
	    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
	    
	};
	
	this.updateFromHSV = function(){
		this.HSV_toRGB();
	};
	this.updateFromRGB = function(){
		this.RGB_toHSV();
	};
	
	//set hsv value
	this.RGB_toHSV();
    
	this.shade = function(optionalFact){
		if(!optionalFact)optionalFact=0.2;
	    var v=[],i
	    this.r = Math.round(this.r*optionalFact);
	    this.g = Math.round(this.g*optionalFact);
	    this.b = Math.round(this.b*optionalFact);
	    
	    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
	    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
	    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
	    
	    this.updateFromRGB();
	};
	this.darker = function(optionalPercent){
		if(!optionalPercent)optionalPercent=95;
		//this.shade(0.1);
		
		var tmpMask = new jscRGB("black");
		this.mixWith(tmpMask,optionalPercent);
	};
	this.lighter = function(optionalPercent){
		if(!optionalPercent)optionalPercent=95;
		//this.shade(1.1);
		
		var tmpMask = new jscRGB("white");
		this.mixWith(tmpMask,optionalPercent);
		
	};
	this.mixWith = function(colorMask, opacity){
		opacity /= 100.0;
		
		this.r = Math.round( (this.r * opacity) + (colorMask.r * (1 - opacity)) );
		this.g = Math.round( (this.g * opacity) + (colorMask.g * (1 - opacity)) );
		this.b = Math.round( (this.b * opacity) + (colorMask.b * (1 - opacity)) );
		
	    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
	    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
	    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
	    this.updateFromRGB();
	};
	this.adjustSaturation = function(percent){
		percent  /= 100.0;
		percent  += 1.0;
		percent  = Math.min(percent, 2.0);
		percent  = Math.max(0.0, percent);
		this.s   *= percent;
		this.updateFromHSV();		
	};
	
	this.isEqual = function(colorTo){
		if(colorTo==null)return false;
		if( (this.r == colorTo.r)&&(this.g == colorTo.g)&&(this.b == colorTo.b) )return true;
		return false;
	};
}


function searchAndReturnColor(str){
	var rit = [];
	try{
		//rgb(123, 234, 45)
		var rex = new RegExp("^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$");
		var bits = rex.exec(str);
        if (bits) {
			rit[0] = parseInt("" + bits[1], 10);
            rit[1] = parseInt("" + bits[2], 10);
            rit[2] = parseInt("" + bits[3], 10);
            return rit;
		}

		//'#00ff00', '336699'
		rex = new RegExp("^(\\w{2})(\\w{2})(\\w{2})$");
		bits = rex.exec(str);
        if (bits) {
			rit[0] = parseInt("" + bits[1], 16);
            rit[1] = parseInt("" + bits[2], 16);
            rit[2] = parseInt("" + bits[3], 16);
            return rit;
		}

		//#fb0', 'f0f'
		rex = new RegExp("^(\\w{1})(\\w{1})(\\w{1})$");
		bits = rex.exec(str);
        if (bits) {
			rit[0] = parseInt(bits[1] + bits[1], 16);
            rit[1] = parseInt(bits[2] + bits[2], 16);
            rit[2] = parseInt(bits[3] + bits[3], 16);
            return rit;
		}
	}
	catch(ex1){
		cm_debuggaTxt("errore in searchAndReturnColor = " + ex1);
	}
	return null;
}



/*
 * Class jscBorderedElement
 * @auth: Andrea Raggi
 * @date: 28/10/2008
 * @descr:
 * Container GUI Class for DIV element with border drawed
 *
 * @param: 
 * - [htlmObj] obj		= HTML GUI Div container
 *
 * - [int] bType		= Type of a border
 *							  Value:
 *  						  0 = no-border, 1=frame, 2=client, 3=modal, 4=modalborder, 5=dashed, 6=dotted
 *							  Default = 1
 *
 * - [int] bSize		= Border size (in pixel)
 *							  Default = 1
 * - [str] bColor		= Border color
 *							  Default = "gray"
*/

function jscBorderedElement(obj, bType, bSize, bColor, noInternalDiv, doc) {
	this.obj = null;
	this.bType = 0;
	this.bSize = 1;
	this.bColor = "gray";
	this.isADIV = true;
	this.isNoInternalDiv = false;
	if(typeof(noInternalDiv)!="undefined")this.isNoInternalDiv = noInternalDiv;
	this.realObj = null;
	
	this.setObj = function(val, doc){
		var tmp_doc = document;
		if(typeof(doc)!="undefined"){
			if(doc!=null)tmp_doc=doc;
		}
		if(!val)return;
		if(!val.nodeName)return;

		if(val.nodeName.toUpperCase()!="DIV"){
			this.isADIV=false;
			this.obj = val;
			this.realObj = this.obj;
			return;
		}

		if(this.isNoInternalDiv==true){
			this.isADIV=false;
			this.obj = val;
			this.realObj = this.obj;
			return;
		}
		
		this.obj = val;
		var div = tmp_doc.createElement("DIV");
		div.style.position = "relative";
		div.style.top = "0px";
		div.style.left = "0px";
		div.style.width = "100%";
		div.style.height = "100%";
		var chnds = this.obj.childNodes;
		if(chnds){
			var newArr = new Array();
			for(var i=0; i < chnds.length; i++){
				newArr[i] = chnds[i].cloneNode(true);
			}
			this.obj.innerHTML = "";
			for(var i =0; i < newArr.length;i++){
				div.appendChild(newArr[i]);
			}
		}
		this.obj.appendChild(div);
		
		div.style.overflow="hidden";
		this.obj.style.overflow="hidden";
		
		this.realObj = this.obj.childNodes[0];
	};
	
	this.setType = function(val){
		if(typeof val=="undefined")val = 1;
		this.bType = val;
		if((this.bType<0)||(this.bType>6))this.bType = 1;
	};
	this.getType = function(){
		return this.bType;
	};
	this.setSize = function(val){
		if(typeof val=="undefined")val = 1;
		this.bSize = val;
		if(!this.bSize)this.bSize = 1;
	};
	this.getSize = function(){
		return this.bSize;
	};
	this.setColor = function(val){
		this.bColor = val;
		if(!this.bColor)this.bColor = "gray";
	};
	this.getColor = function(){
		return this.bColor;
	};
	
	this.setObj(obj, doc);
	this.setType(bType);
	this.setSize(bSize);
	this.setColor(bColor);
	
	this.getObject = function(){
		return this.obj.childNodes[0];
	};
	
	this.applyBorder = function(optionalNewType){
		if(this.obj==null)return;
		if(typeof optionalNewType!="undefined")this.setType(optionalNewType);
		if(this.isADIV==true){
			this.obj.style.paddingTop="0px";
			this.obj.style.paddingLeft="0px";
			this.obj.style.paddingBottom="0px";
			this.obj.style.paddingRight="0px";
			switch(this.bType){
				case 0:
					//flat : no border
					
					this.obj.style.border = "0";
					this.obj.style.borderTop = "0";
					this.obj.style.borderLeft = "0";
					this.obj.style.borderBottom = "0";
					this.obj.style.borderRight = "0";
					

					this._clearBorder(this.obj);
					if(this.obj.childNodes){
						if(this.obj.childNodes[0]){
							this._clearBorder(this.obj.childNodes[0], true);
						}
					}

					break;
				case 1:
					//frame : normal border (solid)
					this.obj.style.border = "";
					this.obj.style.borderTop = this.bSize + "px solid " + this.bColor;
					this.obj.style.borderLeft = this.bSize + "px solid " + this.bColor;
					this.obj.style.borderBottom = this.bSize + "px solid " + this.bColor;
					this.obj.style.borderRight = this.bSize + "px solid " + this.bColor;
					
					if(this.obj.childNodes){
						if(this.obj.childNodes[0]){
							this._clearBorder(this.obj.childNodes[0], true);
						}
					}
					break;
				case 2:
					//client : pressed (inset)
					this._drawPressedBorder(this.obj);
	
					if(this.obj.childNodes){
						if(this.obj.childNodes[0]){
							this._clearBorder(this.obj.childNodes[0], true);
						}
					}
					break;
				case 3:
					//modal : released (outset)
					this._drawReleasedBorder(this.obj);	
					
					if(this.obj.childNodes){
						if(this.obj.childNodes[0]){
							this._clearBorder(this.obj.childNodes[0], true);
						}
					}
					break;
				case 4:
					//modalborder : (double/raised) 
				
					var int_tmp_margin = 0;
					var tmpChild = this.obj.childNodes[0];
					
					
					var tmpPadd = this.bSize*2;
					this._drawReleasedBorder(this.obj);
					if(this.bSize==1){
						this.obj.style.paddingTop="2px";
						this.obj.style.paddingLeft="2px";
						this.obj.style.paddingBottom="3px";
						this.obj.style.paddingRight="3px";
					}
					else {
						this.obj.style.paddingTop="0px";
						this.obj.style.paddingLeft="0px";
						this.obj.style.paddingBottom=tmpPadd+"px";
						this.obj.style.paddingRight=tmpPadd+"px";
					}

									
					if(this.obj.childNodes){
						if(this.obj.childNodes[0]){
							this._drawPressedBorder(this.obj.childNodes[0]);
						}
					}
					
					break;
				case 5:
					//dashed : tratteggiato
					this.obj.style.border = "";
					this.obj.style.borderTop = this.bSize + "px dashed " + this.bColor;
					this.obj.style.borderLeft = this.bSize + "px dashed " + this.bColor;
					this.obj.style.borderBottom = this.bSize + "px dashed " + this.bColor;
					this.obj.style.borderRight = this.bSize + "px dashed " + this.bColor;
					if(this.obj.childNodes){
						if(this.obj.childNodes[0]){
							this._clearBorder(this.obj.childNodes[0], true);
						}
					}
					break;
				case 6:
					//dotted : puntini 
					this.obj.style.border = "";
					this.obj.style.borderTop = this.bSize + "px dotted " + this.bColor;
					this.obj.style.borderLeft = this.bSize + "px dotted " + this.bColor;
					this.obj.style.borderBottom = this.bSize + "px dotted " + this.bColor;
					this.obj.style.borderRight = this.bSize + "px dotted " + this.bColor;
					if(this.obj.childNodes){
						if(this.obj.childNodes[0]){
							this._clearBorder(this.obj.childNodes[0], true);
						}
					}
					break;
			}
		}
		else{
			this.obj.style.paddingTop="0px";
			this.obj.style.paddingLeft="0px";
			this.obj.style.paddingBottom="0px";
			this.obj.style.paddingRight="0px";
			switch(this.bType){
				case 0:
					//flat : no border
					this.obj.style.border = "0";
					this.obj.style.borderTop = "0";
					this.obj.style.borderLeft = "0";
					this.obj.style.borderBottom = "0";
					this.obj.style.borderRight = "0";
					
					this._clearBorder(this.obj);
					break;
				case 1:
					//frame : normal border (solid)
					this.obj.style.border = "";
					this.obj.style.borderTop = this.bSize + "px solid " + this.bColor;
					this.obj.style.borderLeft = this.bSize + "px solid " + this.bColor;
					this.obj.style.borderBottom = this.bSize + "px solid " + this.bColor;
					this.obj.style.borderRight = this.bSize + "px solid " + this.bColor;
					
					break;
				case 2:
					//border : pressed (inset)
					this._drawPressedBorder(this.obj);
	
					break;
				case 3:
					this._drawReleasedBorder(this.obj);	
					
					break;
				case 4:	
					this.obj.style.borderColor = this.obj.style.borderSize = this.obj.style.borderStyle = "";
					this.obj.style.border = this.bSize + "px double " + this.bColor;
					break;
				case 5:
					//dashed : tratteggiato
					this.obj.style.border = "";
					this.obj.style.borderTop = this.bSize + "px dashed " + this.bColor;
					this.obj.style.borderLeft = this.bSize + "px dashed " + this.bColor;
					this.obj.style.borderBottom = this.bSize + "px dashed " + this.bColor;
					this.obj.style.borderRight = this.bSize + "px dashed " + this.bColor;
					break;
				case 6:
					//dotted : puntini 
					this.obj.style.border = "";
					this.obj.style.borderTop = this.bSize + "px dotted " + this.bColor;
					this.obj.style.borderLeft = this.bSize + "px dotted " + this.bColor;
					this.obj.style.borderBottom = this.bSize + "px dotted " + this.bColor;
					this.obj.style.borderRight = this.bSize + "px dotted " + this.bColor;
					break;
			}
		}
	};
	
	this._drawPressedBorder = function(elm){
		if(elm){
			var tmp_rgb = new jscRGB("" + this.bColor);
			tmp_rgb.lighter(20);
			elm.style.borderBottom="" + this.bSize + "px solid " + tmp_rgb.toHexString();
			elm.style.borderRight="" + this.bSize + "px solid " + tmp_rgb.toHexString();
	
			elm.style.borderTop="" + this.bSize + "px solid " + this.bColor;
			elm.style.borderLeft="" + this.bSize + "px solid " + this.bColor;
		}
	};
	
	this._drawReleasedBorder = function(elm){
		if(elm){
			var tmp_rgb = new jscRGB("" + this.bColor);
			tmp_rgb.lighter(20);
			elm.style.borderBottom="" + this.bSize + "px solid " + this.bColor;
			elm.style.borderRight="" + this.bSize + "px solid " + this.bColor;
	
			elm.style.borderTop="" + this.bSize + "px solid " + tmp_rgb.toHexString();
			elm.style.borderLeft="" + this.bSize + "px solid " + tmp_rgb.toHexString();
		}
	};

	this._clearBorder = function(elm, ifClearMargin){
		if(elm){
			elm.style.border = "0";
			elm.style.borderTop = "0";
			elm.style.borderLeft = "0";
			elm.style.borderBottom = "0";
			elm.style.borderRight = "0";

			if(ifClearMargin){
				elm.style.top = "0px";
				elm.style.left = "0px";
				elm.style.width = "100%";
				elm.style.height = "100%";
			}

		}
	};
	
}


function getIntFromPixelString(val){
	var tmp_px = ("" + val).replace("px","");
	var tmp_px = tmp_px.replace("pt","");
	var int_tmp_px = parseInt("" + tmp_px, 10);
	return int_tmp_px;
	
}




/*
 * Class jscAccessKeyGester
 * @auth: Andrea Raggi
 * @date: 28/10/2008
 * @descr:
 * Class for access key
 *
 * @param: 
*/
var tmp_jscAccessKeyGester = null;
var accessKeyGester = null;

function jscAccessKeyGester(){
	
	//Andrea. Static singletone pattern (only one istance for this class is allowed)
	if(tmp_jscAccessKeyGester!=null)return tmp_jscAccessKeyGester;
	
	this._winEventAdded = false;
	this._allowAccessKeyNoModifiers = true;
	this._accessKeyArr = new Array();
	
	this.isCTRL_PRESSED = false;
	this.isSHIFT_PRESSED = false;
	this.isALT_PRESSED = false;
	
	tmp_jscAccessKeyGester = this;
	
	this.addEventListenerForDocument = function(doc){
		//aggiungo ascoltatore di eventi keydown e keyup sul document passato (o su quello corrente)
		if(!doc)doc = document;
		if(this._winEventAdded==true)return;
		var win = getWindow(doc);
		win.addEvent(doc, 'keydown', function(e) {
			tmp_jscAccessKeyGester.gestKeyDown(e, doc); 
		});
		
		win.addEvent(doc, 'keyup', function(e) {
			tmp_jscAccessKeyGester.gestKeyUp(e, doc);
		})
		
		this._winEventAdded = true;
	};
	
	this.addEventListenerForDocument(document);

	//Dato che la casella di input della combo dhtmlx (DOMElem_input) blocca il propagarsi
	//dell'evento keydown (usando cancelBubble=true) ridefinisco il prototipo di funzione (ascoltatore di eventi)
	//dhtmlx ._onKey per eseguire la vecchia funzione e poi riabilitare l'evento andando 
	//a settare nuovamente cancelBubble=false
	if(typeof dhtmlXCombo.prototype._onKey !="undefined"){
		var old_fn = dhtmlXCombo.prototype._onKey;
		dhtmlXCombo.prototype._onKey = function(e){
			old_fn.apply(this,new Array(e));
		    (e||event).cancelBubble=false;
			return true;
		};
	}
	
	this.gestKeyDown = function(e){
		this.detectSpecKeys(e,true);
	};	
		
	this.gestKeyUp = function(e, doc){
		var win = getWindow(doc);
		//usare win.ev_nomeWin per gli accessKey!
		//cm_debuggaTxt("keyUp ! " + win.ev_nomeWin + " target = " + e.target);
		
		this.detectSpecKeys(e,false);
		var keyCode="";
		if(e)keyCode=getCompatibleKeyCode(e);
		else {
			if (window.event){
				var e = window.event;
				keyCode = getCompatibleKeyCode(e);
			}
		}
		var kc = String.fromCharCode(keyCode);

		for(var i=0;i<this._accessKeyArr.length;i++){
			var akBean = this._accessKeyArr[i];
			if(akBean){
				if(akBean.checkIdWin(win.ev_nomeWin)){
					var tmpModArr = akBean.getModifierArray();

					//Blocco accesskey senza modifiers, se il mio flag è abilitato 
					if((this._allowAccessKeyNoModifiers==false)&&(tmpModArr.length==0))continue;
					else{
						if(akBean.checkAccessKeyCode(keyCode)){
							
							var esitModifiers = 0;
							for(var c=0;c<tmpModArr.length;c++){
								switch(tmpModArr[c]){
									case "ALT":
										if(this.isALT_PRESSED==true)esitModifiers++;
										break;
									case "SHIFT":
										if(this.isSHIFT_PRESSED==true)esitModifiers++;
										break;
									case "CTRL":
										if(this.isCTRL_PRESSED==true)esitModifiers++;
										break;
								}
							}
							if(esitModifiers==tmpModArr.length){
								window.setTimeout(function(){ akBean.doCallToObj(); },10);
								//cancelEvent(e,true);
							}
						}
					}
				}
			}
		}
	};

	this.detectSpecKeys = function(evt, isKeyDown){
		var keyCode="";
		if(evt)keyCode=getCompatibleKeyCode(evt);
		else {
			if (window.event){
				var evnt = window.event;
				keyCode = getCompatibleKeyCode(evnt);
			}
		}
	    if (keyCode == "16"){
			this.isSHIFT_PRESSED = isKeyDown;
		}
		else if (keyCode == "17"){
			this.isCTRL_PRESSED = isKeyDown;
		}
		else if (keyCode == "18"){
			this.isALT_PRESSED = isKeyDown;
		}
	};

	this.blockAccessKeyNoModifiers = function(mode){
		if(mode==true)this._allowAccessKeyNoModifiers=false;
		else this._allowAccessKeyNoModifiers=true;
	};
	
	this.addAccessKey = function(idWin, obj, persFunct, accessKeyString){
		if(typeof accessKeyString=="undefined")return false;
		if(accessKeyString=="")return false;
		var aKey = accessKeyString.split("+");
		if(aKey.length==0)return false;
		
		if(this._accessKeyArr==null)this._accessKeyArr=new Array();
		if(this.existsAccessKey(idWin, persFunct, accessKeyString))return false;
			
		this._accessKeyArr[this._accessKeyArr.length] = new jscAccessKeyBean(idWin, obj, persFunct, accessKeyString);
		return true;
	};
	
	this.existsAccessKey = function(idWin, persFunct, accessKeyString){
		for(var i=0;i<this._accessKeyArr.length;i++){
			if(this._accessKeyArr[i].isEqual(idWin, persFunct, accessKeyString)){
				return true;
			}
		}
		return false;
	};
	
	this.removeAccessKey = function(idWin, obj, persFunct, accessKeyString){
		if(typeof accessKeyString=="undefined")return false;
		if(accessKeyString=="")return false;
		var aKey = accessKeyString.split("+");
		if(aKey.length==0)return false;
		
		if(this._accessKeyArr==null)this._accessKeyArr=new Array();

		for(var i=0;i<this._accessKeyArr.length;i++){
			if(this._accessKeyArr[i].isEqual(idWin, persFunct, accessKeyString)){
				if(this._accessKeyArr.length!=1){
					try{
						this._accessKeyArr.splice(i,1);
					}
					catch(exIgn1){}
				}
				else{
					this._accessKeyArr = new Array();
				}
				return true;
			}
		}
		return false;
	};
}

/*
 * Class jscAccessKeyBean
 * @auth: Andrea Raggi
 * @date: 28/10/2008
 * @descr:
 * Bean for access key 
 *
 * @param: 
 * [obj] obj 			= access key object gester
 * [str] persFunct 		= object function to call 
 * [str] modifier 		= key modifier (ALT / SHIFT / CTRL / or combination ALT+SHIFT) + key to catch
*/
function jscAccessKeyBean(idWin, obj, persFunct, accessKeyString){
	this.idWin = idWin;
	this.obj = obj;
	this.persFunct = persFunct;
	this.accessKeyString = accessKeyString;
	
	var aKey = this.accessKeyString.split("+");
	if(aKey.length==0)return;
	
	
	this.accessKey = "";
	this.modifiers = new Array();
	
	for(var i =0;i < aKey.length; i++){
		var tmp_cmd = aKey[i].toUpperCase();
		if( (tmp_cmd=="ALT")||(tmp_cmd=="CTRL")||(tmp_cmd=="SHIFT") )
			this.modifiers[this.modifiers.length] = tmp_cmd;
		else{
			this.accessKey = tmp_cmd;
			break;
		}
	}
	
	this.getModifierArray = function(){
		return this.modifiers;
	};
	this.getAccessKey = function(){
		return this.accessKey;
	};
	this.checkIdWin = function(val){
		if(this.idWin==val)return true;
		return false;
	};
	
	this.checkAccessKeyCode = function(keyCode){
		//Per ora testo il charCode ma potrei avere esigenza di testare altre cose
		//Esempio ... this.accessKey = "F12" devo testare il keyCode numerico e non il charCode!
		var kc = String.fromCharCode(keyCode);
		if(kc==this.accessKey)return true;
		return false;
	};
	
	this.isEqual = function(idWin, persFunct, accessKeyString){
		if(this.checkIdWin(idWin)){
			if(this.accessKeyString.toUpperCase()==accessKeyString.toUpperCase()){
				if(typeof persFunct=="undefined")return true;
				if(persFunct==this.persFunct)return true;
			}
		}
		return false;
	};
	
	this.doCallToObj = function(){
		if(this.obj){
			if(typeof this.obj[this.persFunct]=="function"){
				this.obj[this.persFunct].apply(this.obj,new Array());
			}
		}
		
	};
	
}


function attivaAccessKeyGester(){
	accessKeyGester = new jscAccessKeyGester();
	//accessKeyGester.addEventListenerForDocument();
}

function appendiNewDocumentToKeyGester(doc){
	if(accessKeyGester!=null)accessKeyGester.addEventListenerForDocument(doc);
}

function addAccessKey(idWin, obj, persFunct, accessKeyString){
	if(accessKeyGester!=null){
		accessKeyGester.addAccessKey(idWin, obj, persFunct, accessKeyString);
	}
}

function removeAccessKey(idWin, obj, persFunct, accessKeyString){
	if(accessKeyGester!=null){
		accessKeyGester.removeAccessKey(idWin, obj, persFunct, accessKeyString);
	}
}

//Funzione che blocca gli accesskey senza modificatori (ALT / SHIFT / CTRL)
//NB AccessKeyGester rende possibile definire degli shortcut per alcuni oggetti anche senza modificatori
//es: accessKey "A" = click on button "Add"
//Se però ci si trova all'interno di un campo di input, occorre impedire che alla pressione del tasto A
//si vada ad attivare l'accessKey relativo!!!
function blockAccessKeyNoModifiers(mode){
	if(accessKeyGester!=null){
		accessKeyGester.blockAccessKeyNoModifiers(mode);
	}
}




function doFormattedCaption(txt, useCase, useShortcut, isMultiRow){
	if(!txt)return "";
	var wrk_txt = txt;
	var wrk_useCase = useCase;
	if(!useCase)wrk_useCase=0;
	
	var wrk_shortCut = useShortcut;
	if(!useShortcut)wrk_shortCut = false;
	
	var wrk_isMultiRow = isMultiRow;
	if(!isMultiRow)wrk_isMultiRow= 0;
	
	if(wrk_shortCut==true){
		var cmShort = ottieniShortCutFromText(wrk_txt);
		//hObj.accessKey = "" + cmShort;
		if(cmShort!=""){
			wrk_txt = wrk_txt.replace("&"+cmShort, "<u>" + cmShort + "</u>");
		}
	}
	
	if(wrk_isMultiRow==1){
		wrk_txt = wrk_txt.replace("\n", "<br>");
	}
	
	if(this.UseCase==1){
		wrk_txt = wrk_txt.toUpperCase();
		wrk_txt = wrk_txt.replace("&NBSP;", "&nbsp;");
	}
	if(this.UseCase==2){
		wrk_txt = wrk_txt.toLowerCase();
	}
	
	return wrk_txt;
}

function ottieniShortCutFromText(txt){
	if(containsString(txt,"&")){
		if(!endsWith(txt, "&")){
			var idx = txt.indexOf("&");
			return txt.substr(idx+1,1);
		}
	}
	return "";
}


function getEx(ex){
	var tmp_txt = "Exception " + ex + " - ( ";
	try{
		for(k in ex){
			tmp_txt = tmp_txt + " " + k + " : " + ex[k] + " - ";
		}
	}
	catch(ex1){
		tmp_txt = tmp_txt + " permessi negati " + ex1;
	}
	tmp_txt = tmp_txt + " ) ";
	return tmp_txt;

	/*
	var tmp_rit = "Exception( " + ex;
	if(typeof(ex.message)!="undefined")tmp_rit = tmp_rit + " - Messaggio : " + ex.message;
	
	if(typeof(ex.line)!="undefined")tmp_rit = tmp_rit + " - Linea : " + ex.line;
	else if(typeof(ex.lineNumber)!="undefined")tmp_rit = tmp_rit + " - Linea : " + ex.lineNumber;

	if(typeof(ex.file)!="undefined")tmp_rit = tmp_rit + " - File : " + ex.file;
	else if(typeof(ex.fileName)!="undefined")tmp_rit = tmp_rit + " - File : " + ex.fileName;
	
	tmp_rit = tmp_rit + ")";
	
	return tmp_rit;
	*/
}


function setCompatibleSelectionText(obj, begin, end){
	if(obj.setSelectionRange){
		obj.focus();
		obj.setSelectionRange(begin,end);
	}else if (obj.createTextRange){
		var range = obj.createTextRange();
		range.collapse(true);
		range.moveEnd('character', end);
		range.moveStart('character', begin);
		range.select();
	}
}
function getCompatibleSelectionText(obj){
	var begin = 0;
	var rit = 0;
	if(obj.setSelectionRange){
		begin = obj.selectionStart;
		end = obj.selectionEnd;
	}else if (document.selection && document.selection.createRange){
		var range = document.selection.createRange();			
		begin = 0 - range.duplicate().moveStart('character', -100000);
		end = begin + range.text.length;
	}
	return {begin:begin,end:end};
}


/*
 * Class jscValidInput
 * @auth: Andrea Raggi
 * @date: 27/03/2009
 * @descr:
 * Class for text input mask validation
 *
 * @param: 
 * [str] idObj 			= input field id
 * [str] allowedChar	= single char allowed
 * [int] maxLen			= maximum Len allowed
 * [fnz] maxLen			= maximum Len allowed
*/
function jscValidInput(idObj, allowedChar, maxLen, interceptEventFunz){
	this.idObj = idObj;
	this.allowedChar = allowedChar;
	this.useRegex="";

	this.allowedCharPaste = allowedChar;
	this.useRegexPaste="";
	
	this.maxLen = maxLen;
	this.maxLenPaste = maxLen;
	this.internal_interceptEventFunz = null;
	if(typeof(interceptEventFunz)!="undefined"){
		if(interceptEventFunz){
			if(interceptEventFunz!="")this.internal_interceptEventFunz = interceptEventFunz;
		}
	}
	this.isSHIFT_PRESSED=false;
	this.isCTRL_PRESSED=false;
	this.isALT_PRESSED=false;
	this.interceptEventFunz = function(elm, tmpType, evt){
		if(typeof this.internal_interceptEventFunz=="function"){
			this.internal_interceptEventFunz(elm,tmpType,evt);
		}
	};
	this._caret = function(obj,begin,end){
		if(obj.length==0) return;
		if(typeof(begin)=='number') {
            		end=(typeof(end)=='number')?end:begin;
			return setCompatibleSelectionText(obj, begin, end);
		}
		else{
			return getCompatibleSelectionText(obj);
		}		
	};
	
	this.setMaxLen = function(val){
		this.maxLen = val;
	};
	this.setMaxLenPaste = function(val){
		this.maxLenPaste = val;
	};
	this.setAllowedChar = function(typeVal){
		this.allowedChar = typeVal;
		this.useRegex="";
	};
	this.setAllowedCharPaste = function(typeVal){
		this.allowedCharPaste = typeVal;
		this.useRegexPaste="";
	};
	
	this.setManualRegex = function(allowedCharVal, useRegexVal){
		this.allowedChar = allowedCharVal;
		this.useRegex = useRegexVal;
	}
	this.setManualRegexPaste = function(allowedCharVal, useRegexVal){
		this.allowedCharPaste = allowedCharVal;
		this.useRegexPaste = useRegexVal;
	}

	this.setRegex = function(typeVal){
		switch(typeVal){
			case 0:
				//Qualsiasi carattere printable
				this.allowedChar="";
				this.useRegex="";
				break;
			case 1:
				//ALFANUMERICO qualsiasi carattere no punct
				this.allowedChar="REGEX";
				this.useRegex="[A-Za-z0-9èéùàòì]";
				break;
			case 2:
				//ALPHA lettere minuscole maiuscole accentate [A-Za-z]  
				this.allowedChar="REGEX";
				this.useRegex="[A-Za-zèéùàòì]";
				break;
			case 3:
				//LOWER minuscole [a-z]
				this.allowedChar="REGEX";
				this.useRegex="[a-zèéùàòì]";
				break;
			case 4:
				//UPPER maiuscole [A-Z] 
				this.allowedChar="REGEX";
				this.useRegex="[A-Z]";
				break;
			case 5:
				//DIGIT solo cifre
				this.allowedChar="REGEX";
				this.useRegex="[0-9]";
				break;
			case 6:
				//XDIGIT cifre esadecimali
				this.allowedChar="REGEX";
				this.useRegex="[0-9A-Fa-f]";
				break;
			case 7:
				//CURRENCY (digit with punct)
				this.allowedChar="0123456789,.+-";
				this.useRegex="";
				break;
			case 7:
				//PUNCT qualsiasi carattere non alfanumerico e non spazio: [^A-Za-z0-9\s]
				this.allowedChar="REGEX";
				this.useRegex="[^A-Za-z0-9èéùàòì\s]";
				break;
		}
	};

	this.cm_detectKeys = function(evt, isKeyDown){
		var keyCode="";
		if(evt)keyCode=getCompatibleKeyCode(evt);
		else {
			if (window.event){
				var evnt = window.event;
				keyCode = getCompatibleKeyCode(evnt);
			}
		}
	    if (keyCode == "16"){
			this.isSHIFT_PRESSED = isKeyDown;
		}
		else if (keyCode == "17"){
			this.isCTRL_PRESSED = isKeyDown;
		}
		else if (keyCode == "18"){
			this.isALT_PRESSED = isKeyDown;
		}
	}

	this._perFnEvt = new Array();
	this._listenerAdded=false;
	
	this._skipEvt = false;
	
	this._clear = function(obj){
		obj.value="";
	}
	this.checkVal_isAllowedKeyCode = function(k){
		if ((k>=41 && k<=122) ||k==32 || k>186)return true;
		else{
			if((k>=33)&&(k<=36)){			
				if( (this.isSHIFT_PRESSED==true)||(this.isALT_PRESSED==true) ){
						return true;
				}
			}
		}
		return false;	
	};
	this.checkVal_isAllowedCharRegex = function(ch){
		var reChar=new RegExp(this.useRegex);
		if(ch.match(reChar)){
			return true;
		}
		return false;
	};
	this.checkVal_isAllowedChar = function(ch){
		if(this.useRegex!="")return this.checkVal_isAllowedCharRegex(ch);
		if(this.allowedChar=="")return true;
		var tmp_arr = (""+this.allowedChar).split("");
		for(var i =0; i < tmp_arr.length; i++){
			if(tmp_arr[i]==ch){
				return true;
			}
		}
		return false;
	};
	this.checkVal_isAllowedCharRegexPaste = function(ch){
		var reChar=new RegExp(this.useRegexPaste);
		if(ch.match(reChar)){
			return true;
		}
		return false;
	};
	this.checkVal_isAllowedCharPaste = function(ch){
		if(this.useRegexPaste!="")return this.checkVal_isAllowedCharRegex(ch);
		if(this.allowedCharPaste=="")return true;
		var tmp_arr = (""+this.allowedCharPaste).split("");
		for(var i =0; i < tmp_arr.length; i++){
			if(tmp_arr[i]==ch){
				return true;
			}
		}
		return false;
	};	
	this.checkVal_keydownEvent = function(obj, evt){
		var k = getCompatibleKeyCode(evt);
		this._PERSSINGLECHARIGNORE=(k < 16 || (k > 16 && k < 32 ) || (k > 32 && k < 41));
						
		if((k>33)&&(k<36)){
			if(this.isSHIFT_PRESSED==true)this._PERSSINGLECHARIGNORE=false;
		}
		
		//backspace and delete get special treatment
		if(k==8){//backspace
		}else if(k==46){//delete
			this._PERSSINGLECHARIGNORE = true;
		}else if (k==27){//escape
			this._PERSSINGLECHARIGNORE = true;
		}
		else if (k==13){
			var tmp_esit = this.interceptEventFunz(obj,0,evt);
			if(tmp_esit==false){
				this._clear(obj);
			}
			return false;
		}
		return true;
	};
	
	this.checkVal_keypressEvent=function(obj, evt){
		if(this._PERSSINGLECHARIGNORE){
			//this._PERSSINGLECHARIGNORE=false;
			//Fixes Mac FF bug on backspace
			//return (getCompatibleKeyCode(evt)==8)? null: null;
			return null;
		}
		evt=evt||window.event;
		var k=evt.charCode||evt.keyCode||evt.which;
						
		if(evt.ctrlKey || evt.altKey){//Ignore
			return true;
		} else if (this.checkVal_isAllowedKeyCode(k)){ //typeable characters
			var keyChar = String.fromCharCode(k);
			var tmp_fnd = this.checkVal_isAllowedChar(keyChar);
			if(tmp_fnd==true){
				 return true;
			}
		}
		return false;
	};
	this.checkVal_onPaste = function(obj){
		try{
			var new_val = obj.value;
			var tmp_arr_src = (""+new_val).split("");
			var tmp_alw_src = new Array();
			for(var i =0; i < tmp_arr_src.length;i++){
				if(this.checkVal_isAllowedCharPaste(tmp_arr_src[i])){
					tmp_alw_src[tmp_alw_src.length] = tmp_arr_src[i];
				}
			}
			var tmp_alw_txt = tmp_alw_src.join("");
			obj.value = tmp_alw_txt;
		}
		catch(ex1Ign){
		}
	};

	this._convertFromCharCode = function(k, charMp){
	};
	
	this._blurEvent = function(elm,evt){
		var tmp_esit = this.interceptEventFunz(elm,2,evt);
		if(tmp_esit===false){
			this._clear(elm);
		}
		return true;
	};

	this._focusEvent = function(elm,evt){
		this.isSHIFT_PRESSED=false;
		this.isCTRL_PRESSED=false;
		this.isALT_PRESSED=false;

		elm._PERSFLAGENTERED = true;
		var tmp_esit = this.interceptEventFunz(elm,3,evt);
		return true;
	};

	this._pasteEvent = function(elm, evt){
		try{				
			if(typeof(this.maxLen)=="undefined")this.maxLen=-1;
			if(typeof(this.maxLenPaste)=="undefined")this.maxLenPaste=this.maxLen;
			if(this.maxLenPaste!=-1){
				var old_val = elm.value;
				var new_val = window.clipboardData.getData("Text");
				var tmp_val = old_val + "" + new_val;
				if( (tmp_val.length+1) > this.maxLenPaste ){
					var diff = this.maxLenPaste - old_val.length;					
					var new_data = new_val.substring(0,diff);
					window.clipboardData.setData('Text', new_data);
					
				}
			}				
		}
		catch(ex1){
			//Se sono qui, probabilmente non è possibile usare window.clipboardData
			//quindi ignoro e richiamo comunque check_eventi_onPaste
			//Settando un timeout per l'esecuzione della funzione, il valore della casella di input sarà aggiornato,
			//e posso testarlo subito, per controllare se il valore della casella supera il maxlength
		}
		var tmp_elm = elm;
		var tmp_evt = evt;
		setTimeout ( function(){ elm._PERSVALIDATOR.check_eventi_onPaste(tmp_elm,tmp_evt);},  8);		
	};
	
	this._inputEvent = function(elm, evt){
		this.check_eventi_onPaste(elm, evt);
	};
	
	this.check_eventi_onPaste = function(elm,evt){
		if(typeof(this.maxLen)=="undefined")this.maxLen=-1;
		if(typeof(this.maxLenPaste)=="undefined")this.maxLenPaste=this.maxLen;
		if(this.maxLenPaste!=-1){
			var tmp_val = ""+elm.value;
			if( (tmp_val.length) > this.maxLenPaste ){
				var new_val = (""+tmp_val).substring(0,this.maxLenPaste-1);
				elm.value = new_val;
				var tmp_esit = this.interceptEventFunz(elm,1,evt);
				if(tmp_esit==false){
					this._clear(elm);
				}
			}
		}	
	
		//Controllo su caratteri ammessi 
		if(typeof(this.allowedChar)=="undefined")this.allowedChar="";
		if(this.allowedChar!=""){
			var esit = this.checkVal_onPaste(elm);
		}	
		
	};
	
	this._keydownEvent = function(elm, evt){
		this._PERSSINGLECHARIGNORE=false;
		this.cm_detectKeys(evt,true);
		var tmp_win = getWindow(elm);
		var tmp_esit = this.interceptEventFunz(elm,4,evt);
		if(tmp_esit===false)return true;

		var k=getCompatibleKeyCode(evt);

		//Controllo su caratteri ammessi (prima di max len) perchè l'ultimo carattere potrebbe non essere valido!
		if(typeof(this.allowedChar)=="undefined")this.allowedChar="";
		if(this.allowedChar!=""){
			var tmp_esit = this.checkVal_keydownEvent(elm, evt);
			if(tmp_esit==false) {
				return false;
			}
		}

		if(!(cm_isSpecialKeyCode(k))){
			if(typeof(this.maxLen)=="undefined")this.maxLen=-1;
			if(this.maxLen!=-1){
				var tmp_val = ""+elm.value;
				if( (tmp_val.length+1) >this.maxLen ){
					var tmp_esit = this.interceptEventFunz(elm, 1,evt);
					if(tmp_esit==false){
						this._clear(elm);
					}
					return false;
				}
			}
		}
			
		this.checkVal_keydownEvent(elm,evt);
		return true;
	};
	
	this._keyupEvent = function(elm, evt){
		this.cm_detectKeys(evt,false);
		var old_ignore = this._PERSSINGLECHARIGNORE;
		var k=evt.charCode||evt.keyCode||evt.which;
		var pos=this._caret(elm);
		var tmp_arr = new Array(evt, pos, old_ignore, k);
		var tmp_esit = this.interceptEventFunz(elm,5,tmp_arr);
		return true;
	};
	
	this._keypressEvent = function(elm, evt){
		var tmp_esit = this.interceptEventFunz(elm,6,evt);
		if(tmp_esit===false)return true;
		var old_ignore = this._PERSSINGLECHARIGNORE;

		var k=evt.charCode||evt.keyCode||evt.which;
		var keyChar = String.fromCharCode(k);
		var pos=this._caret(elm);
		var tmp_arr = new Array(evt, pos, old_ignore, k);

		//Controllo su caratteri ammessi 
		if(typeof(this.allowedChar)=="undefined")this.allowedChar="";
		if(this.allowedChar!=""){
			var tmp_esit = this.checkVal_keypressEvent(elm, evt);
			if(tmp_esit==false) {
				var tmp_esit = this.interceptEventFunz(elm,8,tmp_arr);

				return false;
			}
		}
		elm._PERSFLAGENTERED=false;
		var tmp_esit = this.interceptEventFunz(elm,7,tmp_arr);
		
		return true;
	};
	
	this.applyListener = function(obj){
		if(!obj)obj = document.getElementById(this.idObj);
				
		var tmp_id = obj.id;

		if(!obj._PERSVALIDATOR)obj._PERSVALIDATOR = this;
		
		if(obj._PERSVALIDATOR._listenerAdded==true)return;
		
		var tmp_idx = 0;
		this._perFnEvt[tmp_idx] = new Array("keydown",null);

		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'keydown',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
			
			var esit = tmp_obj._PERSVALIDATOR._keydownEvent(tmp_obj, evt);
			if( esit === false ) {
				cancelEvent(evt, true);
				return false;
			}
			return true;
		});

		tmp_idx++;
		this._perFnEvt[tmp_idx] = new Array("keyup",null);
		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'keyup',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
			
			var esit = tmp_obj._PERSVALIDATOR._keyupEvent(tmp_obj, evt);
			if( esit === false ) {
				cancelEvent(evt, true);
				return false;
			}
			return true;
		});
		
		tmp_idx++;
		this._perFnEvt[tmp_idx] = new Array("keypress",null);
		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'keypress',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
			
			var esit = tmp_obj._PERSVALIDATOR._keypressEvent(tmp_obj, evt);
			if( esit === false ) {
				cancelEvent(evt,true);
				return false;
			}
			return true;
		});

		tmp_idx++;
		this._perFnEvt[tmp_idx] = new Array("focus",null);
		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'focus',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;

			tmp_obj._PERSVALIDATOR._focusEvent(tmp_obj,evt);
		});

		tmp_idx++;
		this._perFnEvt[tmp_idx] = new Array("blur",null);
		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'blur',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;

			tmp_obj._PERSVALIDATOR._blurEvent(tmp_obj,evt);
		});


		//Paste events for IE
		if(wizcommon_browser.msie){
			tmp_idx++;
			this._perFnEvt[tmp_idx] = new Array("paste",null);
			this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'paste',function(evt) {
				var tmp_obj = document.getElementById(tmp_id);
				if(!tmp_obj)return;
				if(!tmp_obj._PERSVALIDATOR)return;
				if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
				
				//setTimeout( function(){tmp_obj._PERSVALIDATOR._checkVal(tmp_obj);},0);
				tmp_obj._PERSVALIDATOR._pasteEvent(tmp_obj, evt);
			});
		}
		else{
			//Paste events for Mozilla
			tmp_idx++;
			this._perFnEvt[tmp_idx] = new Array("input",null);
			this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'input',function(evt) {
				var tmp_obj = document.getElementById(tmp_id);
				if(!tmp_obj)return;
				if(!tmp_obj._PERSVALIDATOR)return;
				if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
				
				//tmp_obj._PERSVALIDATOR._checkVal(tmp_obj);
				tmp_obj._PERSVALIDATOR._inputEvent(tmp_obj, evt);
			});
		}
	};

	this.removeListener = function(obj){
		if(!obj)obj = document.getElementById(this.idObj);
		if(this._perFnEvt){
			for(var i =0;i<this._perFnEvt.length;i++){
				window.removeEvent(obj, this._perFnEvt[i][0], this._perFnEvt[i][1]);
			}
		}
		this._listenerAdded=false;
		obj._PERSVALIDATOR=this;
	};
}		



/*
 * Class jscMaskInput
 * @auth: Andrea Raggi
 * @date: 26/11/2008
 * @descr:
 * Class for text input mask validation
 *
 * @param: 
 * [str] idObj 			= input field id
 * [str] maskFormat		= string mask format
*/
function jscMaskInput(idObj, maskFormat, placeHolder, shiftNumeric, completedMaskFunz){

	this.idObj = idObj;
	this.maskFormat = maskFormat;
	this.placeHolder = "_";
	if(typeof(placeHolder)!="undefined"){
		if(placeHolder){
			if(placeHolder!="")this.placeHolder = placeHolder;
		}
	}
	this.completedMaskFunz = null;
	if(typeof(completedMaskFunz)!="undefined"){
		if(completedMaskFunz){
			if(completedMaskFunz!="")this.completedMaskFunz = completedMaskFunz;
		}
	}
	if(this.completedMaskFunz==null){
		this.completedMaskFunz=function(elm,isTxtObj){
			return true;
		};
	}
	
	this.shiftNumeric=false;
	if(typeof(shiftNumeric)!="undefined"){
		this.shiftNumeric = shiftNumeric;
	}

	this._perFnEvt = new Array();
	this._listenerAdded=false;
	
	this._skipEvt = false;
	
	this._charMap={
		'1':"[0-1]",
		'2':"[0-2]",
		'3':"[0-3]",
		'4':"[0-4]",
		'5':"[0-5]",
		'6':"[0-6]",
		'7':"[0-7]",
		'8':"[0-8]",
		'9':"[0-9]",
		'a':"[A-Za-z]",
		'z':"[A-Za-z]",
		'Z':"[A-Za-z]",
		'*':"[A-Za-z0-9]"
	};
	
	this._isNumeric = function(car){
		var tmp_rex = new RegExp(this._charMap['9']);
		return tmp_rex.test(car);		
	};	
	
	this._map = function( elems, callback ) {
		var ret = [];
		// Go through the array, translating each of the items to their
		// new value (or values).
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			var value = callback( elems[ i ], i );

			if ( value != null )
				ret[ ret.length ] = value;
		}
		return ret.concat.apply( [], ret );
	}

	this._mask = function(){
		this._buffer=new Array(this.maskFormat.length);
		this._locked=new Array(this.maskFormat.length);
		this._valid = false;
		this._ignore = false;
		this._firstNonMaskPos=null; 
	
		var tmp_arrSpl = this.maskFormat.split("");
		for(var i = 0 ; i < tmp_arrSpl.length; i++){
			this._locked[i] = (this._charMap[tmp_arrSpl[i]]==null);
			this._buffer[i]=this._locked[i]?tmp_arrSpl[i]:this.placeHolder;
			if(!this._locked[i] && this._firstNonMaskPos==null){
				this._firstNonMaskPos=i;
			}
		}

		var ret = [];
		for(var i=0, length= tmp_arrSpl.length; i < length; i++ ) {
			var value = this._charMap[tmp_arrSpl[i]]||((/[A-Za-z0-9]/.test(tmp_arrSpl[i])?"":"\\")+tmp_arrSpl[i]);
			if(value!=null)
				ret[ret.length] = value;
		}
		ret = ret.concat.apply([],ret);
		
		this._rex = new RegExp("^"+ret.join('')+"$");

	};

	this._mask();

	this.addPlaceholder  = function(c,r){
		this.charMap[c]=r;
	}
	


	this._caret = function(obj,begin,end){
		if(obj.length==0) return;
		if(typeof(begin)=='number') {
            		end=(typeof(end)=='number')?end:begin;
			return setCompatibleSelectionText(obj, begin, end);
		}
		else{
			return getCompatibleSelectionText(obj);
		}
	};


	
	this._writeBuffer = function(obj){
		obj.value = this._buffer.join('');
		return obj.value;
	};

	this._clearBuffer = function(start,end){
		for(var i=start;i<end&&i<this.maskFormat.length;i++){
			if(!this._locked[i]){
				this._buffer[i]=this.placeHolder;
			}
		}				
	};
			
	this._seekNext = function(pos){
		while(++pos<this.maskFormat.length){
			if(!this._locked[pos]){
				return pos;
			}
		}
		return this.maskFormat.length;
	};


	this._checkVal = function(obj){
		if(!obj)obj = document.getElementById(this.idObj);
		var txt=obj.value;
		var pos=this._firstNonMaskPos;
		
		for(var i=0;i<this.maskFormat.length;i++){
			if(!this._locked[i]){
				this._buffer[i]=this._placeHolder;
				while(pos++<txt.length){
					var reChar=new RegExp(this._charMap[this.maskFormat.charAt(i)]);
					if(txt.charAt(pos-1).match(reChar)){
						this._buffer[i]=txt.charAt(pos-1);
						break;
					}
				}
			}
		}
		var s=this._writeBuffer(obj);
		if(!s.match(this._rex)){
			obj.value = "";
			this._clearBuffer(0,this.maskFormat.length);
			this._valid=false;
		}
		else{
			this._valid=true;
		}
		
	};

	this._focusEvent = function(obj){
		this._checkVal(obj);
		this._writeBuffer(obj);
		var tmp_that = this;
		setTimeout(function(){
			//tmp_that._caret(obj, tmp_that._valid?tmp_that.maskFormat.length:tmp_that._firstNonMaskPos);
			if(tmp_that._valid)tmp_that._caret(obj,0,0);
			else tmp_that._caret(obj,tmp_that._firstNonMaskPos);
		},0);
	};

	this._keydownEvent = function(obj, evt){
		var pos=this._caret(obj);
		var k = getCompatibleKeyCode(evt);
		this._ignore=(k < 16 || (k > 16 && k < 32 ) || (k > 32 && k < 41));
		
		//delete selection before proceeding
		if((pos.begin-pos.end)!=0 && (!this._ignore || k==8 || k==46)){
			this._clearBuffer(pos.begin,pos.end);
		}	
		//backspace and delete get special treatment
		if(k==8){//backspace
			while(pos.begin-->=0){
				if(!this._locked[pos.begin]){
					this._buffer[pos.begin]=this.placeHolder;
					if(wizcommon_browser.opera){
						//Opera won't let you cancel the backspace, so we'll let it backspace over a dummy character.
						var s=this._writeBuffer(obj);
						obj.value = s.substring(0,pos.begin)+" "+s.substring(pos.begin);
						this._caret(obj,pos.begin+1);
					}else{
						this._writeBuffer(obj);
						this._caret(obj, Math.max(this._firstNonMaskPos,pos.begin));
					}
					return false;								
				}
			}						
		}else if(k==46){//delete
			this._clearBuffer(pos.begin,pos.begin+1);
			this._writeBuffer(obj);
			this._caret(obj,Math.max(this._firstNonMaskPos,pos.begin));
			return false;
		}else if (k==27){//escape
			this._clearBuffer(0,this.maskFormat.length);
			this._writeBuffer(obj);
			this._caret(this._firstNonMaskPos);					
			return false;
		}
		else if (k==13){
			var txt = obj.value;
			if(txt.length == this.maskFormat.length && this.completedMaskFunz){
				var s=this._writeBuffer(obj);
				if(s.match(this._rex)){
					var esit = this.completedMaskFunz(obj, true);
					if(esit===false)this._mask();
					return false;
				}
			}
		}
		
	};
	
	this._convertFromCharCode = function(k, charMp){
		var rit = String.fromCharCode(k);
		if(!this._isNumeric(rit)){
			if(charMp=="z")rit = rit.toLowerCase();
			if(charMp=="Z")rit = rit.toUpperCase();
		}
		return rit;
	};
	
	this._keypressEvent = function(obj, evt){
		if(this._ignore){
			this._ignore=false;
			//Fixes Mac FF bug on backspace
			return (getCompatibleKeyCode(evt)==8)? false: null;
		}
		evt=evt||window.event;
		var k=evt.charCode||evt.keyCode||evt.which;
		var pos=this._caret(obj);
						
		if(evt.ctrlKey || evt.altKey){//Ignore
			return true;
		} else if ((k>=41 && k<=122) ||k==32 || k>186){//typeable characters
			var p=this._seekNext(pos.begin-1);					
			if(p<this.maskFormat.length){
				var tmp_rex = new RegExp(this._charMap[this.maskFormat.charAt(p)]);
				if(tmp_rex.test(String.fromCharCode(k))){
					this._buffer[p]=this._convertFromCharCode(k, this.maskFormat.charAt(p));
					this._writeBuffer(obj);
					var tmp_next=this._seekNext(p);
					this._caret(obj, tmp_next);
					if(this.completedMaskFunz && tmp_next == this.maskFormat.length){
						var esit = this.completedMaskFunz(obj, false);
						if(esit===false)this._mask();
					}
				}
				else{
					if(this._isNumeric(String.fromCharCode(k))){
						if(this.shiftNumeric==true){
							this._skipEvt=true;
							try{
								var tmp_k = parseInt(""+String.fromCharCode(k), 10);
								for(var i=p; i < this.maskFormat.length; i++){
									if(!(this._isNumeric(this.maskFormat.charAt(i))) ){
										break;
									}
									var tmp_msk = parseInt(""+this.maskFormat.charAt(i), 10);
									if(tmp_k>tmp_msk){
										this._buffer[i]="0";
										this._writeBuffer(obj);
										var tmp_next=this._seekNext(i);
										this._caret(obj, tmp_next);
										if(this.completedMaskFunz && tmp_next == this.maskFormat.length){
											var esit = this.completedMaskFunz(obj, false);
											if(esit===false)this._mask();
											break;
										}
									}
									else{
										this._buffer[i]=""+tmp_k;
										this._writeBuffer(obj);
										var tmp_next=this._seekNext(i);
										this._caret(obj, tmp_next);
										if(this.completedMaskFunz && tmp_next == this.maskFormat.length){
											var esit = this.completedMaskFunz(obj, false);
											if(esit===false)this._mask();
										}
										break;
									}
								}
							}
							catch(ex1){
								cm_debuggaTxt("ex1 = " + ex1);
							}
							this._skipEvt=false;
						}
					}
				}
			}
		}
		return false;				
	};
	
	this.applyListener = function(obj){
		if(!obj)obj = document.getElementById(this.idObj);
				
		var tmp_id = obj.id;

		this._mask();
		if(!obj._PERSVALIDATOR)obj._PERSVALIDATOR = this;
		
		if(obj._PERSVALIDATOR._listenerAdded==true)return;
		
		var tmp_idx = 0;
		this._perFnEvt[tmp_idx] = new Array("keydown",null);

		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'keydown',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
			
			var esit = tmp_obj._PERSVALIDATOR._keydownEvent(tmp_obj, evt);
			if( esit === false ) {
				cancelEvent(evt, true);
			}
		});
		
		tmp_idx++;
		this._perFnEvt[tmp_idx] = new Array("keypress",null);
		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'keypress',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
			
			var esit = tmp_obj._PERSVALIDATOR._keypressEvent(tmp_obj, evt);
			if( esit === false ) {
				cancelEvent(evt,true);
			}
		});

		tmp_idx++;
		this._perFnEvt[tmp_idx] = new Array("focus",null);
		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'focus',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;

			tmp_obj._PERSVALIDATOR._focusEvent(tmp_obj);
		});

		tmp_idx++;
		this._perFnEvt[tmp_idx] = new Array("blur",null);
		this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'blur',function(evt) {
			var tmp_obj = document.getElementById(tmp_id);
			if(!tmp_obj)return;
			if(!tmp_obj._PERSVALIDATOR)return;
			if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;

			tmp_obj._PERSVALIDATOR._checkVal(tmp_obj);
		});


		//Paste events for IE
		if(wizcommon_browser.msie){
			tmp_idx++;
			this._perFnEvt[tmp_idx] = new Array("paste",null);
			this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'paste',function(evt) {
				var tmp_obj = document.getElementById(tmp_id);
				if(!tmp_obj)return;
				if(!tmp_obj._PERSVALIDATOR)return;
				if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
				
				setTimeout( function(){tmp_obj._PERSVALIDATOR._checkVal(tmp_obj);},0);
			});
		}
		else{
			//Paste events for Mozilla
			tmp_idx++;
			this._perFnEvt[tmp_idx] = new Array("input",null);
			this._perFnEvt[tmp_idx][1] = window.addEvent(obj, 'input',function(evt) {
				var tmp_obj = document.getElementById(tmp_id);
				if(!tmp_obj)return;
				if(!tmp_obj._PERSVALIDATOR)return;
				if(tmp_obj._PERSVALIDATOR._skipEvt==true)return;
				
				tmp_obj._PERSVALIDATOR._checkVal(tmp_obj);
			});
		}
	};

	this.removeListener = function(obj){
		if(!obj)obj = document.getElementById(this.idObj);
		if(this._perFnEvt){
			for(var i =0;i<this._perFnEvt.length;i++){
				window.removeEvent(obj, this._perFnEvt[i][0], this._perFnEvt[i][1]);
			}
		}
		this._listenerAdded=false;
		obj._PERSVALIDATOR=this;
	};
}


function isBisestile(anno){
	if((anno % 4 == 0 && anno%100 != 0) || anno%400 == 0){
		return true;		// ANNO BISESTILE: (divisibile per 4 e non per 100) oppure (divisibile per 400)
	}
	else{
	    return false;		// ANNO NON BISESTILE
	}
}

/*
 * Funzione isDataValida
 * @auth: Andrea Raggi
 * @date: 27/11/2008
 * @descr:
 * La funzione si occupa di validare una data passata
 *
 * @param: 
 * - [str] valore   		- data da validare
 * - [str] sep				- eventuale separatore della data
 * - [int] mustLen 			- lunghezza della data prevista (6 0 8) 
 *
 * @returns:
 *	- [int] returnCode 		- 0 = valore ok
 *							  1 = valore vuoto o invalido
 *							  2 = giorno invalido
 *							  3 = giorno invalido rispetto al mese (o anno)
 *							  4 = mese invalido
 */

function isDataValida(valore, sep, mustLen){
	
	if(typeof(sep)=="undefined")sep = "/";
	if(typeof(mustLen)=="undefined")mustLen = 8;
	
	//Rimpiazzo temporaneamente il separatore
	var new_val = ""+valore;
	if(containsString(new_val, sep)){
		var vsep="/" + sep + "/g";
		var rexSep=new RegExp(sep,"g");
		new_val = new_val.replace(rexSep,"");		
	}
	
	var lun = new_val.length;
	if(lun==0 || trim(""+new_val)=="") return 1;
	// CONTROLLO SE LA LUNGHEZZA DELLA DATA E' ERRATA
	
	if(lun!=mustLen){
		return 1;
	}
	
	// DATA DI LUNGHEZZA 8 QUINDI DEVO RIELABORARE LA DATA PER CONVERTIRE L'ANNO 
	// IN ANNO DA 4 ANZICHE' DA 2 CARATTERI
	if(lun==6){
		var fino_ad_anno = new_val.substring(0,5);  // parte della data fino al mese + separatore
		var anno = new_val.substring(6,8);	      // leggo l'anno (ora è da 2)
		if (anno <= 50){
			fino_ad_anno = fino_ad_anno + 20;       // se l'anno è minore< di 50 suppongo che si tratti di anno 2000
		}
		else {
		    fino_ad_anno = fino_ad_anno + 19;       // se l'anno è maggiore di 50 suppongo che si tratti di anno 1900
		}
		fino_ad_anno = fino_ad_anno + anno;         // concateno l'anno alla prima parte della data
		new_val = fino_ad_anno;              // riassegno il valore all'oggetto data
	}
	
	//------------------------------------------------------------------------
	// CONTROLLO SE L'ANNO E' BISESTILE
	//------------------------------------------------------------------------
	var gg = parseInt(""+new_val.substr(0,2),10); // giorno
	var mm = parseInt(""+new_val.substr(2,2),10); // mese
	var anno = new_val.substr(4,4);		  		 // anno

	var array_giorni = new Array(" ",31,28,31,30,31,30,31,31,30,31,30,31);
	if(isBisestile(anno))array_giorni[2] = 29;	  // se l'anno è bisestile al secondo mese assegno 29 giorni
	//------------------------------------------------------------------------
	// CONTROLLO VALIDITA' GIORNO GENERICA
	//------------------------------------------------------------------------
	if(gg>31){
		return 2;
	}
	//------------------------------------------------------------------------
	// CONTROLLO VALIDITA' GIORNO RISPETTO AL MESE
	//------------------------------------------------------------------------
	if(array_giorni[mm]){
		if (gg > array_giorni[mm]){
	    	return 3;
		}
	}
	//------------------------------------------------------------------------
	// CONTROLLO VALIDITA' MESE
	//------------------------------------------------------------------------
	if (mm > 12){
		return 4;
	}	
	
	//------------------------------------------------------------------------
	// CONTROLLO VALIDITA' ANNO
	//------------------------------------------------------------------------
	if(anno==0){
		return 5;
	}

	return 0;
}



/*
 * Funzione isOraValida24
 * @auth: Andrea Raggi
 * @date: 27/11/2008
 * @descr:
 * La funzione si occupa di validare un orario passato in formato 24h
 *
 * @param: 
 * - [str] valore   		- ora da validare
 *
 * @returns:
 *	- [int] returnCode 		- 0 = valore ok
 *							  1 = valore vuoto o invalido
 *							  2 = ora invalida
 */

function isOraValida24(valore, sep){
	
	if(typeof(sep)=="undefined")sep = ":";
	
	if(containsString(valore, sep)){
		var vsep="/" + sep + "/g";
		var rexSep=new RegExp(sep,"g");
		valore = valore.replace(rexSep,"");		
	}
	
	var lun = valore.length;
	if(lun==0 || trim(""+valore)=="") return 1;
	// CONTROLLO SE LA LUNGHEZZA DELLA DATA E' ERRATA
	
	if(lun!= 4){
		return 1;
	}

	
	//------------------------------------------------------------------------
	// CONTROLLO SE L'ANNO E' BISESTILE
	//------------------------------------------------------------------------
	var hh = parseInt(""+valore.substr(0,2),10); // ora
	var mm = parseInt(""+valore.substr(2,2),10); //minuti

	//------------------------------------------------------------------------
	// CONTROLLO VALIDITA' GIORNO GENERICA
	//------------------------------------------------------------------------
	if(hh>24){
		return 2;
	}

	return 0;
}


// FUNZIONI PER I COOKIE
function wiz_setCookie(cookie_name, cookie_value, lifespan_in_days, valid_path, valid_domain, doc){
	if(!doc)doc = document;
	var domain_string = valid_domain ? ("; domain=" + valid_domain) : "" ;
	var path_string = valid_path ? ("; path=" + valid_path) : "; path=/" ;
	var lifespan_string = lifespan_in_days? ("; max-age=" + (60*60*24*lifespan_in_days)) : "" ;

	var tmp_str1 = lifespan_string +  path_string +  domain_string;
	var tmp_len1 = tmp_str1.length;
	//"4,096"
	var tmp_str2 = cookie_name + "=" + encodeURIComponent(cookie_value);
	var tmp_len2 = tmp_str2.length;

	var tmp_tot = tmp_len2+tmp_len1;

	if(tmp_tot>4096){
		try{
			eval( ' throw "wiz_setCookie: Cookie length exceed 4Kb! [ ' + tmp_str2 + tmp_str1 + '];' ) ;
		}
		catch(exIgn){}
	}
	
    doc.cookie = cookie_name + "=" + encodeURIComponent( cookie_value ) +
                       lifespan_string + 
                       path_string + 
                       domain_string;
}

function wiz_getCookie(cookie_name, doc){
	if(!doc)doc = document;
    var cookie_string = doc.cookie;
    if(cookie_string.length != 0){
    	var tmp_search = cookie_name + "=";
		var offset = doc.cookie.indexOf(tmp_search);
		if (offset != -1) {
			offset += tmp_search.length;
			var end = doc.cookie.indexOf(";", offset);
			if (end == -1){
				end = doc.cookie.length;
			}
			return decodeURIComponent(doc.cookie.substring(offset, end)) ;
		}
    }
    return '' ;
}

function wiz_deleteCookie(cookie_name, valid_path, valid_domain, doc){
	if(!doc)doc = document;
    var domain_string = valid_domain ? ("; domain=" + valid_domain) : '' ;
	var path_string = valid_path ? ("; path=" + valid_path) : "; path=/" ;
    doc.cookie = cookie_name + "=; max-age=0" + path_string + domain_string ;
}


/*
 * Class jscCookieGester
 * @auth: Andrea Raggi
 * @date: 02/12/2008
 * @descr:
 * Bean for cookie gestion
 *
 * @param: 
 * [str]  idCookie 		= generic idOfCookie
 * [str]  vDomain		= domain for the url
 * [str]  vPath			= path string for the url (optional, default = "/";
 * [bool] autoLoad		= if load now (optional, default = false;
 * [str]  sepParam		= separator for param (optional, default = "|")
*/
function jscCookieGester(idCookie, vDomain, vPath, autoLoad, sepParam){
	
	this.idCookie = idCookie;
	
	this.sepParam = sepParam;
	if( (typeof(sepParam=="undefined")) || (sepParam=="") ) {
		this.sepParam = "|";
	}
	this.vDomain = vDomain;
	if( (typeof(vDomain=="undefined")) || (vDomain=="") ) {
		this.vDomain = getHostFromUrl(""+window.location);
	}
	this.vPath = vPath;
	if( (typeof(vPath=="undefined")) || (vPath=="") ) {
		this.vPath = "/";
	}
	
	this.cookieArr = new Array();
	this.temp_cookieArr = new Array();
	
	
	this.saveCookie = function(doc, lifespan_in_days){
		if(!doc)doc=document;
		
		var tmp_str_val = "";
		if(this.cookieArr){
			for(var i =0;i < this.cookieArr.length; i++){
				tmp_str_val = tmp_str_val + this.cookieArr[i].value;
				if(i<(this.cookieArr.length-1)){
					tmp_str_val = tmp_str_val + this.sepParam;
				}
			}
		}
			
		try{
			wiz_setCookie(this.idCookie, tmp_str_val, lifespan_in_days, this.vPath, this.vDomain, doc);
		}
		catch(ex1){
			cm_debuggaTxt("Errore in jscCookieGester(" + this.idCookie + ").saveCookie  = " + getEx(ex1));
		}
	};
	
	this.loadCookie = function(doc){
		if(!doc)doc=document;
		var tmp_str = "";
		//this.cookieArr = new Array();
		var tmp_search = this.idCookie + "=";
		try{
			tmp_str =  wiz_getCookie(this.idCookie, doc);
			
			if(tmp_str!=""){
				var tmp_cookieArr = tmp_str.split(this.sepParam);
				for(var i=0; i < tmp_cookieArr.length; i++){
					if(this.cookieArr[i]){
						this.cookieArr[i].value = tmp_cookieArr[i];
					}
					else{
						this.cookieArr[i] = {};
						this.cookieArr[i].name = "";
						this.cookieArr[i].value = tmp_cookieArr[i];
					}
				}
			}
		}
		catch(ex1){
			cm_debuggaTxt("Errore in jscCookieGester(" + this.idCookie + ").loadCookie  = " + getEx(ex1));
		}
	};
	
	
	this.clearCookieSaved = function(doc){
		this.cookieArr = new Array();
		
		for(i=0;i<this.temp_cookieArr.length;i++)this.temp_cookieArr[i].value = "";
		
		wiz_deleteCookie(this.idCookie, this.vPath, this.vDomain, doc);
		
		this.cookieArr = getClonedArray(this.temp_cookieArr);
		
		//this.saveCookie(doc);
	};

	
	this.registerParam = function(paramName){
		if(this.temp_cookieArr==null)this.temp_cookieArr = new Array();
		var tmp_idx = this.getIdxFromParamName(paramName, this.temp_cookieArr);
		this.temp_cookieArr[tmp_idx] = {};
		this.temp_cookieArr[tmp_idx].name = paramName;
		this.temp_cookieArr[tmp_idx].value = "";
		
		this.sortParam();
		this.cookieArr = getClonedArray(this.temp_cookieArr);
	}
	
	this.sortParam = function(){
		var sortableCollector = new jscSortableCollector("str", "asc");
	   	for(var i = 0;i < this.temp_cookieArr.length;i++){
			sortableCollector.addItem(this.temp_cookieArr[i]);
	   	}	   	
	   	sortableCollector.sortBy("name");
	   	
	   	this.temp_cookieArr = new Array();
   		for(var i =0; i < sortableCollector._arrObj.length; i++){
			this.temp_cookieArr[i] = sortableCollector.elementAtToArray(i);
   		}
	}
	
	this.setParam = function(paramName, paramValue, lifespan, doc){
		var tmp_i = this.getIdxFromParamName(paramName,  this.cookieArr);
		this.cookieArr[tmp_i] = {};
		this.cookieArr[tmp_i].name = paramName;
		this.cookieArr[tmp_i].value = paramValue;
		this.saveCookie(doc, lifespan);
	};

	this.getParam = function(paramName, doc){
		var tmp_i = this.getIdxFromParamName(paramName, this.cookieArr);
		if(this.cookieArr[tmp_i]){
			if(this.cookieArr[tmp_i].name==paramName){
				return this.cookieArr[tmp_i].value;
			}
		}
		return "";
	};
	
	this.getIdxFromParamName = function(paramName, tmpArr){
		if(!tmpArr)tmpArr=this.cookieArr;
		for(var i=0; i < tmpArr.length; i++){
			if(tmpArr[i].name==paramName)return i;
		}
		return tmpArr.length;
	};

	
	if(typeof(autoLoad)!="undefined"){
		if(autoLoad)this.loadCookie();
	}
}


// FUNZIONI SUGLI URL
function getQueryStringFromUrl(url){
	var tmp_rit = "";
	if(url.indexOf('?')>=0){
		tmp_rit = url.substring(url.indexOf('?')+1);
		if(tmp_rit.indexOf('#')>=0)tmp_rit = tmp_rit.substring(0,tmp_rit.indexOf('#'));
	}
	return tmp_rit;
}

function getPathFromUrl(url){
	var tmp_rit = "";
	var idx_protocolSep=url.indexOf('://');
	if(idx_protocolSep>=0){
		tmp_rit=url.substring(idx_protocolSep+3);
		tmp_rit=tmp_rit.substring(tmp_rit.indexOf('/'));
	}
	else tmp_rit = url;
	
	if(tmp_rit.indexOf('?')>=0) tmp_rit=tmp_rit.substring(0, tmp_rit.indexOf('?'));
	
	if(tmp_rit.indexOf('#')>=0) tmp_rit=tmp_rit.substring(0,idx_refSep);
	
	return tmp_rit;
}

function getDirnameFromUrl(url){
	var tmp_rit = getPathFromUrl(url);
	return tmp_rit.replace(/\\/g,'/').replace(/\/[^\/]*\/?$/, '');
}

function getReferenceFromUrl(url){
	var tmp_rit = "";
	if(url.indexOf('#')>=0)tmp_rit=url.substring(url.indexOf('#'));
	return tmp_rit;
	
}

function getProcotolFromUrl(url){
	var tmp_rit = "";
	var idx_protocolSep=url.indexOf('://');
	if(idx_protocolSep>=0){
		tmp_rit=url.substring(0,idx_protocolSep).toLowerCase();
	}
	return tmp_rit
}

function getHostFromUrl(url){
	var tmp_rit = "";
	var idx_protocolSep=url.indexOf('://');
	if(idx_protocolSep>=0){
		tmp_rit=url.substring(idx_protocolSep+3);
		
		if(tmp_rit.indexOf('/')>=0) tmp_rit=tmp_rit.substring(0,tmp_rit.indexOf('/'));

		//elimino credenziali (username e password)
		if(tmp_rit.indexOf('@')>=0) tmp_rit=tmp_rit.substring(tmp_rit.indexOf('@')+1);

		//elimino eventuale porta
		if(tmp_rit.indexOf(':')>=0)tmp_rit=tmp_rit.substring(0,tmp_rit.indexOf(':'));
	}	
	
	return tmp_rit;
}

function getPortFromUrl(url){
	var tmp_rit = "80";
	var idx_protocolSep=url.indexOf('://');
	if(idx_protocolSep>=0){
		var tmp_h=url.substring(idx_protocolSep+3);
		
		if(tmp_h.indexOf('/')>=0) tmp_h=tmp_h.substring(0,tmp_h.indexOf('/'));

		//elimino credenziali (username e password)
		if(tmp_h.indexOf('@')>=0) tmp_h=tmp_h.substring(tmp_h.indexOf('@')+1);

		//elimino eventuale porta
		if(tmp_h.indexOf(':')>=0)tmp_rit=tmp_h.substring(tmp_h.indexOf(':'));
	}	
	return tmp_rit;
}


function getFileFromUrl(url){
	var tmp_rit = getPathFromUrl(url);
	var tmp_q = getQueryStringFromUrl(url);
	if(tmp_q.length>0)tmp_rit+='?'+tmp_q;
	
	var tmp_f = getReferenceFromUrl(url);
	if(tmp_f>0)tmp_rit+='#'+tmp_f;

	
    tmp_rit = tmp_rit.replace(/^.*[\/\\]/g, '');   
    
	return tmp_rit;
}

function getArgumentValuesFromUrl(url){
	var tmp_q = getQueryStringFromUrl(url);
	
	var tmp_rit=new Array();
	var comodo_arr1=tmp_q('&amp;');
	var tmp_str='';
	if(comodo_arr1.length<1) return tmp_rit;
	for(i=0;i<comodo_arr1.length;i++){
		tmp_str=comodo_arr1[i].split('=');
		tmp_rit[i]=new Array(tmp_str[0],((tmp_str.length==1)?tmp_str[0]:tmp_str[1]));
	}
	return tmp_rit;
}

function getArgumentValueFromUrl(url, keyArg){
	
	var tmp_arr=getArgumentValues(url);
	if(tmp_arr.length<1) return '';
	for(i=0;i<tmp_arr.length;i++){
		if(tmp_arr[i][0]==keyArg) return tmp_rit[i][1];
	}
	return '';
}



/*
 * Class jscRect
 * @auth: Andrea Raggi
 * @date: 26/11/2008
 * @descr:
 * Class for rectangle object
 *
 * @param: 
 * [int] x 			= x point
 * [int] y			= y point
 * [int] width 	    = width of rect
 * [int] height		= height of rect
*/
function jscRect(x, y, width, height){
	this.x = x;
	this.y = y;
	this.width = width;
	this.height = height;
	
	this.containsPoint = function(x1, y1){
 		var w = this.width;
		var h = this.height;
		if( (w<0)||(h<0) )return false;
		var x = this.x;
		var y = this.y;
		if((x1 < x) || (y1 < y) ){
			return false;
		}
		w += x;
		h += y;
		return ((w < x || w > x1) && (h < y || h > y1));
	};

	this.containsRect = function(objRect){
		return this.containsRectangle(objRect.x, objRect.y, objRect.width, objRect.height);
	};
	this.containsRectangle = function(x1,y1,w1,h1){
		var w = this.width;
		var h = this.height;
		if( (w<0)||(h<0) )return false;
		if( (w1<0)||(h1<0) )return false;
		
		var x = this.x;
		var y = this.y;
		if ( (x1 < x) || (y1 < y) )return false;
		w += x;
		w1 += x1;
		if (w1 <= x1) {
			if((w >= x) || (w1 > w)) return false;
		} else {
			if ( (w >= x) && (w1 > w) ) return false;
		}
		h += y;
		h1 += y1;
		if (h1 <= y1) {
			if ( (h >= y) || (h1 > h) ) return false;
		} else {
		    if ( (h >= y) && (h1 > h) ) return false;
		}
		return true;	
	};
	
	
	this.intersectRect = function(objRect){
		return this.intersectRectangle(objRect.x, objRect.y, objRect.width, objRect.height);
	};
	
	this.intersectRectangle = function(x1,y1,w1,h1){
		var tw = this.width;
		var th = this.height;
		var rw = w1;
		var rh = h1;
		if ( (rw<=0) || (rh<=0) || (tw<=0) || (th<=0) ) return false;

		var tx = this.x;
		var ty = this.y;
		var rx = x1;
		var ry = y1;
		rw += rx;
		rh += ry;
		tw += tx;
		th += ty;
		
		return( ((rw < rx) || (rw > tx)) &&
			((rh < ry) || (rh > ty)) &&
			((tw < tx) || (tw > rx)) &&
			((th < ty) || (th > ry)) );
	};
};

function rectsOverLap(x0, y0, w0, h0, x2, y2, w2, h2) {
	return !((x0 > (x2 + w2)) || ((x0 + w0) < x2) || (y0 > (y2 + h2)) || ((y0 + h0) < y2));
}


function strpos( haystack, needle, offset){
    var i = (haystack+'').indexOf( needle, offset ); 
    return i===-1 ? false : i;
}

