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

// 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){
	/*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 == "indefined")
		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 (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){
    while (stringa.substring(0,1) == ' '){
        stringa = stringa.substring(1, stringa.length);
    }
    while (stringa.substring(stringa.length-1, stringa.length) == ' '){
        stringa = stringa.substring(0,stringa.length-1);
    }
    return stringa;
}

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

function evidenzia(img,valore){
	img.style.opacity = valore/10;
	img.style.filter = 'alpha(opacity=' + valore*10 + ')';
}
function popUp(url){
	window.open(url,'','toolbar=no,scrollbars=1');
}

function popup(page,title,width,height){
var win;
 params = "toolbar=0,";

params += "location=0,";

params += "directories=0,";

params += "status=0,";

params += "menubar=0,";

params += "titlebar=0,";

params += "scrollbars=0,";

params += "resizable=0,";

params += "top=0,";

params += "left=50,";

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

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


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)
	    params += "?";
	else
	    params += "&";
        element = form.elements[i]
	if(element.tagName.toLowerCase() == 'textarea' )
        {
                params+=element.name+"="+Url.encode(element.value);
		
        }
        else if( element.tagName.toLowerCase() == 'input' )
        {
                if( element.type == 'text' || element.type == 'hidden' || element.type == 'password')
                {
                        params+=element.name+"="+Url.encode(element.value);
                }
                else if( element.type == 'radio' && element.checked )
                {
                        if( !element.value )
                                params+=element.name+"="+"on";
                        else
                                params+=element.name+"="+Url.encode(element.value);

                }
                else if( element.type == 'checkbox' )
                {
                        if(  !element.checked )
                                params+=element.name+"="+"";
                        else
                                params+=element.name+"="+Url.encode(element.value);
                }
		
        }else if (element.tagName.toLowerCase()=="select"){
	    if(element.type=="select-one"){
		if (element.selectedIndex>=0)
		    params += 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 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(){
	
	var browser=navigator.appName;
    var b_version=navigator.appVersion;
    var x = b_version.split(';');
    var version=parseInt(x[1].split(" ")[2]);
	var info = Array();
	info["name"] = info[0] = browser;
	info["version"] = info[1] = version;
	return info;

}



/************** 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){
  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){
  
  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;
  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=\"/imgmap/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();
}



/* Funzione creazione mappa googlepersonalizzata, restituisce un oggetto GMAP2 esteso con metodi e attributi custom */
function createMap(idMap,initCenter,initZoom)
{
	var map;
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById(idMap));
		//addEvent(window,"unload",function(){return purgeDomObj(document.getElementById(idMap))});
		if (typeof initCenter!="undefined" && initCenter){	
			map.setCenter(initCenter,initZoom);
		}							
	}
	else{
		var er = new Object();
		er.message = "Browser non compatibile";
		throw(er);
	}
	
	/* DEFINIZIONE ATTRIBUTI ESTESI*/
	map.mapCont = document.getElementById(idMap);
	if (typeof initCenter!="undefined" && initCenter)
		map.centro_iniziale = initCenter;
	if (typeof initZoom!="undefined" && initZoom)
		map.zoom_iniziale = initZoom;
	
	
	map.f_zoom_in=function(){
 // =================================
     checked = false;
     this.zoomIn();
     
	}

	map.f_zoom_out=function(){
	// ==================================
	  this.zoom_p.style.visibility="visible";     
	  this.zoomOut();
     
	}
	
	/* DEFINIZIONE METODI ESTESI*/
	
	map.add_zoom_buttons = function(){
		
		var ph = parseInt("25px");
		var pw = parseInt("25px");
		var pimg = "/imgmap/lenteP.gif";
		
		var mh = parseInt("25px");
		var mw = parseInt("25px");
		var mimg = "/imgmap/lenteM.gif";
		
		if (typeof p_zoom == "Object"){
			ph = parseInt(p_zoom.height);
			ph = parseInt(p_zoom.width);
			pimg = p_zoom.img;
		}
		if (typeof m_zoom == "Object"){
			mh = parseInt(m_zoom.height);
			mw = parseInt(m_zoom.width);
			mimg = m_zoom.img;
		}
		
		var div_mappa=this.getContainer();
		this.zoom_p =document.createElement('div');
		//this.zoom_p.id = "zoom_p";
		this.zoom_p.style.width=pw + "px";
		this.zoom_p.style.height=ph + "px"
		this.zoom_p.style.position="absolute";
		this.zoom_p.style.top="3px";
		this.zoom_p.style.left="3px";
		this.zoom_p.style.background="url("+pimg+") no-repeat";
		this.zoom_p.style.cursor="pointer";
		this.zoom_p.onclick=this.f_zoom_in.bind(this);
		this.zoom_p.style.border="1px solid #319acf";
		this.zoom_p.style.backgroundColor="#FFF";
		div_mappa.appendChild(this.zoom_p);
	
		this.zoom_m =document.createElement('div');
		//this.zoom_m.id = "zoom_m";
		this.zoom_m.style.width=mw + "px";
		this.zoom_m.style.height=mh + "px"
		this.zoom_m.style.position="absolute";
		this.zoom_m.style.top= parseInt(this.zoom_p.style.top) + ph + 4 + "px";
		this.zoom_m.style.left="3px";
		this.zoom_m.style.background="url("+mimg+") no-repeat";
		this.zoom_m.style.cursor="pointer";
		this.zoom_m.onclick=this.f_zoom_out.bind(this);
		this.zoom_m.style.border="1px solid #319acf";
		this.zoom_m.style.backgroundColor="#FFF";
		div_mappa.appendChild(this.zoom_m);       
	}
	return map;
}

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) {
	console[type || 'debug']('[%s]: %s',
	getFuncName(arguments.callee.caller), 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)
{

        var obj = document.getElementById(id);
        var objleft = objtop = 0;

        // find this object position.
        while (obj.offsetParent){
                objleft += obj.offsetLeft;
                objtop += obj.offsetTop;
                obj = obj.offsetParent;
        }

        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(__ti_preload_images){
	__ti_preload_imgs_idx = 0;
	var img = document.createElement("img");
	img.onload = function(){
		if (__ti_preload_images.length > ++__ti_preload_imgs_idx){
			this.src = __ti_preload_images[__ti_preload_imgs_idx]
		}else{
			this.onload = function(){};
		}
	}
	img.src = __ti_preload_images[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;
}


/*crea il boxettino per la conferma della cancellazione annunci pubblicati/preferiti/ricerche salvate relativa agli utenti registrati*/

/*
* sDivContainer: div a cui viene appeso il box overlay
* iWidth, iHeight: dimensioni in px del box
* iIdElToRemove: id annuncio pubblicato/id ricerca da cancellare
* sBookmark: il tipo di bookmark. pubblicati, preferiti, ricerche salvate
*/

function fnConfirmAction(sDivContainer,iWidth,iHeight,iIdElToRemove,sBookmark){
	
	
	var oParentlayer = document.getElementById(sDivContainer);
	
	var oConfirmLayer = document.createElement("div");
	oConfirmLayer.id="confirm_layer_"+iIdElToRemove;
	oConfirmLayer.style.backgroundColor="#aeaeae";
	oConfirmLayer.style.position="absolute";
	oConfirmLayer.style.filter="alpha(opacity = 80)";
	oConfirmLayer.style.opacity="0.8";
	
	oConfirmLayer.style.border="1px solid";
	oConfirmLayer.style.width=iWidth+"px";
	oConfirmLayer.style.height=iHeight+"px";
	oConfirmLayer.style.zIndex="140";
	
	var oConfirmControl = document.createElement("div");
	oConfirmControl.id = "controls_confirm_container_"+iIdElToRemove;
	oConfirmControl.style.filter="alpha(opacity = 100)";
	oConfirmControl.style.opacity = "1";
	oConfirmControl.style.zIndex = "150";
	oConfirmControl.style.width = iWidth+"px";
	oConfirmControl.style.height = iHeight+"px";
	
	oConfirmControl.style.position = "absolute";
	
	//dimensioni contenitore bottoni
	var iControlsDivWidth = 240; 
	var iControlsDivHeight = 35;
	
	oConfirmControl.style.padding = Math.floor(((iHeight/2)-(iControlsDivHeight/2)))+"px "+Math.floor(((iWidth/2)-(iControlsDivWidth/2)))+"px";
	
		
	var sHTMLControlContainer = "<div class=\"confirm_control\"></div>";
	
	var sHTMLButtons = "<div style=\"position:absolute;opacity:1;filter:alpha(opacity = 100);z-index:150;width:"+iControlsDivWidth+"px;height:"+iControlsDivHeight+"px;background-image:url('/imgmap/fondo-box.png');\">";
	
	sHTMLButtons += "<div class=\"bottoneAnnulla\" onclick=\"this.parentNode.parentNode.parentNode.className = (this.parentNode.parentNode.parentNode.className.split('_confirm_box'))[0];fnRemoveNodeById(this.parentNode.parentNode.nextSibling.id);fnRemoveNodeById(this.parentNode.parentNode.id);\"></div>";
	
	switch(sBookmark){
	    case('pubblicati'):
	   	sHTMLButtons += "<div class=\"bottoneCancella\" onclick=\"location.href='pubblicaAnnunci.php?action=delete&id="+iIdElToRemove+"';\"></div>";
		break;
	    case('ricerche'):
		sHTMLButtons += "<div class=\"bottoneCancella\" onclick=\"location.href='bookmarkricerche.php?action=delete&idRicerca="+iIdElToRemove+"';\"></div>";
		break;
	    case('preferiti'):
		sHTMLButtons += "<div class=\"bottoneCancella\" onclick=\"location.href='bookmarkannunci.php?action=delete&id="+iIdElToRemove+"';\"></div>";
		break;
	}
	
	sHTMLButtons += "<div class=\"clear\"></div>";
	
	sHTMLButtons += "</div>";
	
	oConfirmControl.innerHTML = sHTMLButtons;
	
	oConfirmLayer.innerHTML = sHTMLControlContainer;
	
	
	oParentlayer.insertBefore(oConfirmLayer,oParentlayer.firstChild);
	
	//disattivo il rollover sul div padre
	oConfirmLayer.parentNode.className += "_confirm_box";
	
	
	oParentlayer.insertBefore(oConfirmControl,oParentlayer.firstChild);
	
	return false;
}

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

