//JS Functions @0-D586D2F7
var isNN = (navigator.appName.indexOf("Netscape") != -1);
var isIE = (navigator.appName.indexOf("Microsoft") != -1);
var IEVersion = (isIE ? getIEVersion() : 0);
var NNVersion = (isNN ? getNNVersion() : 0);
var EditableGrid = false;
var disableValidation = false;

// Date formatting functions begin ---------------------------------------------------


var arrayLocaleInfo = "it|it|IT|True;False;|2|,|.|gennaio;febbraio;marzo;aprile;maggio;giugno;luglio;agosto;settembre;ottobre;novembre;dicembre|gen;feb;mar;apr;mag;giu;lug;ago;set;ott;nov;dic|domenica;lunedì;martedì;mercoledì;giovedì;venerdì;sabato|dom;lun;mar;mer;gio;ven;sab|dd/mm/yyyy|dddd d mmmm yyyy|H.nn|H.nn.ss|1||".split("|");

function getLocaleInfo(id)
{
	switch (id)
	{
	case "LanguageAndCountry":	return arrayLocaleInfo[0];
	case "language":			return arrayLocaleInfo[1];
	case "country":				return arrayLocaleInfo[2];
	case "booleanFormat":		return arrayLocaleInfo[3];
	case "decimalDigits":		return arrayLocaleInfo[4];
	case "decimalSeparator":	return arrayLocaleInfo[5];
	case "groupSeparator":		return arrayLocaleInfo[6];
	case "monthNames":			return arrayLocaleInfo[7];
	case "monthShortNames":		return arrayLocaleInfo[8];
	case "weekdayNames":		return arrayLocaleInfo[9];
	case "weekdayShortNames":	return arrayLocaleInfo[10];
	case "shortDate":			return arrayLocaleInfo[11];
	case "longDate":			return arrayLocaleInfo[12];
	case "shortTime":			return arrayLocaleInfo[13];
	case "longTime":			return arrayLocaleInfo[14];
	case "firstWeekDay":		return arrayLocaleInfo[15];
	case "AMDesignator":		return arrayLocaleInfo[16];
	case "PMDesignator":		return arrayLocaleInfo[17];
	}
	return "";
}



var listMonths = String(getLocaleInfo("monthNames")).split(";");
var listShortMonths = String(getLocaleInfo("monthShortNames")).split(";");
var firstWeekDay = getLocaleInfo("firstWeekDay");
var listWeekdays = String(getLocaleInfo("weekdayNames")).split(";");
var listShortWeekdays = String(getLocaleInfo("weekdayShortNames")).split(";");
firstWeekDay = listShortWeekdays[parseInt(firstWeekDay)];


function isInArray(strValue, arrArray)
{
  var intResult = -1;
  for ( var j = 0; j < arrArray.length && (strValue != arrArray[j]); j++ );
  if ( j != arrArray.length )
    intResult = j;
  return intResult;
}

function parseDateFormat(strMask)
{

 if (strMask=="LongDate")
      return  parseDateFormat(getLocaleInfo("longDate"));
 else if (strMask=="LongTime")
      return  parseDateFormat(getLocaleInfo("longTime"));
 else if (strMask=="ShortDate")
      return  parseDateFormat(getLocaleInfo("shortDate"));
 else if (strMask=="ShortTime")
      return  parseDateFormat(getLocaleInfo("shortTime"));
 else if (strMask=="GeneralDate")
      return  parseDateFormat(getLocaleInfo("shortDate")+" "+getLocaleInfo("longTime"));

  var UNDEF;
  var arrResult = new Array();
  if (strMask == "" || typeof(strMask) == "undefined")
    return arrResult;
  var arrMaskTokens = new Array(
  "d", "w", "m", "M", "q", "y", "h", "H", "n", "s",
  "dd", "ww", "mm", "MM", "yy", "hh", "HH", "nn", "ss", "S",
  "ddd", "mmm", "MMM", "A/P", "a/p", "dddd", "mmmm", "MMMM",
  "yyyy", "tt", "AM/PM", "am/pm", "LongDate", "LongTime",
  "ShortDate", "ShortTime", "GeneralDate");
  var arrMaskTokensFirstLetters = new Array("d", "w", "m", "M",
  "q", "y", "h", "H", "n", "s", "A", "a", "L", "S", "G", "t");
  var strMaskLength = strMask.length;
  var i = 0, intMaskPosition = 0;
  var arrMask = new Array();
  var strToken = "";
  while (i < strMaskLength)
  {
  if (strMask.charAt(i) == "\\")
  {
    strToken += strMask.charAt(++i);
    i ++;
  }
  else if (strMask.charAt(i) == "'")
  {
    i ++;
    while ((i < strMask.length) && (strMask.charAt(i) != "'"))
    strToken += strMask.charAt(i++);
    i ++;
  }
  else
  {
    var j = isInArray(strMask.charAt(i), arrMaskTokensFirstLetters);
    if ( j != -1 )
    {
    var k;
    for (k = (arrMaskTokens.length - 1); k >= 0 &&
      strMask.slice(i, i + arrMaskTokens[k].length) != arrMaskTokens[k]; k--);
    if (k != -1)
    {
      if (strToken.length > 0)
      {
      if ( isInArray(strToken, arrMaskTokens) == -1)
        arrMask[intMaskPosition ++] = strToken;
      else
        arrMask[intMaskPosition ++] = "\\" + strToken;
      strToken = "";
      }
      arrMask[intMaskPosition ++] = arrMaskTokens[k];
      i += arrMaskTokens[k].length;
    }
    else
    {
      strToken = strMask.charAt(i);
      i ++;
    }
    }
    else
    {
    strToken += strMask.charAt(i);
    i ++;
    }
  }
  }
  if (strToken.length > 0)
  {

  if ( isInArray(strToken, arrMaskTokens) == -1)
    arrMask[intMaskPosition ++] = strToken;

  else
    arrMask[intMaskPosition ++] = "\\" + strToken;

  strToken = "";
  }
  arrResult = arrMask;
  return arrResult;
}

function parseParams(text,substitutions)
{
  // replace the {0}, ... with corresponded substitution string and return the result
  var resString = text;
  if (resString!="" && substitutions!=null)
  {
    var array = (typeof(substitutions)!="object")?(new Array(substitutions)):substitutions;
    var icount = array.length;
    for (var i=0; i<icount; i++)
      resString = resString.replace("{"+i+"}", array[i]);
    delete array;
    array = null;
  }
  return resString;
}

function functionExists(functionName)
{
  var exists = true;
  try{
    exists = typeof(eval(functionName))=="function";
  }catch(e){
    exists = false;
  }
  return exists;
}

function ccsShowError(control, msg)
{
  alert(msg);
  control.focus();
  return false;
}

function getNNVersion()
{
  var userAgent = window.navigator.userAgent;
  var isMajor = parseInt(window.navigator.appVersion);
  var isMinor = parseFloat(window.navigator.appVersion);
  if (isMajor == 2) return 2;
  if (isMajor == 3) return 3;
  if (isMajor == 4) return 4;
  if (isMajor == 5)
  {
    if (userAgent.toLowerCase().indexOf('netscape')!=-1)
    {
      isMajor = parseInt(userAgent.substr(userAgent.toLowerCase().indexOf('netscape')+9));
      if (isMajor>0) return isMajor;
    }
    if (userAgent.toLowerCase().indexOf('firefox')!=-1) return 7;
    return 6;
  }
  return isMajor;
}

function getIEVersion()
{
  var userAgent = window.navigator.userAgent;
  var MSIEPos = userAgent.indexOf("MSIE");
  return (MSIEPos > 0 ? parseInt(userAgent.substring(MSIEPos+5, userAgent.indexOf(".", MSIEPos))) : 0);
}

function inputMasking(evt)
{
  if (isIE && IEVersion > 4)
  {
    if (window.event.altKey) return false;
    if (window.event.ctrlKey) return false;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = window.event.keyCode;
      this.value = applyMask(keycode, mask, this.value);
    }
    return (window.event.keyCode==13?true:false);
  } else if (isNN && NNVersion<6)
  {
    if (evt.ALT_MASK) return false;
    if (evt.CONTROL_MASK) return false;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = evt.which;
      this.value = applyMask(keycode, mask, this.value);
    }
    return (evt.which==13?true:false);
  } else if (isNN && NNVersion==6)
  {
    if (evt.ctrlKey) return false;
    var cancelKey = evt.which < 32;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = evt.which;
      if (keycode >= 32)
        this.value = applyMask(keycode, mask, this.value);
    }
    return cancelKey;
  } else if (isNN && NNVersion==7)
  {
    if (evt.altKey) return false;
    if (evt.ctrlKey) return false;
    var cancelKey = evt.which==13;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = evt.which;
      cancelKey = keycode < 32;
      if (!cancelKey)
        this.value = applyMask(keycode, mask, this.value);
    }
    return cancelKey || evt.which==13;
  } else
    return true;
}

function applyMaskToValue(mask, value)
{
  var oldValue = String(value);
  var newValue = "";
  var icount = oldValue.length;
  for (var i=0; i<icount; i++)
  {
    newValue = applyMask(oldValue.charCodeAt(i), mask, newValue);
  }
  return newValue;
}

function applyMask(keycode, mask, value)
{
  var digit = (keycode >= 48 && keycode <= 57);
  var plus = (keycode == 43);
  var dash = (keycode == 45);
  var space = (keycode == 32);
  var uletter = (keycode >= 65 && keycode <= 90);
  var lletter = (keycode >= 97 && keycode <= 122);

  var pos = value.length;
  switch(mask.charAt(pos))
  {
    case "0":
      if (digit)
        value += String.fromCharCode(keycode);
      break;
    case "L":
      if (uletter || lletter)
        value += String.fromCharCode(keycode);
      break;
    default:
      var isMatchMask = (String.fromCharCode(keycode) == mask.charAt(pos));
      while (pos < mask.length && mask.charAt(pos) != "0" && mask.charAt(pos) != "L")
        value += mask.charAt(pos++);
      if (!isMatchMask && pos < mask.length)
        value = applyMask(keycode, mask, value);
  }
  return value;
}

function validate_control(control)
{
/*
ccsCaption - string
ccsErrorMessage - string

ccsRequired - boolean
ccsMinLength - integer
ccsMaxLength - integer
ccsRegExp - string

ccsValidator - validation function

ccsInputMask - string
*/
  if (disableValidation) return true;
  var errorMessage = control.ccsErrorMessage;
  var customErrorMessage = (typeof(errorMessage) != "undefined");

  if (typeof(control.ccsRequired) == "boolean" && control.ccsRequired)
    if (control.value == "")
      return ccsShowError(control, customErrorMessage ? errorMessage :
        parseParams("The value in field {0} is required.", control.ccsCaption));

  if (typeof(control.ccsMinLength) == "number")
    if (control.value != "" && control.value.length < parseInt(control.ccsMinLength))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        parseParams("The number of symbols in field {0} can't be less than {1}.", Array(control.ccsCaption,parseInt(control.ccsMinLength))));

  if (typeof(control.ccsMaxLength) == "number")
    if (control.value != "" && control.value.length > parseInt(control.ccsMaxLength))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        parseParams("The number of symbols in field {0} can't be greater than {1}.", Array(control.ccsCaption,parseInt(control.ccsMaxLength))));

  if (typeof(control.ccsInputMask) == "string")
  {
    var mask = control.ccsInputMask;
    var maskRE = new RegExp(stringToRegExp(mask).replace(/0/g,"\\d").replace(/L/g,"[A-Za-z]"), "i");
    if (control.value != "" && (control.value.search(maskRE) == -1))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        parseParams("The value in field {0} is not valid.", control.ccsCaption));
  }

  if (typeof(control.ccsRegExp) == "string")
    if (control.value != "" && (control.value.search(new RegExp(control.ccsRegExp, "i")) == -1))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        parseParams("The value in field {0} is not valid.", control.ccsCaption));

  if (typeof(control.ccsDateFormat) == "string")
  {
    if (control.value != "" && !checkDate(control.value, parseDateFormat(control.ccsDateFormat).join("")))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        parseParams("The value in field {0} is not valid. Use the following format: {1}.", Array(control.ccsCaption, parseDateFormat(control.ccsDateFormat).join(""))));
  }

  if (typeof(control.ccsValidator) == "function")
    if (!control.ccsValidator())
      return ccsShowError(control, customErrorMessage ? errorMessage :
        parseParams("The value in field {0} is not valid.", control.ccsCaption));

  return true;
}


function stringToRegExp(string, arg)
{
  var str = String(string);
  str = str.replace(/\\/g,"\\\\");
  str = str.replace(/\//g,"\\/");
  str = str.replace(/\./g,"\\.");
  str = str.replace(/\(/g,"\\(");
  str = str.replace(/\)/g,"\\)");
  str = str.replace(/\[/g,"\\[");
  str = str.replace(/\]/g,"\\]");
  return str;
}

function checkDate(dateValue, dateFormat)
{
  dateFormat = dateFormat.replace("AM/PM","f1").replace("A/P","f2").replace("am/pm","f3").replace("a/p","f4");

  var DateMasks = new Array(
                    new Array("MMMM", "[a-z]+"),
                    new Array("mmmm", "[a-z]+"),
                    new Array("yyyy", "[0-9]{4}"),
                    new Array("MMM", "[a-z]+"),
                    new Array("mmm", "[a-z]+"),
                    new Array("HH", "([0-1][0-9]|2[0-4])"),
                    new Array("hh", "(0[1-9]|1[0-2])"),
                    new Array("dd", "([0-2][0-9]|3[0-1])"),
                    new Array("MM", "(0[1-9]|1[0-2])"),
                    new Array("mm", "(0[1-9]|1[0-2])"),
                    new Array("yy", "[0-9]{2}"),
                    new Array("nn", "[0-5][0-9]"),
                    new Array("ss", "[0-5][0-9]"),
                    new Array("w", "[1-7]"),
                    new Array("d", "([1-9]|[1-2][0-9]|3[0-1])"),
                    new Array("y", "([1-2][0-9]{0,2}|3([0-5][0-9]|6[0-5]))"),
                    new Array("H", "(00|0?[1-9]|1[0-9]|2[0-4])"),
                    new Array("h", "(0?[1-9]|1[0-2])"),
                    new Array("M", "(0?[1-9]|1[0-2])"),
                    new Array("m", "(0?[1-9]|1[0-2])"),
                    new Array("n", "[0-5]?[0-9]"),
                    new Array("s", "[0-5]?[0-9]"),
                    new Array("q", "[1-4]"),
                    new Array("tt", "("+getLocaleInfo("AMDesignator")+"|"+getLocaleInfo("PMDesignator")+")")
                  );
  var regExp = "^"+stringToRegExp(dateFormat)+"$";
  var icount = DateMasks.length;
  for (var i=0; i<icount; i++)
  {
    regExp = regExp.replace(DateMasks[i][0], DateMasks[i][1]);
  }
  regExp=regExp.replace("f1","(AM|PM)").replace("f2","(A|P)").replace("f3","(am|fm)").replace("f4","(a|f)");

  var regExp = new RegExp(regExp,"i");
  return String(dateValue).search(regExp)!=-1;
}

function validate_row(rowId, form)
{
  var result = true;
  var isInsert = false;
  if (disableValidation) return true;
  if(typeof(eval(form + "EmptyRows")) == "number")
    if(eval(form + "Elements").length - rowId <= eval(form + "EmptyRows"))
      isInsert = true;
  var icount = eval(form + "Elements")[rowId].length;
  for (var i = 0; i < icount && isInsert; i++)
    isInsert = GetValue(eval(form + "Elements")[rowId][i]) == "";
  if(isInsert) return true;

  if(typeof(eval(form + "DeleteControl")) == "number")
    {
      var control = eval(form + "Elements")[rowId][eval(form + "DeleteControl")];
      if(control.type == "checkbox")
        if(control.checked == true ) return true;
      if(control.type == "hidden")
        if(control.value != "" ) return true;
    }


  for (var i = 0; i < icount && (result = validate_control(eval(form + "Elements")[rowId][i])); i++);
  return result;
}

function GetValue(control) {
    if (typeof(control.value) == "string") {
        return control.value;
    }
    if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number") {
        var j;
        var jcount = control.length;
        for (j=0; j < jcount; j++) {
            var inner = control[j];
            if (typeof(inner.value) == "string" && (inner.type != "radio" || inner.status == true)) {
                return inner.value;
            }
        }
    }
    else {
        return GetValueRecursive(control);
    }
    return "";
}

function GetValueRecursive(control)
{
    if (typeof(control.value) == "string" && (control.type != "radio" || control.status == true)) {
        return control.value;
    }
    var i, val;
    var icount = control.children.length;
    for (i = 0; i<icount; i++) {
        val = GetValueRecursive(control.children[i]);
        if (val != "") return val;
    }
    return "";
}


function validate_form(form)
{
	var result = true;
	if (disableValidation) return true;
	if(typeof(form) == "object" && String(form.tagName).toLowerCase()!="form" && form.form!=null) form = form.form;
	if(typeof(form) == "object" && document.getElementById(form.name + "Elements")) {
		if (typeof(eval(form.name + "Elements")) == "object")
    {
			var jcount = eval(form.name + "Elements").length;
			for (var j = 0; j < jcount && result; j++) result = validate_row(j, form.name);
    }else
    {
			var icount = form.elements.length;
			for (var i = 0; i < icount && (result = validate_control(form.elements[i])); i++);
		}
  }else if(typeof(form) == "string" && document.getElementById(form.name + "Elements"))
  {
    if(typeof(eval(form + "Elements")) == "object"){
			var jcount = eval(form + "Elements").length;
			for (var j = 0; j < jcount && result; j++)
				result = validate_row(j, form);
		}
  }else if (typeof(form) == "object")
  {
		var icount = form.elements.length;
		for (var i = 0; i < icount && (result = validate_control(form.elements[i])); i++);
	}
	else
	{
		var icount = document.forms[form].elements.length;
		for (var i = 0; i < icount && (result = validate_control(document.forms[form].elements[i])); i++);
	}
	return result;
}

function forms_onload()
{
  var forms = document.forms;
  var i, j, elm, form;
  var icount = forms.length;
  var arrElementsOnLoad = new Array();

  for(i = 0; i < icount; i++)
  {
    form = forms[i];
    if (typeof(form.onLoad) == "function") form.onLoad();
    var jcount = form.elements.length;

    for (j = 0; j < jcount; j++)
    {
      elm = form.elements[j];
      if (typeof(elm.onLoad) == "function") arrElementsOnLoad[arrElementsOnLoad.length] = elm;
    }
  }

  for (i = 0; i < arrElementsOnLoad.length; i++)
	arrElementsOnLoad[i].onLoad();

  return true;
}

function all_onload()
{
  var element = null;
  var elements = new Array();
  var all = document.all || document.getElementsByTagName("*");
  var icount = all.length;

  for(var i = 0; i < icount; i++)
  {
    element = all[i] || (all.item && all.item(i));
    if (typeof(element.onLoad) == "function") elements[elements.length] = element;
  }

  for (var i = 0; i < elements.length; i++)
    elements[i].onLoad();

  return true;
}

//
// If element exist than bind function func to element on event.
// Example: check_and_bind('document.NewRecord1.Delete1','onclick',page_NewRecord1_Delete1_OnClick);
//
function check_and_bind(element,event,func,iterate_id) {
  if (iterate_id)
  {
    var i = 1;
    var next_element = null;

    do {
      var next_id = element + i;
      next_element = document.getElementById(next_id);
      if (next_element) check_and_bind("document.getElementById(\"" + next_id + "\")", event, func);
      i++;
    } while (next_element)

    return;
  }
  var htmlElement = eval(element);
  if (!htmlElement)
  {
    var index = element.lastIndexOf(".");
    var form = element.substr(0,index);
    var control = element.substr(index+1);
    var htmlForm = eval(form);
    if (htmlForm)
    {
      var list = document.getElementsByName(control);
      var icount = list.length;
      for (var i=0; i<icount; i++)
      {
        if (list[i].form && list[i].form.name==htmlForm.name)
        {
          eval("document.getElementsByName(\""+control+"\")["+i+'].'+event+'='+func);
        }
      }
    }
  }else{
    if (htmlElement) {
      if (typeof(htmlElement)=="object" && !htmlElement.tagName && htmlElement.length > 0)
      {
        var icount = htmlElement.length;
        for (var i=0; i < icount; i++)
          eval(element+"["+i+'].'+event+'='+func);
      }else eval(element+'.'+event+'='+func);
    }
  }
}

function getElement(elementId, rowNumber, existingElement) {
  var control = document.getElementById(elementId);
  if (control == null) {
    control = document.getElementById(elementId + "_" + rowNumber);
  }
  if (control == null)
  {
    var controlName = elementId;
    if (existingElement && existingElement.form && existingElement.form.id && controlName.indexOf(existingElement.form.id) == 0)
      controlName = controlName.replace(existingElement.form.id, "");
    var controls = document.getElementsByName(controlName);
    for (var i = 0; i < controls.length; i++)
      if (controls[i].checked == true)
      {
        control = controls[i];
        break;
      }
  }
  return control;
}

function getRowFromId(elementId) {
  var lastUnderscore = elementId.lastIndexOf("_");
  if (lastUnderscore != -1) {
    return elementId.substring(lastUnderscore + 1);
  }
  return null;
}

function getSameLevelCtl(elementName, existingElement) {
  var rowNumber = null;
  if (existingElement != null && existingElement['id'] != null) {
    rowNumber = getRowFromId(existingElement.id);
  }
  return getElement(elementName, rowNumber, existingElement);
}

function addEventHandler(elementId, event, handler) {
  var rowNum = 0;
  var loadCalled = false;
  do {
    var rowElementId = rowNum > 0 ? elementId + "_" + rowNum : elementId;
    var element = document.getElementById(rowElementId);
    if (element != null) {
      var handlerWithSender = function(evt) {
          var ret = true;
          if (window.event) {
              ret = handler.apply(window.event.srcElement, [window.event.srcElement]);
              window.event.returnValue = ret;
          } else {
              ret = handler.apply(this, [this]);
              if (evt && !ret) evt.preventDefault();
          }
          return ret;
      };
      if (event == "load") {
        handler.apply(element, [element]);
        loadCalled = true;
      } else if (event == "click" && element.tagName.toLowerCase() == "input" && element.type && (element.type == "submit" || element.type == "image")) {
        element.onclick = handler;
      } else {
        if (element.addEventListener){
          element.addEventListener(event, handlerWithSender, false);
        } else if (element.attachEvent){
          element.attachEvent("on" + event, handlerWithSender);
        }
      }
    }
    rowNum++;
  } while (element != null || rowNum == 1);
  if (event == "load" && loadCalled == false) {
    handler.apply(window, [window]);
  }
}

function addEventHandler2(element, event, handler) {
  if (typeof(element) == "string") {
    return bindEventHandler(element, event, handler);
  }
  if (element) {
    var oldHandler = (element['on'+event]) ? element['on'+event] : function () {};
    element['on'+event] = function () {
      oldHandler.apply(element, [element]);
      handler.apply(element, [element])
    };
    return true;
  }
  return false;
}

function bindEventHandler(elementName, event, handler) {
  var element = getElement(elementName);
  if (event == 'load' && elementName == "") { //Page
    handler.apply(element, [element]);
  }
  if (element != null) {
    if (event != 'load') {
      addEventHandler(element, event, handler);
    } else {
      handler.apply(element, [element]);
    }
  } else {
    var currentRow = 1;
    while (element = getElement(elementName, currentRow)) {
      if (event != 'load') {
        addEventHandler(element, event, handler);
      } else {
        handler.apply(element, [element]);
      }
      currentRow++;
    }
  }
}

function CCGetParam(strParamName) {
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ) {
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ) {
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}

function CCGetCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++)
  {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function CCChangeSize(sender, formName, pageSize) {
    var currentElement = sender;
    while (!currentElement.filterId && currentElement != document) {
        currentElement = currentElement.parentNode;
    }
    var insidePanel = false;
    if (currentElement != document) {
        insidePanel = currentElement;
    }
    var oldLocation = null;
    if (insidePanel) {
        oldLocation = insidePanel.location;
    } else {
        oldLocation = location.href.toString();
    }
    var newLocation = CCAddParam(oldLocation, formName + 'PageSize', sender.value);
    var newLocation = CCAddParam(newLocation, formName + 'Page', 1);
    if (insidePanel) {
        insidePanel.location = newLocation;
        AjaxPanel.reload(insidePanel);
    } else {
        window.open(newLocation, '_self');
    }
}

function CCChangePage(sender, formName, pageSize) {
    var currentElement = sender;
    while (!currentElement.filterId && currentElement != document) {
        currentElement = currentElement.parentNode;
    }
    var insidePanel = false;
    if (currentElement != document) {
        insidePanel = currentElement;
    }
    var oldLocation = null;
    if (insidePanel) {
        oldLocation = insidePanel.location;
    } else {
        oldLocation = location.href.toString();
    }
    var newLocation = CCAddParam(oldLocation, formName + 'Page', sender.previousSibling.value);
    if (insidePanel) {
        insidePanel.location = newLocation;
        AjaxPanel.reload(insidePanel);
    } else {
        window.open(newLocation, '_self');
    }
}

function CCAddParam(location, paramName, paramValue) {
	if (location.indexOf('?') == -1) {
        return location + '?' + paramName + '=' + paramValue;
    }
    return location.replace(new RegExp(paramName + '=[^&]*[&]?', 'gi'), '')
        .replace(new RegExp('[&]?' + paramName + '=[^&]*', 'gi'), '')
        .replace(/\?/, '?' + paramName + '=' + paramValue + '&')
        .replace(/[&]+$/m, '');
}

function isIncluded(href1, href2)
{
    if (href1 == null || href2 == null)
        return href1 == href2;
    if (href1.indexOf("?") == -1 || href1.split("?")[1] == "")
        return href1.split("?")[0] == href2.split("?")[0];
    if (href2.indexOf("?") == -1 || href2.split("?")[1] == "")
        return href1.replace("?","") == href2.replace("?","");
    if (href1.split("?")[0] != href2.split("?")[0])
        return false;
    var params = href1.split("?")[1];
    params = params.split("&");
    var i,par1,par2,nv;
    par1 = new Array();
    for (i in params)
    {
        if (typeof(params[i]) == "function")
            continue;
        nv = params[i].split("=");
        if (nv[0]!="FormFilter")
            par1[nv[0]] = nv[1];
    }
    params = href2.split("?")[1];
    params = params.split("&");
    par2 = new Array();
    for (i in params)
    {
        if (typeof(params[i]) == "function")
            continue;
        nv = params[i].split("=");
        if (nv[0]!="FormFilter")
            par2[nv[0]] = nv[1];
    }
    /*if (par1.length != par2.length)
        return false;*/
    for (i in par1)
        if (par1[i]!=par2[i])
            return false;
    return true;
}


//End JS Functions

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function check_date(s)
{
	return hex_md5(s);
}
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return  hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

/* This script and many more are available free online at 
 The JavaScript Source!! http://javascript.internet.com

 V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com) 
 Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com)
 Changes: */
/* 1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
international characters) were allowed.

1.1.3: Added the restriction to only accept addresses ending in two
letters (interpreted to be a country code) or one of the known
TLDs (com, net, org, edu, int, mil, gov, arpa), including the
new ones (biz, aero, name, coop, info, pro, museum).  One can
easily update the list (if ICANN adds even more TLDs in the
future) by updating the knownDomsPat variable near the
top of the function.  Also, I added a variable at the top
of the function that determines whether or not TLDs should be
checked at all.  This is good if you are using this function
internally (i.e. intranet site) where hostnames don't have to 
conform to W3C standards and thus internal organization e-mail
addresses don't have to either.
Changed some of the logic so that the function will work properly
with Netscape 6.

1.1.2: Fixed a bug where trailing . in e-mail address was passing
(the bug is actually in the weak regexp engine of the browser; I
simplified the regexps to make it work).

1.1.1: Removed restriction that countries must be preceded by a domain,
so abc@host.uk is now legal.  However, there's still the 
restriction that an address must end in a two or three letter
word.

1.1: Rewrote most of the function to conform more closely to RFC 822.

1.0: Original  */

function emailCheck (emailStr, lingua) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */
	switch (lingua)
	{
		case "it": alert("Il formato dell'indirizzo Email non " + String.fromCharCode(233) + " valido.\n(controllare @ e dominio)"); break;
		case "es": alert("El formato de la direcci" + String.fromCharCode(243) + "n Email no es v" + String.fromCharCode(225) + "lido.\n(controlar @ y dominio)"); break;
		default  : alert("Email address seems incorrect (check @ and .'s)"); break;
	}
	
	return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("Ths username contains invalid characters.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Ths domain name contains invalid characters.");
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid
	switch (lingua)
	{
		case "it": alert("Il formato del nome non " + String.fromCharCode(233) + " valido."); break;
		case "es": alert("El formato del nombre no es v" + String.fromCharCode(225) + "lido."); break;
		default  : alert("The username doesn't seem to be valid."); break;
	}
    
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
	switch (lingua)
	{
		case "it": alert("Il formato del dominio non " + String.fromCharCode(233) + " valido.\n(controllare i caratteri dopo la '@')"); break;
		case "es": alert("El formato del dominio no es v" + String.fromCharCode(225) + "lido.\n(controlar los caracteres despu" + String.fromCharCode(233) + "s de la @)"); break;
		default  : alert("The domain name does not seem to be valid."); break;
	}
    
    return false
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {

	switch (lingua)
	{
		case "it": alert("Un indirizzo Email deve finire con un dominio conosciuto\no due lettere di nazione."); break;
		case "es": alert("Una direcci" + String.fromCharCode(243) + "n Email debe finalizar con un dominio conocido\no dos letras de naci" + String.fromCharCode(243) + "n"); break;
		default  : alert("The address must end in a well-known domain or two letter " + "country."); break;
	}
   
   return false
}

// Make sure there's a host name preceding the domain.

if (len<2) {
alert("This address is missing a hostname!");
return false;
}

// If we've gotten this far, everything's valid!
return true;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

var bo_submit_fatto;

function check_submit_fatto()
{
	if (bo_submit_fatto)
	{
		return true;
	}
	else
	{
		bo_submit_fatto = true;
		return false;
	}
}

function bloccaClickExplorer()
{
	return false;
}

function bloccaClickFirefox()
{
	this.href = "javascript:void(0);";
}

function carica_id_contenuti_categoria(id_destinazioni_contenuti, id_contenuti_categoria, id_contenuti, tipo_template, bo_tipo_click, bo_navigazione_id_destinazioni_contenuti, bo_navigazione_id_contenuti)
{
	if (check_submit_fatto())
	{
		return;
	}

	if (bo_tipo_click == "LLI")
	{
		document.cookie = "ritorno_logout=";

		if (document.forms["contenuti"].id_destinazioni_contenuti != undefined)
		{
			document.cookie = "ritorno_logout=id_destinazioni_contenuti=" + document.forms["contenuti"].id_destinazioni_contenuti.value + "&"

			if (eval("document.forms['contenuti'].id_destinazioni_contenuti_" + document.forms["contenuti"].id_destinazioni_contenuti.value ) != undefined)
			{
				document.cookie = "ritorno_logout=" + readCookie("ritorno_logout") + "id_destinazioni_contenuti_" + document.forms["contenuti"].id_destinazioni_contenuti.value  
								+ "=" + eval("document.forms['contenuti'].id_destinazioni_contenuti_" + document.forms["contenuti"].id_destinazioni_contenuti.value ).value + "&"
			}
		}

		if (document.forms["contenuti"].id_contenuti != undefined)
		{
			document.cookie = "ritorno_logout=" + readCookie("ritorno_logout") + "id_contenuti=" + document.forms["contenuti"].id_contenuti.value + "&"  
		}

		if (document.forms["contenuti"].tipo_template != undefined)
		{
			document.cookie = "ritorno_logout=" + readCookie("ritorno_logout") + "tipo_template=" + document.forms["contenuti"].tipo_template.value + "&" 
		}

		if (document.forms["contenuti"].bo_navigazione_id_destinazioni_contenuti != undefined)
		{
			document.cookie = "ritorno_logout=" + readCookie("ritorno_logout") + "bo_navigazione_id_destinazioni_contenuti=" 
							+ document.forms["contenuti"].bo_navigazione_id_destinazioni_contenuti.value + "&"
		}

		if (document.forms["contenuti"].bo_navigazione_id_contenuti != undefined)
		{
			document.cookie = "ritorno_logout=" + readCookie("ritorno_logout") + "bo_navigazione_id_contenuti=" 
							+ document.forms["contenuti"].bo_navigazione_id_contenuti.value + "&"
		}

		bo_carica_grazie(document.location.protocol + "//" + document.location.hostname + document.location.pathname.replace(/contenuti[/]bo_lista_multiple_contenuti.asp/i, "services/bo_carica_grazie.asp?ambiente=" + CCGetParam("ambiente")) + "|||");
	}

	eval("document.forms['contenuti'].id_destinazioni_contenuti_" + id_destinazioni_contenuti).value = id_contenuti_categoria;
	document.forms["contenuti"].id_destinazioni_contenuti.value = id_destinazioni_contenuti;
	document.forms["contenuti"].id_contenuti.value = id_contenuti;
	document.forms["contenuti"].tipo_template.value = tipo_template;
	document.forms["contenuti"].bo_tipo_click.value = bo_tipo_click;
	document.forms["contenuti"].bo_navigazione_id_destinazioni_contenuti.value = bo_navigazione_id_destinazioni_contenuti;
	document.forms["contenuti"].bo_navigazione_id_contenuti.value = bo_navigazione_id_contenuti;

	document.forms["contenuti"].submit();

	for (k=0; k<document.links.length; k++)
	{
		if (document.all) 
		{
			document.links[k].attachEvent("onclick", bloccaClickExplorer);
		}
		else
		{
			document.links[k].addEventListener("click", bloccaClickFirefox, false)
		}
	}
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i=0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}

	return null;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

var wrisultati_frontend;

function ApriRisultatiSondaggi(ambiente, percorso_http_macro, percorso_server_templates, id_lingue_per_ambiente, priorita_sondaggi, id_domande)
{
	windowprops = "top="+((screen.availHeight-601)/2)+",left="+((screen.availWidth-952)/2)+",resizable=no,scrollbars=yes,menubar=no,titlebar=no,width=952,height=601"

	if (wrisultati_frontend != undefined)
	{
		wrisultati_frontend.close()
	}

	wrisultati_frontend = window.open(percorso_http_macro + "sondaggi/bo_risultati_sondaggi.asp?ambiente=" + ambiente.replace(/[|][|][|]/g, "'") + "&id_domande=" 
						+ id_domande + "&percorso_server_templates=" + percorso_server_templates + "&tipo_risultati=front-end&id_lingue_per_ambiente="+id_lingue_per_ambiente
						+ "&priorita_sondaggi="+priorita_sondaggi, "wrisultati_frontend", windowprops);
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

function bo_addOpacity() 
{
	document.body.style.overflow = "hidden";
	document.getElementById("opacity").style.zIndex = 50;
	document.getElementById("opacity").style.width = screen.availWidth;
	document.getElementById("opacity").style.height = screen.availHeight;
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

function bo_removeOpacity() 
{
	if (!document.getElementById("opacity")) 
	{
		return false;
	}

	document.getElementById("opacity").style.width = 0;
	document.getElementById("opacity").style.height = 0;
	document.body.style.overflow = "auto";
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

var divObject;

function showDiv(divId) 
{
	bo_addOpacity();

	if (divObject)
	{
		divObject.style.visibility = "hidden"
	}

	divObject = document.getElementById(divId);

	if(divObject)
	{
		if (document.getElementById("div_menu"))
		{
			divMenu = document.getElementById("div_menu").offsetWidth;
		}
		else
		{
			divMenu = 0;
		}

		// dimensioni div
		var dw = divObject.offsetWidth;
		var dh = divObject.offsetHeight;

		// calcolo la posizione
		var dleft = Math.round((document.body.offsetWidth - dw) / 2) + Math.round(divMenu / 2);
		var dtop = Math.round((document.body.offsetHeight - dh) / 3);

		// posizionamento
		divObject.style.left = dleft;
		divObject.style.top = dtop;

		// visualizzazione
		divObject.style.visibility = "visible";
	}
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

function corregge_problema_overflow() 
{
	document.getElementById("div_elaborazione").style.visibility = "visible";
	document.getElementById("div_elaborazione").style.visibility = "hidden";
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

var exec_abilita_salva = true;

function delay_dato_padre_addEventHandler(elementId, event, handler, elementIdFiglio)
{
	if (stack_genera_html.search(RegExp("[|][|][|]bo_td_" + elementId + "[|][|][|]", "")) > -1)
	{
		setTimeout("delay_dato_padre_addEventHandler('" + elementId + "', '" + event + "', " + handler + ", '" + elementIdFiglio + "')", 100);
	}
	else
	{
		addEventHandler(elementId, event, handler);
		exec_abilita_salva = false;

		if (list_box_OnChange(elementId) && check_box_OnChange(elementId)) 
		{
			stack_genera_html = stack_genera_html.replace(RegExp("[|][|][|]bo_td_" + elementIdFiglio + "[|][|][|]", "g"), "");
			$("bo_td_" + elementIdFiglio + "_indicator").style.visibility = "hidden";
		}

		exec_abilita_salva = true;
	}
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

function delay_addEventHandler(elementId, event, handler, elementIdPadre)
{
	if (elementIdPadre.length == 0)
	{
		stack_genera_html = stack_genera_html.replace(RegExp("[|][|][|]bo_td_" + elementId + "[|][|][|]", "g"), "");
		$("bo_td_" + elementId + "_indicator").style.visibility = "hidden";
	}

	setTimeout("addEventHandler('" + elementId + "', '" + event + "', " + handler + ")", 100);
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

function delay_bo_removeOpacity()
{
	if (stack_genera_html.length > 0)
	{
		setTimeout("delay_bo_removeOpacity()", 100);
	}
	else
	{
		bo_removeOpacity();
	}
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

var stack_genera_html = "";

function genera_html(url, divid) 
{
	stack_genera_html = stack_genera_html + "|||" + divid + "|||";

    new Ajax.Request(url, 
	{
        method: "post",
        requestHeaders: ['If-Modified-Since', new Date(0)],
        onLoading: 	function() 	
					{
						if (stack_genera_html.indexOf("|||" + divid + "|||") > -1)
						{
							$(divid + "_indicator").style.visibility = "visible";
							bo_addOpacity();
						}
					},
        onSuccess: 	function(transport) 
					{
						var inizio_eval = transport.responseText.search(/<eval>/);

						if (inizio_eval > -1)
						{
							$(divid).innerHTML = transport.responseText.substr(0, inizio_eval);
							var script = transport.responseText.substring((inizio_eval + 6), transport.responseText.search(/<[/]eval>/));
							  
							if (script.length > 0)
							{
								eval(script);
							}							
						}
						else
						{
							$(divid).innerHTML = transport.responseText;							
						}

						corregge_problema_overflow();
						delay_bo_removeOpacity();
						stack_genera_html = stack_genera_html.replace(("|||" + divid + "|||"), "");
						$(divid + "_indicator").style.visibility = "hidden";
					}, 
		onFailure:	function(transport) 	
					{
            			alert(transport.responseText);
        			}
    });
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

var bo_carica_login_fatto = false;

function bo_carica_login()
{
	if (!bo_carica_login_fatto)
	{
		bo_carica_login_fatto = true;
		stack_genera_html = stack_genera_html + "|||block_bo_removeOpacity|||";
		window.open(percorso_http_macro + "bo_login.asp?Logout=True&ambiente=" + document.getElementsByName("ambiente")[0].value + "&bo_login=" + document.getElementsByName("bo_login")[0].value, "_parent", "", true)
	}
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

function bo_carica_grazie(url)
{
	xmlHttpReq = false;

    if(window.XMLHttpRequest && !(window.ActiveXObject)) 
	{
    	try 
		{
			xmlHttpReq = new XMLHttpRequest();
        } 
		catch(errore) 
		{
			xmlHttpReq = false;
        }
    } 
	else if(window.ActiveXObject) 
	{
		try 
		{
        	xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
      	} 
		catch(errore) 
		{
        	try 
			{
          		xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
        	} 
			catch(errore) 
			{
          		xmlHttpReq = false;
        	}
		}
    }

	if(xmlHttpReq) 
	{
		url = url.split("|||");

		for (i=0; i<(url.length-1); i++)
		{
	    	try 
			{
				xmlHttpReq.open("HEAD", url[i], false);
				xmlHttpReq.send("");
				document.cookie = "checkGrazieFatto=" + escape(xmlHttpReq.getResponseHeader("checkGrazieFatto")) + ";path=/;domain=" 
								+ document.location.hostname.substr(document.location.hostname.indexOf("."));
			} 
			catch(errore) 
			{
				void(0);
        	}
		}
	}
}

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

/*
 +-------------------------------------------------------------------+
 |                   H T M L - G R A P H S   (v3.4)                  |
 |                                                                   |
 | Copyright Gerd Tentler               www.gerd-tentler.de/tools    |
 | Created: Sep. 17, 2002               Last modified: Feb. 15, 2006 |
 +-------------------------------------------------------------------+
 | This program may be used and hosted free of charge by anyone for  |
 | personal purpose as long as this copyright notice remains intact. |
 |                                                                   |
 | Obtain permission before selling the code for this program or     |
 | hosting this software on a commercial website or redistributing   |
 | this software over the Internet or in any other medium. In all    |
 | cases copyright must remain intact.                               |
 +-------------------------------------------------------------------+

======================================================================================================
 Example:

   graph = new BAR_GRAPH("hBar");
   graph.values = new Array(234, 125, 289, 147, 190);
   document.write(graph.create());

 Returns HTML code
------------------------------------------------------------------------------------------------------
 This script was tested with the following systems and browsers:

 - Windows XP: IE 6, NN 7, Opera 7, Firefox 1
 - Mac OS X:   IE 5, Safari 1

 If you use another browser or system, this script may not work for you - sorry.
======================================================================================================
*/
  function BAR_GRAPH(type) {
//----------------------------------------------------------------------------------------------------
// Configuration
//----------------------------------------------------------------------------------------------------
    this.type = 'hBar';                       // graph type: "hBar", "vBar", "pBar", or "fader"
    if(type) this.type = type;
    this.values;                              // graph data: string with comma-separated values or array

    this.graphBGColor = '';                   // graph background color: string
    this.graphBorder = '';                    // graph border: string (CSS specification; doesn't work with NN4)
    this.graphPadding = 0;                    // graph padding: integer (pixels)

    this.labels;                              // label names: string with comma-separated values or array
    this.labelColor = 'black';                // label font color: string
    this.labelBGColor = '#C0E0FF';            // label background color: string
    this.labelBorder = '2px groove white';    // label border: string (CSS specification)
    this.labelFont = 'Arial, Helvetica';      // label font family: string (CSS specification)
    this.labelSize = 12;                      // label font size: integer (pixels)
    this.labelSpace = 0;                      // additional space between labels (pixels)

    this.barWidth = 20;                       // bar width: integer (pixels)
    this.barLength = 1.0;                     // bar length ratio: float (from 0.1 to 2.9)
    this.barColor;                            // bar color OR bar image: string with comma-separated values or array
    this.barBGColor;                          // bar background color: string
    this.barBorder = '2px outset white';      // bar border: string (CSS specification)
    this.barLevelColor;                       // bar level color: array (bLevel, bColor[,...]); draw bars >= bLevel with bColor

    this.showValues = 0;                      // show values: 0 = % only, 1 = abs. and %, 2 = abs. only, 3 = none

    this.absValuesColor;                      // abs. values font color: string (if not set, same color like labels)
    this.absValuesBGColor;                    // abs. values background color: string (if not set, same color like labels)
    this.absValuesBorder;                     // abs. values border: string (CSS specification; doesn't work with NN4; if not set, same border like labels)
    this.absValuesFont = 'Arial, Helvetica';  // abs. values font family: string (CSS specification)
    this.absValuesSize = 12;                  // abs. values font size: integer (pixels)
    this.absValuesPrefix = '';                // abs. values prefix: string (e.g. currency)

    this.percValuesColor = 'black';           // perc. values font color: string
    this.percValuesFont = 'Arial, Helvetica'; // perc. values font family: string (CSS specification)
    this.percValuesSize = 12;                 // perc. values font size: integer (pixels)
    this.percValuesDecimals = 0;              // perc. values number of decimals: integer

    this.stackedBars = false;                 // show grouped bars as stacked bars: true = yes, false = no;

    this.charts = 1;                          // number of charts: integer

    // hBar/vBar only:
    this.legend;                              // legend items: string with comma-separated values or array
    this.legendColor = 'black';               // legend font color: string
    this.legendBGColor = '#F0F0F0';           // legend background color: string
    this.legendBorder = '2px groove white';   // legend border: string (CSS specification)
    this.legendFont = 'Arial, Helvetica';     // legend font family: string (CSS specification)
    this.legendSize = 12;                     // legend font size: integer (pixels)

    // debug mode: false = off, true = on; just shows some extra information
    this.debug = false;

    // default bar colors; only used if barColor isn't set
    this.colors = new Array('#0000FF', '#FF0000', '#00E000', '#A0A0FF', '#FFA0A0', '#00A000');

    // error messages
    this.err_type = 'ERROR: Type must be "hBar", "vBar", "pBar", or "fader"';

    // CSS names (don't change)
    this.cssGRAPH = '';
    this.cssBAR = '';
    this.cssBARBG = '';
    this.cssLABEL = '';
    this.cssLABELBG = '';
    this.cssLEGEND = '';
    this.cssLEGENDBG = '';
    this.cssABSVALUES = '';
    this.cssPERCVALUES = '';

//----------------------------------------------------------------------------------------------------
// Functions
//----------------------------------------------------------------------------------------------------
    this.set_styles = function() {
      if(this.graphBGColor) this.cssGRAPH += 'background-color:' + this.graphBGColor + ';';
      if(this.graphBorder) this.cssGRAPH += 'border:' + this.graphBorder + ';';
      if(this.barBorder) this.cssBAR += 'border:' + this.barBorder + ';';
      if(this.barBGColor) this.cssBARBG += 'background-color:' + this.barBGColor + ';';
      if(this.labelColor) this.cssLABEL += 'color:' + this.labelColor + ';';
      if(this.labelBGColor) this.cssLABEL += 'background-color:' + this.labelBGColor + ';';
      if(this.labelBorder) this.cssLABEL += 'border:' + this.labelBorder + ';';
      if(this.labelFont) this.cssLABEL += 'font-family:' + this.labelFont + ';';
      if(this.labelSize) this.cssLABEL += 'font-size:' + this.labelSize + 'px;';
      if(this.labelBGColor) this.cssLABELBG += 'background-color:' + this.labelBGColor + ';';
      if(this.legendColor) this.cssLEGEND += 'color:' + this.legendColor + ';';
      if(this.legendFont) this.cssLEGEND += 'font-family:' + this.legendFont + ';';
      if(this.legendSize) this.cssLEGEND += 'font-size:' + this.legendSize + 'px;';
      if(this.legendBGColor) this.cssLEGENDBG += 'background-color:' + this.legendBGColor + ';';
      if(this.legendBorder) this.cssLEGENDBG += 'border:' + this.legendBorder + ';';
      if(this.absValuesColor) this.cssABSVALUES += 'color:' + this.absValuesColor + ';';
      if(this.absValuesBGColor) this.cssABSVALUES += 'background-color:' + this.absValuesBGColor + ';';
      if(this.absValuesBorder) this.cssABSVALUES += 'border:' + this.absValuesBorder + ';';
      if(this.absValuesFont) this.cssABSVALUES += 'font-family:' + this.absValuesFont + ';';
      if(this.absValuesSize) this.cssABSVALUES += 'font-size:' + this.absValuesSize + 'px;';
      if(this.percValuesColor) this.cssPERCVALUES += 'color:' + this.percValuesColor + ';';
      if(this.percValuesFont) this.cssPERCVALUES += 'font-family:' + this.percValuesFont + ';';
      if(this.percValuesSize) this.cssPERCVALUES += 'font-size:' + this.percValuesSize + 'px;';
    }

    this.level_color = function(value, color) {
      if(this.barLevelColor) {
        for(var i = 0; i < this.barLevelColor.length; i += 2) {
          if((this.barLevelColor[i] > 0 && value >= this.barLevelColor[i]) ||
             (this.barLevelColor[i] < 0 && value <= this.barLevelColor[i])) {
            color = this.barLevelColor[i+1];
          }
        }
      }
      return color;
    }

    this.draw_bar = function(width, height, color) {
      var bg = (color.search(/\.(jpg|jpeg|jpe|gif|png)$/i) != -1) ? 'background' : 'bgcolor';
      var bar = '<table border=0 cellspacing=0 cellpadding=0><tr>';
      bar += '<td style="' + this.cssBAR + '" ' + bg + '=' + color + '>';
      bar += '<table border=0 cellspacing=0 cellpadding=0><tr>';
      bar += '<td width=' + width + ' height=' + height + '></td>';
      bar += '</tr></table>';
      bar += '</td></tr></table>';
      return bar;
    }

    this.set_fader = function(width, height, x, color) {
      var btn = '<table border=0 cellspacing=0 cellpadding=0><tr>';
      x -= Math.round(width / 2);
      if(x > 0) btn += '<td width=' + x + '></td>';
      btn += '<td>' + this.draw_bar(width, height, color) + '</td>';
      btn += '</tr></table>';
      return btn;
    }

    this.format_value = function(val, dec) {
      if(dec) {
        if(val < 0) {
          var neg = true;
          val *= -1;
        }
        else var neg = false;
        var v = (Math.round(val * Math.pow(10, dec))).toString();
        if(v.length <= dec) for(var i = 0; i < dec - v.length + 1; i++) v = '0' + v;
        v = v.substr(0, v.length - dec) + '.' + v.substr(v.length - dec);
        if(v.substr(0, 1) == '.') v = '0' + v;
        if(neg) v = '-' + v;
      }
      else v = Math.round(val);
      return v;
    }

    this.show_value = function(val, max_dec, sum, align) {
      val = max_dec ? this.format_value(val, max_dec) : val;
      if(sum) sum = max_dec ? this.format_value(sum, max_dec) : sum;
      value = '<td style="' + this.cssABSVALUES + '"';
      if(align) value += ' align=' + align;
      value += ' nowrap>';
      value += '&nbsp;' + this.absValuesPrefix + val;
      if(sum) value += ' / ' + this.absValuesPrefix + sum;
      value += '&nbsp;</td>';
      return value;
    }

    this.build_legend = function(barColors) {
      var legend = '<table border=0 cellspacing=0 cellpadding=0><tr>';
      legend += '<td style="' + this.cssLEGENDBG + '">';
      legend += '<table border=0 cellspacing=4 cellpadding=0>';
      var l = (typeof(this.legend) == 'string') ? this.legend.split(',') : this.legend;

      for(var i = 0; i < barColors.length; i++) {
        legend += '<tr>';
        legend += '<td>' + this.draw_bar(this.barWidth, this.barWidth, barColors[i]) + '</td>';
        legend += '<td style="' + this.cssLEGEND + '" nowrap>' + l[i] + '</td>';
        legend += '</tr>';
      }
      legend += '</table></td></tr></table>';
      return legend;
    }

    this.create_hBar = function(percent, mPerc, mPerc_neg, max_neg, mul, valSpace, bColor, border, spacer, spacer_neg) {
      var bar = '<table border=0 cellspacing=0 cellpadding=0 width=100%><tr align=center>';

      if(percent < 0) {
        percent *= -1;
        bar += '<td style="' + this.cssLABELBG + '" height=' + this.barWidth + ' width=' + Math.round((mPerc_neg - percent) * mul + valSpace) + ' align=right nowrap>';
        if(this.showValues < 2) bar += '<span style="' + this.cssPERCVALUES + '">' + this.format_value(percent, this.percValuesDecimals) + '%</span>';
        bar += '&nbsp;</td><td style="' + this.cssLABELBG + '">';
        bar += this.draw_bar(Math.round(percent * mul), this.barWidth, bColor);
        bar += '</td><td width=' + spacer + '></td>';
      }
      else {
        if(max_neg) {
          bar += '<td style="' + this.cssLABELBG + '" width=' + spacer_neg + '>';
          bar += '<table border=0 cellspacing=0 cellpadding=0><tr><td></td></tr></table></td>';
        }
        if(percent) {
          bar += '<td>';
          bar += this.draw_bar(Math.round(percent * mul), this.barWidth, bColor);
          bar += '</td>';
        }
        else bar += '<td height=' + (this.barWidth + (border * 2)) + '></td>';
        bar += '<td style="' + this.cssPERCVALUES + '" width=' + Math.round((mPerc - percent) * mul + valSpace) + ' align=left nowrap>';
        if(this.showValues < 2) bar += '&nbsp;' + this.format_value(percent, this.percValuesDecimals) + '%';
        bar += '&nbsp;</td>';
      }
      bar += '</tr></table>';

      return bar;
    }

    this.create_vBar = function(percent, mPerc, mPerc_neg, max_neg, mul, valSpace, bColor, border, spacer, spacer_neg) {
      var bar = '<table border=0 cellspacing=0 cellpadding=0 width=100%><tr align=center>';

      if(percent < 0) {
        percent *= -1;
        bar += '<td height=' + spacer + '></td></tr><tr align=center valign=top><td style="' + this.cssLABELBG + '">';
        bar += this.draw_bar(this.barWidth, Math.round(percent * mul), bColor);
        bar += '</td></tr><tr align=center valign=top>';
        bar += '<td style="' + this.cssLABELBG + '" height=' + Math.round((mPerc_neg - percent) * mul + valSpace) + ' nowrap>';
        bar += (this.showValues < 2) ? '<span style="' + this.cssPERCVALUES + '">' + this.format_value(percent, this.percValuesDecimals) + '%</span>' : '&nbsp;';
        bar += '</td>';
      }
      else {
        bar += '<td style="' + this.cssPERCVALUES + '" valign=bottom height=' + Math.round((mPerc - percent) * mul + valSpace) + ' nowrap>';
        if(this.showValues < 2) bar += this.format_value(percent, this.percValuesDecimals) + '%';
        bar += '</td>';
        if(percent) {
          bar += '</tr><tr align=center valign=bottom><td>';
          bar += this.draw_bar(this.barWidth, Math.round(percent * mul), bColor);
          bar += '</td>';
        }
        else bar += '</tr><tr><td width=' + (this.barWidth + (border * 2)) + '></td>';
        if(max_neg) {
          bar += '</tr><tr><td style="' + this.cssLABELBG + '" height=' + spacer_neg + '>';
          bar += '<table border=0 cellspacing=0 cellpadding=0><tr><td></td></tr></table></td>';
        }
      }
      bar += '</tr></table>';

      return bar;
    }

    this.create = function() {
      this.type = this.type.toLowerCase();
      var d = (typeof(this.values) == 'string') ? this.values.split(',') : this.values;
      if(this.labels) var r = (typeof(this.labels) == 'string') ? this.labels.split(',') : this.labels;
      else var r = new Array();
      var label = graph = bColor = '';
      var percent = rowspan = colspan = 0;
      if(this.barColor) var drf = (typeof(this.barColor) == 'string') ? this.barColor.split(',') : this.barColor;
      else var drf = new Array();
      var drw, val = new Array();
      var bc = new Array();
      if(this.barLength < 0.1) this.barLength = 0.1;
      else if(this.barLength > 2.9) this.barLength = 2.9;
      var bars = (d.length > r.length) ? d.length : r.length;

      if(!this.absValuesColor) this.absValuesColor = this.labelColor;
      if(!this.absValuesBGColor) this.absValuesBGColor = this.labelBGColor;
      if(!this.absValuesBorder) this.absValuesBorder = this.labelBorder;

      if(this.type == 'pbar' || this.type == 'fader') {
        if(!this.barBGColor) this.barBGColor = this.labelBGColor;
        if(this.labelBGColor == this.barBGColor) {
          this.labelBGColor = '';
          this.labelBorder = '';
        }
      }

      this.set_styles();

      graph += '<table border=0 cellspacing=0 cellpadding=' + this.graphPadding + '><tr>';
      graph += '<td' + (this.cssGRAPH ? ' style="' + this.cssGRAPH + '"' : '') + '>';

      if(this.legend && this.type != 'pbar' && this.type != 'fader')
        graph += '<table border=0 cellspacing=0 cellpadding=0><tr valign=top><td align=center>';

      if(this.charts > 1) {
        divide = Math.ceil(bars / this.charts);
        graph += '<table border=0 cellspacing=0 cellpadding=6><tr valign=top><td>';
      }
      else divide = 0;

      var sum = max = max_neg = max_dec = ccnt = lcnt = chart = 0;
      val[chart] = new Array();

      for(var i = 0; i < bars; i++) {
        if(divide && i && !(i % divide)) {
          lcnt = 0;
          chart++;
          val[chart] = new Array();
        }
        if(typeof(d[i]) == 'string') drw = d[i].split(';');
        else {
          drw = new Array();
          drw[0] = d[i];
        }
        val[chart][lcnt] = new Array();

        for(var j = v = 0; j < drw.length; j++) {
          val[chart][lcnt][j] = v = drw[j] ? parseFloat(drw[j]) : 0;

          if(v > max) max = v;
          else if(v < max_neg) max_neg = v;

          if(v < 0) v *= -1;
          sum += v;

          v = v.toString();
          if(v.indexOf('.') != -1) {
            v = v.substr(v.indexOf('.') + 1);
            dec = v.length;
            if(dec > max_dec) max_dec = dec;
          }

          if(!bc[j]) {
            if(ccnt >= this.colors.length) ccnt = 0;
            bc[j] = (!drf[j] || drf[j].length < 3) ? this.colors[ccnt++] : drf[j];
          }
        }
        lcnt++;
      }

      var border = parseInt(this.barBorder);
      var mPerc = sum ? Math.round(max * 100 / sum) : 0;
      if(this.type == 'pbar' || this.type == 'fader') var mul = 2;
      else var mul = mPerc ? 100 / mPerc : 1;
      mul *= this.barLength;

      if(this.showValues < 2) {
        if(this.type == 'hbar')
          valSpace = (this.percValuesDecimals * (this.percValuesSize / 1.7)) + (this.percValuesSize * 2.2);
        else valSpace = this.percValuesSize * 1.2;
      }
      else valSpace = this.percValuesSize;
      var spacer = maxSize = Math.round(mPerc * mul + valSpace + border * 2);

      if(max_neg) {
        var mPerc_neg = sum ? Math.round(-max_neg * 100 / sum) : 0;
        var spacer_neg = Math.round(mPerc_neg * mul + valSpace + border * 2);
        maxSize += spacer_neg;
      }

      for(chart = lcnt = 0; chart < val.length; chart++) {
        graph += '<table border=0 cellspacing=2 cellpadding=0>';

        if(this.type == 'hbar') {
          for(i = 0; i < val[chart].length; i++, lcnt++) {
            label = (lcnt < r.length) ? r[lcnt] : lcnt+1;
            rowspan = val[chart][i].length;
            graph += '<tr><td style="' + this.cssLABEL + '"' + ((rowspan > 1) ? ' rowspan=' + rowspan : '') + ' align=center>';
            graph += '&nbsp;' + label + '&nbsp;</td>';

            for(j = 0; j < val[chart][i].length; j++) {
              percent = sum ? val[chart][i][j] * 100 / sum : 0;
              bColor = this.level_color(val[chart][i][j], bc[j]);

              if(this.showValues == 1 || this.showValues == 2)
                graph += this.show_value(val[chart][i][j], max_dec, 0, 'right');

              graph += '<td' + (this.cssBARBG ? ' style="' + this.cssBARBG + '"' : '') + ' height=100% width=' + maxSize + '>';
              graph += this.create_hBar(percent, mPerc, mPerc_neg, max_neg, mul, valSpace, bColor, border, spacer, spacer_neg);
              graph += '</td></tr>';
              if(j < val[chart][i].length - 1) graph += '<tr>';
            }
            if(this.labelSpace && i < val[chart].length-1) graph += '<tr><td colspan=3 height=' + this.labelSpace + '></td></tr>';
          }
        }
        else if(this.type == 'vbar') {
          graph += '<tr align=center valign=bottom>';
          for(i = 0; i < val[chart].length; i++) {

            for(j = 0; j < val[chart][i].length; j++) {
              percent = sum ? val[chart][i][j] * 100 / sum : 0;
              bColor = this.level_color(val[chart][i][j], bc[j]);

              graph += '<td' + (this.cssBARBG ? ' style="' + this.cssBARBG + '"' : '') + '>';
              graph += this.create_vBar(percent, mPerc, mPerc_neg, max_neg, mul, valSpace, bColor, border, spacer, spacer_neg);
              graph += '</td>';
            }
            if(this.labelSpace) graph += '<td width=' + this.labelSpace + '></td>';
          }
          if(this.showValues == 1 || this.showValues == 2) {
            graph += '</tr><tr align=center>';
            for(i = 0; i < val[chart].length; i++) {
              for(j = 0; j < val[chart][i].length; j++) {
                graph += this.show_value(val[chart][i][j], max_dec);
              }
              if(this.labelSpace) graph += '<td width=' + this.labelSpace + '></td>';
            }
          }
          graph += '</tr><tr align=center>';
          for(i = 0; i < val[chart].length; i++, lcnt++) {
            label = (lcnt < r.length) ? r[lcnt] : lcnt+1;
            colspan = val[chart][i].length;
            graph += '<td style="' + this.cssLABEL + '"' + ((colspan > 1) ? ' colspan=' + colspan : '') + '>';
            graph += '&nbsp;' + label + '&nbsp;</td>';
            if(this.labelSpace) graph += '<td width=' + this.labelSpace + '></td>';
          }
          graph += '</tr>';
        }
        else if(this.type == 'pbar' || this.type == 'fader') {
          for(i = 0; i < val[chart].length; i++, lcnt++) {
            label = (lcnt < r.length) ? r[lcnt] : '';
            graph += '<tr>';

            if(label) {
              graph += '<td style="' + this.cssLABEL + '" align=right>';
              graph += '&nbsp;' + label + '&nbsp;</td>';
            }
            sum = val[chart][i][1] ? val[chart][i][1] : 0;
            percent = sum ? val[chart][i][0] * 100 / sum : 0;

            if(this.showValues == 1 || this.showValues == 2)
              graph += this.show_value(val[chart][i][0], max_dec, sum, 'right');

            graph += '<td' + (this.cssBARBG ? ' style="' + this.cssBARBG + '"' : '') + '>';

            this.barColor = drf[i] ? drf[i] : this.colors[0];
            bColor = this.level_color(val[chart][i][0], this.barColor);
            graph += '<table border=0 cellspacing=0 cellpadding=0><tr><td>';
            if(this.type == 'fader') graph += this.set_fader(Math.round(this.barWidth / 2), this.barWidth, Math.round(percent * mul), bColor);
            else graph += this.draw_bar(Math.round(percent * mul), this.barWidth, bColor);
            graph += '</td><td width=' + Math.round((100 - percent) * mul) + '></td>';
            graph += '</tr></table></td>';
            if(this.showValues < 2) graph += '<td style="' + this.cssPERCVALUES + '" nowrap>&nbsp;' + this.format_value(percent, this.percValuesDecimals) + '%</td>';
            graph += '</tr>';
            if(this.labelSpace && i < val[chart].length-1) graph += '<td colspan=3 height=' + this.labelSpace + '></td>';
          }
        }
        else graph += '<tr><td>' + this.err_type + '</td></tr>';

        graph += '</table>';

        if(chart < this.charts - 1 && val[chart+1].length) {
          graph += '</td>';
          if(this.type == 'vbar') graph += '</tr><tr valign=top>';
          graph += '<td>';
        }
      }

      if(this.charts > 1) graph += '</td></tr></table>';

      if(this.legend && this.type != 'pbar' && this.type != 'fader') {
        graph += '</td></tr><tr><td width=10>&nbsp;</td></tr><tr><td>';
        graph += this.build_legend(bc);
        graph += '</td></tr></table>';
      }

      if(this.debug) {
        graph += '<br>sum='+sum+' max='+max+' max_neg='+max_neg+' mPerc='+mPerc;
        graph += ' mPerc_neg='+mPerc_neg+' mul='+mul+' valSpace='+valSpace;
      }

      graph += '</td></tr></table>';

      return graph;
    }
  }

//-------------------------------------------------------------------------------------------------------------------------------------------------------------

