/* *********************************************************************************************** */

// Oggetto per interazioni MEAjax

function getMEAjaxObj(){
    var MEAjax = new Object(); 
    MEAjax.isUpdating = true;
    
    
    MEAjax.Request = function(method, url, callback) 
    {
	this.url = url;
	this.sendData = url;
	this.isUpdating = true; 
	this.callbackMethod = callback; 
	this.request = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("MSXML2.XMLHTTP");
	
	this.request.onreadystatechange = function() { MEAjax.checkReadyState(); }; 
	if (method == "POST"){
	    var nPos = url.search(/\?/);
	    this.sendData = "";
	    if (nPos >= 0) {
    	    this.url = url.substr(0, nPos);
    	    this.sendData = url.substr(nPos + 1);
	    
	    }

        //alert("ORIGINAL URL: " + url + "\nURL:" + this.url + "\nDATA: " + this.sendData + "\nLENGTH: " + this.sendData.length);

	    this.request.open(method, this.url, true);
	    this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
	    this.request.setRequestHeader("Content-length",this.sendData.length);
	    this.request.setRequestHeader("Connection","close");
	}else{
	    this.request.open(method, this.url, true);
	}
	this.request.send(this.sendData); 
    }
    
    
    MEAjax.checkReadyState = function(_id){ 
	switch(this.request.readyState) 
	{ 
	    case 1: break; 
	    case 2: break; 
	    case 3: break; 
	    case 4: 
		this.isUpdating = false; 
		this.callbackMethod(this.request); 
	} 
    }
    
    MEAjax.updateHTML = function(method, url, idElement){
	this.url = url;
	this.sendData = url;
	this.isUpdating = true; 
	this.callbackMethod = function(doc){document.getElementById(idElement).innerHTML = doc.responseText}; 
	this.request = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("MSXML2.XMLHTTP");
	
	this.request.onreadystatechange = function() { MEAjax.checkReadyState(); }; 
	if (method == "POST"){
	    var nPos = url.search(/\?/);
	    this.sendData = "";
	    if (nPos >= 0) {
    	    this.url = url.substr(0, nPos);
    	    this.sendData = url.substr(nPos + 1);
	    }

        //alert("ORIGINAL URL: " + url + "\nURL:" + this.url + "\nDATA: " + this.sendData + "\nLENGTH: " + this.sendData.length);

	    this.request.open(method, this.url, true);
	    this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
	    this.request.setRequestHeader("Content-length",this.sendData.length);
	    this.request.setRequestHeader("Connection","close");
	}else{
	    this.request.open(method, this.url, true);
	}
	this.request.send(this.sendData); 
    }
    return MEAjax;
}
/* *********************************************************************************************** */

/*
	@obj oggetto dom
	@ev quale avento registrare (click,mouseover,mouseout....)
	@fn handler a funzione da eseguire al catch dell'evento
	@captureMethod true=capturingEventMethod, false bubblingEventMethos
*/
function addEvent(obj,ev,fn,captureMethod){
	
	if (typeof obj=="undefined" || !obj)
		return;
		
	try{
		removeEvent(obj,ev,fn);
	}catch(e){
		//no event to remove
	}
	
	if (typeof captureMethod == "undefined")
		captureMethod = false;
	
	if(obj.addEventListener){
		// metodo w3c
		obj.addEventListener(ev, fn, captureMethod);	
	} else if(obj.attachEvent) {
		// metodo IE
		obj.attachEvent('on'+ev, fn);
	} else {
		// se i suddetti metodi non sono applicabili
		// se esiste gia' una funzione richiamata da quel gestore evento
		if(typeof(obj['on'+ev])=='function'){
			// salvo in variabile la funzione gia' associata al gestore
			var f=obj['on'+ev];
			// setto per quel gestore una nuova funzione 
			// che comprende la vecchia e la nuova
			obj['on'+ev]=function(){if(f)f();fn()}
		}
		// altrimenti setto la funzione per il gestore
		else obj['on'+ev]=fn;
	}
}

function removeEvent(obj,ev,fn,captureMethod){
	if (typeof captureMethod == "undefined")
		captureMethod = false;
  if(obj.removeEventListener)
	obj.removeEventListener(ev,fn,captureMethod);
  else if(obj.detachEvent){
    obj.detachEvent('on'+ev,fn);
    obj['on'+ev]=null;
    obj['on'+ev]=null;
  }
}

/* *********************************************************************************************** */
//ricerca elementi in base alla classe

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|.*[\\s]+)"+searchClass+"([\\s]+.*|$)");
	for (var i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}

	return classElements;
}



/*
	restituisce un array di elementi che coincidono con il prametro tagl contenuti nel nodo node
*/
function _getElementsByTagName(tag,node) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	
	return els;
}

/* *********************************************************************************************** */

/*
function hide(el){
    el.style.display='none';
}
function show(el){
    el.style.display='block';
}
*/

function hideClass(className){
	var els = getElementsByClass(className);
	for (i=0;i<els.length;i++)
		els[i].style.display = "none";
}
function showClass(className){
	var els = getElementsByClass(className);
	for (i=0;i<els.length;i++)
		els[i].style.display = "";
}
/* ********************************************************************************************** */

// elimina spazi prima e dopo di una stringa

function trim(stringa){
	if (typeof stringa != "number" && typeof stringa != "object")
		return stringa.replace(/^\s*/, '').replace(/\s*$/, '');
	else
		return stringa;
}

function trim2(stringa,symbol){
	
	if (typeof stringa == "number" || typeof stringa == "object")
		return stringa;

	if (!!symbol){
		if (typeof symbol == "string"){
			return stringa.replace("/^"+symbol+"*/", '').replace("/"+symbol+"*$/", '');		
		}
		else
		if (typeof symbol[0] != "undefined"){
			for (var i=0;i<symbol.length;i++)
				return_string =  stringa.replace("/^"+symbol[i]+"*/", '').replace("/"+symbol[i]+"*$/", '');
			return return_string;
		}
	}
	
	return stringa.replace(/^\s*/, '').replace(/\s*$/, '');
}

/* ********************************************************************************************** */

function evidenzia(img,valore){
	img.style.opacity = valore/10;
	img.style.filter = 'alpha(opacity=' + valore*10 + ')';
}


function showAlertTip(message,type,closeAfter,top){
	
	if (typeof message=="undefined" || message == ''){
		if (typeof _msg_tip!="undefined")
			_msg_tip.parentNode.removeChild(_msg_tip);
		return;
	}
	if (typeof top!="undefined")
		top = parseInt(top) + "px";
	else
		top = "10px";
	if (typeof type== "undefined"){
		type = "info";
	}
	
	if (typeof _msg_tip == "undefined"){
		_msg_tip = document.createElement("div");
		_msg_tip.className = "top_message_tip";
	}
	switch (type){
		case "error":
			_msg_tip.style.backgroundColor="red";
			//_msg_tip.style.backgroundImage="url(/img2/transparent_red.png)";
			break;
		
		default:
			_msg_tip.style.backgroundColor="green";
			//_msg_tip.style.backgroundImage="url(/img2/transparent_green.png)";
	
			break;
	}
	
	if (typeof _msg_tip_timer!="undefined")
		clearTimeout(_msg_tip_timer);
	
	_msg_tip.style.padding="10px 10px 10px 10px";
	_msg_tip.style.color="#FFF";
	_msg_tip.style.position="fixed";
	_msg_tip.style.top=top;
	
	_msg_tip.style.zIndex="999";
	_msg_tip.style.border="2px solid #AEAEAE";
	_msg_tip.innerHTML=message;
	_msg_tip.visibility="hidden";
	
	_msg_tip.style.fontWeight="bold";
	_msg_tip.style.fontSize="15px";
	_msg_tip.style.textAlign = "center";
	document.body.appendChild(_msg_tip);
	
	var sWidth = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth;
	var tWidth = MEgetWidth(_msg_tip);
	
	
	_msg_tip.style.left= sWidth/2 - tWidth/2 - 4 + "px";
	
	MEfadeIn(_msg_tip);
	if (typeof closeAfter=="undefined" || !closeAfter){
		closeAfter = 5000;
	}
	if (closeAfter)		
		_msg_tip_timer = setTimeout(function(){MEfadeOut(_msg_tip)},closeAfter);

}


function popUp(url){
	window.open(url,'','toolbar=no,scrollbars=1');
}

function popup(page,title,width,height){
var win=null;
var winl='';
var wint='';

if (width)
	winl = (screen.width-width)/2;
if (height)
	wint = (screen.height-height)/2;

 params = "toolbar=0,";

params += "location=0,";

params += "directories=0,";

params += "status=0,";

params += "menubar=0,";

params += "titlebar=0,";

params += "scrollbars=1,";

params += "resizable=0,";

params += "top="+wint+",";

params += "left="+winl+",";

params += "width="+width+",";

params += "height="+height;
win=window.open(page,title,params);
return win;
}


function callMEAjax(url,params,idtarget){
    var myMEAjax = new MEAjax.Request(url,
            {
             method: 'post',
             parameters:params,
             onSuccess: function(response){
              var html = response.responseText;
		
              $('mailRes').update(html).show();

             },
             onFailure: function(){
        //        alert('Si è verificato un errore, la preghiamo di riprovare');
             }
            });
}


function qsFromForm(form)
{
    
    var params = "";
    var length = form.elements.length
    for( var i = 0; i < length; i++ )
    {
	
	if (i==0)
	    parSep = "?";
	else
	    parSep = "&";
        element = form.elements[i];
	
	if (!element.name)
		continue;
	
	if(element.tagName.toLowerCase() == 'textarea' )
        {
                params+=parSep+element.name+"="+Url.encode(element.value);
		
        }
        else if( element.tagName.toLowerCase() == 'input' )
        {
                if( element.type == 'text' || element.type == 'hidden' || element.type == 'password')
                {
                        params+=parSep+element.name+"="+Url.encode(element.value);
                }
                else if( element.type == 'radio' && element.checked )
                {
                        if( !element.value )
                                params+=parSep+element.name+"="+"on";
                        else
                                params+=parSep+element.name+"="+Url.encode(element.value);

                }
                else if( element.type == 'checkbox' )
                {
                        if(element.checked)
                            params+=parSep+element.name+"="+Url.encode(element.value);
						//else
						//    params+=element.name+"="+"";
                        
                }
		
        }else if (element.tagName.toLowerCase()=="select"){
	    if(element.type=="select-one"){
		if (element.selectedIndex>=0)
		    params += parSep+element.name+"="+Url.encode(element.options[element.selectedIndex].value);
	    }
	}
    }
    return params;

}

function emptyForm(form)
{
    var length = form.elements.length
    for( var i = 0; i < length; i++ )
    {
	
    element = form.elements[i]
	if(element.tagName.toLowerCase() == 'textarea' )
        {
                element.innerHTML = "";
        }
        else if( element.tagName.toLowerCase() == 'input' )
        {
                if( element.type == 'text' || element.type == 'hidden' || element.type == 'password')
                {
                        element.value = "";
                }
                else if( element.type == 'radio' && element.checked )
                {
                        element.checked = false;

                }
                else if( element.type == 'checkbox' )
                {
                        element.checked = false;
                }
		
        }else if (element.tagName.toLowerCase()=="select"){
	    if(element.type=="select-one"){
			element.value = "";
		    element.selectedIndex = 0;
		}
	}
    }
    return true;

}


function emptyField(element)
{
	if (!element)
		throw("missing required parameter for function emptyField");
	if(element.tagName.toLowerCase() == 'textarea' )
        {
                element.innerHTML = "";
		
        }
        else if( element.tagName.toLowerCase() == 'input' )
        {
                if( element.type == 'text' || element.type == 'hidden' || element.type == 'password')
                {
                        element.value = "";
                }
                else if( element.type == 'radio' && element.checked )
                {
                        element.checked = false;

                }
                else if( element.type == 'checkbox' )
                {
                        element.checked = false;
                }
		
        }else if (element.tagName.toLowerCase()=="select"){
	    if(element.type=="select-one"){
			element.value = "";
		    element.selectedIndex = 0;
		}
	}
    
    return true;

}


function checkUrl(url) {
	
	var urlRegEx = /^(http(s)?:\/\/)([a-z0-9-]+)(\.[a-z0-9-]+)*(\:[0-9]+)*(\/.*)?$/ig;
	url = url.toLowerCase();
	if (!url.match(urlRegEx)) return false
	 else return true					
}

function checkEmail(email) {

//var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

var emailRegEx = /^[a-z0-9!#$%&'*+=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/ig;
email = email.toLowerCase();
if (!email.match(emailRegEx)) return false
 else return true					
}
//definisco un alias per la funzione di verifica email
isEmail = checkEmail;

function getValue(name)
{
    var str=window.location.search;
    if (str.indexOf(name)!=-1){
      var pos_start=str.indexOf(name)+name.length+1;
      var pos_end=str.indexOf("&",pos_start);
      if (pos_end==-1){
	 return str.substring(pos_start);
      }else{
	 return str.substring(pos_start,pos_end)
      }
   }else{
      return null;
 }
}

function createCookie(name,value,days,hours,mins) {
	var interval=0;
        if (days!='')  interval = interval + (days * 24 * 60 * 60);
        if (hours!='')  interval = interval + (hours * 60 * 60);
        if (mins!='')  interval = interval + (mins * 60);
        
            if (interval>0){
             interval = interval * 1000;
		var date = new Date();
		date.setTime(date.getTime()+interval);
                
		var expires = "; expires="+date.toGMTString();
        }
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	var date = new Date();
	var expires = "; expires="+date.toGMTString();
	value = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/************** URL UTF8 ENCODE E DECODE ************************/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


/* Base 64 encode/decode */

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

/***************  AGGIUNGI CSS RUNTIME ******************/

function appendCss(file,idCss){
    var headID = document.getElementsByTagName("head")[0];         
    var cssNode = document.createElement('link');
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    if (typeof idCss !="undefined" && idCss!="")
	cssNode.id = idCss;
    else
    	idCss = file;
    cssNode.href = file + (typeof __gvs_EXTERNAL_LIBRARY_VERSION != 'undefined' ? __gvs_EXTERNAL_LIBRARY_VERSION : '');
    cssNode.media = 'screen';
    if (!document.getElementById(idCss))
		headID.appendChild(cssNode);
}

/************** RESTITUISCE INFO SUL BROWSER ********************/

function getBrowser(){	
	try{
		var info = Array();
		var browser=navigator.appName;
		info["name"] = info[0] = browser;
    
		var b_version=navigator.appVersion;
		var version = "";

		if (browser.toLowerCase().search(/explorer/)>=0){
			var x = b_version.split(';');
			var version=parseInt(x[1].split(" ")[2]);
		}else{
			var x = b_version.split(' ');
			var version=parseInt(x[0]);
		}
		info["version"] = info[1] = version;
		
		return info;
	}catch(e){
		return null;
	}
	
}



/************** CENTRA UN DIV IN MEZZO ALLA PAGINA *********************/
	function MEcenterDiv(divId){
		document.getElementById(divId).style.position="absolute";
		
		var pWidth= document.body.clientWidth? document.body.clientWidth: document.documentElement.clientWitdh;
		var pHeight = document.body.clientHeight ? document.body.clientHeight : document.documentElement.clientHeight;

		var sWidth= window.innerWidth ? window.innerWidth: document.documentElement.clientWidth;
		var sHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight;
			
		prevVis = document.getElementById(divId).style.visibility;
		prevDisp = document.getElementById(divId).style.display;
		document.getElementById(divId).style.visibility="hidden";
		document.getElementById(divId).style.display="block";

		var divWidth= document.getElementById(divId).clientWidth;
		var divHeight = document.getElementById(divId).clientHeight;
		if (sWidth<= divWidth){
			sWidth= pWidth;
		}
		
		if (sHeight <= divHeight){
			sHeight = pHeight;
		}
		var scrolly = (document.all)?document.documentElement.scrollTop:window.pageYOffset;
		
		var top = scrolly + (sHeight/2 - divHeight/2);
	    if (top<0) top = 10;
	    top+="px";
		var left = (sWidth/2 - divWidth/2) + "px";
		document.getElementById(divId).style.top =  top;
		
		document.getElementById(divId).style.left = left;
		document.getElementById(divId).style.visibility=prevVis;
		document.getElementById(divId).style.display=prevDisp;
	}
	
/* submit di un form mediante una POST ajax */	
	
	function submitAjaxForm(form,handleFunction,action){
		
				if (typeof action == "undefined"){
					action = form.action;
				}
				if (typeof form == "string")
					var form = document.getElementById(form);
					
				var pars = qsFromForm(form);
				
				if (action)
					action += pars;
				else
					action = form.action + pars;
				
				
				var ajaxObj = getMEAjaxObj();
				ajaxObj.Request("POST", action, handleFunction);
	}

/* effettua il submit del form premendo enter - l'evento deve essere associato a keypress sui campi input del form */
	
	function submitOnEnter(e,oForm){
		var kC  = (window.event) ?    // MSIE or Firefox?
	           window.event.keyCode : (e.keyCode ? e.keyCode : e.which);
		var returnCode = 13;
		if (kC == returnCode)
			oForm.submit();
	}

/* esegue una azione sulla pressione di invio l'evento deve essere associato a keypress sui campi input del form */
	function eventOnEnter(e,handler){
		var kC  = (window.event) ?    // MSIE or Firefox?
	           window.event.keyCode : (e.keyCode ? e.keyCode : e.which);
		var returnCode = 13;
		if (kC == returnCode)
			handler();
	}
			
/* Bind di funzioni per non perdere il riferimento all'oggetto originario */
/* Estende le funzioni di javascript */

Function.prototype.bind=function(obj,arguments){
  var fx=this;
  return function(){
    return fx.apply(obj,arguments);
  }
}


/**
/* IMPLEMENTAZIONE DEL MERGE_SORT PER ORDINARE IN AMNIERA VELOCE UN ARRAY E POTER USARE LA RICERCA BINARIA ER SELEZIONARE GLI ELEMENTI*/
/* @metodoConfronto(a,b)  funzione utilizzata per esffettuare il confronto (restituisce 1 se a>b, -1 se a<b, 0 se a == b)
/* 							se non specificata ne usa una di default che effettua il confronto tra stringhe (_defaultMetodoConfronto)
																								
																								

																								
																																		*/
//merge_sort ricorsivo

function mergeSort(items,metodoConfronto){
	if (!metodoConfronto)
		metodoConfronto = _defaultMetodoConfronto;
    if (items.length == 1) {
        return items;
    }

    var middle = Math.floor(items.length / 2),
        left    = items.slice(0, middle),
        right   = items.slice(middle);

    return merge(mergeSort(left,metodoConfronto), mergeSort(right,metodoConfronto),metodoConfronto);
}



function merge(left, right, metodoConfronto){
    var result = [];

    while (left.length > 0 && right.length > 0){
		
//		alert(left[0]+" - "+ right[0] +" = " + metodoConfronto(left[0],right[0]));
        if (metodoConfronto(left[0],right[0]) < 0){
            result.push(left.shift());
        } else {
            result.push(right.shift());
        }
    }
    return result.concat(left).concat(right);
}

function _defaultMetodoConfronto(left, right)
{
	if(left == right)
		return 0;
	else if(left < right)
		return -1;
	else
		return 1;
}

/**
/* IMPLEMENTAZIONE DEL MERGE_SORT PER ORDINARE IN AMNIERA VELOCE UN ARRAY E POTER USARE LA RICERCA BINARIA ER SELEZIONARE GLI ELEMENTI*/
/* @metodoConfronto(a,b)  funzione utilizzata per effettuare la ricerca Binaria in un array ordinato
/* Restituisce l'indice dell'elemento nell'array se esiste, -1 altrimenti
/* 							se non specificata ne usa una di default che effettua il confronto tra stringhe (_defaultMetodoConfronto)
															*/
function binarySearch (needle, haystack, metodoConfronto ) {
	if (typeof(haystack) === 'undefined' || !haystack.length) return -1;
	
	var high = haystack.length - 1;
	var low = 0;
	while (low <= high) {
		mid = parseInt((low + high) / 2)
		element = haystack[mid];
		if (metodoConfronto(element,needle)==1) {
			high = mid - 1;
		} else if (metodoConfronto(element,needle)==-1) {
			low = mid + 1;
		} else {
			return mid;
		}
	}
	
	return -1;
};


function getPosition( oElement )
{
	var pos = {};
	pos.y = 0;
	pos.x = 0;
	while( oElement != null ) {
		pos.y += oElement.offsetTop ?  oElement.offsetTop : 0;
		pos.x += oElement.offsetLeft ?  oElement.offsetLeft : 0;
		oElement = oElement.offsetParent;
	}
	return pos;
}


function getMousePosition(e){
  try{
	tempX = e.pageX ? e.pageX : event.clientX + document.body.scrollLeft;
	tempY = e.pageY ? e.pageY : event.clientY + document.body.scrollTop;
	// catch possible negative values in NS4
	if (tempX < 0){tempX = 0}
	if (tempY < 0){tempY = 0}  
	// show the position values in the form named Show
	// in the text fields named MouseX and MouseY
	var pos = {};
	pos.x = tempX;
	pos.y = tempY;
  }catch(e){
	return null;
  }
  return pos;
}

/******* PseudoAjax Image Upload ********************/


function get(theVar){
	return document.getElementById(theVar);
}

function removeElement(element){
	if (typeof element == "string")
		var element = document.getElementById(element);
    try{
	    element.parentNode.removeChild(element);
	}catch(e)
	{
		//alert(e);
	}
}

function submitImgForm(form,resultContainer){
	get(resultContainer).innerHTML = "<img src=\"/img2/loader7.gif\" />";
	function doUpload(){
		removeEvent(get('iFrameImg'),"load", doUpload);
		if (typeof resultContainer!="undefined"){
			var cross = "javascript: ";
			cross += "window.parent.get('"+resultContainer+"').innerHTML = document.body.innerHTML;void(0);";
			get('iFrameImg').src  = cross;
            doUpload2();
		}		
	}
    function doUpload2(){
		
        removeEvent(get('iFrameImg'),"load", doUpload2);

        setTimeout("removeElement('"+_uploader_iframeContainer.id+"')",1000);
    }
try{
	_uploader_iframeHTML = "<iframe name=\"iFrameImg\" id=\"iFrameImg\" width=\"0\" height=\"0\" border=\"0\" style=\"width: 0; height: 0; border: none;\";></iframe>";
	_uploader_iframeContainer = document.createElement("div");
	_uploader_iframeContainer.id = "iFrameImgContainer";
	_uploader_iframeContainer.innerHTML = _uploader_iframeHTML;
	get(resultContainer).parentNode.appendChild(_uploader_iframeContainer);
	iFrameImg = document.getElementById("iFrameImg");

	_target = form.getAttribute("target");
	_method = form.getAttribute("method");
	_enctype = form.getAttribute("enctype");
	_encoding = form.getAttribute("encoding");
	
	form.setAttribute("target","iFrameImg");
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	addEvent(get('iFrameImg'),"load", doUpload);
	form.submit();
	if (!_target)
		form.setAttribute("target","");
	else
		form.setAttribute("target",_target);
	form.setAttribute("method",_method);
	form.setAttribute("enctype",_enctype);
	form.setAttribute("encoding",_encoding);
}
catch(e){
}
	return false;
}

/***************************************************/

//variabile globale per testare se si tratta di internet explorer 6
function isIE6() {
	return false /*@cc_on || @_jscript_version < 5.7 @*/;
}
function isIE(){
	var br = getBrowser();
	var br = br["name"];
	if (br.search(/Internet Explorer/) > 0)
		return true;
	else
		return false;
}



function getPageScroll(){
	scrolly = (document.all)?document.documentElement.scrollTop:window.pageYOffset;
	scrollx = (document.all)?document.documentElement.scrollLeft:window.pageXOffset;
	var scroll = new Object();
	scroll.x = scrollx;
	scroll.y = scrolly;
	return scroll
}

function setPageScroll(scroll){
	window.scrollTo(scroll.x,scroll.y);	
}

function addJS(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
	
    return false;
}


/* FUNIONE ESPANZIONE TEXTAREA AUTO */
function espandiBox(id){
    setTimeout("_espandiBox('"+id+"')",500);
}
function _espandiBox(id){
	
	/* oDiv = document.getElementById(div); */
	oTxtArea=document.getElementById(id);
	
	if (typeof oTxtArea.isExpanding !="undefined" && oTxtArea.isExpanding == true)
		return;
	else
		oTxtArea.isExpanding = true;
	if (typeof oTxtArea.initRows == "undefined")
		oTxtArea.initRows = oTxtArea.rows;
		
	if (oTxtArea.rows * oTxtArea.cols < 0)
		return;

	a = oTxtArea.value.split('\n');
	b=0;
	for (x=0;x < a.length; x++) {
		if (a[x].length >= oTxtArea.cols) b+= Math.floor(a[x].length/oTxtArea.cols);
	}
	
	b+=a.length;
	
	if (b > oTxtArea.initRows)
		oTxtArea.rows = b;
	else{
		oTxtArea.rows = oTxtArea.initRows;
	}
	oTxtArea.isExpanding = false;
	oTxtArea.focus();
}


function isNumeric(input)

{
   if (typeof input == "undefined" || input == "")
	return false;

   var ValidChars = "0123456789,";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < input.length && IsNumber == true; i++) 
      { 
      Char = input.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function getFuncName(oFunction){
	if (typeof oFunction != "function" || !oFunction)
		return "main";
	var fn = oFunction.toString();
	
	var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf('(')) || 'anonymous';
	return fname;
	
}

function _raiseError(message){
	if (typeof message=="undefined")
		message = "no description";
		throw new Error('[error] '+ (getFuncName(arguments.callee.caller)) + ': '+message+"\n\n StackTrace : "+getStackTrace().join(",\n\n"));
}

function _doLog(message, type) {
	if (typeof console!="undefined" && console[type || 'debug']){
		console[type || 'debug']('[%s]: %s',
		getFuncName(arguments.callee.caller), message);
	}else{
		if (typeof console!= "undefined" && console.log)
			console.log(message);
		
	}
}


//restituisce stringa con var dump
function var_dump(variable,full,maxDeep,_count) {
	
	var message = "";
	try{
		if (!maxDeep)
			maxDeep = 2;
		
		if (!full)
			full = false;
		
		if (!_count)
			_count = 0;
		
		_count = _count + 1;
			
		var type = typeof variable;
		
			
		tabs = "";
		tabs_1 = "";
		for (var i = 0; i< _count;i++)
			tabs= tabs+"\t";
		for (var i = 0; i< _count-1;i++)
			tabs_1= tabs_1+"\t";
		
		if (_count == 1)
			message+=type+"\n";
		
		if (type == "object"){
			
			if (_count>maxDeep){
				for (var name in variable){
					message = message + tabs +name+" = \""+(typeof variable[name])+"\" { .... },\n";
				}
			}else{
				for (var name in variable){
					message = message + (typeof variable[name] == "object" ? "\n"+tabs_1 : tabs) +name+" = \""+(typeof variable[name])+"\" {"+(typeof variable[name] == "object" ? "\n"+tabs_1 : "")+" "+_var_dump(variable[name],full,maxDeep,_count)+(typeof variable[name] == "object" ? "\n"+tabs_1 : "")+"},\n";
				}
				
			}
			message+="\n";
		}else{
			
			if ((type == "function" && full) || type!="function"){
				message+=variable;

			}else{
				message+="....... (set full = 1 to see the func body)";			
			}
		}
		
	}catch(e){
		return message;
	}
	
	return(message);
}

function getStackTrace() {
  var callstack = [];
  var isCallstackPopulated = false;
  var i = null;
  try {
    i.dont.exist+=0; //doesn't exist- that's the point
  } catch(e) {
    if (e.stack) { //Firefox
      var lines = e.stack.split('\n');
      for (var i=0, len=lines.length; i<len; i++) {
        if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
          callstack.push(lines[i]);
        }
      }
      //Remove call to printStackTrace()
      callstack.shift();
      isCallstackPopulated = true;
    }
    else if (window.opera && e.message) { //Opera
      var lines = e.message.split('\n');
      for (var i=0, len=lines.length; i<len; i++) {
        if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
          var entry = lines[i];
          //Append next line also since it has the file info
          if (lines[i+1]) {
            entry += "&quot; at &quot;" + lines[i+1];
            i++;
          }
          callstack.push(entry);
        }
      }
      //Remove call to printStackTrace()
      callstack.shift();
      isCallstackPopulated = true;
    }
  }
  if (!isCallstackPopulated) { //IE and Safari
    var currentFunction = arguments.callee.caller;
    while (currentFunction) {
	  var fn = currentFunction.toString();
      var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf('(')) || 'anonymous';
      callstack.push(fname);
      currentFunction = currentFunction.caller;
    }
  }
  return callstack;
}


stringify = function (obj) {
	var t = typeof (obj);
	if (t != "object" || obj === null) { 
		// simple data type 
		if (t == "string") obj = '"'+obj+'"'; 
			return String(obj); 
		} 
		else { 
			var n, v, json = [], arr = (obj && obj.constructor == Array);
			//voglio glia array sempre associativi (obj jSon)
			arr = false;
			for (n in obj) {
				
				v = obj[n]; t = typeof(v); 
				if (t == "function")
					continue;
				if (t == "string") v = '"'+v+'"'; 
				else if (t == "object" && v !== null) v = stringify(v); 
				
				if (arr)
					json.push(String(v));
				else
					json.push( ('"' + n + '":') + String(v)); 
			} 
	 
			return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}"); 
		} 
	};

/*
	cerca un elemento (neddle) dentro ad  un array (haystack)
*/
function in_array(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++){
        if(haystack[i] == needle) return true;
    }
    return false;
}

	
/* Scroll Progressivo*/	

	
/* 
 * getPageSize()
 * 
 * Returns array with page width, height and window width, height
 *
 */
function getPageSize(){
 
 var xScroll, yScroll;
 
 if (window.innerHeight && window.scrollMaxY) {    
     xScroll = document.body.scrollWidth;
     yScroll = window.innerHeight + window.scrollMaxY;
 } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
     xScroll = document.body.scrollWidth;
     yScroll = document.body.scrollHeight;
 } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
     xScroll = document.body.offsetWidth;
     yScroll = document.body.offsetHeight;
 }
 
 var windowWidth, windowHeight;
 if (self.innerHeight) {    // all except Explorer
     windowWidth = self.innerWidth;
     windowHeight = self.innerHeight;
 } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
     windowWidth = document.documentElement.clientWidth;
     windowHeight = document.documentElement.clientHeight;
 } else if (document.body) { // other Explorers
     windowWidth = document.body.clientWidth;
     windowHeight = document.body.clientHeight;
 }    
 
 // for small pages with total height less then height of the viewport
 if(yScroll < windowHeight){
     pageHeight = windowHeight;
 } else {
     pageHeight = yScroll;
 }

 // for small pages with total width less then width of the viewport
 if(xScroll < windowWidth){    
     pageWidth = windowWidth;
 } else {
     pageWidth = xScroll;
 }

 return [ pageWidth,pageHeight,windowWidth,windowHeight ];
}

/*
 * getScrollXY()
 * 
 * Finds current window scroll position.
 */

function getScrollXY() {
          var scrOfX = 0, scrOfY = 0;
          if( typeof( window.pageYOffset ) == 'number' ) {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
          } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
          } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
          }
          return [ scrOfX, scrOfY ];
        }

/*
 * ScrollTo(id,stps) (see below)
 * 
 * Scrolls display window up to object (id) position.
 * The scroll lasts "stps" µ-secs.
 */

// Auxiliary function for scrollTo(id)
var steps;
var scrollTimeOut = 0;

var date,startTime;

function myScrollBy(idToActivate,sx,sy,ex,ey){
        var scroll,nx,ny;
        scroll = getScrollXY();
        nx = scroll[0]; ny = scroll[1];

        sx += 30.7*(ex-nx)/(steps*Math.log(Math.abs(ex-nx+1)));
        sy += 30.7*(ey-ny)/(steps*Math.log(Math.abs(ey-ny+1)));

        // This works even when the user plays with the scroll wheel...
        if (sx-nx != 0 || sy-ny != 0){
                window.scrollBy(sx-nx,sy-ny);
        }

        if (scrollTimeOut){
                clearTimeout(scrollTimeOut);
        }
        
        var date2 = new Date();
        // Stop anyway if too much time has passed (twice as requested).
        if ( (date2.getTime()-startTime) < (steps*40) && (Math.abs(sx - ex)>1 || Math.abs(sy - ey)>1) ){
                scrollTimeOut = setTimeout(function(){myScrollBy(idToActivate,sx,sy,ex,ey)},20);
        } else {
			if (typeof idToActivate!="undefined" && idToActivate)
                document.getElementById(idToActivate).focus();
        }
}

function progScrollTo(id,idToActivate,stps,offsetTop)
{
		var obj;
		if (typeof id == "String")
			obj = document.getElementById(id);
		else
			obj = id;
        var objleft = objtop = 0;

        // find this object position.
        while (obj.offsetParent){
                objleft += obj.offsetLeft;
                objtop += obj.offsetTop;
                obj = obj.offsetParent;
        }
		
		if (!!offsetTop)
			objtop+=parseInt(offsetTop);
		
        steps = stps/20;
        var dims = getPageSize();
        
        if (dims[1] - objtop < dims[3])
                objtop = dims[1]-dims[3];

        if (dims[0] - objleft < dims[2])
                objleft = dims[0]-dims[2];
        
        var scr = getScrollXY();

        date = new Date();
        startTime = date.getTime();
        myScrollBy(idToActivate,scr[0],scr[1],objleft,objtop,0);
}


/* Fine Scroll Progressivo*/


//IE memory leak purge
function purgeDomObj(d) {
	try{
		if (typeof d == "undefined" || !d){
		  return;
		}
		var a = d.attributes, i, l, n;
		var b = d.childNodes;
		
			for (var i in d){
				if (d[i] && typeof d[i] == "Object"){			
					d.purgeDomObj(d[i]);
				}
			}
		
		
			if (a) {
				l = a.length;
				for (i = 0; i < l; i += 1) {
					n = a[i].name;
					if (typeof d[n] === 'function') {
						d[n] = null;
					}
				}
			}
		
			if (b) {
				l = b.length;
				for (i = 0; i < l; i += 1) {
					
					if (d.childNodes[i]){
						purgeDomObj(d.childNodes[i]);
						d.removeChild(d.childNodes[i]);
					}
				}
				
			}
		d.innerHTML = "";
		d = null;
	}catch(e){
		//_doLog("error:"+e,'error');
	}

}

function updateVisibilita(id,field,obj){
    if (!obj || !id || field.trim()=="") return;
    var oAjax = new getMEAjaxObj();
    var value=0;
    if (obj.checked) value=1; 
    var pars = "id="+id+"&field="+field+"&value="+value;
    var url = "/backoffice/updateVisibilita.php?"+pars;
    oAjax.Request('POST',url, updateVisibilitaH);
}

function updateVisibilitaH(data){
    if (data.responseText=="-1"){
	alert("Si è verificato un problema, riprovare l'operazione");
	return;
    }
}

function preloadImages(aImages,onloadF){
	__ti_preload_imgs_idx = 0;
	var img = document.createElement("img");
	img.onload = function(){
		if (aImages.length > ++__ti_preload_imgs_idx){
			this.src = aImages[__ti_preload_imgs_idx]
		}else{
			this.onload = function(){};
			if (typeof onloadF == "function")
			onloadF();
		}
	}
	img.src = aImages[0];	
}


/*confronta due array passati per argomento e ritorna true se l'array2 contiene gli stessi elementi dell'array1, anche in ordine diverso, altrimenti ritorna false*/
function fnSameElemArray(aArray1, aArray2){
    if(aArray1.length != aArray2.length)
		bSame = false;
    else{
        bSame = true;
        var iCounter = 0;
        var aSorted1 = mergeSort(aArray1);
        var aSorted2 = mergeSort(aArray2);
	for(var i=0;i<aSorted1.length;i++)
	    if(aSorted1[i] != aSorted2[i]){
		bSame = false;
		break;
	    }
    }
    return bSame;
}


/*elimina un nodo dal dom passandogli il suo id*/
function fnRemoveNodeById(sNode){
    var oNodeToRemove = document.getElementById(sNode);
	if (oNodeToRemove)
		oNodeToRemove.parentNode.removeChild(oNodeToRemove);
    return;
}

function disableAutoComplete(selector){
    
    if (!selector)
		return;
	var first = selector.charAt(0);
    var id =selector.split(first)[1];
    if (first=='#'){
		var inputElement = document.getElementById(id);
        if (inputElement)
			inputElement.setAttribute("autocomplete","off");
	}
    else
	if (first=='.'){
        var inputElements = document.getElementsByClass(id);
        for (i=0; inputElements[i]; i++) {
                inputElements[i].setAttribute("autocomplete","off");
        }
    }
}

function trackGAClickEvent(category,action,opt_label){
	var debug = true;
	if (typeof category == "undefined" || typeof action == "undefined" || typeof opt_label == "undefined"){
		if (debug)
			_doLog("Missing Required Field");
		return false;
	}
	if (typeof _gaq == "undefined"){
		if (debug)
			_doLog("_gaq is undefined");
		return false;
	}
	
	
	if (category!=null && action && opt_label){
		_gaq.push(['_trackEvent', category, action, opt_label]);
		_doLog("_gaq.push(['_trackEvent','"+category+"','"+ action+ "','"+opt_label+"']);");
	}
	
	return true;
	
}

Function.prototype.clone=function(obj){
	function F(){}
	F.prototype = obj;
	return new F();
}


String.prototype.ucwords = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
}

if (typeof Event != "undefined" && typeof Event.prototype != "undefined")
Event.prototype.stopBubbling = function(){
	try{
		this.cancelBubble = true;
		this.stopPropagation
	}catch(e){
		_doLog(e);
	}
}

function simulateClickOnLink(oA,forceNewWindow) {
	if (typeof forceNewWindow == "undefined")
		forceNewWindow = false;
	if (typeof(oA.click) != 'undefined' && /msie/i.test(navigator.userAgent)) {
		var fakeLink = document.createElement("a");
		fakeLink.href = oA.href;
		if (forceNewWindow)
			fakeLink.target = "_blank";
		else
			fakeLink.target = oA.target;
		document.body.appendChild(fakeLink);
		fakeLink.click();
	} else {
		if ((oA.target && oA.target == "_blank") || forceNewWindow) {
			window.open(oA.href);
			setTimeout(function(){document.body.focus();},0);
		} else {
			document.location.href = oA.href;
		}
	}
}

stop_event_bubbling=function(e){
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

function getCaretPosition(oField) {

  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {

    // Set focus on the element
    oField.focus ();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange ();

    // Move selection start to 0 position
    oSel.moveStart ('character', -oField.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }

  // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionStart;

  // Return results
  return (iCaretPos);
}

function setCaretPos(fieldOrId,pos){

    var oField = (typeof fieldOrId == "string" || fieldOrId instanceof String) ? document.getElementById(fieldOrId) : fieldOrId;

    if(!oField){
        return false;
    }else if(oField.createTextRange){
        var textRange = oField.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd('character',pos);
        textRange.moveStart('character',pos);
        textRange.select();
		
		
        return true;
    }else if(oField.setSelectionRange){
		
        oField.setSelectionRange(pos,pos);
        return true;
    }

    return false;
}

