/*-------------------- External Js Dependency Management ---------------------------*/
function w3gIncludeJs(filename){ 
	if(w3gIsJsIncluded(filename)==true)return;
	document.write('<script type="text/javascript" src="/'+window.w3gContex+'/'+filename+'"></script>');

}
function w3gIsJsIncluded(filename)
{ 	
	if (window.document.getElementsByTagName) {
	   var inclusion = document.getElementsByTagName('head')[0].getElementsByTagName("script");
	   for (i = 0; i < inclusion.length; i++) {
	   	var obj = inclusion[i];
	   	if(obj && obj.src){
	   		if(obj.src.toString().indexOf(filename)>-1) return true;
	   }
	  }
	}
	return  false;
}

/*-------------------- openPop ----------------------------------*/
//2010.12.17@SO Estensioni valide che non sono immagini...
function w3gCheckMediaExtension(myUrl) {
	if (myUrl.indexOf('.') > -1) {
		var sBuffer = ',' + w3gNoMediaExtensions + ',';
		var sExt = myUrl.substr(myUrl.lastIndexOf(".") + 1);
		if (sExt.indexOf("?") > -1 )
			sExt = sExt.substr(0, sExt.indexOf("?"));
		return (sBuffer.indexOf(',' + w3gUtils.Trim(sExt) + ',') == -1) ;	
	}
	return true;
}

function w3gOpenPop(myIndirizzo, myTarget, popTitle, option ){ 
	if(myTarget && myTarget!=null && typeof myTarget != 'undefined'){
		try {// forzo la chiusura della finestra precedentemente aperta per permettere l'apertura con dimensione corretta
			popUpWindow = window.open('/'+window.w3gContex+'/portal/pageBlank.jsp',myTarget,winOpt);
			if (!popUpWindow.closed) popUpWindow.close();
		} catch (e) {/*DO NOTHING*/}
	}
	
	if ((popTitle) && (popTitle!=null) && (popTitle.length>0))
		myIndirizzo += (myIndirizzo.indexOf("?")>=0 ? "&" : "?") + "popTitle="+popTitle;
		
	if (getW3gParameterCheck("idDevice=mobile"))
		myTarget =  "_top";
	//2007.07.24@IV fix openpop from pop, target must be setted otherwise 'access denied'
	if (myTarget==null) myTarget = "_blank";
		
	if (option==null){
		var viewport = window.screenDimensions();		
		
		//	2009.03.03@SO Controllo se è stato ridefinito il default...
		var defaultOption = null;
		if (typeof w3gPopupDefaultDimension == 'undefined') {
			defaultOption = 'width=510,height=580,status=yes,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,top=20px,left=20px';		
		} else {
			defaultOption = w3gPopupDefaultDimension + ',status=yes,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,top=20px,left=20px';		
		}
		
		if (/*myIndirizzo.indexOf("show?")>=0 && */myTarget!="_top") {					
//			if(myIndirizzo.indexOf("show?")>=0){
			//	2010.12.15@SO Problema delle url semantiche e dei media semantici...
			if((myIndirizzo.indexOf('://') == -1) && (w3gCheckMediaExtension(myIndirizzo)) &&
				((myIndirizzo.indexOf("media/show")>=0) || 
				(myIndirizzo.lastIndexOf('/') > -1 && myIndirizzo.lastIndexOf('.') > myIndirizzo.lastIndexOf('/')))) {
				//	2010.12.01@SO Se è un media non può essere un immagine...
				//2008.04.28@FC open window with 90% user screen resolution 
				var screen = window.screenDimensions();
				var winOpt = "status=yes,resizable=yes,toolbar=no,menubar=no,width="+(screen.width*0.9)+",height="+(screen.height*0.8);
				window.open(myIndirizzo, myTarget, winOpt).focus();
				return;
			}else{
				//2008.04.28@FC open window with 90% user screen resolution 
				option = defaultOption;
			}
		} else{
			option = defaultOption;
		}
	}
	window.open(myIndirizzo, myTarget, option).focus();
}

var w3gOpenPopImg = function(url, myTarget, popTitle, options){

	//	2011.01.27@SO Fix per mobile...
	if (typeof Prototype=="undefined") {
		window.open(url, myTarget, options).focus();
		return;
	}

	options = (options||'').replace(/,/g,'&');
  	options = options.parseQuery();
  	var parameters = {'width':0,'height':0};
  	Object.extend(parameters,options);
  	var idMedia = Try.these(
		function(){
		return new RegExp(".*show\\?(\\d+)","ig").exec(url)[1];
		},
		
		function(){
		return new RegExp(".*show\\/(\\d+)","ig").exec(url)[1];
		},
		
		function(){
		return new RegExp("/([0-9]*?)[_/]","g").exec(url)[1];
		}
	);
	
	function next(){
	  Object.extend(parameters, {title:popTitle,fullview:false,draggable:false});
	  var viewport  = window.viewportDimensions();
	  var bfact = .9;
	  var factors = {
	    width: (parameters.width || (viewport.width* bfact)) / (viewport.width * bfact),
	    height: (parameters.height || (viewport.height* bfact)) / (viewport.height * bfact)
	  }
	  var sfact = 1;
	  if(factors.width>1 || factors.height >1){
	    sfact =  Math.max(factors.width,factors.height);
	  }
	  url = url.replace(/(show\?\d+)_.*/ig,'$1');
	  url = url.replace(/(show\/\d+)_.*/ig,'$1');
	  url = url.replace(new RegExp("(/[0-9]*?)_.*?(/)","g"),'$1$2');
	  
	  var image = '<img src="'+url+'"'
	  +(parameters.width?' width="'+Math.floor((parameters.width/(parameters.fullview ? 1 : sfact)))+'"':'')
	  +(parameters.height?' height="'+Math.floor((parameters.height/(parameters.fullview ? 1 : sfact)))+'"':'')
	    +' alternate="'+ (parameters.title || url) +'"/>';
	  var container = '<div style="margin:0;padding:0';
	  if(parameters.fullview && sfact>1){
	    container +=  
	    ';width:'+((viewport.width* bfact)-15)+'px'+
	    ';height:'+((viewport.height* bfact)-15)+'px'+
	    ';overflow:scroll;scroll:auto';
	  }
	  container += ';">'+image+'</div>';
	  var dialog = new w3gDialogs.image({title:parameters.title||url,message:container,className:'w3gDialogsImg'});    
	  dialog.undraggable();  
	  Event.observe(dialog.underveil, 'click', dialog.close.bind(dialog));
  }
  
   // Se non sono specificate le dimensioni le vado a leggere dal media...  
  if (parameters.width == 0 || parameters.height == 0) {
		var myMedia = new w3gMedia(idMedia);
			myMedia.load(function (mm){
				if (mm.isImage()) {
					parameters.width = mm.getImageWidth();
					parameters.height = mm.getImageHeight();
					if (!popTitle)	//	Se non c'è il titolo ci metto il nome del media...
						popTitle = mm.getNome();
					next();
				}
			});
	} else {
		next();
	}
  return void(0);
}

function openPop(myIndirizzo, myTarget, popTitle, option ){ 
	if(myTarget && myTarget!=null && typeof myTarget != 'undefined'){
		try {// forzo la chiusura della finestra precedentemente aperta per permettere l'apertura con dimensione corretta
			popUpWindow = window.open('/'+window.w3gContex+'/portal/pageBlank.jsp',myTarget,winOpt);
			if (!popUpWindow.closed) popUpWindow.close();
		} catch (e) {/*DO NOTHING*/}
	}
	
	if ((popTitle) && (popTitle!=null) && (popTitle.length>0))
		myIndirizzo += (myIndirizzo.indexOf("?")>=0 ? "&" : "?") + "popTitle="+popTitle;
		
	if (getW3gParameterCheck("idDevice=mobile"))
		myTarget =  "_top";
	//2007.07.24@IV fix openpop from pop, target must be setted otherwise 'access denied'
	if (myTarget==null) myTarget = "_blank";
		
	if (option==null){
		var viewport = window.screenDimensions();		
		// 2008.05.05@FC REMOVED, resolution 90%x80% only for media...
		//var defaultOption = 'width='+(screen.width*0.9)+',height='+(screen.height*0.8)+',status=yes,resizable=yes,scrollbars=yes,toolbar=no,menubar=no';
		//var defaultOption = 'width=510,height=580,status=yes,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,top=20px,left=20px';
		
		//	2009.03.03@SO Controllo se è stato ridefinito il default...
		var defaultOption = null;
		if (typeof w3gPopupDefaultDimension == 'undefined') {
			defaultOption = 'width=510,height=580,status=yes,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,top=20px,left=20px';		
		} else {
			defaultOption = w3gPopupDefaultDimension + ',status=yes,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,top=20px,left=20px';		
		}
		
		if (/*myIndirizzo.indexOf("show?")>=0 && */myTarget!="_top") {					
			var myIdMedia = null;
			//	2010.12.15@SO Problema delle url semantiche...
//			if(myIndirizzo.indexOf("show?")>=0){
			if(myIndirizzo.indexOf("media/show")>=0){
				myIdMedia = myIndirizzo.substr(myIndirizzo.indexOf("media/show") + (("media/show").length) + 1);
			} else if ((myIndirizzo.indexOf('://') == -1) && (w3gCheckMediaExtension(myIndirizzo)) && (myIndirizzo.lastIndexOf('/') > -1) && (myIndirizzo.lastIndexOf('.') > myIndirizzo.lastIndexOf('/'))) {
				//	2010.12.15@SO Gestione media semantici...
				myIdMedia = new RegExp("/([0-9]*?)[_/]","g").exec(myIndirizzo)[1];
			}else if(myIndirizzo.indexOf("popupMedia.do?id=")>=0){				
				myIdMedia = myIndirizzo.substr(myIndirizzo.indexOf("popupMedia.do?id=")+(("popupMedia.do?id=").length));
			}			
			if(myIdMedia!=null){
				myIdMedia = myIdMedia.match(/\d*(_del)?/g)[0];
				var myMedia = new w3gMedia(myIdMedia);
				myMedia.load(function(){w3gOpenPop4MediaAjax(myMedia,myIndirizzo,myTarget,popTitle)});
				return;
			}else{
				//2008.04.28@FC open window with 90% user screen resolution 
				option = defaultOption;
			}
		} else{
			option = defaultOption;
		}
	}
	window.open(myIndirizzo, myTarget, option).focus();
}  
function w3gOpenPop4MediaAjax(mediaObj,requestUrl,myTarget,popTitle){
	//if (myTarget==null) myTarget = "_blank";
	var winOpt = "status=yes,resizable=yes,toolbar=no,menubar=no";
	if(myTarget != 'mediaViewer' && mediaObj.isImage()){
		try {
		//	2010.11.30@SO Richiama la w3gOpenPopImg...
/*			var myImage = mediaObj.getImage();
			var iw = mediaObj.getImageWidth()
			if(iw==null || iw<=0)iw = myImage.width;
			var ih = mediaObj.getImageHeight()
			if(ih==null || ih<=0)ih = myImage.height;
			//if (iw>50||ih>50)	
			
			//21.08.2008@MV if image is larger than screen dimensions show scrollbars
			var screen = window.screenDimensions();	
			if (ih>screen.height || iw>screen.width)
				winOpt += ",scrollbars=yes";*/
				
			winOpt = "width="+(mediaObj.getImageWidth())+",height="+(mediaObj.getImageHeight());
			if (!popTitle)
				popTitle = mediaObj.getNome();
			w3gOpenPopImg(requestUrl, myTarget, popTitle, winOpt);
			return;
		}catch(err){winOpt += ",width=100,height=100";}
	}else{
		//2008.04.28@FC open window with 90% user screen resolution 
		var screen = window.screenDimensions();
		winOpt += ",width="+(screen.width*0.9)+",height="+(screen.height*0.8);
	}	
	window.open( (requestUrl || mediaObj.getUrl()), myTarget, winOpt).focus();
}
var myTtFunction = new function(){};
/* ---------------- openPop4Media with autosizing for true image objects -----------------*/
var cntPict=0;
var idPict=new Array();

function openPop4Media(img, target){
	if (target==null) target = "_blank"; //2007.07.24@IV fix openpop from pop, target must be setted otherwise 'access denied'
	cntPict++;
	idPict[cntPict] = new Image();
	idPict[cntPict].src = img;
	idPict[cntPict].target = target;
	targetWin = window.open("/"+window.w3gContex+"/portal/pageBlank.jsp", target, "width=100,height=100"); //2006.05.03@FV fix "openpop from pop"
	if (targetWin!=window) targetWin.close(); //close pre-opened target window 
	var interrupt = "viewPop4Media("+cntPict+")";  
	setTimeout( interrupt, 200 ); // set delay to allow data download
}
function viewPop4Media(id){
	var winOpt = "status=yes,resizable=yes,toolbar=no,menubar=no";
	try {
		if (idPict[id].width>50||idPict[id].height>50)	
		winOpt += ",width="+(idPict[id].width+20)+",height="+(idPict[id].height+25);
	} catch (e) {}
	var popUpWindow = window.open(idPict[id].src, idPict[id].target, winOpt);
	if (popUpWindow!=null) popUpWindow.focus();
}

/*-------------------- getW3gDocumentURL ---------------------------*/
function getW3gDocumentURL(){
	var urlLimit = document.URL.indexOf("?");
	var strUrl = document.URL.substring( 0, (urlLimit>0 ? urlLimit : document.URL.length));
	if (w3gItemAndSezione!=null) strUrl += "?"+w3gItemAndSezione;
	return strUrl;
} 
/*-------------------- getW3gDocumentURL ---------------------------*/
function getW3gParameterCheck( p ){
	try {
		var w3gp = w3gItemAndSezione.split("&");
		for (var i=0; i<w3gp.length; i++) {
			if (w3gp[i]==p) return true;
		}
	} catch (err) {};
	return false;
} 
/*-------------------- getW3gFullPath ---------------------------*/
//	2009.12.18@SO getW3gFullPath...
function getW3gFullPath() {
	var sResult = document.location.protocol + "//" + document.location.hostname;
	if (document.location.port != "") {
		sResult = sResult + ":" + document.location.port;
	}
	sResult = sResult + "/" + window.w3gContex + w3gCalledAction;
	if (w3gCalledParams != "") {
		sResult = sResult + "?" + decodeURIComponent(w3gCalledParams);
	}
	
	return sResult;
}
/*-------------------- language ----------------------------------*/
//var var w3gItemAndSezione; 2008.05.29@FC FIX, in mobile devices redraw with undefined SezioneMetaTile w3gItemAndSezione in page.
//23-07-2008@IV w3gItemAndSezione cannot be undefined; next check statement destroys the meaning of w3gItemAndSezione in mobile javascript engine
//if(typeof w3gItemAndSezione == 'undefined')var w3gItemAndSezione=false;

//2006.09.25@FV fix "location" value is not persistent on IE browser.
//2007.02.21@FV fix clear idLanguage parameter if present in qs
function language(idLanguage) {
//	2009.12.18@SO modifica gestione cambio lingua...
	var strUrl = getW3gFullPath().replace(/#.*/g,"");
//	var strUrl = getW3gDocumentURL().replace(/#.*/g,"");
	var args = strUrl.split("&");
	var newUrl="";
	for (var i=0; i<args.length; i++) {
	 newUrl += (args[i].indexOf("idLanguage")>=0 ) ? "" : (i>0?"&":"")+args[i];
	}
	newUrl += (newUrl.indexOf("?")>0 ? "&":"?") + "idLanguage=" + idLanguage;
	window.open(newUrl,'_self','');
}
/*--------------------------- onloadFunctionAppender ----------------------*/
function onloadAddFunction( fnctn ) {
	if (window.addEventListener) 
		window.addEventListener( 'load', fnctn, false );
	else if (window.attachEvent)  
		window.attachEvent( 'onload', fnctn );
	else window.onLoad = fnctn;
}
/*-------------------- openerWindow ----------------------------------*/
//23.05.2008@FV-FC ADD mobile exception managment - 25.07.08@FV fix
function openerWindow( url ) {
var win;
try {
	if (getW3gParameterCheck("idDevice=mobile"))
		win = window.open( url, '_self','');
	else if (typeof opener != 'undefined' && opener!=null)
		win = opener.window.open( url, '_self','');
} catch (e) { 
	if (confirm("W3G lost synchronization. Please re-load main page"))
		window.close();
}
return win;
}

/*-------------------- formatData ----------------------------------*/
var w3gDateExclusive = false;

function w3gDateAlert(message,obj){
	if(!w3gDateExclusive){
		w3gDateExclusive=true;
		w3gAlert(message,w3gDateCallback.bind(null,obj));
	}
}
function w3gDateCallback(obj){
	w3gDateExclusive=false;
	if(obj)obj.focus();
}
function formatData(campo){
   app = campo.value;
   lungh = app.length;
   // put the separator during the typing
   if(lungh == 3 || lungh == 6) campo.value = campo.value.substring(0,lungh-1) + "-";
   if(lungh == 11) campo.value = campo.value.substring(0,lungh-1) + " ";
   if(lungh == 14) campo.value = campo.value.substring(0,lungh-1) + ":";
} // formatData

/*------------------------- isDateTime ---------------------------------*/
function isDateTime(dateTime, messDescr, messFormat, messNumDays, messFebruary, messMonth, messYear, fullCondition) {
	var dateTimeStr = dateTime.value;
	var isOk = false;
	dateTime.value = (dateTimeStr.length>10) ? dateTimeStr.substring(0,10) : dateTimeStr; // isDate() need html object
	if (isDate(dateTime, messDescr, messFormat, messNumDays, messFebruary, messMonth, messYear, fullCondition) ) {
		dateTime.value = dateTimeStr;
		var timeStr  = (dateTimeStr.length>10) ? dateTimeStr.substring(11) : dateTimeStr;
		isOk = isTime( timeStr, messDescr, messFormat ,dateTime);
		if (!isOk) dateTime.focus();
	}
	return isOk;
}

/*------------------------- isTime ---------------------------------*/
function isTime(timeCrt, messDescr, messFormat ,dateObj){
   var timePat = /^(\d{2})(\:)(\d{2})$/;
   var matchArray = timeCrt.match(timePat); // il formato è corretto?

   if(matchArray == null && timeCrt != "") {
	  w3gDateAlert(messDescr + " : " + messFormat);
      return false;
   }

   if(matchArray != null)  {    
	   hh = matchArray[1];
   	mm = matchArray[3];
   	if (!(hh.length==2 && hh>="00" && hh<"24" && mm.length==2 && mm>="00" && mm<"60" )) {
	   	w3gDateAlert(messDescr + " : " + messFormat,dateObj);
      	return false;
      }
   }  

   return true;
}//isTime*/

/*------------------------- isDate ---------------------------------*/
function isDate(dateObj, messDescr, messFormat, messNumDays, messFebruary, messMonth, messYear, fullCondition) {
   dateCrt = dateObj.value;
   var datePat = /^(\d{2})(\-)(\d{2})(\-)(\d{4})$/;
   var matchArray = dateCrt.match(datePat); // il formato è corretto?
   if(matchArray == null && dateCrt != "") {
	   w3gDateAlert(messDescr + " : " + messFormat,dateObj);
	   //dateObj.focus();
      return false;
   }  
   if(matchArray != null)  {    
      day = matchArray[1];
      month = matchArray[3];
      year = matchArray[5];
    	// look the format
    	if (! checkDataValue("" + day, "" + month, "" + year, messDescr, messNumDays, messFebruary, messMonth, messYear, fullCondition, dateObj) != "" ) {
		  // dateObj.focus();
  			return false;
  		}
	}
   return true;
} // isDate


/*-------------------------- checkDataValue ------------------------*/
function checkDataValue(valGG, valMM, valYY, messDescr, messNumDays, messFebruary, messMonth, messYear, fullCondition,dateObj){
   dataFormatted = "";
   if(valMM != "" && valGG != "" && valYY != "") {
      if (valGG > "31") { // more than 31 days
         w3gDateAlert (messDescr + " : "+ messNumDays,dateObj );
         return dataFormatted;
      }
      if(valGG == "31") { // 31 days
         if(valMM == "04" || valMM == "06" || valMM == "09" || valMM == "11") {
            w3gDateAlert (messDescr + " : " + messNumDays,dateObj );
            return dataFormatted;
         }
      }
      if(valMM == "02") { // feb with 28 days
         if (valGG > "29") {
            w3gDateAlert (messDescr + " : " + messNumDays,dateObj );
            return dataFormatted;
         }
   	   // look if the number of days is 28 or 29 (leap year)
			var data = new Date(valYY, parseInt(valMM), 1);
         data = new Date(data - (24 * 60 * 60 * 1000));
         numDaysInMonth = data.getDate();
			if(parseInt(valGG) > parseInt("" + numDaysInMonth)) {
            w3gDateAlert (messDescr + " : " + messFebruary,dateObj);
            return dataFormatted;
         }
      }
      // check the month
      if(valMM < "01" || valMM > "12") {
         w3gDateAlert (messDescr + " : " + messMonth,dateObj);
         return dataFormatted;
      }
         
      if (fullCondition) {
        	// check the year only if fullCondition IS TRUE
      	if(valYY < "1900") {
         	w3gDateAlert (messDescr + " : " + messYear,dateObj);
         	return dataFormatted;
      	}
      }
   }
   // returns the formatted data
   dataFormatted = valGG + "/" + valMM + "/" + valYY;
   return dataFormatted;
} // checkDataValue
  
/*-------------------------- adjustIFrameSize ------------------------*/
function adjustIFrameSize(iframeWindow) {
 	  if (iframeWindow.document.height) {
	    var iframeElement = parent.document.getElementById(iframeWindow.name);
	    iframeElement.style.height = iframeWindow.document.height + 'px';
	    iframeElement.style.width = iframeWindow.document.width + 'px';
	  }
	  else if (document.all) {
	    var iframeElement = parent.document.all[iframeWindow.name];
	    if (iframeElement) {
		    if (iframeWindow.document.compatMode &&
		        iframeWindow.document.compatMode != 'BackCompat') 
		    { 
		      iframeElement.style.height = iframeWindow.document.documentElement.scrollHeight + 'px';// + 5 + 'px';
		      iframeElement.style.width = iframeWindow.document.documentElement.scrollWidth + 'px';// + 5 + 'px';
		    }
		    else {
		      iframeElement.style.height = iframeWindow.document.body.scrollHeight + 'px';// + 5 + 'px';
		      iframeElement.style.width = iframeWindow.document.body.scrollWidth + 'px';// + 5 + 'px';
		    }
			 //15.12.2008@MV FIX scroll page to top to display admin frame (not scroll when section panel is loaded)
			 //move scrollbar to display window
			 if (iframeWindow.name!="w3gSectionPanelFrame")
			 	parent.window.scrollTo(iframeWindow.screenLeft-iframeElement.style.pixelWidth,iframeWindow.screenTop-iframeElement.style.pixelHeight)
		}
	  }
}

/*----------------------------- hideAdmin ----------------------------*/
function hideAdmin() {
    //MV
    if ( typeof window.parent.advancedWindows != 'undefined' && 
         window.parent.advancedWindows[window.name] !=null ) {
        removeAdvancedWindow(window.name);
    }
    
	displayAdmin( window.name, "none", "none" );
}
  		  
/*----------------------------- showAdmin ----------------------------*/
function showAdmin( winName, noCover ) {
    displayAdmin( winName, "block", "none", noCover );
}

/*----------------------------- displayAdmin ----------------------------*/
function displayAdmin( winName, mode, modeInnerWin, noCover ) {
  if (winName == 'w3gAdminFrame') {
     
	   if (noCover==null || !noCover) {
		   // admin window blocks/releases browser page 
	  	   window.top.displayCover( 'Page', mode );
		   
		   // admin window blocks/releases control panel
	  	   //2008.04.17@MV
	  	   //panel=window.open('','w3gPanel','height=1,width=1,status=no,toolbar=no,menubar=no,titlebar=no,scrollbar=no');
	  	   //if (panel!=null)
		   // try { panel.displayCover( 'Panel', mode ); } catch (e) { panel.close() }
	   }
    	   
	   window.parent.w3gAction.style.display=modeInnerWin;
	   window.parent.w3gList.style.display  =modeInnerWin;
	   window.parent.w3gAdmin.style.display =mode;

	   //reduce frame to 1x1 px, new content will resize window!     
	   hideFrame(window.parent.w3gActionFrame.window);
	   hideFrame(window.parent.w3gListFrame.window);
	   hideFrame(window.parent.w3gAdminFrame.window);
	   
  }
 
  if (winName == 'w3gListFrame') {
	   window.parent.w3gAction.style.display=modeInnerWin;
	   window.parent.w3gList.style.display  =mode;
	   
	   hideFrame(window.parent.w3gActionFrame.window);
	   hideFrame(window.parent.w3gListFrame.window);
  }
  
  if (winName == 'w3gActionFrame') {
	   window.parent.w3gAction.style.display=mode;

  	   hideFrame(window.parent.w3gActionFrame.window);
  }	
  
  //2008.04.17@MV added map frame
  if (winName == 'w3gMapFrame') {
	   window.parent.w3gMap.style.display=mode;

  	   hideFrame(window.parent.w3gMapFrame.window);
  }	
  //2008.08.08@MV added section panel frame
  if (winName == 'w3gSectionPanelFrame') {
       window.parent.w3gSectionPanel.style.display=mode;

  	   hideFrame(window.parent.w3gSectionPanelFrame.window);
  }
}

/*---------------------------- hideFrame ------------------------------*/
function hideFrame (iframeWindow) {
 try {
  if (iframeWindow.document.height) {
    var iframeElement = parent.document.getElementById(iframeWindow.name);
    iframeElement.style.height = '1px';
    iframeElement.style.width = '1px';
  }
  else if (document.all) {
    var iframeElement = parent.document.all[iframeWindow.name];
    if (iframeWindow.document.compatMode &&
        iframeWindow.document.compatMode != 'BackCompat') 
    {
      iframeElement.style.height = '1px';
      iframeElement.style.width  = '1px';
    }
    else {
      iframeElement.style.height = '1px';
      iframeElement.style.width  = '1px';
    }
  }
 } catch (e) {}
}

/*2008.08.08@MV----------------------------- new coverAdmin ----------------------------*/
/*2006.07.27@FV----------------------------- coverAdmin ----------------------------*/
//coverStyleFilter="Alpha(Opacity=40, FinishOpacity=80, Style=2, StartX=50, StartY=50, FinishX=0, FinishY=0)"; 
var covertStyleOpacityValue = 70;
var covertStyleOpacityColor = "#000";
//coverStyleFilter="Alpha(Opacity=35, FinishOpacity=35, Style=2, StartX=50, StartY=50, FinishX=0, FinishY=0)"; 
function displayCover( name, status, msg ) {
    var cover = document.getElementById("w3g"+name+"Cover");
	var wait = document.getElementById("w3g"+name+"Wait");
	if (cover!=null) {
	    var coverBody = cover.contentWindow.document.body;
	
		if (status=='block') {
			try { // to extend cover to current window height&width..... 
			    cover.style.height = window.dimensions().height;
			    cover.style.width = window.dimensions().width;
                //cover.style.height= document.getElementById("w3gEndPage").offsetTop;
				//cover.style.width= document.getElementById("w3gEndPage").offsetLeft;
			} catch (e) {}
			//cover.style.filter = coverStyleFilter;
			cover.style.opacity = "."+ covertStyleOpacityValue;
			cover.style.filter ="alpha(opacity="+ covertStyleOpacityValue +")";
			coverBody.style.backgroundColor = covertStyleOpacityColor;
			
			// nascondi menu e pannello sezioni
			//06.08.2009@MV blocca scorrimento pannello di amministrazione sezioni
			blockWindow(getWindowParent().getIframeWinDoc('w3gSectionPanelFrame')[0]);
			if ($('w3gAdminMenu')) $('w3gAdminMenu').style.display = "none";
			if ($('w3gSectionPanel')) $('w3gSectionPanel').style.display = "none";
			
		} else {
			// rivisualizza menu e pannello sezioni
			//06.08.2009@MV ripristina scorrimento pannello di amministrazione sezioni
			blockWindow(getWindowParent().getIframeWinDoc('w3gSectionPanelFrame')[0]);
			if ($('w3gAdminMenu')) $('w3gAdminMenu').style.display = "block";
			if ($('w3gSectionPanel')) $('w3gSectionPanel').style.display = "block";
		}
		cover.style.display = status;
	}	
	if (wait!=null) {
		wait.style.display = status;
		if (msg!=null) wait.innerText = msg;
	}		
}
/*---------------------------- normalizeUTF8 ------------------------------*/
if (document.layers) { //in Netscape4 always filtered!
	window.captureEvents(Event.KEYPRESS);
	window.onkeypress = normalizeUTF8;
}
function normalizeUTF8( evt ) {
	wkc = (evt.which || evt.keyCode || evt.charCode);
	return (wkc<255)&&(wkc!=128);
}

/*2005.07.18@FV new--------------------------------- isEmail ------------------------------*/
function isEmail (s){
   if (s.length == 0) return (false);
   i = s.indexOf(" ");
   if (i > 0) return (false);
   indiceAt = s.indexOf("@");
   if (indiceAt <= 0) return (false);
   indiceUltimoPunto = s.lastIndexOf(".", s.length);
   if (indiceUltimoPunto <= 0) return (false);
   nomeDominio = s.substring((indiceAt+1), indiceUltimoPunto);
   if (!isDomainName(nomeDominio,1)) return (false);
   topLevelDomain = s.substring((indiceUltimoPunto+1), s.length);
   if (!isDomainName(topLevelDomain,2))  return (false);

   return (true);
}

/*2005.07.18@FV new------------------------------------- isDomainName ----------------------------*/
function isDomainName(checkStr, minLength){
  if (checkStr.length < minLength) return false;
  var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  return allValid;
}

/*2005.09.01@FV new------------------------------------- myInnerText ----------------------------*/
function myInnerText( xStr ) {
   var regExp = /<\/?[^>]+>/gi;
   xStr = xStr.replace(regExp,"");
   return xStr;
}

/*2006.07.18@FV new------------------------------------- set/get cookie ----------------------------*/
function getCookie( cookieName ) {
	var cookieJar = document.cookie.split( "; " );
	for( var x = 0; x < cookieJar.length; x++ ) {
		var oneCookie = cookieJar[x].split( "=" );
		if( oneCookie[0] == escape( cookieName ) ) { 
		return unescape( oneCookie[1] ); 
		}
	}
	return null;
}

function setCookie( cookieName, cookieValue, lifeTime, path, domain, isSecure ) {
	if( !cookieName ) { return false; }
	if( lifeTime == "delete" ) { lifeTime = -1; } //this is in the past. Expires immediately.
	/* document.cookie = newValue is equivalent to document.cookie = newValue + "; " + document.cookie; */
	document.cookie = escape( cookieName ) + "=" + escape( cookieValue ) +
		( lifeTime ? ";expires=" + ( new Date( ( new Date() ).getTime() + ( 1000 * lifeTime ) ) ).toGMTString() : "" ) +
		( path ? ";path=" + path : "") + ( domain ? ";domain=" + domain : "") + 
		( isSecure ? ";secure" : "");
	//check if the cookie has been set/deleted as required
	if( lifeTime < 0 ) { if( typeof( getCookie( cookieName ) ) == "string" ) { return false; } return true; }
	if( typeof( getCookie( cookieName ) ) == "string" ) { return true; } return false;
}

/*2006.07.18@FV new------------------------------------- hotkey check ----------------------------*/
function isJSHotKeyActive(){
	var fname=''+document.onkeypress;
	var hkfname='HotKey';
	if (fname==''||fname==null) return false;
	// recupera il nome della funzione dal corpo
	if(fname.substr(0,'function'.length).toLowerCase()=='function')
		fname=fname.substr('function'.length+1,fname.indexOf('(')-('function'.length+1));
	return fname==hkfname?true:false;
}

/*2007.04.23@FV new------------------------------------- tags visibility ----------------------------*/
function hideTags(elemID) {
	setTagsVisibility( elemID, "hidden" );
}
function showTags(elemID) {
	setTagsVisibility( elemID, "visible" );
}
function setTagsVisibility(elemID, status) {
	 if (window.document.all) {
	   for (i = 0; i < document.all.tags(elemID).length; i++) {
		obj = document.all.tags(elemID)[i];
		if (! obj || ! obj.offsetParent) {alert(i + ' skipped');continue;}
		obj.style.visibility = status;
	   }
	 }	
	 if (parent.frames["result_set"]!=null) {   
	   for (i = 0; i < result_set.document.all.tags(elemID).length; i++) {
		 obj = result_set.document.all.tags(elemID)[i];
		 if (! obj || ! obj.offsetParent) 
		 	continue;
		 obj.style.visibility = status;
	   }
	 }
}
/*2007.05.15@FV ----------------------------- WAI facility ------------------*/
function w3gFixBadAnchorsAttributes() {
	try {
		 if (window.document.getElementsByTagName) {
		   var anchors = window.document.getElementsByTagName("A");	  
		   for (i = 0; i < anchors.length; i++) {
		   	 var obj = anchors[i];
		   	 if (! obj || ! obj.offsetParent) continue;
		   	 w3gAdjustOpenPopAnchorTitle(obj);
		   	 w3gApplyContexRootToAnchorURL(obj);
		   	 
		   	 /*2008.02.05@MV esegue altre funzioni dichiarate all'interno dell'array di funzioni
		   	 w3gAnchorFunctionArray dichiarato all'intero del media
		   	 */
		   	 if(typeof(w3gAnchorFunctionArray)!='undefined'){
		   	 	if(w3gAnchorFunctionArray!=null)
		   	 		for(j=0;j<w3gAnchorFunctionArray.length;j++)
      					w3gAnchorFunctionArray[j](obj);
      		}
             	 		 			
		   }	
	   	}
	}catch (e) {/*alert(e)*/
	}
}

//15.10.2008@MV to enable link highlighting from keyboard
/*
Event.observe(document, 'keypress', function(e){ 	
				var code;	
				if (!e) var e = window.event;	
				if (e.keyCode) code = e.keyCode;	
				else if (e.which) code = e.which;	
				var character = String.fromCharCode(code);
				if (character == 'L' || character == 'l')
					w3gAddOpenPopAnchorImg();
				});
*/
//15.10.2008@MV function to enable link highlighting in page
function w3gAddOpenPopAnchorImg(enableIcon) { 
	try {
		 if (window.document.getElementsByTagName) {
		   var anchors = window.document.getElementsByTagName("A");	   
		   for (i = 0; i < anchors.length; i++) {
		   	 var obj = anchors[i];
		   	 if (! obj || ! obj.offsetParent) continue;
		   	 
		   	 var addLinkImg=false;
		   	 // abilita immagine solo in ancore che contengo del testo
		   	 if (document.all) { //IE
                  if (obj.innerText!="") addLinkImg=true;
			 } else { //FF
			      if (obj.textContent!="" && obj.textContent!="\n" ) { 
			         addLinkImg=true;
                  }
            }
		   	
		   	if (addLinkImg) {	
		   	      var img = $(obj).getElementsByClassName('w3g_link_arrow_img')[0];
				  
				  if (typeof enableIcon == 'undefined') {// switch automatico derivante da keypress  	
				      if ( img )  // immagine link già presente ma nascosta
				    	if (!img.visible() ) img.show();
				    	else  img.hide(); 
				  } else if (enableIcon) { // aggiungi immagine a link    
				    if ( img )  // immagine link già presente ma nascosta
				    	if (!img.visible() ) img.show();
				  } else  // togli immagine a link
				  	 if ( img && img.visible() ) img.hide();  // immagine link già presente ma nascosta  	
				  
				  if (!img) { // immagine link non presente: viene creata
						var linkImg = document.createElement('img');
						linkImg.className = 'w3g_link_arrow_img';
						linkImg.src="img/link_arrow.gif";
						obj.appendChild(linkImg);
				  }
			 }	 			
		   }	
	   	}
	} catch (e) {}
}

function w3gAdjustOpenPopAnchorTitle(obj, enableIcon){
    enableIcon = true;
	if(w3gUtils.Undefined(obj))return;	
	try {	
	  var w3gSN = location.host;
	  var w3gCTX = "/" + window.w3gContex;
      if (waiOpenPopKeywords && waiOpenPopAlert && waiOpenPopAttachment) {	   
			//if (! obj || ! obj.offsetParent) continue;
			// 2008.09.16@SO fix su controllo waiOpenPopKeywords e previene che venga settato il titolo più di una volta
			if ((obj.href.indexOf("openPop(")>=0) && 
			    (!new RegExp(waiOpenPopKeywords.replace(/,/g,'|')).test(obj.title)) &&
//				(obj.title.length==0 || waiOpenPopKeywords.indexOf(obj.title)<0)) { //not already set via cms
				(obj.title.length==0 || (obj.title.indexOf(waiOpenPopAttachment)<0 && obj.title.indexOf(waiOpenPopAlert)<0))) { //not already set via cms
					var txt="";
					if (obj.href.indexOf("media/show")>=0) //link to an attachment
						txt = waiOpenPopAttachment;
					else
						txt = waiOpenPopAlert;
					obj.title = (obj.title.length>0) ? obj.title+". "+txt : txt;
			}
            
   	  }
      //2009.05.07@FC-FV merge functions.
      /*var href_lower = obj.href.toLowerCase();
      if (!((href_lower.indexOf("http://")>=0 || href_lower.indexOf("https://")>=0) && obj.href.indexOf(w3gSN)<0)) {		
		  	//2007.07.21@IV redraw internal links for media
		    if (obj.href.indexOf("openPop")>=0 && obj.href.indexOf("media/show?")>=0)
	    		obj.href = obj.href.replace("media/show?","popupMedia.do?id=");  
		}*/
  } catch(e) {/*alert(e)*/} 
}

function w3gApplyContexRootToAnchorURL(obj) {
	if(w3gUtils.Undefined(obj))return;
	try {
	 	var w3gSN = location.host;
  	 	var w3gCTX = "/" + window.w3gContex; 	  		  
   	  	var original_href = w3gUtils.Undefined(obj.getAttribute('href'))?null:obj.getAttribute('href');	
	  	var openPopRegExp = new RegExp("(javascript(?: )?:(?: )?openPop(?: )?\\((?: )?')","i");
   	  	if(w3gUtils.Nullalize(original_href)!=null){
 	 		var new_href = w3gUtils.Trim(original_href);
     	 	var lnew_href=  new_href.toLowerCase();
/*     	 	if(lnew_href.indexOf('/')!=0
	     	 	&& lnew_href.indexOf('javascript:')<0
	     	 	&& lnew_href.indexOf('#')!=0
	     	 	&& lnew_href.indexOf('http:')!=0
	     	 	&& lnew_href.indexOf('https:')!=0	
	     	 	&& lnew_href.indexOf('mailto:')<0	 			
 	 		)*/
			//FC@2010.12.06 match ANY link protocol pattern (eg. "http:" "tel:" "sms:" "mailto:" "javascript:" etc.)
		    if(lnew_href.indexOf('/')!=0 && !/^\w+:/.test(lnew_href) && lnew_href.indexOf('#')!=0 )
 	 		{
   	 	 		new_href = w3gCTX+'/'+ new_href;
	   	 	 	obj.setAttribute('href',new_href);		   	 	 	
	     	 }else if(
	     	 	new_href.match(openPopRegExp)&&
	     	 	(!new_href.match(new RegExp("'( )?http",'i')))&&
				(!new_href.match(new RegExp("'( )?/",'i')))
	     	 ){
	     	 	new_href = new_href.replace(openPopRegExp,'$1'+w3gCTX+'/')		     	 	
	     	 	obj.removeAttribute('href');
	   	 	 	obj.setAttribute('href',new_href);		   	 	 		     	 
	     	 }
     	}
	}catch(e){/*alert(e)*/} 
}


/*2008.02.05@MV Funzione per la generazione di Help balloons da associare alle chiamate al Wrapper */
var w3gWrapperCalled=0;
var w3gHelpBalloons=new Array();

function w3gAdjustWrapperUrl(obj) {
	  try {
	    var href = obj.href;
	    if (href.indexOf("W3GWrapper?W3GAction=help")>=0) {
		    //trova la prima occorrenza del carattere '
		    var indexOfWrapperUrl = href.indexOf("'");
		    var wrapperUrl = href.substring(indexOfWrapperUrl+1);
		    //trova la seconda occorrenza del carattere '
		    var indexOfLastChar = wrapperUrl.indexOf("'");
		    // estrae l'url della chiamata al wrapper
		    wrapperUrl = wrapperUrl.substring(0,indexOfLastChar);
		    // associa una id incrementale all'ancora (per poterci associare un evento)
		    obj.id='w3gHelpBalloon'+w3gWrapperCalled;
		      
		    //trova il titolo di default
		    var patternForTitleStart = "W3GAction=";
		    var patternForTitleEnd = "\&";
		     
		    var indexForTitleStart = wrapperUrl.indexOf(patternForTitleStart);
		    var indexForTitleEnd = wrapperUrl.indexOf(patternForTitleEnd);
		    var title = wrapperUrl.substring(indexForTitleStart+patternForTitleStart.length,indexForTitleEnd); 
		    // estrae l'url della chiamata al wrapper
		    wrapperUrl = wrapperUrl.substring(0,indexOfLastChar);

            if(typeof(w3gCostumizedHelpBalloon)=='function') {
                // deve essere definita la funzione w3gCostumizedHelpBalloon nella quale passare tutti
                // i parametri necessari alla generazione dell'help balloons (si veda esempio helpBalloons.js)
                w3gWrapperCalled++;
                w3gHelpBalloons[obj.id] = w3gCostumizedHelpBalloon(obj.id, title, wrapperUrl);
		    	obj.href="javascript: void(0);";  
		    	obj.title = title;
		    }
	   }	     
	 } catch(e) {/*alert(e)*/} 
}


onloadAddFunction(w3gFixBadAnchorsAttributes);

//2008.04.28@FC get user's screen resolution.
window.screenDimensions= function() {
   var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
	var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
	return {
        height: parseInt(height||0, 10),
        width: parseInt(width||0, 10)
   	 }; 
}
//2008.04.28@FC get window full dimension (scrollSize included).
window.dimensions=  function() {
	var width = Math.max(Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth), document.body.scrollWidth);
    var height =  Math.max(Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.body.scrollHeight));
		
	return {
        height: parseInt(height||0, 10),
        width: parseInt(width||0, 10)
   	 };     
}
//2008.04.28@FC get the current viewport on user browser.
window.viewportDimensions= function() {
    var intH = 0, intW = 0;
        
    if(self.innerHeight) {
       intH = window.innerHeight;
       intW = window.innerWidth;
    } 
    else if(document.documentElement && document.documentElement.clientHeight) {
            intH = document.documentElement.clientHeight;
            intW = document.documentElement.clientWidth;
    }
    else if(document.body) {
            intH = document.body.clientHeight;
            intW = document.body.clientWidth;
    }
    return {
        height: parseInt(intH, 0),
        width: parseInt(intW, 0)
    };
}

var w3gCSS = {
	css_namePrefix: 'generali',
    css_cookieId: 'w3gStyleSheet'
}

w3gCSS.changeParam = function(name,value){
	//2009.03.10@FC FIX reload also with ALL the parameters in qs
	var fontParam={};
	fontParam[name]=value;
	w3gLocation.reload(fontParam);
}
w3gCSS.setFontSize = function(preferredStyle) {
	if(!preferredStyle)preferredStyle=w3gCSS.css_namePrefix;
	setCookie(w3gCSS.css_cookieId+'-fontSize',preferredStyle,0,'/');	
	w3gCSS.changeParam('fontSize',preferredStyle);
}

w3gCSS.setContrast = function(preferredStyle) {
	if(!preferredStyle)preferredStyle=w3gCSS.css_namePrefix;
	setCookie(w3gCSS.css_cookieId+'-contrast',preferredStyle,0,'/');	
	w3gCSS.changeParam('contrast',preferredStyle);
}

w3gCSS.toggleContrast = function() {
	//2009.03.10@FC FIX contrast first call now set 'dark' in params
	var w3gPars = w3gLocation._queryStringToHash(w3gItemAndSezione);
	value = ((!w3gPars.contrast) || w3gPars.contrast=='null') ? 'dark' : 'null';
	w3gCSS.setContrast(value);
}

//08.11.07@FC Classe di utilità;
function w3gUtils(){return;}
w3gUtils.Undefined = function(variable){
	return typeof(variable)=='undefined';
}
w3gUtils.Trim= function (toTrim){
	if(w3gUtils.Undefined(toTrim))throw 'w3gUtils.Trim require parameter';
	while (toTrim.substring(0,1) == ' ')
		toTrim = toTrim.substring(1, toTrim.length);
	while (toTrim.substring(toTrim.length-1, toTrim.length) == ' ')
		toTrim = toTrim.substring(0,toTrim.length-1);
	return toTrim;
}	
w3gUtils.Nullalize = function (toNull){
	if(w3gUtils.Undefined(toNull))throw 'w3gUtils.Nullalize require parameter';
    if(toNull==null)return toNull;
    return w3gUtils.Trim(toNull)==''? null : toNull;
}
w3gUtils.NullToBlank = function (toBlank){
    if(w3gUtils.Undefined(toBlank))throw 'w3gUtils.NullToBlank require parameter';
    if(toBlank==null)return '';
    return toBlank;
}
w3gUtils.Version= function(){
	var release ='1';
	var major='0';
	var minor='0';		
	this.release=release;this.major=major;this.minor=minor;	
	function fullVersion(){	return release+'.'+major+'.'+minor; }
	return fullVersion();
}
//ritorna il contex w3g o quello contenuto nella location
w3gUtils.Contex = function(){
	return window.w3gContex || location.pathname.split("/")[1];
}

if(!window.find){
	window.find=function (pattern){	
	    if(!pattern || pattern=='')return false;
		var textRange = document.body.createTextRange();
	    var found = textRange.findText(pattern); 
	    if(found){
	      try{textRange.select();}catch(err){/*IE6 CSS bug, unselectable text*/}
	      textRange.scrollIntoView();  
	    }
		return found;
	}
}
/** STRING EXTENSION ******************************************************************************************************/
if(typeof String.prototype.trim =='undefined'){
    String.trim = function(string) { return string ==null ? string : string.replace(/^\s+|\s+$/g, ''); };
    String.prototype.trim=function(){
      return String.trim(this);
    }
}
String.encodeHTML= function(text){
  var len = text.length, escaped='', thisChar = '';
  for (var i=0; i < len; ++i)  {
    thisChar = text.substring(i, i+1);
    var codeChar = thisChar.charCodeAt(0);
    if (codeChar>160) thisChar="&#"+codeChar+";";    
    escaped += thisChar;         
  }
  return escaped;
}
String.prototype.encodeHTML= function(){
  return String.encodeHTML(this);
}
String.decodeHTML=function(text){
  var match = text.match(/&#(\d\d\d\d?);/g);  
  if(match!=null){
	  for(var i=0; i<match.length; i++){
	    var html = match[i];
	    var thisChar = Number(html.replace(/&|#|;/g,''));
	    if(!isNaN(thisChar)){
	      var thisChar = String.fromCharCode(thisChar);       
	      text = text.replace(html,thisChar);
	    }
	  }
  }
  return text;
}
String.prototype.decodeHTML= function(){
  return String.decodeHTML(this);
}
String.translateAccents= function (strAccents) {
    strAccents = strAccents.split('');
    strAccentsOut = new Array();
    strAccentsLen = strAccents.length;
    var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
    var accentsOut = ['A', 'A', 'A', 'A', 'A', 'A', 'a', 'a', 'a', 'a', 'a', 'a', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'o', 'o', 'o', 'o', 'o', 'o', 'E', 'E', 'E', 'E', 'e', 'e', 'e', 'e', 'e', 'C', 'c', 'D', 'I', 'I', 'I', 'I', 'i', 'i', 'i', 'i', 'U', 'U', 'U', 'U', 'u', 'u', 'u', 'u', 'N', 'n', 'S', 's', 'Y', 'y', 'y', 'Z', 'z'];
    for (var y = 0; y < strAccentsLen; y++) {
        if (accents.indexOf(strAccents[y]) != -1) {
            strAccentsOut[y] = accentsOut[accents.indexOf(strAccents[y])];
        } else strAccentsOut[y] = strAccents[y];
    }
    strAccentsOut = strAccentsOut.join('');
    return strAccentsOut;
} 
String.prototype.translateAccents= function(){
  return String.translateAccents(this);
}
String.blank=function(string) {
  return /^\s*$/.test(string);
}
String.prototype.blank= function(){
  return String.blank(this);
}

/***************************************************************************************************************************/
/**
* Evidenza tutte le ricorrenza di un dato patter di ricerca (supporto wild char google like)
*/
window.search = function(pattern/*[,container-element]*/){
    window.undoHighlight();
    var timeout = 10000;
    var container = arguments[1] || $$('.w3gSectionOuterContainer')[0] || document.body;
    var first = null;
    var start = new Date().getTime();
    var excludeTags = /script|style|embeded|noscript|object/ig;
    function purgeTerm(key){
        key = key.replace(/\+/g,"")
                .replace(/\-/g,"")			
                .replace(/\./g,"\\\\.")	
                .replace(/\~/g,"")
                .replace(/\?/g,".")
                .replace(/\*/g,".*?")
                .replace(/\s/g,"\\\\s");
        return key;
    }
    var styles =[
        {color:'black','background-color':'yellow'},
        {color:'black','background-color':'cyan'},
        {color:'black','background-color':'PaleGreen'},
        {color:'black','background-color':'LightPink'},    
        {color:'black','background-color':'Orange'},    
        {color:'white','background-color':'red'},
        {color:'black','background-color':'SkyBlue'},
        {color:'black','background-color':'Violet'},
        {color:'white','background-color':'Crimson'},
        {color:'white','background-color':'Coral'},
        {color:'white','background-color':'DodgerBlue'}        
    ];       
    function getTextNodes(parent){
        var textNodes = new Array();
        if(document.evaluate){ //XPATH LEVEL 3                                                       
           var xPathResult = document.evaluate('.//text()[normalize-space(.) != ""]',parent, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
           if(xPathResult){
               for (var i = 0, l = xPathResult.snapshotLength; i < l; i++) {
                var textNode = xPathResult.snapshotItem(i);
                textNodes.push(textNode);                                                     
               }
           }
        }else {            
            var nodes = parent.descendants();
            nodes.push(parent);
            nodes.each(function(element){
                       $A(element.childNodes).each(function(node){
                            if(node.nodeType==3){
                               textNodes.push(node);  
                            }
                       })
            });
        }
        return textNodes;
    }
    function doHighlight(node, searchTerm, styleHash) {
        node = $(node);
        var parent = node.parentNode;
        if(excludeTags.test(parent.tagName)){
            return;
        }var style='';
        styleHash =  styleHash||{color:'black','background-color':'yellow'};        
        for(name in styleHash){
          style += name+':'+styleHash[name]+" !important;"
        }
        var text = node.nodeValue;   
        var modified = false;
        var next = true;
        while(next){
            next = false;
            //FC@2010.11.17, fix multiline bug...
            //FC@2010.11.03, add banduary clausole
            //FC@2010.11.25, drop regexp matcher... using substring  
            var hits =text.search(new RegExp(searchTerm,'ig'));
            if(hits===-1)
              continue;
            var preText = text.substr(0,hits);
            var wrapText= text.substr(hits,searchTerm.length);
            var postText =  text.substr(hits+searchTerm.length);
            if(typeof wrapText!='undefined' && wrapText!=''){
                if(first==null){
                    first=wrapText;
                }
                preText = typeof preText!='undefined' ? document.createTextNode(preText) : null;    
                var wrap = $(document.createElement('SPAN'));                
                if(preText!=null){
                    parent.insertBefore( preText , node);
                }
                parent.insertBefore( wrap   , node );
                wrap.className='highlighted';
                wrap.setStyle(styleHash);
                wrap.update(wrapText);
                text = typeof postText!='undefined' ? postText: null;
                if(text!=null)
                    next = true;
                modified = true;
            }
        }
        if(modified){
            text = typeof text!='undefined' && text!='' ? document.createTextNode(text):null;
            if(text!=null){
               parent.insertBefore( text    , node);
            }
            parent.removeChild(node);
        }
    }
    var searchArray = new Array();
    //estrazione ricerca frase "string1 string2 ... stringN"
    pattern =pattern.replace(/\+(".+?")/g,"$1").replace(/\-".+?"/g,"").replace(/\-.+?(\s|$)/g,"").trim();
    var phrases = pattern.match(/".+?"/)|| new Array();    
    for(var i=0; i < phrases.length; i++){
     pattern = pattern.replace(phrases[i],'');
     phrases[i] = phrases[i].replace(/"/g,'');
    }
    for(var i=0; i < phrases.length; i++){if(phrases[i]!="") searchArray.push(phrases[i]);}
    var keys = pattern.split(" "); 
    for(var i=0; i < keys.length; i++){
      var key = purgeTerm(keys[i]);      
      if(key!="" && key.length>3){
        searchArray.push(key);
      }
    }
    //odering key by length;
    var unsorted = true;
    while(unsorted){
      unsorted=false;
      for(var i=0;i<searchArray.length-1;i++ ){
        var k1 = searchArray[i];
        var k2 = searchArray[i+1];        
        if(k1.length< k2.length){
          searchArray[i+1]=k1;
          searchArray[i]=k2;
          unsorted=true;
        }
      }
    }
    for (var i = 0; i < searchArray.length; i++) {
        var textNodes = getTextNodes(container);     
        for (var j = 0; j < textNodes.length; j++) {
            var node = textNodes[j];
            if(node.nodeValue.trim()!=''){
              try{
                doHighlight(node, searchArray[i],styles[i % styles.length]);
              }catch(e){
                //NOP
              }
            }
            if(new Date().getTime()-start > timeout){
                return;
            }
        }     
    }
   /*if(first!=null){        
        window.find($$('span.highlighted')[0].innerHTML);
        return;
    }*/
    window.focus();
    return;
}
<%if (prototype){%>
Element.addMethods({
   highlight:function(element,pattern){
      element = $(element);      
      window.search(pattern,element);
   },
   undoHighlight:function(){      
      window.undoHighlight();
   }
})
<%}%>
window.undoHighlight = function(){
  var fonts = $$('span.highlighted'); 
  for(var i=0;i<fonts.length;i++){
    var font =fonts[i];
      if(font.outerHTML){
        font.outerHTML = font.innerHTML;
      }else{
        var iRange = document.createRange();
        iRange.setStartBefore(font);
        var strFragment = iRange.createContextualFragment(font.innerHTML);
        var sRangeNode = iRange.startContainer;
        iRange.insertNode(strFragment);
        sRangeNode.removeChild(font);
      }
  }
}

function existFunction(functionName) {
  try {
	   if (typeof (eval(functionName)) == "function" ) {
	   	return true;
	   } else 
	   	return false;
  } catch (e) {return false;}
}


function deleteCookie(name, path, domain) {
	if(getCookie(name)) {
	    var date = new Date();
		date.setTime(date.getTime()-100000);
		document.cookie=name+"="+((path)?"; path="+path:"")+
		((domain)?"; domain="+domain:"")+"; expires="+ date.getTime();
	}
}
    
//2008.08.08@MV opacizza sezioni in pagina e nel pannello delle sezioni (utilizzata in amministrazione)
function w3gOpacifyElement(elementId, opacityValue, opacityColor, isFromOnResizeEvent) {
  try {	 	
    var element =$(elementId);
	// getHeight, getWidth and cumulativeOffset are prototype function
	//var height = element.getHeight();
	//var width = element.getWidth();

	var offset = Position.cumulativeOffset(element);
	
	var opacityDiv = $("opacityDiv"+elementId);
	if (isFromOnResizeEvent)
		opacityDiv.style.display = "none";
	var newDiv = false;
	if (!opacityDiv) { // if not opacity div already exits
	    newDiv = true;
    	opacityDiv = document.createElement("div");
    	opacityDiv.id = "opacityDiv"+elementId;
    	opacityDiv.style.position = "absolute";
		opacityDiv.style.zIndex = "1000";
		// opacity value
		if (!opacityValue) { // default opacity
			opacityDiv.style.opacity = ".25"; // 0 is transparent, 1 is full color
			opacityDiv.style.filter ="alpha(opacity=25)";
		} else { // specified opacity
			opacityDiv.style.opacity = "."+ opacityValue;
			opacityDiv.style.filter ="alpha(opacity="+ opacityValue +")";
		}
		// opacity color
		if (!opacityColor) // default color
			opacityDiv.style.backgroundColor = "#C0C0C0"; // gray	
		else // specified color
			opacityDiv.style.backgroundColor = opacityColor;	

    }    	
	//opacityDiv.style.top = offset[1]+"px";
	//opacityDiv.style.left =  offset[0]+"px";
	opacityDiv.style.height = "100%";
	opacityDiv.style.width = "100%";

	if (newDiv) element.appendChild(opacityDiv);
    // necessary for a correct immediate visualization of the opacify div
    opacityDiv.style.display = "block";
   } catch(e) {}
}

onloadAddFunction(function(){
	//2009.03.10@FC ADD new w3gLocation class manager
	window.location.w3gParameters = w3gLocation.getParameters();
	if(window.location.w3gParameters.highlightSearch){
		    var pattern = unescape(window.location.w3gParameters.highlightSearch).decodeHTML();
			window.search(pattern);			
	}

});

/*18.12.2008@MV moved here from usability.jsi to share these functions */
function w3gOpenPopOrPrint() {
   // 2009.01.26@SO Fix per gestione Tabber e Pager...
   var sPage = '';
   var nPage = 0;
   // 2009.01.26@SO Aggiunta anche sezionePSV...
   // 2009.08.18@IV Fix sezionePSV per url semantiche
   if (getW3gDocumentURL().indexOf("sezione.do")>0 || getW3gDocumentURL().indexOf("/sezione/")>0 || getW3gDocumentURL().indexOf("sezionePSV.do")>0 || getW3gDocumentURL().indexOf("/sezionePSV/")>0) {
      if (document.forms['sezioneInternetVis'] 
            && document.forms['sezioneInternetVis'].currentPage) {
         nPage = Number(document.sezioneInternetVis.currentPage.value);
         if (nPage != 0 && !isNaN(nPage)) {
            if (nPage > 1) {
               sPage = '&currentPage=' + (nPage-1) + '&operation=Succ';
               if (document.location.search.indexOf('tabberPos=') > 0) {
                   sPage = sPage + '&' + document.location.search.substr(document.location.search.indexOf('tabberPos='));
               }
            } 
         }
      }
      // 2009.06.04@FV need context for semantic url compliance
      openPop('/'+window.w3gContex+'/sezionePop.do?print=true'+w3gItemAndSezione+sPage);
   }
   else window.print();
}
function w3gSendAMail() {
 window.open('mailto:?subject='+escape(document.title)+'&body='+escape(getW3gDocumentURL()),'_self','');
}

/*08.01.2009@MV show time voyager value in the top of page */
function w3gTimeVoyagerFilterActived(date) {
 try {
    var div = document.createElement("div");
    div.id="w3gTimeVoyagerInfo";
    div.innerHTML = "Time voyager: <font style='font-weight:bold;'>" + date+"</font>";
    div.style.position = "absolute";
    div.style.top = "0px";
    div.style.left = "0px";
    div.style.width="100%";
    div.style.padding = "0px";
    div.style.zIndex = "100000";
    div.style.backgroundColor = "#000000";
    div.style.opacity = ".50";
    div.style.filter ="alpha(opacity=50)";
    div.style.textAlign = "center";
    div.style.fontFamily = "Verdana, Geneva, Arial, Helvetica, sans-serif";
    div.style.fontSize = "12px";
    div.style.color = "#ffffff";
    // button to hide 'w3gTimeVoyagerInfo' div
    var divClose = document.createElement("div");
    divClose.id="w3gTimeVoyagerClose";
    divClose.innerHTML="chiudi[x]";
    divClose.style.position = "absolute";
    divClose.style.top = "0px";
    divClose.style.right = "10px";
    divClose.style.color = "red";
    divClose.style.cursor = "pointer";

    div.appendChild(divClose);
    document.body.appendChild(div);
    Event.observe( 'w3gTimeVoyagerClose', 'click', function() { $('w3gTimeVoyagerInfo').style.display='none'; } );
 } catch (e) {}
}
/*
2009.03.10@FC document location manager
*/
var w3gLocation={  
    _queryStringToHash:function(string){
		var params = {};
		if(string){
			if(string.charAt(0)=='?')
				string = string.substr(1);
			string = string.split('&');
			for(var i=0;i<string.length;i++){
				string[i]= string[i].split('=');
				params[string[i][0]]=string[i][1]||null;
			}		
		}
		return params;
    },
    _hashToQueryString:function(hash){
       var qs = '';
       for(var name in hash){
           if(name){
               qs+=(qs==''?'':'&')+name;
               qs+='='+(hash[name]==null?'':hash[name]);
           }
       }
       return qs;
    },
    _joinHash:function(destination,source){
        for(var name in source){
            destination[name]=source[name];
        }
    },
    /**
    *Ritorna la URI della pagina corrente, senza query string
    *return <String>: uri senza QS
    */
    getURI:function(){/*FC@2011.01.25 FIX reload with duplicated params issiue*/
        var urlLimit = document.URL.indexOf("?");
        var URI =  document.URL.substring( 0, (urlLimit>0 ? urlLimit : document.URL.length));        
        return URI;
    },
    /**
    *Ritorna l'hash (acnora interna) URI della pagina corrente, senza query string
    *return <String>: uri senza QS
    */
    getHash:function(){
        var parts = (document.URL).match(/.*(#[^\?]*)/);
        return parts && parts.length>1?parts[1]:'';
    },
    /**
    *Converte la query string in un hash
    *@return <Hash> di parametri, nome:valore
    */
    getParameters:function(){                
        return w3gLocation._queryStringToHash(window.location.search);
    },
    /**
    *Sovrascrive/aggiunge il set di parametri nella query string e ricarica la pagina (vedi. w3gLocation.reload)
    *@param newparam <Hash>: set di parametri da sovrascrivere/aggiungere {nome1:valore1, nome2:valore2...}
    */
    setParameters:function(newparam){
        var parameter = w3gLocation.getParameters();
        w3gLocation._joinHash(parameter,newparam);
        w3gLocation.reload(parameter);
    },
    /**
    *Ricarica la pagina ed se specificato sovrascrive/aggiunge il set di parametri nella query string
    *@param [parameter] <Hash>: set di parametri da sovrascrivere/aggiungere {nome1:valore1, nome2:valore2...}
    */
    reload:function(parameter){
        var reloadParam = w3gLocation.getParameters();
        w3gLocation._joinHash(reloadParam,w3gLocation._queryStringToHash(w3gItemAndSezione));
        if(parameter)
            w3gLocation._joinHash(reloadParam,parameter);
        var url = w3gLocation.getURI() + '?' + w3gLocation._hashToQueryString(reloadParam);
        window.open(url+w3gLocation.getHash(),'_self','');
    }
}

/*31.03.2009@MV Return an array with windows (1st element of array) and document (2nd element) objects reference of the iframe  */
function getIframeWinDoc(iframeName) {
 try {
 var iframe = $(iframeName);
  
 if (iframe != null) {
    var doc = iframe.document;
    var win;
    if(iframe.contentDocument) {
        win = iframe;
        doc = iframe.contentDocument; // For NS6
    } else if(iframe.contentWindow) {
        win = iframe.contentWindow;
        doc = iframe.contentWindow.document; // For IE5.5 and IE6
    }
 }
 } catch (e) {}
 objReference = new Array();
 objReference[0]= win;
 objReference[1]= doc;
 return objReference;
}
function getWindowParent() {
  return window.parent.window;
}

/*20.08.2009@IV flash loader */
/*20.08.2009@MV added new flash management by image */
/*18.01.2010@MV FIX mantiene protocollo (http o https) nei link assoluti degli attributi 
                codebase e pluginsapge per evitare alert di sicurezza in IE in https */
function w3gLoadFlash( mediaId, targetId, w, h, bg, fvars, debug, replace ) {

 try {
  if ( w==null && h==null ) { // retrieve flash width and height from img src (like /media/show?XXX_wXX_hXX)
	  var img =$(targetId);
	  src = img.src; 
	  //img src is a flash file and in IE if it's not corrected with a valid image type the page not complete loading 
	  img.src='/'+w3gContex+'/img/px.gif'; 
	  var espressione=new RegExp('\\/media\\/show\\?.*_w([0-9]*)_h([0-9]*)');
	  var matching = src.match(espressione);
	  if (matching.length==3) {
		  w = matching[1];
		  h = matching[2];
	  } 
  }
  
  var protocol=window.location.protocol;
  if (protocol==null || typeof protocol=="undefined")
  	protocol="http:";

  var swfSrc='<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
  swfSrc+='codebase="'+protocol+'//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" ';
  swfSrc+='width="'   +w+   '" height="'   +h+   '" valign="bottom"> ';
  swfSrc+='<PARAM NAME="movie" VALUE="/'   +w3gContex+   '/media/show?'  +mediaId+  '"> ';
  swfSrc+='<PARAM NAME="bgcolor" value="#'   +bg+   '"> ';
  if (!(typeof(fvars)=="undefined" || fvars==null))
    swfSrc+='<PARAM NAME="flashVars" VALUE="'  +fvars+  '"> ';  
  swfSrc+='<PARAM NAME="quality" VALUE="high"> ';
  swfSrc+='<PARAM NAME="allowScriptAccess" value="sameDomain"> ';
  swfSrc+='<PARAM NAME="allowFullScreen" value="false"> ';
  swfSrc+='<PARAM NAME="wmode" VALUE="transparent"> ';
  swfSrc+='<EMBED src="/'   +w3gContex+   '/media/show?'  +mediaId+  '" ';
  swfSrc+=' width="'   +w+   '" height="'   +h+   '" bgcolor="#'   +bg+   '" ';
  if (!(typeof(fvars)=="undefined" || fvars==null))
    swfSrc+=' flashVars="'  +fvars+  '" ';  
  swfSrc+=' quality="high" allowScriptAccess="sameDomain" allowFullScreen="false" wmode="transparent" ';
  swfSrc+=' TYPE="application/x-shockwave-flash" ';
  swfSrc+=' PLUGINSPAGE="'+protocol+'//www.macromedia.com/go/getflashplayer" ></EMBED>';
  swfSrc+='</OBJECT>';
  var swfTarget = $(targetId);
  if  (! (typeof(debug)=="undefined" || debug==null) )  alert (swfSrc);
  if (swfTarget!=null)  {
    if (typeof(replace)=='undefined') //update innerHTML of the target element
     swfTarget.innerHTML = swfSrc;
    else //replace target element (remove element) with flash code
     swfTarget.replace(swfSrc);
    
  } else 
     window.status='loadFlash failed: '+targetId+': not found';
 } catch (e) {} 
}

/*20.08.2009@IV cross browser bookmark  */
function w3gCreateBookmarkLink(myurl,mytitle) { 
	if (window.sidebar) { // Mozilla Firefox Bookmark		
		window.sidebar.addPanel(mytitle, myurl,"");
	} else if( window.external ) { // IE Favorite		
		window.external.AddFavorite( myurl, mytitle); 
	} else if(window.opera && window.print) { // Opera Hotlist		
		return true; 
	} 
}

/*18.02.2010@IV return a string from an xml document*/
function w3gXMLToString(oXML) {
  if (window.ActiveXObject) {
    return oXML.xml;
  } else {
    return (new XMLSerializer()).serializeToString(oXML);
  }
}

/*18.02.2010@IV return an xml document from a string*/
function w3gXMLFromString(sXML) {
  if (window.ActiveXObject) {
    var oXML = new ActiveXObject("Microsoft.XMLDOM");
    oXML.loadXML(sXML);
    return oXML;
  } else {
    return (new DOMParser()).parseFromString(sXML, "text/xml");
  }
}

