// header {{{
// --======================================================================--
// --       A S S O C I A T I O N   D  E S   D I P L O M E S   D E  
// --    L ' E C  O L E   P O L Y T E C H N I Q U E   D E   T U N I S I E
// --======================================================================--
// --======================================================================--
// --  File        : config_manager.class.php
// --  Project     : ADEPT Directory
// --  Author      : Rochdi BZAINE <rochdi.bazine@gmx.net>
// --  Copyright   : (C) 2007 ADEPT.org
// --  Begin       : Monday, January 30, 2007
// --  Modified    : - 
// --  Description : Global JavaScript utility functions  
// --  Notes       :
// --======================================================================--
// --  $Id: main.js,v 1.1 2007/02/04 18:47:47 rochdi Exp $
// --
// 
// }}}


// ----------------------------------------------------------------------
// Create the begin/end part of a form panel with standard layout 
// (background picture, border, etc). The width parameter can be omitted
// 
// Parameters: 
//    - width:  The width of form panel. Is NOT required. 
//    - height: The height of form panel. Is NOT required. 
// ----------------------------------------------------------------------
function renderBeginFormPanel(width, height){
    document.write('<table background="' + imagesDir + 'form_panel_bg.jpg" class="panelwrapper" border=0 cellSpacing=0 cellPadding=0 ');
    if(width != null) document.write(' width="' + width + '"');
    if(height != null) document.write(' height="' + height + '"');
    document.write('><tr><td valign=top>');    
} // func

function renderEndFormPanel() { document.write('</td></tr></table>'); }

// ----------------------------------------------------------------------
// Create the form action panel with standard layout
// ----------------------------------------------------------------------
function renderActionFormPanel(){
    document.write('</td><tr><td background="' + imagesDir + 'form_action_bg.jpg" valign=middle align=right>');
} // func





// ------------------------------------------------------------------------------------
// Display an icon graphic button with an optional hyperlink.
// The 'type' parameter must be one of available files in /bz/html/images/buttons
//
// Parameters: 
//    - type  : The button icon type. Example: 'save', 'info', 'help', etc. 
//              See the 'html/images/buttons' for a complete list of icon types
//    - label : The button text label
//    - link  : The triggered hyperlink. REQUIRED
//    - target: An optional target frame for the hyperlink
//    - width : The button width (0 = autosize)
// ------------------------------------------------------------------------------------
function renderIconButton(type, label, link, target, width){
    bzRenderButton(type, label, link, null, target, width, null);
} // func

function renderButton(label, link, target, width){
    bzRenderButton(null, label, link, null, target, width, null);
} // func

// ------------------------------------------------------------------------------------
// Display an icon graphic button with an optional hyperlink.
// The 'type' parameter must be one of available files in /bz/html/images/buttons
//
// Parameters: 
//    - icon  : The button icon type. 
//                Example:  'save' for 'button_save.gif', 
//                          'info' for 'button_info.gif' etc. 
//                See the 'html/images/buttons' for a complete list of icon.
//    - label:      The button text label
//    - link:       The triggered hyperlink that will be used in the HREF attribute. 
//                  If it is NULL the function will use the jsFunction parameter.
//    - jsFunction: The triggered JavaScript name. This parameter is used
//                  only if the link parameter is NULL. It will put a '#'
//                  character in the HREF attribute and the jsFunction in 
//                  the ONCLICK attribute.
//                  IT IS A MISTAKE TO USE BOTH 'link' AND 'jsFunction' ATTRIBUTES
//    - target:     An optional target frame for the hyperlink
//    - width :     The button width (0 = autosize)
//    - tooltip:    The tooltip displyed text
// ------------------------------------------------------------------------------------

var _bzDisplayButtonAsLink = true;
var _bzLeftLinkMarker  = '[';
var _bzRightLinkMarker = ']';
function bzRenderButton(icon, label, link, jsFunction, target, width, tooltip){//{{{
    if(_bzDisplayButtonAsLink)
        bzRenderButtonAsLink(icon, label, link, jsFunction, target, width, tooltip);
    else
        bzRenderButtonAsButton(icon, label, link, jsFunction, target, width, tooltip);
} // func }}}
function bzRenderButtonAsButton(icon, label, link, jsFunction, target, width, tooltip){//{{{
  var href    = (link == null) ? 'href="#" onclick="' + jsFunction + '"' 
                               : 'href="' + link + '"';

  if(width == null) width = 0;
  if("undefined" == tooltip || tooltip == null) tooltip = label;

  var tmp = '<TABLE cellSpacing=0 cellPadding=0 border=0><TR>'+
              '<TD><IMG src="' + imagesDir + 'buttons/button_left.gif"></TD>';               
              
    if(icon != null && icon != '') 
    {
       tmp += '<TD>' + 
                 '<A class=graphic_button title="' + tooltip + '" ' + href + 
                 (target == null ? '' : (' TARGET=' + target))+ '>' +
                    '<IMG alt="' + tooltip + '" border=0 src="' + imagesDir + 'buttons/button_'+icon+'.gif" align=middle></A>' +                 
              '</TD>';
    } // if
    
   tmp += '<TD background="' + imagesDir + 'buttons/button_middle.gif" nowrap ' +
            ((width == 0) ? '' : ('width=' + width)) + '>' +                           
           '<A class=graphic_button title="' + tooltip + '" ' + href + (target == null ? '' : (' TARGET=' + target))+ '>'+label+'</A>'+
          '</TD><TD><IMG src="' + imagesDir + 'buttons/button_right.gif"></TD>' +
        '</TR></TABLE>';
  document.write(tmp);
} // func }}}
function bzRenderButtonAsLink(icon, label, link, jsFunction, target, width, tooltip){ //{{{
  var href    = (link == null) ? 'href="#" onclick="' + jsFunction + '"' 
                               : 'href="' + link + '"';

  if("undefined" == tooltip || tooltip == null) tooltip = label;

  var tmp = '<TABLE cellSpacing=0 cellPadding=0 border=0><TR>' +
            '<TD nowrap>' + 
            '<A class=graphic_button title="' + tooltip + '" ' + href + (target == null ? '' : (' TARGET=' + target))+ '>'+
             _bzLeftLinkMarker + label + _bzRightLinkMarker + '</A>'+
            '</TD></TR></TABLE>';
  document.write(tmp);
} // func }}}
function renderIcon(iconName, link, target){ //{{{
// ------------------------------------------------------------------------------------
// Display an icon with an optional hyperlink.
//
// Parameters: 
//    - iconName: The button icon type. See the 'html/images/icons' directory for complete list
//    - link  : The triggered hyperlink. REQUIRED
//    - target: An optional target frame for the hyperlink
// ------------------------------------------------------------------------------------

    if(link != null) document.write('<A HREF="' + link + '" ' + (target == null ? '' : (' TARGET=' + target))+ '>');
    document.write('<IMG border=0 src=' + imagesDir + 'icons/icon_' + iconName + '.gif ALT="' + iconName + '">');
    if(link != null) document.write('</A>');
} // func }}}
function bzRB(icon, label, link, jsFunction, target, width, tooltip){//{{{
// short function name for bzRenderButton function
// (used to reduce the generated HTML)
	bzRenderButton(icon, label, link, jsFunction, target, width, tooltip)
}
//}}}



//{{{

var PARAM_EVT_CLASS       = "_cl"; var PARAM_TYPE         = "_ty";
var PARAM_TARGET          = "_tg"; var PARAM_ACTION       = "_ac";
var PARAM_PAGE_EVENT      = "_pe"; var PARAM_SUBMIT       = "_sb";
var PARAM_SERVER_VALIDATE = "_sv"; var PARAM_CONTROL_NAME = "_ct";

// ----------------------------------------------------------------------
// Browser checks
// ----------------------------------------------------------------------
function isIE()         { return (document.all != null);                          }
function isNS4()        { return (document.layers) && (!document.getElementById); }
function isNS6()        { return (document.getElementById) && (!document.all);    }
function isDOMBrowser() { return (document.getElementById != null); 		   	  }
function isMac()        { return navigator.userAgent.indexOf("Mac") > -1; 		  }
function isNS7()        { return isNS6() && (navigator.userAgent.indexOf("Netscape/7") > -1); }

// Return the current system time (in millisecs)
function getCurrentTime() { return (new Date()).getTime(); }

// ----------------------------------------------------------------------
// Transform special characters (<, >, &, ") 
// in the related HTML entities (&lt;, &gt;, &amp;, &quot;) 
// ----------------------------------------------------------------------
function encodeStringForHTML(value){	
    var tmp = "";
    if(value)
	{
	    var c;
	    for(var i = 0; i < value.length; i++)
	    {
	        c = value.charAt(i);
	        // Manage special/simple characters
	        if(c == '&') tmp += "&amp;";
	            else if(c == '<') tmp += "&lt;";
	            else if(c == '>') tmp += "&gt;";
	            else if(c == '"') tmp += "&quot;";
	            else tmp += c;
	    } // for
	    
    } // if
    return tmp;
} // func

// ----------------------------------------------------------------------
// The function encode a string as hex values
// ----------------------------------------------------------------------
function encodeStringToHex(value){
	var result = '';
	if(value)
	{
	    var n = value.length;    
    	for (var i = 0; i < n; i++) 
    	{	
    		var tmp = value.charCodeAt(i).toString(16);
    		if (tmp.length < 2) tmp = "0" + tmp;
    		result += tmp;
    	} // for
    } // if
    return result;
} // func

// ----------------------------------------------------------------------
// The function decode a string from hex values
// ----------------------------------------------------------------------
function decodeStringFromHex(value){
	if(!value) return "";
    var n = value.length / 2, result = '';    
    for (var i = 0; i < n; i++) result += String.fromCharCode(eval("0x" + value.substr(i*2, 2)));    
    return result;
}

// ----------------------------------------------------------------------
// Create a title bar (100% of width) applying the '.header' class style
//
// Parameters:
//    - title: The title to be displayed
// ----------------------------------------------------------------------
function renderTitleBar(title){
    document.write(isIE() ? 
        '<div class=header>' + title + '</div>' :
        '<table border=0 cellSpacing=0 cellPadding=2 width=100%><tr><td class=header>' + title + '</td></tr></table>');
} // func





// ----------------------------------------------------------------------
// Create the begin/end part tabbed panel structure
// ----------------------------------------------------------------------
function renderEndTabbedPanel()   { document.write('</tr></table>'); }
function renderBeginTabbedPanel() { document.write('<table cellSpacing=0 cellPadding=0 border=0><tr>'); }

// ------------------------------------------------------------------------------------
// Display a single tabbed panel
//
// Parameters: 
//    - label     : The tab text label (REQUIRED)
//    - isSelected: If TRUE the tab will be drawn as selected
//    - link      : The triggered hyperlink. REQUIRED
//    - target    : An optional target frame for the hyperlink
// ------------------------------------------------------------------------------------
function renderTab(label, isSelected, link, target){ 
  var sel = isSelected ? "_sel" : "";
  var tmp = '<TD><IMG alt="" src="' + imagesDir + 'tab_left' + sel + '.gif" align=middle border=0></TD>' +
	        '<TD  background="' + imagesDir + 'tab_middle' + sel + '.gif">' +
	        '<A class=' + (isSelected ? 'tab_selected' : 'tab_normal') + ' HREF="' + link + '" ' + (target == null ? '' : (' TARGET=' + target))+ '>' +
	        (isSelected ? '<font color=white><b>' + label + '</b></font>' : label) +
	        '</A></TD><TD><IMG alt="" src="' + imagesDir + 'tab_right' + sel + '.gif" align=middle border=0></TD>';
  document.write(tmp); 
} // func


// ==================================================
// LIOTRO-X EVENTS
// ==================================================

// ------------------------------------------------------------------------------------
// Create a new event with the specified type/target/action
// All this parameters are required
// ------------------------------------------------------------------------------------
function BZEventParam(name,value) { this.name = name; this.value = value; }
function BZEvent(type, target, action){
    this.params = new Array();

    var i = 0;
    this.params[i++] = new BZEventParam(PARAM_TYPE, type);
    this.params[i++] = new BZEventParam(PARAM_TARGET, target);
    this.params[i++] = new BZEventParam(PARAM_ACTION, action);
    this.params[i++] = new BZEventParam(PARAM_PAGE_EVENT, false);
    this.params[i++] = new BZEventParam(PARAM_SUBMIT, false);
} // func


// ----------------------------------------------------------------------
// Generic parameter (String value)
// ----------------------------------------------------------------------
function _xevt_findParameter(name)
{
    var n = this.params.length;
    
    for (i = 0; i < n; i++)
        if(this.params[i].name == name) return i;
        
    return -1;
}
BZEvent.prototype.findParameter = _xevt_findParameter;

// ----------------------------------------------------------------------
// Add an array of parameters 
// ----------------------------------------------------------------------
function _xevt_addParameters(paramArray) 
{
    //if (paramArray == null || paramArray.length == 0) return;
    
    var key = "";
    for(key in paramArray)
        this.params[this.params.length] = new BZEventParam(key, paramArray[key]);
} // func
BZEvent.prototype.addParameters = _xevt_addParameters;

// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Set a generic parameter (name and value)
// ----------------------------------------------------------------------
function _xevt_setParameter(paramName, paramValue) 
{
    var p = this.findParameter(paramName);
    if(p == -1)
    {
        this.params[this.params.length] = new BZEventParam(paramName, paramValue);
    } 
    else 
    {
        this.params[p].name  = paramName;
        this.params[p].value = paramValue;
    } // if
} // func

// ----------------------------------------------------------------------
// Return a generic parameter value
// ----------------------------------------------------------------------
function _xevt_getParameter(paramName)
{ 
    var p = this.findParameter(paramName);
    if(p == -1) return '';
      else return this.params[p].value
}
BZEvent.prototype.setParameter = _xevt_setParameter;
BZEvent.prototype.getParameter = _xevt_getParameter;

// ----------------------------------------------------------------------
// Encode the event as a string (key:value|...|key:value)
// ----------------------------------------------------------------------
function _xevt_encode()
{
    var n = this.params.length;
    
    var s = '';
    for (var i = 0; i < n; i++)
    {
        if(i > 0) s += '|';        
        s += encodeStringToHex(this.params[i].name) + '.' + encodeStringToHex(this.params[i].value);
    } // for

    return '$' + s;
} 
BZEvent.prototype.encode = _xevt_encode;

// ----------------------------------------------------------------------
// Create a event from a encoded string (key:value|...|key:value)
// ----------------------------------------------------------------------
BZEvent.prototype.createFromString = function(encodedEvent)
{
    if(encodedEvent == null || encodedEvent.length == 0 || encodedEvent.charAt(0) != '$') return null;
    
    // remove $ chart
    encodedEvent = encodedEvent.substr(1);

    // reset event parameters    
    this.params = new Array();
    
	// split event to retrieve all parameters
	var newParams   = encodedEvent.split("|");

	var keyValue = null;
	for(var i = 0; i < newParams.length; i++)
	{
	    // split a single parameter
	    keyValue = newParams[i].split(".");
		this.setParameter(decodeStringFromHex(keyValue[0]),decodeStringFromHex(keyValue[1]));
    } // for

    return this;
}  // func


// ----------------------------------------------------------------------
// Event Class (if omitted the default is: 'st.bz.Event')
// ----------------------------------------------------------------------

function _xevt_setClass(value) { this.setParameter(PARAM_EVT_CLASS, value); }
function _xevt_getClass()      { this.getParameter(PARAM_EVT_CLASS); }
BZEvent.prototype.setClass = _xevt_setClass;
BZEvent.prototype.getClass = _xevt_getClass;

// ----------------------------------------------------------------------
// Event Type (String value)
// ----------------------------------------------------------------------

function _xevt_setType(value) { this.setParameter(PARAM_TYPE, value); }
function _xevt_getType()      { this.getParameter(PARAM_TYPE); }
BZEvent.prototype.setType = _xevt_setType;
BZEvent.prototype.getType = _xevt_getType;

// ----------------------------------------------------------------------
// Event Target (String value)
// ----------------------------------------------------------------------
function _xevt_setTarget(value) { this.setParameter(PARAM_TARGET, value); }
function _xevt_getTarget()      { this.getParameter(PARAM_TARGET); }
BZEvent.prototype.setTarget = _xevt_setTarget;
BZEvent.prototype.getTarget = _xevt_getTarget;

// Event Action (String value)
// ----------------------------------------------------------------------
function _xevt_setAction(value) { this.setParameter(PARAM_ACTION, value); }
function _xevt_getAction()      { this.getParameter(PARAM_ACTION); }
BZEvent.prototype.setAction = _xevt_setAction;
BZEvent.prototype.getAction = _xevt_getAction;

// Event PageEvent (Boolean value)
// ----------------------------------------------------------------------
function _xevt_setPageEvent(value) { this.setParameter(PARAM_PAGE_EVENT, value); }
function _xevt_isPageEvent()       { this.getParameter(PARAM_PAGE_EVENT); }
BZEvent.prototype.setPageEvent = _xevt_setPageEvent;
BZEvent.prototype.isPageEvent  = _xevt_isPageEvent;

// Event Submit (Boolean value)
// ----------------------------------------------------------------------
function _xevt_setSubmit(value) { this.setParameter(PARAM_SUBMIT, value); }
function _xevt_isSubmit()       { this.getParameter(PARAM_SUBMIT); }
BZEvent.prototype.setSubmit = _xevt_setSubmit;
BZEvent.prototype.isSubmit  = _xevt_isSubmit;

// Event Server Input Validation (Boolean value)
// ----------------------------------------------------------------------
function _xevt_setServerValidation(value) { this.setParameter(PARAM_SERVER_VALIDATE, value); }
function _xevt_isServerValidation()       { this.getParameter(PARAM_SERVER_VALIDATE); }
BZEvent.prototype.setServerValidation = _xevt_setServerValidation;
BZEvent.prototype.isServerValidation  = _xevt_isServerValidation;


// Function used from client validation controls to change dynamically tooltips
function setAltText(id,text) { if (isDOMBrowser()) document.getElementById(id).title = text; }

// ----------------------------------------------------------------------
// Used internally by LIOTRO-X to manage selectionList controls
// ----------------------------------------------------------------------
function bz_selectionList_select(fbox, tbox, flist, tlist, sort) 
{
	var arrFbox = new Array();
	var arrTbox = new Array();
	var arrLookup = new Array();
	var i;

	for (i = 0; i < tbox.options.length; i++) 
	{
		arrLookup[tbox.options[i].text] = tbox.options[i].value;
		arrTbox[i] = tbox.options[i].text;
	} //for
	var fLength = 0;
	var tLength = arrTbox.length;
	for(i = 0; i < fbox.options.length; i++) 
	{
		arrLookup[fbox.options[i].text] = fbox.options[i].value;
		if (fbox.options[i].selected && fbox.options[i].value != "") 
		{
			arrTbox[tLength] = fbox.options[i].text;
			tLength++;
		}
		else {
			arrFbox[fLength] = fbox.options[i].text;
			fLength++;
		} //if
	} //for
	
	if(sort)
	{
		//arrFbox.sort();
		arrTbox.sort();
	}//if
	
	fbox.length = 0;
	tbox.length = 0;
	var c;

	flist.value="";
	for(c = 0; c < arrFbox.length; c++) 
	{
		var no = new Option();
		no.value = arrLookup[arrFbox[c]];
		no.text = arrFbox[c];
		fbox[c] = no;
		//flist.value = flist.value +','+ arrFbox[c];
		flist.value = flist.value +','+ encodeStringToHex(arrLookup[arrFbox[c]]);
	} //for
	
	tlist.value="";
	for(c = 0; c < arrTbox.length; c++) 
	{
		var no = new Option();
		no.value = arrLookup[arrTbox[c]];
		no.text = arrTbox[c];
		tbox[c] = no;
		//tlist.value = tlist.value +','+ arrTbox[c];
		tlist.value = tlist.value +','+ encodeStringToHex(arrLookup[arrTbox[c]]);
	} //for
	
}//func

// -------------------------------------------------------------------------
// this function is used to sort a list 
// param fbox       the list to sort
// param flist      a hidden obj filled with fbox encoded values
// param up         if true move the selected items up
// param flistCodes a optional hidden obj filled with fbox encoded text
// -------------------------------------------------------------------------
function bz_selectionList_sort(fbox,flist,up,flistCodes, eventNotification)
{
	if(up)
	{
		if(eventNotification != null)
		{
			var msg = eval(eventNotification + "(fbox, 'moveUp');");
			if(msg != null)	{ alert(msg); return; }
		} // if

		for(var i = 0; i < fbox.options.length; i++) 
		{
			if (fbox.options[i].selected && fbox.options[i].value != "" && i>0 &&  !fbox.options[i-1].selected)
			{
				var previus   = new Option();
				previus.text  = fbox.options[i-1].text;
				previus.value = fbox.options[i-1].value;
				
				var curr    = new Option();
				curr.text   = fbox.options[i].text;
				curr.value  = fbox.options[i].value;
				
				fbox[i-1] = curr;
				fbox[i]   = previus;
				fbox.options[i-1].selected = true;
			}
		} //for
	}
	else
	{
		if(eventNotification != null)
		{
			var msg = eval(eventNotification + "(fbox, 'moveDown');");
			if(msg != null)	{ alert(msg); return; }
		} // if
		
		for(var i = fbox.options.length-1; i > -1; i--) 
		{
			if (fbox.options[i].selected && fbox.options[i].value != "" && i<fbox.options.length-1 &&  !fbox.options[i+1].selected)
			{
				var next   = new Option();
				next.text  = fbox.options[i+1].text;
				next.value = fbox.options[i+1].value;
				
				var curr    = new Option();
				curr.text   = fbox.options[i].text;
				curr.value  = fbox.options[i].value;

				fbox[i+1] = curr;
				fbox[i]   = next;
				fbox.options[i+1].selected = true;
			} // if
		} //for
	}

	if(flist)
	{
		flist.value="";
		for(var c = 0; c < fbox.length; c++) 
		{
			if(c > 0) flist.value += ",";
			flist.value += encodeStringToHex(fbox.options[c].value);
		} // for
	} // if
	
	if(flistCodes)
	{
		flistCodes.value="";
		for(var c = 0; c < fbox.length; c++) 
		{
			if(c > 0) flistCodes.value += ",";
			flistCodes.value += encodeStringToHex(fbox.options[c].text);
		} // for
	} // if

}//func

//---------------------------------------------------------------
// delete a items from 'listName' list and from two 
// hidden obj named 'listNameHiddenItems' and 'listNameHiddenCodes'
//---------------------------------------------------------------
function bz_editableList_delete(listName, conf, eventNotification) 
{
	if (listName.selectedIndex < 0)
	{
		alert("You must select a item");
		return;
	} // if
	
	if(eventNotification != null)
	{
		var msg = eval(eventNotification + "(listName, 'delete');");
		if(msg != null)	{ alert(msg); return; }
	} // if
	
	if(conf && conf == true)
	{
		var res = confirm("Delete item '"+listName.options[listName.selectedIndex].text+"'?");
		if(!res) return;
	} // if
	
	listName.remove(listName.selectedIndex);
	bz_refresh_editableList_hidden(listName);	
} // func

function bz_refresh_editableList_hidden(listName)
{
	var hiddenItems = eval('document.xform.' + listName.name + 'HiddenItems');
	hiddenItems.value = "";
	for(var c = 0; c < listName.length; c++) 
		hiddenItems.value = hiddenItems.value +','+ encodeStringToHex(listName.options[c].text);
} // func

//---------------------------------------------------------------
// Edit a items from 'listName' list and from two 
// hidden obj named 'listNameHiddenItems' and 'listNameHiddenCodes'
// param editCode if true change 'listNameHiddenItems' and 'listNameHiddenCodes'
//---------------------------------------------------------------
function bz_editableList_edit(listName, validAction, editCode, eventNotification) 
{
	
	if (listName.selectedIndex < 0) 
	{
		alert("You must select a item");
		return;
	} // if

	if(eventNotification != null)
	{
		var msg = eval(eventNotification + "(listName, 'edit');");
		if(msg != null)	{ alert(msg); return; }
	} // if
	
	var tmp = prompt("Insert new value for selected item",listName.options[listName.selectedIndex].text);
	if (tmp == null) return;
	
	if(tmp.length <= 0) 
	{
		alert("The item can't be empty"); 
		return;
	} // if

	if(validAction != null)
	{
		var msg = eval(validAction + "('" + tmp + "');");
		if(msg != null)	{ alert(msg); return; }
	} // if
	
	listName.options[listName.selectedIndex].text = tmp;
	if(editCode) listName.options[listName.selectedIndex].value = tmp;
	bz_refresh_editableList_hidden(listName);

} // func

//---------------------------------------------------------------
// Remove all element of 'listName' list
//---------------------------------------------------------------
function bz_editableList_clear(listName,conf, eventNotification) 
{
	if (listName.length < 1) return;

	if(eventNotification != null)
	{
		var msg = eval(eventNotification + "(listName, 'clear');");
		if(msg != null)	{ alert(msg); return; }
	} // if
	
	if(conf && conf == true)
	{
		var res = confirm("Delete all items?");
		if(!res) return;
	} // if
	
	listName.length = 0;
	bz_refresh_editableList_hidden(listName);

} // func

//---------------------------------------------------------------
// Add a new element in 'listName' list
//---------------------------------------------------------------
function bz_editableList_add(listName, validAction, eventNotification) 
{
	if(eventNotification != null)
	{
		var msg = eval(eventNotification + "(listName, 'add');");
		if(msg != null)	{ alert(msg); return; }
	} // if
	
	var tmp = prompt("Insert value for new item","");
	if (tmp == null) return;
	
	if(tmp.length <= 0) 
	{
		alert("The item can't be empty"); 
		return;
	} // if

	if(validAction != null)
	{
		var msg = eval(validAction + "('" + tmp + "');");
		if(msg != null)	{ alert(msg); return; }
	} // if

	var elem   = new Option();
	elem.text  = tmp;
	elem.value = tmp;
	
	listName[listName.length] = elem;
	bz_refresh_editableList_hidden(listName);

} // func

//---------------------------------------------------------------
// Reset original elements in 'listName' list
//---------------------------------------------------------------
function bz_editableList_reset(listName, eventNotification) 
{
	if(eventNotification != null)
	{
		var msg = eval(eventNotification + "(listName, 'reset');");
		if(msg != null)	{ alert(msg); return; }
	} // if
	
	bz_editableList_clear(listName,false);

	var originalItems = eval('document.xform.' + listName.name + 'OriginalItems');

	var items = originalItems.value.split(",");

	for(var i = 0; i < items.length - 1; i++)
	{
		var elem   = new Option();
		elem.text  = decodeStringFromHex(items[i]);
		elem.value = elem.text;
		listName[i] = elem;
	}

	bz_refresh_editableList_hidden(listName);

} // func

// ---------------------------------------------------------------------------
// Functions used with the <xc:lookupList> control to set mapped output fields
// parameters: 
//      - textBoxArray      is a String[] containing the HTML input object names 
//      - hexValueArray     is a String[] containing the HTML input object values
//      - autoClose         a boolean value, if true the window will be closed aftre selection
//      - hexAppendString   is a String used as separator to concatenate selecdted values
//      - controlName       the lookupList control name
//      - onBeforeSelection the javascript function name called before filling HTML inputs
//      - onAfterSelection  the javascript function name called after  filling HTML inputs
// ---------------------------------------------------------------------------
function setLookupListFields(textBoxArray, hexValueArray, autoClose, hexAppendString, controlName, onBeforeSelection, onAfterSelection)
{
    var textBoxes = textBoxArray.split(",");
    var hexValues = hexValueArray.split(",");
    var txt= ''; v = '';
    var obj = null;
    
    // create a String[] with decoded values
    var decodedValues = new Array();
    for(var i = 0; i < hexValues.length; i++) 
        decodedValues[i] = decodeStringFromHex(hexValues[i]);
        
    // create a map HTML input objects and related values
    var values = new Array();
    for(var i = 0; i < textBoxes.length; i++) 
        values[textBoxes[i]] = decodedValues[i];
    
    // create LX client event with 'controlName' and 'values' as attributes
    var evtAttributes = new Array();
    evtAttributes['controlName'] = controlName;
    evtAttributes['values']      = values;
    var bze = new BZClientEvent(evtAttributes);
    
    
    // call the user function if it is defined
    // if called function return false the HTML inputs won't filled
    var result = true;
    if(onBeforeSelection != 'null')        
        result = eval('window.opener.' + onBeforeSelection + '(bze)');   

   // if called function return false the HTML inputs won't filled
   if(result && ((''+result).toLowerCase() == 'true'))
   { 
        var appendString = hexAppendString ? decodeStringFromHex(hexAppendString) : '@REPLACE';
        
        for(var i = 0; i < textBoxes.length; i++) 
        {      
            txt = textBoxes[i]; 
            v   = decodedValues[i];
            
            obj = eval('window.opener.document.' + txt);
            if( (obj.type == 'text') || (obj.type == 'textarea') || (obj.type == 'hidden') || (obj.type == 'password'))
            {
                // If the 'appendString' parameter is '@REPLACE' the value is replaced
                // in the target control, else it will be appended (and separed from the
                // existing value using the 'appendString' separator            
                if(appendString == '@REPLACE' || obj.value == '') obj.value = v;   
                    else obj.value += appendString + v;   
            }
            else
                for(var j = 0; j < obj.options.length; j++)
                    if(obj.options[j].value == v)
                        obj.options[j].selected = true;
        } // for
        
        if(onAfterSelection != 'null')
            eval('window.opener.' + onAfterSelection + '(bze)');
    } // if
    
   if(autoClose) window.close();
}

// ----------------------------------------------------------------------
// Used internally by LIOTRO-X to manage popup
// ----------------------------------------------------------------------
function bzPopup(e,msg,color,bgcolor,bordercolor)
{
	color       = (!color)       ? "#000080" : color;
	bgcolor     = (!bgcolor)     ? "#FAFAD2" : bgcolor;
	bordercolor = (!bordercolor) ? "#C0C0C0" : bordercolor;
	
	var content="<TABLE BORDER=1 BORDERCOLOR="+bordercolor+" CELLPADDING=2 CELLSPACING=0 BGCOLOR="+bgcolor+">"+
				"<TR><TD ALIGN=center><FONT COLOR="+color+" SIZE=1 face=verdana>"+msg+"</FONT></TD>"+
				"</TR></TABLE>";

	writePopup('bzpopup',content);
	movePopup(e,'bzpopup','true',10);
}//func

function writePopup(divName,content)
{

	if(document.all)
		document.getElementById(divName).innerHTML=content;
	
	if(document.layers)
	{
		var pop = document.layers[divName];
		pop.document.open("text/html");
		pop.document.write(content);
		pop.document.close();
	}

	if(navigator.appName == 'Netscape')
		if(parseInt(navigator.appVersion) >= 5)
			document.getElementById(divName).innerHTML=content;

}//func


function movePopup(e,divName,show,offset)
{
	offset = (!offset) ? 0 : offset;

	if(document.all)
	{
		var pop = document.getElementById(divName);
		if(pop.style.visibility == "hidden")
		{
			pop.style.left = e.x+document.body.scrollLeft+offset;
			pop.style.top  = e.y+document.body.scrollTop+offset;
		}//if
	}//if
	
	if(document.layers)
	{
		var pop = document.layers[divName];
		if(pop.visibility == "hide")
		{
			pop.pageX= e.x+offset;
			pop.pageY= e.y+offset;
		}//if
	}//if

	if(navigator.appName == 'Netscape')
		if(parseInt(navigator.appVersion) >= 5)
		{
			var pop = document.getElementById(divName);
			if(pop.style.visibility == "hidden")
			{
				pop.style.left = e.pageX+offset;
				pop.style.top  = e.pageY+offset;
			}//if
		}

	if(show == "true") objShow(divName);
}//func

function helpListHide(e,divName)
{
	
	if(document.all)
	{
		var pop   = document.getElementById(divName);
		if(!(e.x+document.body.scrollLeft > (parseInt(pop.style.left)+5) && e.x+document.body.scrollLeft < (parseInt(pop.style.left)+pop.clientWidth-5) && e.y+document.body.scrollTop  > (parseInt(pop.style.top)+5) && e.y+document.body.scrollTop < (parseInt(pop.style.top)+pop.clientHeight-5)))
			pop.style.visibility="hidden";
	}
	
	if(document.layers)
	{
		var pop = document.layers[divName];
		pop.visibility="hide"
	}

	if(navigator.appName == 'Netscape')
	{
		if(parseInt(navigator.appVersion) >= 5)
		{
			var pop   = document.getElementById(divName);
			if(!(e.pageX > (parseInt(pop.style.left)+5) && e.pageX < (parseInt(pop.style.left)+pop.offsetWidth-5) && e.pageY  > (parseInt(pop.style.top)+5) && e.pageY < (parseInt(pop.style.top)+pop.offsetHeight-5)))
			{
				pop.style.left = -2000;
				pop.style.top  = -2000;
				pop.style.visibility="hidden";
			}//if
		}//if
	}//if
	
}//func

// Return the current page vertical scroll position
// ------------------------------------------------------------------
function getPageScrollTop() 
{
    return isIE() ? document.body.scrollTop : window.pageYOffset;
}

// Return the current page horizontal scroll position
// ------------------------------------------------------------------
function getPageScrollLeft() 
{
    return isIE() ? document.body.scrollLeft : window.pageXOffset;
}

// Set the current page horizontal/vertical scroll positions
// ------------------------------------------------------------------
function scrollPage(top, left)
{
    if(isIE())
    {
        document.body.scrollTop  = top;
        document.body.scrollLeft = left;        
    }
    
    if(isNS6() || isNS4())
    {
	   window.scrollTo(left, top);
    }
}//func


function objShow(divName)
{

	if(document.all)
		document.getElementById(divName).style.visibility="visible";
	
	if(document.layers)
		document.layers[divName].visibility="visible";

	if(navigator.appName == 'Netscape')
		if(parseInt(navigator.appVersion) >= 5)
			document.getElementById(divName).style.visibility="visible";

}//func

function objHide(divName)
{
	if(document.all)
	{
		var pop   = document.getElementById(divName);
		pop.style.visibility="hidden";
	}
	
	if(document.layers)
	{
		var pop = document.layers[divName];
		pop.visibility="hidden"
	}

	if(navigator.appName == 'Netscape')
		if(parseInt(navigator.appVersion) >= 5)
		{
			var pop   = document.getElementById(divName);
			pop.style.left = -2000;
			pop.style.top  = -2000;
			pop.style.visibility="hidden";
		}

}//func

function invertVisibility(divName)
{
	var pop;
	if(document.all)
		pop   = document.getElementById(divName).style.visibility;
	
	if(document.layers)
		pop = document.layers[divName].visibility;

	if(navigator.appName == 'Netscape')
		if(parseInt(navigator.appVersion) >= 5)
			pop   = document.getElementById(divName).style.visibility;


	if(pop == "visible")
		objHide(divName);
	else
		objShow(divName);
		
}//func


// ----------------------------------------------------------------------
// Open the administration console window
// ----------------------------------------------------------------------
function openAdminConsole()
{
    var x = "menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=10,left=10," +
            "width=" + (screen.width - 50) + ",height=" + (screen.height - 50);
    var w = window.open("app?path=/system/admin/console.show", "ConsoleWindow", x);
    w.focus();
} 


// ----------------------------------------------------------------------
// Open the customization window
// ----------------------------------------------------------------------
function openCustomizationConsole(viewName, viewType, viewPath, editorTitle, customizableOptions)
{
	internalOpenCustomizationConsole(false, null, null, viewName, viewType, viewPath,null, editorTitle, customizableOptions)
} // func

// ----------------------------------------------------------------------
// Open the customization window
// ----------------------------------------------------------------------
function internalOpenCustomizationConsole(isAdmin, fieldName, applyCallback, viewName, viewType, viewPath, formName, editorTitle, customizableOptions)
{
	var event = new BZEvent();
	event.setType('openCustomization');
	event.setTarget('/pages/bz/customizationPage');
	event.setAction('open');
	
	event.setParameter('isAdmin',isAdmin);
	event.setParameter('fieldName', fieldName);
	event.setParameter('applyCallback', applyCallback);
	event.setParameter('viewName',viewName);
	event.setParameter('viewType', viewType);
	event.setParameter('viewPath', viewPath);
	event.setParameter('editorTitle', editorTitle);
	
	//if (isNS4()) event.setParameter('_gzip_', 'false');

	event.setParameter('customizableOptions', (customizableOptions) ? customizableOptions : "*" );
	
    var windowParams = "menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=20,left=5," +
                        "width=1000,height=600";

	handleActionControl(formName, null, 'customization', windowParams, true, false, event.encode());
} // func

// ----------------------------------------------------------------------
// Open the MultipleSort window
// param windowId        the new window name
// param inputField      HTML input object used to get/set encoded MultipleSort instance
// param applyCallback   the javascript function invoked at the apply time
// param editorTitle     the title used into page
// param returnReference if true the function return a reference at the opened window
// es. openMultipleSortConsole('myReportMultipleSort', 'document.xform.myReportMultiSort', 'myReportApplyMultiSort')
// ----------------------------------------------------------------------
function openMultipleSortConsole(windowId, inputField, applyCallback, editorTitle, returnReference)
{
    var x = "menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,top="+((screen.height - 350)/2)+",left="+((screen.width - 450)/2)+"," +
            "width=450,height=300";
            
    var url = "app?path=/pages/bz/multiSortReportPage.open";
    
    if(inputField)
    	url += "&inputField=" + escape(inputField);
    
    if(applyCallback)
    	url += "&applyCallback=" + escape(applyCallback);

    if(editorTitle)
    	url += "&editorTitle=" + escape(editorTitle);		
             
    var w = window.open(url, windowId, x);
    w.focus();

    if(returnReference)return w;
} // func

// ----------------------------------------------------------------------
// Open the AdvancedSearch window
// param windowId         the new window name or IFRAME id (this is required)
// param inputField       HTML input object used to get/set encoded MultipleSort instance
// param applyCallback    the javascript function invoked at the apply time
// param showFilterButton if 'false' the filter button will not displayed
// param showSearchButton if 'false' the search button will not displayed
// param message		  result of previous search
// param editorTitle      the title used into page
// param returnReference  if true the function return a reference at the opened window
// param inFrame          if 'true' the advancedSearch Page will be opened in to an iframe (only NS6 and IE)
// param autoClose        if 'true' when a search/filter is performed the advancedSearch Page is automatically closed
// param winWidth         the window/iframe width
// param winHeight        the window/iframe Height
// param condRowsHeight   the condition panel Height
// ----------------------------------------------------------------------
function openAdvancedSearchConsole(windowId, inputField, applyCallback, showFilterButton, showSearchButton, showHelpButton, message, editorTitle, returnReference, inFrame, autoClose, winWidth, winHeight, condRowsHeight)
{
            
    var newUrl = "app?path=/pages/bz/advancedSearchPage.open&windowID=" + windowId;

    if(inputField)
    	newUrl += "&inputField=" + escape(inputField);
    
    if(applyCallback)
    	newUrl += "&applyCallback=" + escape(applyCallback);

    if(showFilterButton)
    	newUrl += "&showFilterButton=" + escape(showFilterButton);

    if(showSearchButton)
    	newUrl += "&showSearchButton=" + escape(showSearchButton);

    if(showHelpButton)
    	newUrl += "&showHelpButton=" + escape(showHelpButton);

    if(message)
    	newUrl += "&message=" + escape(message);

    if(editorTitle)
    	newUrl += "&editorTitle=" + escape(editorTitle);		

  	newUrl += "&autoClose=" + escape(autoClose);		
  	newUrl += "&conditionPanelHeight=" + escape(condRowsHeight);		

    if(inFrame && !isNS4())
    {
    	newUrl += "&inFrame="  + 'true';		

        var myFrame      = document.getElementById(windowId);
        if(myFrame == null) 
        {
            alert("Unable to open AdvancedSearch: HTML IFrame '" + windowId + "' is not defined.");
            return;
        } // if
        var myFrameState = eval ("document.xform." +windowId + "_state");
        myFrameState.value = newUrl;
        myFrame.width   = winWidth;
        myFrame.height  = winHeight;
        myFrame.src     = newUrl;
        myFrame.style.visibility = "visible";


    }
    else
    {
        var tmpWidth   = (isNaN(parseInt(winWidth)))  ? 50  : ((screen.width - winWidth)/2);
        var tmpHeight  = (isNaN(parseInt(winHeight))) ? 50 : ((screen.height - winHeight)/2);

        var x = "menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,top="+tmpHeight+",left="+tmpWidth+"," +
                "width=" + winWidth + ",height=" + winHeight;

    	newUrl += "&inFrame=" + 'false';		

        var w = window.open(newUrl, windowId, x);
        w.focus();
        
        if(returnReference)return w;
    } // if
    
} // func

function showAdvancedSearchIFrame(dvControlName)
{
    document.write('<x:get path="&@PAGE.controls[\''+ dvControlName +'\'].advancedSearchIFrame"/>');
} // func

// ----------------------------------------------------------------------
// Open the Aggregration Groups Console window
// param windowId      			the new window name
// param groupListTree    		HTML object used to get/set encoded groupListTree instance
// param columnsAvailableForGroup    	HTML object used to get/set columns available  for group (sortable columns)
// param columnsAvailable    	HTML object used to get/set columns available (sortable)
// param allColumns    			HTML object used to get/set all columns available (contains group class and renderer class information)
// param availableMeasures		HTML object used to get/set available measures
// param applyCallback 			the javascript function invoked at the apply time
// param disableCallback        the javascript function invoked at the disable an group
// param editorTitle     		the title used into page
// param returnReference 		if true the function return a reference at the opened window
// ----------------------------------------------------------------------
function openGroupsConsole(windowId, groupListTree, columnsAvailableForGroup, columnsAvailable, allColumns, availableMeasures, applyCallback, disableCallback, editorTitle, returnReference)
{
    var x = "menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=50,left=50," +
            "width= 950, height= 546";
            
    var url = "app?path=/pages/bz/groupsEditorPage.open";
    
    if(groupListTree)
    	url += "&groupListTree=" + escape(groupListTree);
    
    if(columnsAvailableForGroup)
    	url += "&columnsAvailableForGroup=" + escape(columnsAvailableForGroup);

    if(columnsAvailable)
    	url += "&columnsAvailable=" + escape(columnsAvailable);
    
    if(allColumns)
    	url += "&allColumns=" + escape(allColumns);
    
    if(availableMeasures)
    	url += "&availableMeasures=" + escape(availableMeasures);

    if(applyCallback)
    	url += "&applyCallback=" + escape(applyCallback);
    
    if(disableCallback)
    	url += "&disableCallback=" + escape(disableCallback);		

    if(editorTitle)
    	url += "&editorTitle=" + escape(editorTitle);		
    			             
    var w = window.open(url, windowId, x);
    w.focus();

    if(returnReference)return w;
} // func



// ----------------------------------------------------------------------
// Open the style console window
// param windowId      the new window name
// param inputField    HTML input object used to get/set encoded MultipleSort instance
// param applyCallback the javascript function invoked at the apply time
// es. openMultipleSortConsole('myReportMultipleSort', 'document.xform.myReportMultiSort', 'myReportApplyMultiSort')
// ----------------------------------------------------------------------
function openStyleEditor(windowId, inputField, applyCallback, editorTitle, returnReference)
{
    var x = "menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,top="+((screen.height - 400)/2)+",left="+((screen.width - 450)/2)+"," +
            "width=450,height=320";
            
    var url = "app?path=/pages/bz/styleEditorPage.open";
    
    if(inputField)
    	url += "&inputField=" + escape(inputField);
    
    if(applyCallback)
    	url += "&applyCallback=" + escape(applyCallback);

    if(editorTitle)
    	url += "&editorTitle=" + escape(editorTitle);		
             
    var w = window.open(url, windowId, x);
    w.focus();
    
    if(returnReference)return w;

} // func


// ----------------------------------------------------------------------
// Return an unique random ID (128 chars)
// ----------------------------------------------------------------------
function getUniqueID()
{
	var bz_unique_id_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	var bz_unique_id_len   = 128;

	var name = "bz_";
	var len = bz_unique_id_chars.length - 1;
	for (i=0; i<bz_unique_id_len; i++) name += bz_unique_id_chars.charAt(Math.round(Math.random()*len));
	return name;
} // func

// ----------------------------------------------------------------------
// Handle the 'click' event for action controls (xc:link and xc:button)
// ----------------------------------------------------------------------

function handleActionControl(formName, validateAction, frame, windowParams, submit, mustValidate, event, loadingDivID, loadingMsg)
{
    // Manage the (optional) validate action JavaScript function
    if(validateAction != null)
    {
        var msg = eval(validateAction);
        if(msg != null) { alert(msg); return; }
    } // if    

    if(formName == null) formName = 'xform';
    
	// Check (if required) that all client checks are passed
    if( ('' + mustValidate) == 'true' && (('' + submit) == 'true'))
       if(!doBZValidation()) { alert(alert_text); return; }   
    
    // Manage the 'window' (current window/open an existing one/open a new one
    var win = window;          // Current window
    
    // A new window is required to be opened 
    // if the frame value is not '_blank'
    if (frame == '_blank') frame = getUniqueID();
    
    if (frame != null) 
    {
    	if (windowParams != null)  
        	win = window.open('', frame, windowParams);
     	else 
        	win = window.open('', frame);
    } 
    
    if(win != window) win.focus();

    if(('' + submit) == 'true')
    {
        var formObj = eval('document.' + formName);
        var tmpTarget = null;
        if(frame != null) 
        { 
        	tmpTarget = formObj.target; 
            if(tmpTarget == null || tmpTarget == '') tmpTarget = '_self';
            formObj.target = frame;
        } // if

        // Handling loading message
        //--------------------------------------------
        if(loadingMsg != null)
        {
            if(frame != null && win != window)
            {
                   bzWriteNewPage(win,loadingMsg);
                   doBZEvent(event, formName, false);       
            }
            else
            {
                doBZEvent(event, formName, false);       
                if(loadingDivID != null && !isNS4()) 
                    bzWriteMessage(document.getElementById(loadingDivID), loadingMsg);
            }
        } // if
        else doBZEvent(event, formName, false);       
        
        // ========================================================================
        // Correct a NS 4.7x synchronization bug (due to a bad multithread mgmt)!!!
        // ========================================================================
        if(isNS4() || isMac()) 
        {  
            var d = new Date(), t1, t2;
            t1 = d.getTime(); t2 = t1;
            while( (t2-t1) < 1000) { d = new Date(); t2 = d.getTime(); } // Wait N msecs
        }
        // ========================================================================


        // Restore the 'old' target
        if(frame != null) formObj.target = tmpTarget;
    } // if
    else win.location.href = 'app?bz_event=' + event + '&bz_page_event=' + event;    
    
} // func

var bz_frm_bkm_parameters = "";
var bz_frm_bkm_original_action = null;
var bz_frm_bkm_max_url_size = 2000;

function bz_frm_append_bkm_event(ev)
{
	if(bz_frm_bkm_original_action == null)
		bz_frm_bkm_original_action = document.xform.action;
		
    var encodedParams = "";
    if(bz_frm_bkm_parameters != null && bz_frm_bkm_parameters.length > 0)
    {
	    var controls = bz_frm_bkm_parameters.split(',');
	    for(var i = 0; i < controls.length; i++)
	    {
	    	if(bz_trim(controls[i]).length <= 0) continue;
	    	var control = eval('document.xform.' + controls[i]);
	    	if(control)
	    	{
	    		if(control.type != 'select-multiple')
	    		{
	    			encodedParams += '&bzb_' +  controls[i] + '=' + escape(bz_get_control_value(control));
	    		}
	    		else
	    		{
					for(var k=0; k < control.options.length; k++)
					{	
						if(control.options[k].selected)
							encodedParams += '&' +  controls[i] + '=' + escape(control.options[k].value);
					} // for
				} // if
	    	} // if
	    } // for
	} // if

    var encodedUrl = bz_frm_bkm_original_action;

    var stateBag = "";
    if(document.xform.LX_BKM_STATE)    
        stateBag += document.xform.LX_BKM_STATE.value;

    if((encodedUrl.length + stateBag.length) < bz_frm_bkm_max_url_size)
        encodedUrl += stateBag;
    
    if((encodedUrl.length + encodedParams.length) < bz_frm_bkm_max_url_size)
        encodedUrl += encodedParams;

    var encodedEvent = '&LX_BKM_EVT=' + escape(ev);
    if((encodedUrl.length + encodedEvent.length) < bz_frm_bkm_max_url_size)
        encodedUrl += encodedEvent;
    document.xform.action = encodedUrl;
} // func

function bz_setBookmarkParameters(controlName)
{
	if(controlName == null || bz_trim(controlName).length == 0) return;
	
	if(bz_frm_bkm_parameters == null)
		bz_frm_bkm_parameters = controlName;
	else bz_frm_bkm_parameters += controlName;

	bz_frm_bkm_parameters += ',';
} // func

function bz_get_control_value(control)
{
    if( (control.type == 'text') || (control.type == 'textarea') || 
        (control.type == 'hidden') || (control.type == 'password'))
		return control.value;
    else if(control.type == 'checkbox')
		return control.checked;
    else if(control.type == 'select-one' && control.selectedIndex > -1)
    	return control.options[control.selectedIndex].value;
    else if(control.length && control.length > 0 && control[0].type &&  control[0].type == 'radio')
    {	
    	for(var i=0; i < control.length; i++)
    		if(control[i].checked)
				return control[i].value;
	} // if

    return "";
} // func

// STRIPPED function do reduce HTML code
function bz_hac(formName, validateAction, frame, windowParams, submit, mustValidate, event, loadingDivID, loadingMsg)
{
  handleActionControl(formName, validateAction, frame, windowParams, submit, mustValidate, event, loadingDivID, loadingMsg);
}

/*---------------------------------------------------------------*/
/*------------- Functions to handle loading message -------------*/
/*---------------------------------------------------------------*/

	function bzWriteNewPage(windowObject, message)
	{
		//writing a lot of newlines first (for https)
		windowObject.document.write("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
		windowObject.document.write("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
		
		// write the Html header 
		windowObject.document.write("<HTML>\n");
		windowObject.document.write("<HEAD>\n");
		windowObject.document.write("</HEAD>\n");
		windowObject.document.write("<BODY BGCOLOR='#ffffff'>\n");
        windowObject.document.write("<form name='xform'>");		
        windowObject.document.write(bzGetWaitingHTML(message));		
        windowObject.document.write("</form");		
		windowObject.document.write("</BODY>\n");
		windowObject.document.write("</HTML>\n");
		windowObject.document.close();

        
	} // func
	
	function bzWriteMessage(formID, message)
	{
	    if(formID == null || (('' + formID) == 'undefined')) return null;
	    if(isNS4()) return null;
	    
        
        formID.innerHTML = bzGetWaitingHTML(message);
        
        if(formID.id == 'bzpopup')
        {
            bzCenterMessage(formID);
    	    objShow('bzpopup');
            
        } // if
	} // func
	
	function bzGetWaitingHTML(message)
	{
	    var content = "";
		
		content += "<center>\n";
	    	content += "<TABLE BGCOLOR='#ffffff' CELLPADDING=10 CELLSPACING=10 " ;
	    	content += " HEIGHT=100% WIDTH=100%";
	      	content += ">\n<TR>\n";
	        content += "<TD WIDTH='100%' HEIGHT='100%' BGCOLOR='#ffffff' ALIGN='CENTER' VALIGN='TOP'><br><br><br>\n";
	        content += "<FONT FACE='Tahoma,Helvetica,Verdana,Arial' SIZE=4 COLOR='#000066'>\n";
	        content += message + "\n";
	        content += "</FONT>\n";
            content += "<br><IMG border=0 src='" + imagesDir + "icons/wait.gif' >";
	        content += "</TD>\n";
	      	content += "</TR>\n";
	    	content += "</TABLE>\n";
		content += "</center>\n";  

        return content;
	} //func
	
function bzCenterMessage(pop)
{

    var w = 480, h = 340;
    
    if (document.all) {
       /* the following is only available after onLoad */
       w = document.body.clientWidth;
       h = document.body.clientHeight;
    }
    else if (document.layers) {
       w = window.innerWidth;
       h = window.innerHeight;
    }
    //alert("W: " + w + " H: " + h);
    var popW = 200, popH = 500
    
    var leftPos = (w-popW)/2, topPos = (h-popH)/2;

	pop.style.left = leftPos;//e.x+document.body.scrollLeft+offset;
	pop.style.top  = leftPos;//e.y+document.body.scrollTop+offset;

}//func
	
	
/*---------------------------------------------------------------*/



// --------------------------------------------------------------------
// Removes leading and 'trim' spaces from the passed string. Also removes
// If something besides a string is passed in (null, custom object, etc.) then return the input.
// --------------------------------------------------------------------
function bz_trim(inputString) 
{
   if (typeof inputString != "string") { return inputString; }
   
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   // Check for spaces at the beginning of the string
   while (ch == " " || ch.charCodeAt(0) == 13  || ch.charCodeAt(0) == 10 || ch.charCodeAt(0) == 9) 
   { 
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }

   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " " || ch.charCodeAt(0) == 13  || ch.charCodeAt(0) == 10 || ch.charCodeAt(0) == 9) 
   // Check for spaces at the end of the string
   { 
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   return retValue; 
} // Ends the "trim" function

// --------------------------------------------------------------------------------------------
// This object manage url parameters with get/add/toString functions
// --------------------------------------------------------------------------------------------
function BZxParameter(url)
{
	this.params = new Array();
	this.keySet = new Array();
	if(url)
	{
		var tmp = url.split("?");
		if(tmp.length > 1)
		{
			tmp = tmp[1].split("&");
		} // if
		
		for(var i = 0; i < tmp.length; i++)
		{
			var entry = tmp[i].split("=");
			if(entry.length > 1)
			{
				this.params[entry[0]] = entry[1];
				this.keySet[this.keySet.length] = entry[0];
			} // if
		} // for 
	} // if url

} // func
BZxParameter.prototype.getParameter = function(key,decode)
{
	if(key != null && key.length > 0)
	{
		var value = this.params[key];
		if(value != null)
		{
			if(decode)
				return decodeStringFromHex(value);
			else
				return unescape(value);
		} // if	
	} // if
	return null;
} // func

BZxParameter.prototype.addParameter = function(key,value,encode)
{
	if(key != null && key.length > 0 && value != null && value.length > 0)
	{
		if(encode)
			this.params[key] = encodeStringToHex(value);
		else
			this.params[key] = escape(value);
		
		this.keySet[this.keySet.length] = key;
	} // if	
} // func
BZxParameter.prototype.toString = function()
{
	var result = "";
	for(var i = 0; i < this.keySet.length; i++)
		result = result + "&" + this.keySet[i] + "=" + this.params[this.keySet[i]];
	return result;
} // func


// ---------------------------------------------------------
// MENU MANAGEMENT
// ---------------------------------------------------------

function toggleDisplay(elem) 
{
    if(!document.getElementById) { alert("Feature not supported with this browser"); return; }
    
    // ONLY FOR IE6 and NS6
	var obj = document.getElementById(elem);
    obj.style.display = (obj.style.display == "none") ? "block" : "none";
    
}

function toggleMenuDisplay(elem, icon, iconExpanded, changeTooltip) 
{
    toggleDisplay(elem);    
    
	var obj = document.getElementById(elem);    
    var imgVal = document.getElementById (elem + "_IMG");
    var lnkVal = document.getElementById (elem + "_LNK");
            
    imgVal.src = (obj.style.display == "block") ? decodeStringFromHex(iconExpanded) : decodeStringFromHex (icon);
    
    if (changeTooltip == "true")
    {
        imgVal.alt   = (obj.style.display == "block") ? "Collapse" : "Expand";
        lnkVal.title = (obj.style.display == "block") ? "Collapse" : "Expand";
        
    }
    
}


function toggleMenu(elem, icon, iconExpanded, changeTooltip) 
{
    if(!document.getElementById) { alert("Feature not supported with this browser"); return; }
    
    toggleMenuDisplay(elem, icon, iconExpanded, changeTooltip);

    if(!document.xform) return;    // SimpleWPage derived classes
    
    // Change the global menu state   
    var state = document.xform.local_bz_menu_state.value;   
    var p = state.indexOf(elem + ",");
    
    if(p == -1) state = state + elem + ",";
        else state = state.substr(0, p) + state.substr(p + elem.length + 1);
            
    document.xform.local_bz_menu_state.value = state;
    
} // func

function fireMenuEvent(encUrl, frame, isDefaultWPage, loadingDivID, loadingMsg)
{
    var url = decodeStringFromHex(encUrl);
      
    var win = window;          
    if(frame) win = window.open('', frame);
    
    var tmp = (url.indexOf('?') == -1) ? "?" : "&";
    var additionalState = isDefaultWPage ? tmp + "bz_menu_state=" + encodeStringToHex(document.xform.local_bz_menu_state.value) 
                                         : "";


        // Handling loading message
        //--------------------------------------------
        if(loadingMsg != null)
        {
            if(frame != null && win != window)
                   bzWriteNewPage(win,loadingMsg);
            else if(loadingDivID != null && !isNS4()) 
                   bzWriteMessage(document.getElementById(loadingDivID), loadingMsg);
        } // if

        win.location.href = url + additionalState;

} // func


// ---------------------------------------------------------
// Get/Set absolute position cross browser functions. These
// functions return (or uses) a Point object
// ---------------------------------------------------------
function Point(left, top)
{
    this.left = left;
    this.top  = top;
}

function getAbsolutePosition(divName, debug)
{
	if(isIE() || isNS6())	
 	{
  		var pop = document.getElementById(divName);
  		var ol  = pop.offsetLeft;
  		var ot  = pop.offsetTop;
        while ((pop=pop.offsetParent) != null) 
  		{  
   			ol += pop.offsetLeft; 
   			ot += pop.offsetTop;
  		} // while
  		
  		return new Point(ol, ot);
	} // if

 	if(isNS4())
 	{
  		var pop = document.layers[divName];
  		return new Point(pop.pageX, pop.pageY);
 	}//if
} // func

function setAbsolutePosition(divName, pointPos)
{
	if(isNS4())
	{
		var pop   = document.layers[divName];
		pop.pageX = pointPos.left;
		pop.pageY = pointPos.top;
	}
	else
	{
		var pop = document.getElementById(divName);
		pop.style.left = pointPos.left + "px";
		pop.style.top  = pointPos.top + "px";
	} //if
} // func


function openUserMessagesWindow()
{
    var x = "menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=10,left=10,width=650,height=400";
    var w = window.open("app?path=/pages/bz/userSessionsPage.displayUserMessages", "UserMessagesWindow", x);
    w.focus();
}

// Highligh the checkbox or radiobutton
function DVCheck(check)
{
    if (isNS4()) return;    
     
    var rowId = check.getAttribute('ROWID');
    DVSelRow (document.getElementById(rowId), check.checked);
} // func

function DVSelRow(obj, checkVal)
{
    if (isNS4()) return;    
    
    var selectedCss = 'dataview_row_selected';
    var normalCss   = obj.getAttribute('LX_DEFCLASS');    
            
    if (checkVal) 
    {         
        obj.className = selectedCss; 
        obj.setAttribute('LX_OLDCLASS', selectedCss) ;        
    } 
    else 
    { 
        obj.className = normalCss; 
        obj.setAttribute('LX_OLDCLASS', normalCss);
    } // if

} // func


// Handle select row style in DataView
function DVHandleSelect (check, manageHighlight, dvId, first, last, rowId, rowNumber, onClickFunction)
{  
	// manage row highlight 
    if (! isNS4() && manageHighlight)                   
        DVCheck (check);
    
    // Handle select all    
    var checkAll = eval ('document.xform.'+ dvId + '_rSel_All');
           
    if (checkAll != null)
    {      
        if (! check.checked) 
        {
            checkAll.checked = false;
        }
        else
        {
            var selAll = true;
            
            for(var i = first; i <= last; i++)
            {
                var checkTemp = eval ('document.xform.'+ dvId + '_rSel' + i);
                
                if (checkTemp != null)
                    if (! checkTemp.checked)
                    {
                        selAll = false;
                        break;
                    }                                        
            } // for
            
            if (selAll) checkAll.checked = true;
            
        } // if
    
    } // if
    
    // call user function
    if(onClickFunction)
    	eval(onClickFunction + "(" + rowNumber + "," + check.checked + ",'" + check.name + "','" + dvId + "'," + first + "," + last + ",'" + rowId + "')");
    
        
} // func

// Handle select row style in DataView
function DVHandleSelectAll (checkAll, dvId, first, last, highlight, onClickFunction)
{
    //if (!isNS4()) return;    
        
    for(var i = first; i <= last; i++)
    {
        var checkTemp = eval ('document.xform.'+ dvId + '_rSel' + i);
        
        if (checkTemp != null)
        {
            checkTemp.checked = checkAll.checked;
            if (highlight && (!isNS4())) DVCheck (checkTemp);            
        } // if
    } // for
        
    if(onClickFunction)
    	eval(onClickFunction + "(0," + checkAll.checked + ",'" + checkAll.name + "','" + dvId + "'," + first + "," + last + ",null)");
} // func


// Handle select row style in DataView
function DVHandleSingleSelect (check, manageHighlight, dvId, first, last, rowNumber, onClickFunction)
{   
    if (!isNS4() && manageHighlight)
    {    
	    var hidInput = eval ('document.xform.'+ dvId + '_rSingleSel');
            
	    if (hidInput.value != '')
	    {
    	    var obj = document.getElementById (hidInput.value);
	        DVSelRow (obj, false);
    	} // false
       
	    DVCheck (check);
    
	    hidInput.value = check.getAttribute ('ROWID');
	} // if
    
    if(onClickFunction)
    	eval(onClickFunction + "(" + rowNumber + "," + check.checked + ",'" + check.name + "','" + dvId + "'," + first + "," + last + ",null)");    
                   
} // func


// --------------------------------------------------------------------
// This function returns 'true' if the pressed key is enter
// --------------------------------------------------------------------
function bz_isEnterKey(event)
{ 
    var isEnter = false;
    
    if(isIE())
    {
        if (event.keyCode == 13)
            isEnter = true;    
    }
	else if(isNS6() || isNS4())
	{
        if (event.which == 13)
            isEnter = true;    
	}
	
	return isEnter;
} // func


// --------------------------------------------------------------------
// Handle the enter key using the DataView filter. 
// If the pressed button is the enter
// the function name passed as parameter is executed
// --------------------------------------------------------------------
function dv_filterHandleEnterKey(event, funcName)
{ 
    if (bz_isEnterKey(event)) funcName();
} // func


// --------------------------------------------------------------------
// This function returns the name of an HTML edit control used
// inside DataView cells to edit data
// The dataViewRef is the string obtained using the 
// st.bz.dataview.DataView.getName() method.
// --------------------------------------------------------------------
function getDataViewEditControlName(dataViewRef, rowIndex, columnName)
{
    return dataViewRef + '_' + rowIndex + '_' + columnName + '_edit';
}


// 'STRIPPED' functions to reduce generated HTML code
function bz_lce(attrsArray, paramsArray) { return new BZClientEvent(attrsArray, paramsArray); }

// Creates and returns an array-map, getting keys and values from from variable function arguments
// -----------------------------------------------------------------------------------------------
function bz_ca()
{
    var n = bz_ca.arguments.length;
    if(n == 0) return null;
    if((n % 2) > 0) return null;

    var result = new Array();
    for(var i = 0; i < n; i += 2) result[bz_ca.arguments[i]] = bz_ca.arguments[i+1];
    return result;
} // func

function BZClientEvent(attrsArray, paramsArray)
{   
    // Copy all attributes in this object properties (if they are defined)
    if(attrsArray && attrsArray != null)
    {
        // Copy a map-array in a 2 indexed arrays
        var i = 0, keys = new Array(), values = new Array();
        for(k in attrsArray) { keys[i]=k; values[i]=attrsArray[k]; i++; } 
        
        // Create the object properties (using the 2 indexed arrays)
	    for(var i = 0; i < keys.length; i++) this[keys[i]] = values[i];
	} // if

    this.params = null;
    if (paramsArray) this.params = paramsArray;
} // func



// --------------------------------------------------------------------------------
//         JS FUNCTIONS FOR SCROLLABLE DATAVIEW
// --------------------------------------------------------------------------------

// Adjust dinamically the cell width for scrollable DataViews
function bz_adjustDataViewColumnWidth(dvName, startRow, divOffset)
{
	var headerName         =  dvName + '_bz_headerBodyRow';
	var headerIcon         =  dvName + '_bz_iconsHeaderBodyRow';	
	var rowName            =  dvName + '_ID_' + startRow;
	var footerName         =  dvName + '_bz_footerBodyRow';
	
	var dvHeader     = document.getElementById(headerName);
	var dvHeaderIcon = document.getElementById(headerIcon);
	var dvRow        = document.getElementById(rowName);
	var dvFooter     = document.getElementById(footerName);
	
	var currentRow = null;
	
	if      (dvHeader)     currentRow = dvHeader;
	else if (dvHeaderIcon) currentRow = dvHeaderIcon;
	else if (dvRow)        currentRow = dvRow;
	else if (dvFooter)     currentRow = dvFooter;
	else return;

	var offset = divOffset;
	if (offset == null) offset = 100;
	
	var scrollDivOffset = document.getElementById(dvName + "_div_scroll_offset");	
	var scrollDiv       = document.getElementById(dvName + "_div_scroll");	
	
	// Enlarge the TABLE here otherwise the new widths for cells
	// doesn't work fine
	scrollDivOffset.style.width = "3000px";	
	scrollDiv.style.width       = "3000px";	

	var childCollection = currentRow.childNodes;	

	var myWidth        = 0;	
	var j              = 0;
	var maxLoopCount   = 1;
	var differentWidth = true;
	
	if (isIE()) maxLoopCount = 5;
	while (differentWidth && (j < maxLoopCount))
	{
		differentWidth = false;
		j++;
	    for (var i=0; i < childCollection.length; i++) 
	    {
			if(childCollection[i].nodeName.toLowerCase() == 'td')
			{
				myWidth = bz_getWidth(childCollection[i]);
						
				if(dvHeader != null && bz_getWidth(dvHeader.childNodes[i])> myWidth) myWidth = bz_getWidth(dvHeader.childNodes[i]);				
				if(dvRow != null    && bz_getWidth(dvRow.childNodes[i])> myWidth)    myWidth = bz_getWidth(dvRow.childNodes[i]);
				if(dvFooter != null && bz_getWidth(dvFooter.childNodes[i])>myWidth)  myWidth = bz_getWidth(dvFooter.childNodes[i]);
				if(dvHeaderIcon != null && bz_getWidth(dvHeaderIcon.childNodes[i])> myWidth) myWidth = bz_getWidth(dvHeaderIcon.childNodes[i]);
	
				if (dvHeader != null)     dvHeader.childNodes[i].style.width = myWidth + "px";
				if (dvHeaderIcon != null) dvHeaderIcon.childNodes[i].style.width = myWidth + "px";
				if (dvRow != null)        dvRow.childNodes[i].style.width    = myWidth + "px";
				if (dvFooter != null)     dvFooter.childNodes[i].style.width = myWidth + "px";
	
				myWidth = bz_getWidth(childCollection[i]);
				if(dvHeader != null && bz_getWidth(dvHeader.childNodes[i]) != myWidth) differentWidth = true;
				if(dvHeaderIcon != null && bz_getWidth(dvHeaderIcon.childNodes[i]) != myWidth) differentWidth = true;
				if(dvRow != null    && bz_getWidth(dvRow.childNodes[i])    != myWidth) differentWidth = true;
				if(dvFooter != null && bz_getWidth(dvFooter.childNodes[i]) != myWidth) differentWidth = true;
								
			} // if
	    } // for
    } // while
	
	scrollDiv.style.width = (currentRow.offsetWidth) + 'px';
	
	// find the main table to calculate the border width
	var myTable = currentRow.parentNode;
	while (myTable != null && myTable.nodeName.toLowerCase() != 'table')
		myTable = myTable.parentNode;
	
	var tableBorder = 1;	
	if (myTable != null) tableBorder = parseInt(myTable.style.borderWidth);
	
	var sbw = 15 + tableBorder * 2;
	
	// Adjust DIV height and column alignment in IE	
	if (dvRow != null)
	{
		myTable = dvRow;
		// find the table object related to the DataView rows
		while (myTable != null && myTable.nodeName.toLowerCase() != 'table')
			myTable = myTable.parentNode;
	
		// calculate table height
		if (myTable != null && myTable.offsetHeight<=scrollDiv.offsetHeight)
		{
			sbw = tableBorder * 2;
			scrollDiv.style.height = myTable.offsetHeight + 'px';
		}
		
		// Adjust column alignment in IE6
		if (myTable != null && isIE())
		{
			for (var i=1; i<myTable.rows.length; i++)
				for (var j=0; j<myTable.rows(i).childNodes.length; j++)
					myTable.rows(i).childNodes[j].style.width = myTable.rows(0).childNodes[j].style.width;
		} // if		
	}
	else
	{
		// if there aren't rows set the div height to 0
		scrollDiv.style.height = '0px';
	}
	
	if (isIE()) sbw = scrollDiv.offsetWidth - scrollDiv.clientWidth + tableBorder * 2;
	scrollDiv.style.width = (scrollDiv.offsetWidth + sbw ) + 'px';
	
	scrollDivOffset.style.width = (currentRow.offsetWidth + sbw + divOffset) + 'px';	

} // func

// Gets the width of the object passed as parameter.
// If the obj is NULL or the browser is NS4 this method
// return 0
function bz_getWidth(obj)
{
	if (isNS4() || obj == null) return 0;
	else if (isIE()) return obj.clientWidth;
	else return obj.offsetWidth;
}

//******************************************************
//              handle Benchmark function
//******************************************************
function bz_isBenchmark()
{
    if("undefined" == parent.benchmarkPage) return false;
    if("undefined" == parent.progress)      return false;
    if("undefined" == parent.transaction)   return false;
    return true;
} // func

function bz_getBenchmarkPage()
{
	return parent.benchmarkPage;
} // func

function bz_transactionCompleted()
{
    if(bz_isBenchmark())
    {
        var endTime = new Date().getTime();
        var bp = bz_getBenchmarkPage();
        if (bp == null) return;
        bp.bz_internalTransactionCompleted(endTime);
    } // if
} // func


//}}}







