// -------------------------------------
// Nome: 		functions.js
// Descrizione:	Funzioni JSCript di utilità ed uso generale
// Versione JS:	1.2
// Copyright:	Futuria Informatica Srl
// Ultima Mod:	18.05.2010
// -------------------------------------

// FUNZIONI DI DETECT BROWSER TYPE
// -------------------------------------------------------------
function Init()
{
	isDOM=document.getElementById?true:false
	isOpera=isOpera5=window.opera && isDOM
	isOpera6=isOpera && window.print
	isOpera7=isOpera && document.readyState
	isMSIE=isIE=document.all && document.all.item && !isOpera
	isStrict=document.compatMode=='CSS1Compat'
	isNN=isNC=navigator.appName=="Netscape"
	isNN4=isNC4=isNN && !isDOM
	isMozilla=isNN6=isNN && isDOM
}



// FUNZIONI ESTENSIONE FUNZIONALITA' CLASSE String
// -------------------------------------------------------------
String.prototype.isInt = function()
{
	return (this.match(/^-?[\d]+$/)!=null);
} 


Init();


// FUNZIONI DI SUPPORTO PER GESTIONE PAGE
// -------------------------------------------------------------
function GetWndBody(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isStrict) return p_Wnd.document.documentElement;
	else return p_Wnd.document.body;
}

function GetWndScrollX(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isMSIE || isOpera7) return GetWndBody(p_Wnd).scrollLeft;
	if(isNN || isOpera) return p_Wnd.pageXOffset;
}

function GetWndScrollY(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isMSIE || isOpera7) return GetWndBody(p_Wnd).scrollTop;
	if(isNN || isOpera) return p_Wnd.pageYOffset;
}

function GetWndLeft(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isMSIE || isOpera7) return p_Wnd.screenLeft;
	if(isNN || isOpera) return p_Wnd.screenX;
}

function GetWndTop(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isMSIE || isOpera7) return p_Wnd.screenTop;
	if(isNN || isOpera) return p_Wnd.screenY;
}

function GetWndWidth(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isMSIE) return GetWndBody(p_Wnd).clientWidth;
	if(isNN || isOpera) return p_Wnd.innerWidth;
}

function GetWndHeight(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isMSIE) return GetWndBody(p_Wnd).clientHeight;
	if(isNN || isOpera) return p_Wnd.innerHeight;
}

function GetDocumentWidth(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isMSIE || isOpera7) return GetWndBody(p_Wnd).scrollWidth;
	if(isNN) return p_Wnd.document.width;
	if(isOpera) return p_Wnd.document.body.style.pixelWidth;
}

function GetDocumentHeight(p_Wnd)
{
	if(!p_Wnd) p_Wnd=window;
	if(isMSIE || isOpera7) return GetWndBody(p_Wnd).scrollHeight;
	if(isNN) return p_Wnd.document.height;
	if(isOpera) return p_Wnd.document.body.style.pixelHeight;
}


function GetObjXMLHttp()
{
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
	
   return null;	
}


// FUNZIONI DI SUPPORTO PER GESTIONE PAGE ITEMS
// -------------------------------------------------------------

// Restituisce il riferimento ad un Item dato il suo ID
function GetItemFromId(p_sItemId)
{
	//if (document.all && document.all[p_sItemId]) return document.all[p_sItemId];
	if (document.getElementById(p_sItemId)) return document.getElementById(p_sItemId);
	else if (document.layers && document.layers[p_sItemId]) return (document.layers[p_sItemId]);

	return null;
}


// Restituisce il valore di un Item, dato il suo riferimento o il suo ID
function GetItemValue(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	
	sItemType = GetItemType(p_oItem);
	if (sItemType=='text' || sItemType=='textarea')
		return p_oItem.value;
	if (sItemType=='select-one')
	{
		if (p_oItem.selectedIndex<0) return '';
		SelOption = p_oItem.options[p_oItem.selectedIndex];
		if (SelOption.value != '') return SelOption.value;
		else return SelOption.text;
	}
	if (sItemType=='select-multiple')
	{
	}
	
	// Restituisce l'inner-text (utile nel caso degli item <span>)
	return p_oItem.innerText;
}


// Imposta il valore di un Item, dato il suo riferimento o il suo ID
function SetItemValue(p_oItem, p_sValue)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	
	sItemType = GetItemType(p_oItem);

	if ((sItemType=='text') || (sItemType=='textarea') || (sItemType=='hidden'))
		p_oItem.value = p_sValue;
}


// Restitruisce il tipo di un Item, dato il suo riferimento o il suo ID
function GetItemType(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
		
	if (p_oItem.type != null) return p_oItem.type;
	if (p_oItem.tagName != null) return p_oItem.tagName.toLowerCase();

	return 'unknown';
}

// Imposta lo stato di visibilità dell'Item, dato il suo riferimento o il suo ID
//optionally if sname is a radio button, then an optional third parameter restricts to a specific radio button
//if sname is a radio and the third parameter is ommitted then the function acts upon ALL;
function SetItemVisible(p_oItem, p_bshow)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return;
	var sDisplay = "";
	if(p_bshow != true) sDisplay = "none";

	if(p_oItem.style==null)
	{
		//the object isn't null by the name is.  Must be an array;
		//checkbox or radio
		if(p_oItem.length > 1)
		{
			var sValue = "";
			if(arguments.length > 2) sValue = arguments[2];
			//if Radio then we will check an optional third parameter to restrict to a value or all;
			for(var nIndex = 0; nIndex < oItem.length; nIndex++)
			{
				if(p_oItem[nIndex].style != null)
				{
					if(sValue.length > 0)
					{
						if(p_oItem[nIndex].value == sValue)
							p_oItem[nIndex].style.display = sDisplay;
						if(p_oItem[nIndex].value == null)
						{
							if(p_oItem[nIndex].innerText == sValue )
								p_oItem[nIndex].style.display = sDisplay;
						}
					}
					else
					{
						p_oItem[nIndex].style.display = sDisplay;
					}
				}
			}
		}
	}
	else
	{
		p_oItem.style.display = sDisplay;
	}
}


// Ritorna lo stato di visibilità di un Item, dato il suo riferimento o il suo ID
function GetItemVisible(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return false;
	if (p_oItem.style==null) return false;
	
	return ((p_oItem.style.display != 'none') && (p_oItem.style.display != ''));
}


// Alterno lo stato di visibilità di un Item, dato il suo riferimento o il suo ID
function DynToggleItemVisible(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	SetItemVisible(p_oItem, !GetItemVisible(p_oItem));
}


// Modifica lo stato di abilitazione di un controllo
function SetItemEnabled(p_oItem, p_bEnable)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return false;

	p_oItem.disabled = !p_bEnable;


	// Modifica la classe CC dell'oggetto
	var sClassName = p_oItem.className;
	if (sClassName==null || sClassName=='') return;
	
	if (p_bEnable)
	{
		if (sClassName.substr(sClassName.length-9, 9)=='_disabled')
			sClassName = sClassName.substr(0, sClassName.length-9);
	}
	else
	{
		//alert('className: ' + sClassName);
		if (sClassName.substr(sClassName.length-9, 9)!='_disabled')
			sClassName += '_disabled';
	}

	p_oItem.className = sClassName;	
}

// Imposta il valore di uno style CSS
function SetItemStyle(p_oItem, p_sStyle, p_sValue)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return false;
	eval("p_oItem.style."+p_sStyle+"='"+p_sValue+"'");
}


function GetItemLeft(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;

	if(isMSIE || isMozilla || isOpera7) return p_oItem.offsetLeft
	if(isOpera) return p_oItem.css.pixelLeft;
	if(isNN4) return p_oItem.x;
}

function GetItemTop(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;

	if(isMSIE || isMozilla || isOpera7) return p_oItem.offsetTop
	if(isOpera) return p_oItem.css.pixelHeight;
	if(isNN4) return p_oItem.y;
}

// Return absolute X Position
function GetItemPosX(p_oItem)
{
 	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
	var obj = p_oItem;

	var curleft = 0;
    if (obj.offsetParent) {
        while (1) {
            curleft+=obj.offsetLeft;
            if (!obj.offsetParent) {
                break;
            }
            obj=obj.offsetParent;
        }
    } else if (obj.x) {
        curleft+=obj.x;
    }
    return curleft;
}

// Return absolute Y Position
function GetItemPosY(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
 	var obj = p_oItem;

   var curtop = 0;
    if (obj.offsetParent) {
        while (1) {
            curtop+=obj.offsetTop;
            if (!obj.offsetParent) {
                break;
            }
            obj=obj.offsetParent;
        }
    } else if (obj.y) {
        curtop+=obj.y;
    }
    return curtop;
}


function GetItemHeight(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;

	if(isMSIE || isMozilla || isOpera7) return p_oItem.offsetHeight
	if(isOpera) return p_oItem.css.pixelHeight
	if(isNN4) return p_oItem.document.height
}


function GetItemWidth(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
	
	if(isMSIE || isMozilla || isOpera7) return p_oItem.offsetWidth;
	if(isOpera) return p_oItem.style.pixelWidth;
	if(isNN4) return p_oItem.document.width;
}

// Utilizzabile su DIV
function GetItemScrollTop(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
	
	if(isMSIE || isMozilla || isOpera7) return p_oItem.scrollTop;
	if(isOpera) return p_oItem.scrollTop;
	if(isNN4) return p_oItem.scrollTop;
}

// Utilizzabile su DIV
function GetItemScrollLeft(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
	
	if(isMSIE || isMozilla || isOpera7) return p_oItem.scrollLeft;
	if(isOpera) return p_oItem.scrollLeft;
	if(isNN4) return p_oItem.scrollLeft;
}

function SetItemWidth(p_oItem, p_sValue)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
	
	if (isNN) p_oItem.style.width = p_sValue;
	else if(isMSIE || isMozilla || isOpera7) p_oItem.style.width = p_sValue;
	else if(isOpera) p_oItem.style.pixelWidth = p_sValue;
	else if(isNN4) p_oItem.document.width = p_sValue;
}

function SetItemHeight(p_oItem, p_sValue)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
	if (p_sValue == null) return false;
	var sValuePx = p_sValue + (p_sValue.toString().isInt()?'px':'');
	
	if (isNN) p_oItem.style.height = sValuePx;
	else if(isMSIE || isMozilla || isOpera7) p_oItem.style.height = sValuePx;
	else if(isOpera) p_oItem.style.pixelHeight = p_sValue;
	else if(isNN4) p_oItem.document.height = sValuePx;
}

function GetItemVisibility(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
	
	if(isMSIE || isMozilla || isOpera7) return p_oItem.style.visibility;
	if(isOpera) return p_oItem.style.visibility;
	if(isNN4) return p_oItem.document.visibility;
}

function SetItemVisibility(p_oItem, p_sValue)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return;
	
	if(isMSIE || isMozilla || isOpera7) p_oItem.style.visibility = p_sValue;
	else if(isOpera) p_oItem.style.visibility = p_sValue;
	else if(isNN4) p_oItem.document.visibility = p_sValue;
}

function SetItemLeft(p_oItem, p_nLeft)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;

	if(isOpera) p_oItem.style.pixelLeft = p_nLeft;
	else if(isNN4) p_oItem.x = p_nLeft;
	else p_oItem.style.left = p_nLeft+"px";
}

function SetItemTop(p_oItem, p_nTop)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;

	if(isOpera) p_oItem.style.pixelTop = p_nTop;
	else if(isNN4) p_oItem.y = p_nTop;
	else p_oItem.style.top = p_nTop+"px";
}

function SetItemZIndex(p_oItem, p_nZIndex)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;

	if(isOpera) p_oItem.style.zIndex = p_nZIndex;
	else if(isNN4) p_oItem.zIndex = p_nZIndex;
	else p_oItem.style.zIndex = p_nZIndex;
}

function GetItemOuterHTML(p_oItem)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return null;
	if (isMSIE) return p_oItem.outerHTML;
	
	temp=p_oItem.cloneNode(true);
	document.getElementById('TempDiv').appendChild(temp);
	outer=document.getElementById('TempDiv').innerHTML;
	document.getElementById('TempDiv').innerHTML="";
	return outer;
}

function SetItemOuterHTML(p_oItem, p_sHtml)
{
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);
	if (p_oItem == null) return;
	if (isMSIE || isOpera) { p_oItem.outerHTML = p_sHtml; return; }
	
	var r = p_oItem.ownerDocument.createRange();
	r.setStartBefore(p_oItem);
	var df = r.createContextualFragment(p_sHtml);
	p_oItem.parentNode.replaceChild(df, p_oItem);
}

function ItemCopyValueToClipboard(p_oItem)
{
	var sValue = GetItemValue(p_oItem);
	
	//
	if (isMSIE)
	{
		window.clipboardData.setData("Text", sValue);
	}
}

function ItemAddClass(p_oItem, p_sClassName, p_bAdd)
{
	if (p_bAdd==null) p_bAdd=true;
	if (typeof(p_oItem) != 'object') p_oItem = GetItemFromId(p_oItem);

	var sClassName = p_oItem.className;
	var asClass = sClassName.split(' ');
	sClassName = '';
	for(var n=0; n<asClass.length; n++)
	{
		if (asClass[n] != p_sClassName) sClassName += (sClassName!=''?' ':'') + asClass[n];
	}
	if (p_bAdd)
	{
		sClassName += (sClassName!=''?' ':'') + p_sClassName;
	}
	p_oItem.className = sClassName;
}

function ItemRemoveClass(p_oItem, p_sClassName)
{
	return ItemAddClass(p_oItem, p_sClassName, false);
}

// Esegue il check di compatibilità del browser mostrando un opportuno messaggio
// di avvertimento all'utente se richiesto
function CheckBrowser()
{
	return true;
	
	var sBrowser;
	if (navigator.appName == 'Microsoft Internet Explorer') 
	    sBrowser = 'IE';
	else if (navigator.appName == 'Netscape') 
	    sBrowser = 'NS';

	if (sBrowser != 'IE')
		alert(APP_BROWSER_NOT_ENABLED);
}


// FUNZIONI DI SUPPORTO PER GESTIONE PAGE ITEMS - LIST (select)
// -------------------------------------------------------------

// Rimuove la lista delle Options del List Item
function ListResetContent(p_oItem)
{
	if(p_oItem == null) return false;
	
	p_oItem.options.length = 0;
}

// Aggiunge una nuova Options al List Item
function ListAddOption(p_oItem, p_sText, p_sValue, p_bSelected, p_nPos)
{
	if(p_oItem == null) return false;
	if(p_oItem.nodeName != "SELECT") return false;

	var index = 0;
	//var newitem = document.createElement("option");
	var newitem = new Option(p_sText, p_sValue, false, p_bSelected);
	if(newitem == null) return -1;

	if(p_nPos != null)
		index = p_oItem.options.add(newitem, p_nPos);
	else
		index = p_oItem.options.add(newitem, p_oItem.options.length);
	return index;
}


// FUNZIONI DI SUPPORTO PER GESTIONE TEXTAREA
// -------------------------------------------------------------
function TAreaToggleHeight(p_oItem)
{
	if(p_oItem == null) return false;
	if (p_oItem.oheight==undefined || p_oItem.oheight==0)
	{
		var nHeight = GetItemHeight(p_oItem);
		p_oItem.oheight = nHeight;
		SetItemHeight(p_oItem, Math.round(nHeight*2.5));
	}
	else
	{
		SetItemHeight(p_oItem, p_oItem.oheight);
		p_oItem.oheight = 0;
	}
	return true;	
}


// FUNZIONI DI SUPPORTO PER DIV POPUP
// -------------------------------------------------------------

// Apre un popup contenete il <div> in input
function DivPopupOpen(p_sItem)
{
	var oDiv = GetItemFromId(p_sItem);
	var bOpen = !GetItemVisible(oDiv);
	oDiv.style.display = (bOpen ? 'block':'none');

	if (!bOpen) return true;
	
	// Remove header block if present
	$('#'+p_sItem+ ' .header').remove();
	var sTitle = oDiv.getAttribute('title');
	if (!sTitle) sTitle='';
	
	// Create Close Button Code
	var sPBClose ="<div class=\"tbutton\"><a href='#' onclick=\"DivPopupClose('"+p_sItem+"')\" title=\"Close\"><img src=\""+g_PSV_sRootUrl+"/img/Library/popup_pb_close.gif\"></a></div>";

	// Create Header Code
	var sHtml = sPBClose + "<div class='caption'>"+sTitle+"</div>";
	
	// Add new Header block
	$$(p_sItem).create('div', {className: "header"}, true, sHtml);

	// Imposta min-height	
	var nDlgWidth = GetItemWidth(oDiv);
	var nDlgHeight = GetItemHeight(oDiv);
	if (nDlgHeight < 70)
	{
		nDlgHeight = 70;
		SetItemHeight(oDiv, nDlgHeight);
	}	

	// Center
	oDiv.style.top = ((GetWndHeight() - nDlgHeight) / 2)+ "px";
	oDiv.style.left =  ((GetWndWidth() - nDlgWidth) / 2) + "px";

	// Adjust padding-top for title
	oDiv.style.paddingTop = GetItemHeight($('#'+p_sItem+ ' .header')[0])+8+'px';
}

// Chiude il Div-Popup
function DivPopupClose(p_sItem)
{
	var oDiv = GetItemFromId(p_sItem);
	SetItemVisible(oDiv, false);
}


// FUNZIONI DI SUPPORTO PER GESTIONE TABELLE
// -------------------------------------------------------------

// Seleziona/Deseleziona tutte le righe visibili della tabella
function TblSelectAllRows(p_sTblName, p_oSwitch)
{
	bChecked = p_oSwitch.checked;
	for (var nRow=0; true; nRow++)
	{
		oRowSelector = GetItemFromId(p_sTblName + '.SEL.' + nRow);
		if (oRowSelector == null) break;
		oRowSelector.checked = bChecked;
	}
}


// FUNZIONI DI SUPPORTO PER GESTIONE cFWDataFieldHtmlEdit FIELDS
// -------------------------------------------------------------

function HtmlField_Init(p_sFieldId)
{
	var sUILang = 'en';
	if (g_PSV_sLanguage=='ITA') sUILang = 'it';
	if (g_PSV_sLanguage=='FRE') sUILang = 'fr';

	tinyMCE.init({        // General options
		mode : "exact",        
		elements : p_sFieldId,        
		theme : "advanced",
		readonly : false,
		language : sUILang,
		//skin : "o2k7",        
		//skin_variant : "black",        
		plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull|,bullist,numlist,|,outdent,indent,|,visualchars,nonbreaking,charmap,|,sub,sup,|,forecolor,backcolor,|,hr,removeformat,|,cleanup,code,visualaid,fullscreen",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,link,unlink,|,tablecontrols,|,iespell",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true    
		});
						
}

// FUNZIONI DI SUPPORTO PER GESTIONE TRANSLATED FIELDS
// -------------------------------------------------------------

function TRTF_EditorSaveValue(p_oTRField, p_sLang, p_sValue)
{
	//alert('Saving TR Field ' + p_oTRField.id);
	var oRegExp = new RegExp("[\\r\\n\\t\\s]*((<TR:"+p_sLang+"/>)|(<TR:"+p_sLang+">[\\w\\W]*</TR:"+p_sLang+">))");
	if (p_sValue!='')
		sNewPart = "\n<TR:"+p_sLang+">"+p_sValue+"</TR:"+p_sLang+">";
	else
		sNewPart = "\n<TR:"+p_sLang+"/>";
	
	var sTRValue = p_oTRField.value;
	if (sTRValue.match(oRegExp))
		sTRValue = sTRValue.replace(oRegExp, sNewPart);
	else
		sTRValue += sNewPart;

	// Trim left
	p_oTRField.value = sTRValue.replace(/^[\r\n\t\s]*/, '');
	//alert('save - oTRField.value.length: '+ oTRField.value.length);
	return true;
}

	
// Trasforma una textarea multilanguage in un set di campi per l'editing dei valori
// nelle diverse lingue
function TRTF_Init(p_sTRFieldId)
{
	var oTRField = document.getElementById(p_sTRFieldId);
	if (!oTRField) return;
	oTRField.style.display = 'none';
	
	// Imposta per gli EditField la stessa width css impostata per il MLField
	var sEditLangList = oTRField.getAttribute('fwlanguages');
	var sEditParams = oTRField.getAttribute('fwparams');
	var nEditMaxlen = oTRField.getAttribute('fwmaxlength')*1.0;

	var sEditWidth= oTRField.style.width;
	if ((sEditWidth=='') || (sEditWidth=='100%')) sEditWidth='96%';
	var sEditHeight= oTRField.style.height;
	var nEditRows = oTRField.getAttribute('rows');
	var sEditDisabled = oTRField.getAttribute('disabled');
	var bEditDisabled = (sEditDisabled != null) && (sEditDisabled != 'undefined') && (sEditDisabled != false);
	
	var asLangs = new Array();
	if (sEditLangList==null) return;
	asLangs = sEditLangList.split(/,/);
	var nEditLangCount = asLangs.length;
	//alert(oTRField.value.length);
	var asValues = StrMatchAll('(?:<TR:(\\w+)/>)|(<TR:(\\w+)>([\\w\\W]*)</TR:\\3>)', oTRField.value);
	
	var asEditLang = new Array();
	var asEditValue = new Array();
	nEditors = 0;

	if (nEditLangCount>0)
	{
		// Se è passata una Lang-List devo presentare solo i campi richiesti e 
		// nell'ordine corretto
		for(n=0; n<nEditLangCount; n++)
		{
			var	bFound = false;
			for(m=0; m<asValues.length; m+=5)
			{
				var sLang = ((asValues[m+1]!=undefined)&&(asValues[m+1]!='')) ? asValues[m+1] : asValues[m+3];
				var sText = ((asValues[m+4]!=undefined)&&(asValues[m+4]!='')) ? asValues[m+4] : '';
				//alert(sLang+': '+sText);
				if (sLang==asLangs[n])
				{
					asEditLang[nEditors] = asLangs[n];
					asEditValue[nEditors] = sText;
					nEditors++;
					bFound = true;
				}
			}
			if(!bFound)
			{
				asEditLang[nEditors] = asLangs[n];
				asEditValue[nEditors] = '';
				nEditors++;
			}
		}
	}
	else
	{
		// Se non è passata una Lang-List presenta i campi per tutti i testi presenti
		// nel TRField
		for(m=0; m<asValues.length; m+=5)
		{
			var sLang = ((asValues[m+1]!=undefined)&&(asValues[m+1]!='')) ? asValues[m+1] : asValues[m+3];
			var sText = ((asValues[m+4]!=undefined)&&(asValues[m+4]!='')) ? asValues[m+4] : '';
			asEditLang[nEditors] = sLang;
			asEditValue[nEditors] = sText;
			nEditors++;
		}
		
	}
	
	
	var fsEditorType = StrItemGet(sEditParams, 'type');
	
	var sEditLangList = '';
	for(var n=0; n<nEditors; n++)
	{
		var sLang = asEditLang[n];
		var sFlagTip = "Value in " + sLang;
		eval("if(typeof(TRTF_EDIT_"+sLang+")=='string') sFlagTip=TRTF_EDIT_"+sLang);
		
		// Salva elnco dei languages effettivamente gestiti
		sEditLangList += (sEditLangList!=''?',':'')+sLang;

		// inserisce separatore tra due campi di editing
		if (n>0)
		{
			oBreak = document.createElement("br");
			oTRField.parentNode.insertBefore(oBreak, oTRField);
		}
		
		if (fsEditorType=='D')
		{
			oEditor = document.createElement("input");
		}
		else if (fsEditorType=='M')
		{
			oEditor = document.createElement("textarea");
			oEditor.ondblclick=TAreaToggleHeight;
		}
		else if (fsEditorType=='H')
		{
			oEditor = document.createElement("textarea");
			// per evitare un effetto flickering in cui è visibile per alcuni istanti il codice html
			oEditor.style.backgroundcolor="#ffffff";
			oEditor.style.color="#ffffff";
			
			oContainer = document.createElement("div");
			// Se viene mostrato un solo Editor (una sola lingua) non mostra la bandiera
			if ((nEditLangCount==0) || (nEditors>1))
			{
				oContainer.style.backgroundImage='url('+g_PSV_sRootUrl+'/img/library/tr_editor_'+sLang+'.gif)';
				oContainer.style.backgroundRepeat="no-repeat";
				oContainer.style.backgroundPosition="0% 0%";
		  		oContainer.style.paddingLeft="20px";
		  		oContainer.style.border="1px solid gray";
	  		}	
		}

		if(oTRField.size) oEditor.size = oTRField.size;
		oEditor.name = '';
		oEditor.id = p_sTRFieldId+'_EDIT_'+sLang;
		if (nEditMaxlen>0) oEditor.setAttribute('maxlength', nEditMaxlen);
  		oEditor.style.width = sEditWidth;
  		if (fsEditorType!='D')
  		{
	  		if (sEditHeight!='') oEditor.style.height = sEditHeight;
	  		if (nEditRows!='') oEditor.setAttribute('rows', nEditRows);
		}
		oEditor.value = asEditValue[n];		

		if (fsEditorType!='H')
		{
			oEditor.setAttribute('edited', 'false');
			oEditor.className= oTRField.className;
	 		if (bEditDisabled) oEditor.setAttribute('disabled', true);

			oEditor.style.marginBottom='2px';
			// Se viene mostrato un solo Editor (una sola lingua) non mostra la bandiera
			if ((nEditLangCount==0) || (nEditors>1))
			{
				oEditor.style.backgroundImage='url('+g_PSV_sRootUrl+'/img/library/tr_editor_'+sLang+'.gif)';
				oEditor.style.backgroundRepeat="no-repeat";
				oEditor.style.backgroundPosition="0% 0%";
		  		oEditor.style.paddingLeft="20px";
				oEditor.title = sFlagTip;
			}

			oTRField.parentNode.insertBefore(oEditor, oTRField);
  		}
		else
		{
			oContainer.title = sFlagTip;
			oContainer.appendChild(oEditor);
			
			var sUILang = 'en';
			if (g_PSV_sLanguage=='ITA') sUILang = 'it';
			if (g_PSV_sLanguage=='FRE') sUILang = 'fr';

			tinyMCE.init({        // General options
				mode : "exact",        
				elements : oEditor.id,        
				theme : "advanced",
				readonly : bEditDisabled,
				language : sUILang,
				//skin : "o2k7",        
				//skin_variant : "black",        
				plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
				// Theme options
				theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull|,bullist,numlist,|,outdent,indent,|,visualchars,nonbreaking,charmap,|,sub,sup,|,forecolor,backcolor,|,hr,removeformat,|,cleanup,code,visualaid,fullscreen",
				theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,link,unlink,|,tablecontrols,|,iespell",
				theme_advanced_buttons3 : "",
				theme_advanced_buttons4 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true    
				});
							
			oTRField.parentNode.insertBefore(oContainer, oTRField);	
		}
		
	}
	
	// Salva lista languages gestiti
	oTRField.setAttribute('fwlanguages', sEditLangList);
}


// effettua salvataggio valori editati per il campo specificato
function TRTF_Save(p_sTRFieldId)
{
	var oTRField = document.getElementById(p_sTRFieldId);
	if (!oTRField) return;

	var nEditMaxlen = oTRField.getAttribute('maxlength')*1.0;
	var sEditLangList = oTRField.getAttribute('fwlanguages');
	var sEditParams = oTRField.getAttribute('fwparams');

	var fsEditorType = StrItemGet(sEditParams, 'type');

	var asLangs = new Array();
	if (sEditLangList==null) return;
	asLangs = sEditLangList.split(/,/);

	// Valuta length complessiva prima di modificare i valori
	if (nEditMaxlen>0)
	{
		var nTotLen = 0;
		for(n=0; n<asLangs.length; n++)
		{
			var sEditorId = p_sTRFieldId+'_EDIT_'+asLangs[n];
			if (fsEditorType=='H')
			{
				var oEditor = tinyMCE.get(sEditorId);
				if (oEditor!=null) nTotLen += oEditor.getContent().length;
			}
			else
			{
				var oEditor = document.getElementById(sEditorId);
				if (oEditor!=null) nTotLen += oEditor.value.length;
			}
			nTotLen += 20; // space for Tags <TR:ITA></TR:ITA>
		}
		if (nTotLen > nEditMaxlen)
		{
			var asTokens = new Array('$LABEL', '$MAXLEN', '$OVERFLOW');
			var asValues = new Array(oTRField.getAttribute('fwlabel'), nEditMaxlen, nTotLen-nEditMaxlen);

			var sTitle = StrReplaceTokens(DVM_ALERT_TITLE, asTokens, asValues);
			var sMsg = StrReplaceTokens(TRTF_MAXTOTLEN_EXCEDED, asTokens, asValues);
			
			WebMsgBox(sTitle, sMsg, 'OK');
			return false;
		}
	}
	
	for(n=0; n<asLangs.length; n++)
	{
		var sEditorId = p_sTRFieldId+'_EDIT_'+asLangs[n];
		//alert('saving value of '+sEditorId+'; type:'+fsEditorType);
		if (fsEditorType=='H')
		{
			var oEditor = tinyMCE.get(sEditorId);
			if (oEditor==null) alert('null editor '+sEditorId);		// Se la creazione dei fields TR non fosse andata a buon fine non modifica alcun dato
			if (oEditor.isDirty())
				TRTF_EditorSaveValue(oTRField, asLangs[n], oEditor.getContent());
		}
		else
		{
			var oEditor = document.getElementById(sEditorId);
			if (oEditor==null) alert('null editor '+sEditorId);		// Se la creazione dei fields TR non fosse andata a buon fine non modifica alcun dato
			if (oEditor.getAttribute('edited')=='true')
				TRTF_EditorSaveValue(oTRField, asLangs[n], oEditor.value);
		}
	}
	
	return true;
}


// FUNZIONI DI GESTIONE DEI COOKIES
// -------------------------------------------------------------

// Funzione di settaggio di un cookie per la pagina corrente
// Sintassi: SetCookie(name, value, ExpireTimeMin, path, domain, secure)
function SetCookie (p_sName, p_sValue)
{ 
	var today = new Date();
	var expire = new Date();	
	var argv = SetCookie.arguments; 
	var argc = SetCookie.arguments.length; 
	if(argc > 2) expire.setTime(today.getTime() + argv[2]*60*1000);
	else expire = null;
	var path = (argc > 3) ? argv[3] : '/'; 
	var domain = (argc > 4) ? argv[4] : null; 
	var secure = (argc > 5) ? argv[5] : false; 

	// kill cookie if exists
	var dKillDate = new Date("January 1, 1970"); // in the past
	var sKillDate = dKillDate.toGMTString();
	document.cookie = p_sName + '=dummy;expires=' + sKillDate;
	
	// rewrite cookie
	document.cookie = p_sName + '=' + escape(p_sValue) + 
		((expire == null) ? "" : ("; expires=" + expire.toGMTString())) + 
		((path == null) ? "" : ("; path=" + path)) + 
		((domain == null) ? "" : ("; domain=" + domain)) + 
		((secure == true) ? "; secure" : "");
}


// Funzione di lettura di un cookie per la pagina corrente
// Se il cookie non esiste viene restituito null; se il cookie non è valorizzato viene restituito ''
function GetCookie( check_name )
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}


// FUNZIONI DI SUPPORTO PER GESTIONE STRINGHE
// -------------------------------------------------------------

// Esegue il Trim di spazi all'inizio e alla fine di una stringa
function StrTrim(p_sStr)
{
	return p_sStr.replace(/^\s*/, '').replace(/\s*$/, ''); 
}


// Esegue il Replace
function StrReplace(p_sStr, p_sSearch, p_sReplace, p_bCaseSensitive)
{
	p_sSearch = p_sSearch.replace(/\$/, '\\$');
	p_sSearch = p_sSearch.replace(/\./, '\\.');
	
	var oRE = new RegExp(p_sSearch, 'g'+(p_bCaseSensitive?'':'i'));
	return p_sStr.replace(oRE, p_sReplace); 
}


// Effettua il Match globale sulla stringa [p_sStr] con l'expr reg [p_sRE]
function StrMatchAll(p_sRE, p_sStr, p_bCaseSensitive)
{
	var oRE = new RegExp(p_sRE, 'g'+(p_bCaseSensitive?'':'i'));
	var aResult = new Array();
	while(oRE.lastIndex < p_sStr.length)
	{
		aMatch = oRE.exec(p_sStr);
		if (aMatch==undefined) break;
		aResult = aResult.concat(aMatch);
	}
	return aResult; 
}


// Sostituisce ogni occorrenza di token con il relativo valore
function StrReplaceTokens(p_sStr, p_asTokens, p_asValues)
{
	var sText = p_sStr;
	for(var n=0; n<p_asTokens.length; n++)
	{
		sText = sText.replace(p_asTokens[n], p_asValues[n]);
	}
	return sText;
}


function StrItemGet(p_sStr, p_sItemName)
{
	if (p_sStr==undefined) return '';
	if (p_sItemName=='') return '';
	
	var oRE = new RegExp('(^|;)\\s*' + p_sItemName + '\\s*:\\s*([^;]*)', 'gi');

	var aTokens = oRE.exec(p_sStr);
	if (aTokens==null) return '';
	return aTokens[2];
}

function StrItemSet(p_sStr, p_sItemName, p_sItemValue)
{
	if (p_sStr==undefined) return '';
	if (p_sItemName=='') return '';
	
	var oRE = new RegExp('(^|;)\\s*' + p_sItemName + '\\s*:\\s*([^;]*)', 'gi');

	if (oRE.test(p_sStr))
		p_sStr = p_sStr.replace(oRE, '$1'+p_sItemName+':'+p_sItemValue);
	else
		p_sStr += p_sItemName+':'+p_sItemValue+';';
	
	return p_sStr; 
}


// Adatta l'altezza di un iFrame in base al suo contenuto.
// Può/Deve essere chiamata sull'evento onload() dell'Iframe stesso
function IFrameAdjustHeight(p_sIframeId)
{
	oIFrame = GetItemFromId(p_sIframeId);
	if (oIFrame == null) return;
	
	// if contentDocument exists, W3C compliant (e.g. Mozilla) 
	var oFrameDoc = null;
	if (oIFrame.contentDocument)
		oFrameDoc = oIFrame.contentDocument;
	else // bad Internet Explorer  
		oFrameDoc = document.frames[p_sIframeId].document;
	if (oFrameDoc)
		SetItemHeight(oIFrame, oFrameDoc.body.offsetHeight);
}


// FUNZIONI VARIE 
// -------------------------------------------------------------

// Mostra un messaggio in un dialog di alert
function MessageBox(p_sMessage, p_sTitle, nFlags)
{
   sTitle = unescape(p_sTitle);
   sMessage = unescape(p_sMessage);
   alert(sTitle + "\n\n" + sMessage);
}


// p_sPointer = wait|default
// NB: sugli Input di tipo 'select' non è supportato!
function SetPointer(p_sPointer)
{
	document.body.style.cursor = p_sPointer;
}


// Converte un numero esadecimale di n cifre in numero decimale
// Formati: hhhh 0xhhhh hhhhH
function HexToDec(p_sHex)
{
	return parseInt(p_sHex, 16);
}


// Converte un numero intero in esadecimale
function DecToHex(p_nDec, p_nDigits)
{
	var sDigits = "0123456789ABCDEF";
	var nNibble;
	var sOut = '';
	while(p_nDec>0)
	{
		nNibble = p_nDec & 0x0F;
		p_nDec = p_nDec >>> 4;
		sOut = sDigits.substr(nNibble,1) + sOut;
	}
	if (p_nDigits != null)
	{
		var sPad = '00000000';
		sOut = sPad.substr(0, p_nDigits-sOut.length) + sOut;
	}
	return sOut;
}


// Esegue il dump Hex/Char di una stringa di caratteri/bytes
function StrDumpHex(p_sStr)
{
	var nLen = p_sStr.length;
	var nChar;
	var sChar;
	var sLineChar;
	var sLineHex;
	var sOut = '';
	
	for(var n=0; n<nLen; n+=16)
	{
		sLineChar = '';
		sLineHex = '';
		for(var b=0; b<16; b++)
		{
			nChar = p_sStr.charCodeAt(n+b);
			sChar = p_sStr.substr(n+b, 1);
			if (nChar<32 || nChar>127) sChar = '.';
			sLineChar += sChar;
			sLineHex += DecToHex(nChar, 2)+' ';
		}
		sOut += DecToHex(n, 8) + ': ' + sLineHex + ' ' + sLineChar + '\n';
	}
	
	return sOut;
}


function StrRandom(p_nLength)
{
	var sChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var sStr = '';
	for (var i=0; i<p_nLength; i++) {
		var nNum = Math.floor(Math.random() * sChars.length);
		sStr += sChars.substring(nNum, nNum+1);
	}
	return sStr;
}

// Delta Compression Explode procedure
function DCExplode(p_sDelta)
{
	p_sDelta = p_sDelta.replace(/_script_/gi, 'script');
	//TraceMsg('\nDELTA '+p_sDelta.length+'\n'+StrDumpHex(p_sDelta));
	//TraceMsg('\nDELTA '+p_sDelta.length+'\n'+p_sDelta+'----');
	//TraceMsg('\nOLD '+parent.g_sLastReqBody.length+'\n'+parent.g_sLastReqBody);
	
	var sOutput = '';	
	var nByte, nCmd, nOpt;
	var nDeltaLen = p_sDelta.length;
	var nPos = 0;
	var sLog = '';
	while(nPos < nDeltaLen)
	{
		//Print(nPos);
		nCmd = p_sDelta.charCodeAt(nPos++);
		if (nCmd>=97)
		{
			// Put
			nLenDigits = (nCmd-97)+1;
			nDataLen = parseInt(p_sDelta.substr(nPos, nLenDigits), 16);
			nPos += nLenDigits;
			
			//sLog += 'P:' + nDataLen +':' + p_sDelta.substr(nPos, nDataLen) + '\n';
			sOutput = sOutput + p_sDelta.substr(nPos, nDataLen);
			nPos += nDataLen;
		}
		else
		{
			// Copy
			nCmd -= 65;
			nPosDigits = (nCmd >>> 2)+1;
			nLenDigits = (nCmd & 0x03)+1;
			//sLog += 'C:'+ nPosDigits + ' - ' + nLenDigits + '\n';
			
			//Print(sDelta.substr(nPos, nLenDigits));
			nDataLen = parseInt(p_sDelta.substr(nPos, nLenDigits),16);
			nPos += nLenDigits;
			
			//Print(sDelta.substr(nPos, nPosDigits));
			nDataPos = parseInt(p_sDelta.substr(nPos, nPosDigits),16);
			nPos += nPosDigits;
					
			//sLog += 'C:' + nDataLen + ':' + nDataPos + ':' + parent.g_sLastReqBody.substr(nDataPos, nDataLen) + '\n';
			sOutput = sOutput + parent.g_sDCLastReqBody.substr(nDataPos, nDataLen);
		}
	}
	
	//TraceMsg(sLog);
	//alert('OUTPUT '+sOutput.length+'\n'+sOutput);
	parent.g_sDCLastReqBody = sOutput;
	
	return sOutput;
}
