var moveTimer; // timer per lo scrolling dello scaffale virtuale
var onTimer;
var uploadTimer; // timer intervallo check upload file
var div_suggread; // scorrimento del widget dei suggerimenti di lettura
var firstDocList = null; // progressivo del primo documento della pagina in una lista risultati (es.: 0, 10, ...)
var listType;
var oldListType;

var $E = YAHOO.util.Event;
var $D = YAHOO.util.Dom;

errorHandler = function(data) {
  LOG.error(data);
  var sts = STATUS.get();
	if(data === "Timeout") {
		HINT.error("L'applicazione sta impiegando troppo tempo per rispondere. Riprova");
	}	
  //var dtoMsg = dwr.util.toDescriptiveString(sts[2],10,{oneLineMaxItems: -1, shortStringMaxLength: 10000, baseIndent: "", childIndent: "  "});
	var dtoMsg = "dtoMsg non inoltrato per vedere se le performance migliorano";
  A.a01m04(data, sts[0], sts[1], dtoMsg, function(){LOG.info("il messaggio d'errore è stato loggato sul server");});	
};

window.onerror=errorHandler;

DWREngine.setErrorHandler(errorHandler);

DWREngine.setTimeout(60000);

String.prototype.normWhiteSpace = function () {
  return $.trim(this.replace(/\s+/g," "));
};

String.prototype.isEmpty = function() {
  return (this == undefined || this.length == 0);
};

String.prototype.isBlank = function() {
  return $.trim(this).isEmpty();
};

String.prototype.fromJSON = function() {
  return $.trim(this.replace( /\&apos;/g, "'" ));
};

Array.prototype.indexAt = function(what){
	// la funzione nativa di javascript 1.6 non è gestita da ie7
	var L= this.length;
	var i= 0;
	while(i< L){
		if (this[i] === what) {
			return i;
		}
		++i;
	}
	return -1;
};

Array.prototype.add= function(wot){
	if (this.indexAt(wot) == -1) {
		this.push(wot);
	}
	return this;
};

clone = function(obj) {
	return $.extend(true, {}, obj);
};

function stopPropagation(event) {
  if (event) 
    $E.stopPropagation(event);        
}    

function $ID(element) {
  if (arguments.length > 1) alert ("error $ 1");
  if (typeof element == 'string') return document.getElementById(element);
  else alert ("error $ 2: " + element);
}

function $NAME(element) {
  if (arguments.length > 1) alert ("error $ 1");
  if (typeof element == 'string') return document.getElementsByName(element); 
  else alert ("error $ 2: " + element);
}

LOG = (function () {
  
  var options = {
    debugLevel: "info",
    useELog: false,
    useLog4Js: false,
    useFirebug: false
  }
  
  var logs = {
    eLog: false,
    log4Js: false,
    firebug: false
  };

  function getLog4JsLevel(val) {
    if(val=="trace") {
      return log4javascript.Level.TRACE;
    } else if(val=="debug") {
      return log4javascript.Level.DEBUG;
    } else if(val=="info") {
      return log4javascript.Level.INFO;
    } else if(val=="warn") {
      return log4javascript.Level.WARN;
    } else if(val=="error") {
      return log4javascript.Level.ERROR;
    } else if(val=="fatal") {
      return log4javascript.Level.FATAL;
    }  
  }
  
  function initialize(params) {
    if (typeof params == "string" && params == "") return; 
    
    if (typeof params == "string" && params != "") {
      var arr = params.split(",");
      for(var i=0; i<arr.length; i++) {
        switch (arr[i]) {
          case "elog":
            options.useELog = true;
            break;
          case "log4js":
            options.useLog4Js = true;
            break;
          case "firebug":
            options.useFirebug = true;
            break;
          default:
            options.debugLevel = arr[i];
            break;
        }
      }
    } else if (typeof params == "object") {
      $.extend(options, params);
    } 

    if (options.useELog) {
      $.getScript("sebinayou/js/logs/eLog.js", function() {
        eLOG.init();
        logs.eLog = eLOG;
        logs.eLog.info("eLog initialized");
      });
    }

    if (options.useLog4Js) {
      $.getScript("sebinayou/js/logs/log4javascript.js", function() {
        var l = log4javascript.getLogger("sy");
        var appender = new log4javascript.PopUpAppender();
        l.addAppender(appender);
        l.setLevel(getLog4JsLevel(options.debugLevel));
        logs.log4Js = l;
        logs.log4Js.info("log4javascript initialized");
      });
    }

    if (options.useFirebug && typeof console != "undefined") {
      logs.firebug = console;
      logs.firebug.info("Firebug present");
    }
  }
  
  function show(msg, type) {
    $.each(logs, function(i) {
      if (this == false) return;
      if (typeof this[type] != "undefined") {
        
        if (typeof msg != "undefined") {
          
          if(typeof msg == "object" && i == "log4Js") {
            msg = dwr.util.toDescriptiveString(msg,10,{oneLineMaxItems: -1, shortStringMaxLength: 10000});
          }
          
          this[type](msg);  
        } else {
          this[type]();
        }
      }
    });
  }
   
  return {
    init: function(params) {
      initialize(params);
    },
    
    // Metodi comuni 
    debug: function(msg) {
      show(msg, "debug");
    },
    
    info: function(msg) {
      show(msg, "info");
    },
    
    warn: function(msg) {
      show(msg, "warn");
    },

    error: function(msg) {
      show(msg, "error");
    },
    
    fatal: function(msg) {
      show(msg, "fatal");      
    },
    
    trace: function(msg) {
      show(msg, "trace");      
    },
    
    custom: function(msg, type) {
      show(msg, type);
    },
    
    getLevel: function(){
      return options.debugLevel;
    }, 

    // Metodi Log4Js e Firebug
    dir: function(val) {
      show(val, "dir");
    },
    
    time: function(val) {
      show(val, "time");
    },
    
    timeEnd: function(val) {
      show(val, "timeEnd");
    },
    
    group: function(val) {
      show(val, "group");
    },
    
    groupCollapsed: function(val) {
      show(val, "groupCollapsed");
    },
    
    groupEnd: function(val) {
      show(val, "groupEnd");
    }, 
    
    profile: function(val) {
      show(val, "profile");
    },
    
    profileEnd: function(val) {
      show(val, "profileEnd");
    },
    
    count: function(msg) {
      show(msg, "count");
    }         

  }
})();

STATUS = (function () {
  var curF = null; // funzione corrente
  var curData = null; // dati correnti (DTO)
  
  var lsDTO = new Array();
  var lsStatus = new Array();
  var lsReply = new Array();

  var bb_count = 0;
  var bb_curr_idx = "";
  var bb_cache = new Array;
  var bb_debug = false;
  var bb_iframe_script = "status.do";
  var bb_iframe_loaded = false;
  var bb_target_div = "";

  function bb_debug_update (str) {
    if (bb_debug) {
      var divBBDebug = $ID("statusDebug");
      $ID("statusDiv").style.display="block";
      $ID("statusFrame").style.display="block";
      if(!divBBDebug) {
        $("<div id='statusDebug'/>").prependTo($ID("Page"));
        divBBDebug = $ID("statusDebug");
      } 
      divBBDebug.innerHTML = divBBDebug.innerHTML + "<br/>" + str;
    }
  }

  // Run from the interval timer (every 1.5 seconds), this function reads a cache index value that 
  // is stored in the DIV element of the child IFRAME.
  // If this extracted cache index differs from the current cache index, then the back button was
  // pressed.  In this case, we pull the corresponding data from the cache and update the page.
  function bb_check_state () {
    if (bb_iframe_loaded == false) {
      return;
    }
  
    var doc =  window.frames['statusFrame'].document;
    var new_idx = doc.getElementById('divFrameCount').innerHTML;
    
    if (new_idx != bb_curr_idx) {
    var debug_msg = "IFRAME changed. Was " + bb_curr_idx + ", now " + new_idx;
  
    // Pull a previous state from the cache (if it exists).
    if (bb_cache[new_idx]) {
      var divBody = $ID(bb_target_div);
      divBody.innerHTML = bb_cache[new_idx];
      _loadS(lsStatus[new_idx]);
    
      debug_msg += " [pulled " + new_idx + " from cache] " + lsStatus[new_idx];
    } else if(bb_cache.length>0){
      //STATUS.init("statusDiv", true);
      HINT.error(i18n.js_status_error);    
      //window.setTimeout("window.location.href=window.location.href", 5000);
      
    }
    bb_curr_idx = new_idx;
    bb_debug_update (debug_msg);
    }
  }

  function bb_loadframe() {
    var bbFrame1 = $ID("statusFrame");
    bb_iframe_loaded = false;
    bbFrame1.src = bb_iframe_script + "?sts=" + bb_count;
  }

  function bb_save_state () {
    var div_to_cache = $ID(bb_target_div);
    bb_count++;
    bb_cache[bb_count] = div_to_cache.innerHTML;
    
    bb_debug_update ("Added " + bb_count + " to cache");
    
    bb_loadframe();
    
    bb_curr_idx = bb_count;
    lsStatus[bb_curr_idx] = $ID(bb_target_div).innerHTML;
    bb_debug_update (bb_curr_idx + "-" + $ID(bb_target_div).innerHTML);
  }

  function _changeVal(v, func, data) {
    $ID(bb_target_div).innerHTML = v;
    if(curF!=func || curData!=data) {
      bb_save_state();
    }
  }

  function _loadS(v) {
    if(lsReply[v]) {
      curF = lsReply[v];
      curData = lsDTO[v];
      A.a01m03(v,function (data){eval(lsReply[v] + "(lsDTO[v])");});
    } else if (bb_debug) {
      LOG.error("errore nel recupero della pagina: " + v);
    }
  }

  return {
    init: function (div_name, debug_val) {
      curF = null;
      curData = null;
      lsDTO = new Array();
      lsStatus = new Array();
      lsReply = new Array();
      bb_count = 0;
      bb_curr_idx = "";
      bb_cache = new Array;
      bb_iframe_loaded = false;
    
      bb_target_div = div_name;
      bb_debug = debug_val;
      
      bb_loadframe();
      window.setInterval ('STATUS.checkState()', 1000);
      //bb_save_state ();        
    },

    checkState: function() {
      bb_check_state();
    },

    doneLoading: function () {
      bb_iframe_loaded = true;
    },
      
    store: function(data,func) {
      _changeVal(data.idStatus, func, data);
      if(!data.stored) {
        lsDTO.push(data);
        lsReply.push(func);
      }
      data.stored = true;  
    },
		
		get: function() {
			return [lsStatus,lsReply,lsDTO];
		}  
  };
})();

function statusFrameLoaded() {
  STATUS.doneLoading();
}

TIMEOUT = (function () {
  var warnTimerTimeout; // timeout di sessione
  var timeoutUltimoMinuto; // timeout ultimo minuto della sessione
  var dialog;
  var logoutLink;

  /** dialog che mostra l'avviso di sessione scaduta */
  function dialogTimeout(){
    var msg = "<p>"+i18n.js_timeout_text+"</p><p>"+i18n.js_timeout_text2+"</p>";
    W.d01(function(data){
      logoutLink = data.data;
      DIALOG.simple({
        message: msg,
        buttons: [{ text: i18n.js_btn_continua, handler: logOut }]
      });
    });

  }

  function logOut() {
    window.location = logoutLink;
  }
  
  return {
    /** aggiorna il contatore della scadenza della sessione */
    updateSess: function () {
      window.clearTimeout(warnTimerTimeout);
      warnTimerTimeout = window.setTimeout("TIMEOUT._dialogWarnTimeout()", (TIMEOUT_VALUE-60000));
    },
    
    /** contatore per l'ultimo minuto del timeout di sessione */
    _countdownSessione: function(){
      var tempoRimasto = $ID("countdownvalue").innerHTML - 1;
      if(tempoRimasto===0){
        dialogTimeout();
        DIALOG.close(dialog);
        return;
      }
      $ID("countdownvalue").innerHTML = tempoRimasto;
      timeoutUltimoMinuto = window.setTimeout("TIMEOUT._countdownSessione()", 1000);
    },
    
    /** dialog che mostra l'avviso che la sessione scadrà tra 1 minuto*/
    _dialogWarnTimeout: function(){
      
      var msg = i18n.js_avvisotimeout_text1 
        + " <span id=\"countdownvalue\">60</span> " 
        + i18n.js_avvisotimeout_text2 
        + "! <br/><br/>" 
        + i18n.js_avvisotimeout_text3 
        + ".";
        
      var handleYes = function() {
        DIALOG.close(dialog);
        W.d00(function(){
          window.clearTimeout(timeoutUltimoMinuto);
          TIMEOUT.updateSess();
        });
      };
      
      dialog = DIALOG.simple({
        title: i18n.js_avvisotimeout_title,
        message: msg,
        handler: handleYes,
        width: "400px" 
      });
      
      TIMEOUT._countdownSessione();
    }      
  };
})();

WIDGET = (function () {
  /** introdotto per evitare memory-leak (prima era richiamato come funzione anonima) */
  function widgetDragDropEvent() {
    var lWidgets = ""; 
    var rWidgets = "";
    var lWElements = $ID("ol_pageleftcontent").childNodes;
    var rWElements = $ID("ol_pagerightcontent").childNodes; 
    var i;
    for(i=0; i < lWElements.length; i++) {
      lWidgets = lWidgets + lWElements.item(i).firstChild.getAttribute("id") + ",";         
    }
    for(i=0; i < rWElements.length; i++) {
      rWidgets = rWidgets + rWElements.item(i).firstChild.getAttribute("id") + ",";              
    }
    
    W.d122(lWidgets.substr(0, lWidgets.length-1), rWidgets.substr(0, rWidgets.length-1));
    return true;
  }
  
  return {
    /** inserisce nella pagina i widget necessari */
    genera: function (idColonna, lsWidgets){
      var d = $ID(idColonna).firstChild;
      
      var oldWidgets = document.createElement("div");
      oldWidgets.className = "hidden";
      document.body.appendChild(oldWidgets);
      
      var widgets = d.childNodes
      for (var i = (widgets.length - 1); i >= 0; i--) {
        var widget = widgets[i];
        if(widget.id !== '' && widget.id !== null) {
          oldWidgets.appendChild(widget);
        }
      }

      // per nascondere le colonne che non hanno widget
      showColumn(idColonna, lsWidgets.length !== 0);

      new YAHOO.util.DDTarget("ol_" + idColonna);
      var DDWdgs = []; 

      for( var x = 0; x < lsWidgets.length; x++){
        var lsWidget = lsWidgets[x];
        
        var oldWidget = document.getElementById("li" + lsWidget.id);
        if (oldWidget 
            && oldWidget.getAttribute('freeze') == 'Y') {
          d.appendChild(oldWidget);
        } else {
          oldWidget = document.createElement('li');
          oldWidget.id = 'li' + lsWidget.id;
          oldWidget.className = 'widget-block';
          oldWidget.setAttribute('freeze', lsWidget.freeze);

          if(lsWidget.showload == 'N'){
            oldWidget.style.display = "none";      
            oldWidget.setAttribute('showload', 'N');
          }
          
          var nodo = document.createElement('div');
          nodo.id = lsWidget.id;
          nodo.innerHTML = lsWidget.title;
          oldWidget.appendChild(nodo);
          d.appendChild(oldWidget);

          W.m00(lsWidget.id, w01m00);          
        }
              
        // DDWidget
        DDWdgs[x] = new YAHOO.sebyou.DDList(oldWidget);
        DDWdgs[x].setHandleElId(lsWidget.id + "_header");
        DDWdgs[x].on('dragDropEvent', widgetDragDropEvent);
        // DDWidget end 

      }

      UTIL.purgeNode(oldWidgets);
      delete oldWidgets;
    }

  };
})();  

GALLERY = (function () {
  return {
    query: function (query) {
      var fields = query.split("@");
      var params = new Object();
      for(var i=0; i<fields.length-1; i++) {
        params[fields[i].split(":")[0]] = fields[i].split(":")[1];
      }
      params["idFiltro"] = "galleria";
      A.a10m04(params, getCheckedValue(document.ricerca.biblioradio), R.b13);
    },
    
    search: function (id) {
      W.m02(id, RENDERING.html);
    },
    
    init: function () {
      $gi = $("#galleria_immagini");
      
      $gi.find(".gi_elemento").each(function(index) {
         $(this).hover(function() {
            $(this).animate( { backgroundColor: "#FFF3DD" }, 400).css("border", "1px solid orange");
         }, function() {
            $(this).animate( { backgroundColor: "#F7F8FC" }, 400).css("border", "1px solid #EFEFEF"); 
         });
      });
      
      $gi.find(".gi_nav_elemento").each(function(index) {
         $(this).hover(function() {
            $(this).animate( { backgroundColor: "orange" }, 300);
         }, function() {
            $(this).animate( { backgroundColor: "#F7F8FC" }, 300);
         });
      });
    }
        
  };
})();

LISTMANIA = (function () {
  var lastBibliografia; // identificativo dell'ultima Bib0 selezionata

  return {
    last: lastBibliografia,

    /** mostra le etichette delle Bib0 sulle liste documenti */
    show: function(progrDoc,dat){
      var result = "";
      if(dat!=null){
        for(z=0;z<dat.length;z++){
          for(n=0;n<cfgMieListe.liste.length;n++){
            if(dat[z]==cfgMieListe.liste[n].id){
              result += '<span id="l_' + progrDoc + '_' + cfgMieListe.liste[n].id + '" class="lsBib0" style="color: ' + cfgMieListe.liste[n].color + ';">- ' + cfgMieListe.liste[n].cd + '</span> ';   
            }
          }
        }  
      }
      return result;
    },
    
    /** abilita/disabilita l'inserimento di un documento nell'ultima bib0 selezionata */
    enableAdd: function(){
      for(i=firstDocList;;i++){
        if($ID('addListmania_' + i)){
          if($ID('l_' + i + "_" + LISTMANIA.last)){
            $ID('addListmania_' + i).style.display="none";
          } else {
            $ID('addListmania_' + i).style.display="inline";
          }
        } else {
          break;
        }
      }
    },

    /** dialog per la scelta della lista in fase di inserimento documento */
    d70: function(progrTitolo){
      var data = new Object();
      data.html = '<form id="mieliste" name="mieliste">';
      data.html += '<table id="infoDocDialog"><tr>';
      
      var titolo;
      var autore;
      var altridati;
      var copertina;
      if($("#listadocumenti_" + progrTitolo).length>0) {
        copertina = $("#listadocumenti_" + progrTitolo + " .copertina");
        titolo = $("#listadocumenti_" + progrTitolo + " .titololistarisultati");
        autore = $("#listadocumenti_" + progrTitolo + " .autorelistarisultati");
        altridati = $("#listadocumenti_" + progrTitolo + " .testolistarisultati");
      } else {
        copertina = $(".copertina");
        titolo = $(".titololistarisultati");
        autore = $(".autorelistarisultati a");
      }
      if(copertina.length > 0) {
        data.html += '<td class="copertina" width="1%">' + copertina[0].innerHTML + '</td>';
      }
    
      data.html += '<td width="99%">';
    
      if(titolo.length > 0) {
        data.html += '<div class="titololistarisultati">' + titolo[0].innerHTML + '</div>';
      }
      
      if(autore.length > 0) {
        data.html += '<div>' + autore[0].innerHTML + '</div>';
      }
    
      if(altridati !=null && altridati.length > 0) {
        data.html += '<div class="testolistarisultati">' + altridati[0].innerHTML + '</div>';
      }
      
      data.html += '</td></tr></table>';
    
      data.html += "<p class='tagwarnarea'>" + i18n.js_listmania_giornodopo + "</p>";
    
      var select = "";
      var count = 0;
      if(cfgMieListe.liste.length>0){
        select += '<div style="margin-bottom: 1em;">' + i18n.js_listmania_aggiungidoc + ': <select id="listaSelezionata">';
        for(n=0;n<cfgMieListe.liste.length;n++){
          if($ID('l_' + progrTitolo + "_" + cfgMieListe.liste[n].id)){
            continue;
          }
          count++;
          select += '<option value="' + cfgMieListe.liste[n].id + '" style="color:' + cfgMieListe.liste[n].color + '"';
          if(LISTMANIA.last==cfgMieListe.liste[n].id){
            select += ' selected="selected"';
          }
          select += '>' + cfgMieListe.liste[n].ds + '</option>';
        }
        select += '</select></div>';
      }
      if(count>0){
        data.html += select;
      }
      data.html += '<div style="margin-bottom: 1em;"><a href="#" onclick="LISTMANIA.nuova(); return false;">' + i18n.js_listmania_aggiungilista + '</a></div></form>';
      
      var handleCancel = function() {
        DIALOG.close(dialog);
      };  
      
      var handleConfirm = function() {
        var nform = document.mieliste;
        if(nform && nform.titoloBib0){
          var cdBib0 = nform.titoloBib0.value;
          var dsBib0 = nform.dsBib0.value;
          var statoBib0 = getCheckedValue(nform.statoBib0);
          
          if (DIALOG.Strings.isBlank(cdBib0)) {
            HINT.error(i18n.js_listmania_titolovuoto);
            return;
          } else if (cdBib0.length > 30) {
            HINT.warn(i18n.js_listmania_titololungo);
            return;
          }
          
          W.d72(cdBib0, dsBib0, statoBib0, progrTitolo, function(data){
            LISTMANIA.rd72(data.data, progrTitolo);
            DIALOG.close("d-listmania");
          });
        } else if($ID('listaSelezionata')){
          var idBib0 = $ID('listaSelezionata').value;
          W.d71(idBib0,progrTitolo,function(val){LISTMANIA.rd71(idBib0,progrTitolo);});
          DIALOG.close(dialog);
        } else {
          LISTMANIA.nuova();
        }
      };
      
      var buttons = [{ text:i18n.js_btn_conferma, handler:handleConfirm },
        { text:i18n.js_btn_annulla, handler:handleCancel, isDefault:true }];
      
      var dialog = DIALOG.open({
        id: "d-listmania",
        title: i18n.js_listmania_dialog_titolo,
        html: data,
        buttons: buttons,
        width: "500px"
      });
    },

    /** mostra nel dialog la form per la creazione di una nuova Bib0 */
    nuova: function(){
      var html = i18n.js_listmania_nuovalista_crea + ':<br/><table>'
        + '<tr><td>' + i18n.js_listmania_nuovalista_titolo + ':</td><td><input type="text" name="titoloBib0" size="65"/></td></tr>'
        + '<tr><td>' + i18n.js_listmania_nuovalista_descrizione + ':</td><td><textarea name="dsBib0" cols="40" rows="3"></textarea></td></tr>'
        + '<tr><td>' + i18n.js_listmania_nuovalista_accesso + ':</td><td><input type="radio" value="pubblica" name="statoBib0" checked="checked"/>' + i18n.js_listmania_nuovalista_pubblico + ' <input type="radio" value="privata" name="statoBib0"/>' + i18n.js_listmania_nuovalista_privato + '</td></tr>'
        + "</table>";
      $ID('mieliste').innerHTML=html;
    },
    
    /** applica l'etichetta della nuova Bib0 al documento */
    rd71: function(idBib0, progressivoTitolo){
      UTIL.modifyClassAttribute("addListmania","display","inline");
      LISTMANIA.last = idBib0;
      for( n = 0; n < cfgMieListe.liste.length; n++) {
        if (idBib0 == cfgMieListe.liste[n].id) {
          $ID('l_' + progressivoTitolo).innerHTML += '<span id="l_' + progressivoTitolo + '_' + idBib0 + '" class="lsBib0" style="color: ' + cfgMieListe.liste[n].color + ';">- ' + cfgMieListe.liste[n].ds + '</span> ';
          if (cfgMieListe.liste[n].color)
            UTIL.modifyClassAttribute("addListmania","color","" + cfgMieListe.liste[n].color.replace(";",""));
          if (cfgMieListe.liste[n].ds)
            UTIL.modifyHtmlAttribute("addListmania","title", i18n.js_listmania_add_ultima_title + " " + cfgMieListe.liste[n].ds);
        }
      }
      LISTMANIA.enableAdd();
    },
    
    /** inserisce nell'array delle bib0 la nuova creata e applica l'etichetta della nuova Bib0 al documento */
    rd72: function(data, progressivoTitolo){
      var newBib0 = eval("("+data+")");

      if (cfgMieListe.liste) {      
        cfgMieListe.liste.push(newBib0);
        LISTMANIA.rd71(newBib0.id, progressivoTitolo);
      }
    }    
    
  };
})();

T = (function () {
  var tag4Doc = {}; // tag dell'utente su un documento
  
  function addTagConsigliato(value){
    var oldValue = $.trim($ID("tagfield").value);
    var newValue = "";
    if(oldValue.length == 0) {
      newValue = $.trim(value);
    } else {
      if(oldValue.lastIndexOf(",")==(oldValue.length-1)) {
        newValue = oldValue + " " + $.trim(value);  
      } else {
        newValue = oldValue + ", " + $.trim(value);  
      }
    }
    if(newValue.lastIndexOf(",",0)!=(newValue.length-1)) {
      newValue = newValue + ", ";
    }
    $ID("tagfield").value = newValue;
  }
  
  return {
    /** dialog per i tag */
    rd111: function(data){
      DIALOG.open({
        id: "d-tagview",
        html: data,
        width: "600px"
      });
    },

    /** dialog per l'inserimento di nuovi tag */
    rd112: function(data){
   
      var handleCancel = function() {
        DIALOG.close(this);
      };
      
      var handleConfirm = function() {
        W.d113($ID("progressivoTitolo").value, $ID("tagfield").value, function(){
          HINT.info(i18n.js_taginserito);
          DIALOG.close(dialog);
        });
      };  
    
      var buttons = [{ text:i18n.js_btn_conferma, handler:handleConfirm },
        { text:i18n.js_btn_annulla, handler:handleCancel, isDefault:true }];
        
      var dialog = DIALOG.open({
        id: "d-taginsert",
        html: data,
        buttons: buttons,
        width: "500px"
      });
    
      // Aggiunta per rimuovere le icone materiale ove le copertine siano presenti
      // questo controllo non è fattibile lato server
      $("img[alt='copertina']").load(function() {
        if ($(this).height() < 75) {
          $(this).parents("td").removeClass().addClass("lt_normal copertina");
        }
      });
      
      var normalize = function(str) {
        return str.toLowerCase().normWhiteSpace();
      };
      
      var initTagSugg = function () {
        tag4Doc = {};
        var field = $ID("tagfield").value.split(",");
        for(i = 0; i < field.length; i++) {
          var val = normalize(field[i]);
          if(val.length==0) {
            continue;
          }
          tag4Doc[val] = val;  
        }  
    
        $("#tagsuggarea a").each(function (n, el) {
          var valHTML = normalize(this.innerHTML);
          if(tag4Doc[valHTML] == valHTML) {
            $(this).parents("span").addClass("tagconsigliatosel");
          } else {
            $(this).parents("span").removeClass("tagconsigliatosel");
          }
        });  
      };
    
      initTagSugg();
      
      $("#tagfield").keyup(function (el){
        initTagSugg();
      });
    
      $("#tagfield").autocomplete({ 
        source: function (terms) {
            var r;
            W.d114(terms.normWhiteSpace(), { async: false, callback: function(s){ r = s; } });
            return r;
          },
        minChars: 3,
        multiple: true,
        multipleSeparator: ", ",
        selectFirst: false,
        parse: parseArray,
        scroll: false,
        delay: 490
      });
      
      $("#tagsuggarea a").click(function(el){
        var valHTML = normalize(this.innerHTML);
        if(tag4Doc[valHTML] == valHTML) {
          $(this).parents("span").removeClass("tagconsigliatosel");
          tag4Doc[valHTML] = "";
          var field = $ID("tagfield").value.split(",");
          var newValue = "";
          for(i = 0; i < field.length; i++) {
            var val = field[i].normWhiteSpace();
            if(val.length==0 || val.toLowerCase() == valHTML) {
              continue;
            }
            newValue += val + ", ";  
          }
          $ID("tagfield").value = newValue;
        } else {
          $(this).parents("span").addClass("tagconsigliatosel");
          tag4Doc[valHTML] = valHTML;
          addTagConsigliato(this.innerHTML);
        }
        return false;
      });
			
      BOL.checkImages();
    }
    
  };
})();

/** selettore biblioteche */
BIBSEL = (function () {
	var biblioradiov = [false,false,false]; // status del radio della selezione delle biblioteche
	var countBibSel = 0; // contatore delle biblioteche selezionate
	var cfgBiblioteche = {};
	var cfgBibliotecheNew = {}; 
	
	return {
		biblioradios: biblioradiov,
		
		count: countBibSel,
		
		init: function(data) {
			cfgBiblioteche = data;
		},

    getConf: function() {
      return cfgBiblioteche;
    },
		
		/** risponde alla selezione del radio della selezione delle biblioteche */
		checkbiblio: function(data){
		  var dataInt = parseInt(data.value, 10);
		  if(dataInt!=2){
		    if(!biblioradiov[dataInt]){
		      BIBSEL.bibliodialog(dataInt);
		    }
		  }
		},
		
		/** invocazione del dialog per la selezione delle biblioteche */
		bibliodialog: function(data){
		  document.ricerca.biblioradio[data+1].checked = true;
		  W.d60(data,BIBSEL.rd60);
		},
		
		/** dialog per selezione delle biblioteche */
		rd60: function(data){

		  var handleCancel = function() {
				cfgBibliotecheNew = {};
        DIALOG.close(this);
		  }; 
		  
		  var handleConfirm = function() {
				cfgBiblioteche = cfgBibliotecheNew;
				var lsSelezionati = $("#lsSelezionate li");
				BIBSEL.count = lsSelezionati.length;
				var ris = [];
				
				for(i=0;i<BIBSEL.count;i++) {
					ris[i] = lsSelezionati.get(i).id.replace("bib_", "");
				}
				
				W.d61(ris,document.formBiblioSel.idLista.value,function (res){
					if(idLista=="0" || idLista =="1") {
						if(res.data === null) {
							if (idLista == "0") {
								$("#linkbibliosel").html(i18n.js_pagesearch_selezionabiblioteche);
							}
							document.ricerca.biblioradio[0].checked = true;
							biblioradiov[idLista] = false;							
						} else if(res.data === 0) {
							if (idLista == "0") {
								$("#linkbibliosel").html(i18n.js_pagesearch_bibliotecheselezionate + " (" + BIBSEL.count + ")");
							}
							biblioradiov[idLista] = true;
						}
					}
		    });				

        DIALOG.close(this);
		  };

      var buttons = [{ text:i18n.js_btn_conferma, handler:handleConfirm, isDefault:true },
        { text:i18n.js_btn_annulla, handler:handleCancel }];

		  var dialog = DIALOG.open({
		    id: "d-biblioteche",
		    html: data,
		    buttons: buttons,
		    width: "800px"
		  });  
		    
      cfgBibliotecheNew = clone(cfgBiblioteche);
      var idLista = document.formBiblioSel.idLista.value;
			var cfgSistemi = cfgBiblioteche.sistemi;
			
		  var sisbiblio;
		  if(cfgSistemi.length==1 && cfgSistemi[0].c==="" && cfgSistemi[0].d===""){
		    sisbiblio = "";
				$("#lblSistemaBibliotecario").hide();
			$('#selSistemaBibliotecario').hide();
		    BIBSEL.switchComboBiblio();
		  } else {
		    sisbiblio = "<ul class='listalink'>";
		    for(i=0 ; i<cfgSistemi.length ; i++){
					var jsFunc = "";
					if(cfgSistemi[i].c=="sistemi_tutti") {
						jsFunc = "BIBSEL.sistemiTutti()";
					} else {
						jsFunc = "BIBSEL.switchComboBiblio()";
					}
					sisbiblio += "<li><input type='checkbox' name='checksistema' onclick='" + jsFunc + "' value='" + i + "'/>" + cfgSistemi[i].d.fromJSON() + "</li>";
		    }
				//sisbiblio += "<li><input type='checkbox' name='checksistema' value='xxx'/>filtra per descrizione <input type='text' size='15' name='dsFilter' onChange='BIBSEL.dsFilter(this.value)'></li>";
		    sisbiblio += "</ul>";  
		  }
		
			$('#selSistemaBibliotecario').html(sisbiblio);
			
			var biblioteche = cfgBiblioteche.biblioteche;
			var res = "";
			
			for(var x in biblioteche){
				if(biblioteche[x].s[idLista]) {
					res += "<li id='bib_" + biblioteche[x].c + "'>";
					res += '<span title="' + i18n.js_bib_rimuovi + '" class="remove" onclick="BIBSEL.removeBibl(\'' + biblioteche[x].c +'\');return false;">&nbsp;</span>';
					res += biblioteche[x].d.fromJSON() + "</li>";
				}
			}

			$("#lsSelezionate ul").html(res);
		},

		sistemiTutti: function() {
			var checksistema = document.formBiblioSel.checksistema;
			
			var selezionato = checksistema[0].checked;
			for (i = 1; i < checksistema.length; i++) {
				checksistema[i].checked = selezionato;
				checksistema[i].disabled = selezionato;
			}				
			
			BIBSEL.switchComboBiblio();
		},
		
		dsFilter: function(val) {
			switchComboBiblio();
		},
		
		/** risponde alla selezione di un sistema bibliotecario dal radio del dialog */
		switchComboBiblio: function(){
			var tmpList = [];
			var checksistema = document.formBiblioSel.checksistema;
			var idLista = document.formBiblioSel.idLista.value;
			
			$ID('PoloBiblio').length = 0;
			
			if(checksistema !== undefined) {
				for (i = 0; i < checksistema.length; i++) {
					if(checksistema[i].checked) {
						var sistema = cfgBiblioteche.sistemi[checksistema[i].value];
						if (sistema !== undefined) {
							for (n = 0; n < sistema.bib.length; n++) {
								tmpList.add(sistema.bib[n].c);
							}
						}
					}
				}				
			} else {
				var biblioteche = cfgBiblioteche.biblioteche;
				for (var x in biblioteche) {
					tmpList.add(biblioteche[x].c);
				}
			}
			
			/*var filter = "";
			var lastCheck = checksistema[checksistema.length-1];
			LOG.info(lastCheck.value +" - "+ lastCheck.checked);
			if(lastCheck.value=="xxx" && lastCheck.checked) {
				filter = document.formBiblioSel.dsFilter.value;
			}*/
	
			for(i=0;i<tmpList.length;i++) {
				var opt = new Option();
				if(tmpList[i]=="biblioteche_tutte") {
					opt.text = i18n.js_bib_tutte;
					opt.value = tmpList[i];
					opt.selected = false;
					UTIL.addOption($ID('PoloBiblio'), opt);
				} else {
					var bib = cfgBibliotecheNew.biblioteche[tmpList[i]];
					if (bib !== undefined) {
						opt.text = bib.d.fromJSON();
						opt.value = tmpList[i];
						opt.selected = bib.s[idLista];
						UTIL.addOption($ID('PoloBiblio'), opt);
						/*if(filter.length>0) {
							if(bib.d.toLowerCase().indexOf(filter.toLowerCase())>=0) {
								opt.text = bib.d.fromJSON();
								opt.value = tmpList[i];
								opt.selected = bib.s[idLista];
								UTIL.addOption($ID('PoloBiblio'), opt);								
							}
						}  else {
							opt.text = bib.d.fromJSON();;
							opt.value = tmpList[i];
							opt.selected = bib.s[idLista];
							UTIL.addOption($ID('PoloBiblio'), opt);
						} */

					}				
				}
			}

		},
		
		/** risponde alla selezione di una biblioteca dalla select del dialog */
		checkBibl: function(){
			var idLista = document.formBiblioSel.idLista.value;
			var fragment = document.createDocumentFragment();
			var li = document.createElement('li');
			var biblioCfg = cfgBibliotecheNew.biblioteche;

			var sel = $ID('PoloBiblio').options;
			
			if(sel[0].value == "biblioteche_tutte" && sel[0].selected) {
				sel[0].selected = false;
				for (i = 1; i < sel.length; i++) {
					sel[i].selected = true;
				}	
			}
			
			for (i = 0; i < sel.length; i++) {
				var opt = sel[i];
				var bib = biblioCfg[opt.value];
				if (bib !== undefined) {
					bib.s[idLista] = opt.selected;
				}
			}
			
			for(var x in biblioCfg){
				var bibx = biblioCfg[x];
				if(bibx.s[idLista]) {
					li.innerHTML = '<span title="' + i18n.js_bib_rimuovi + '" class="remove" onclick="BIBSEL.removeBibl(\'' + bibx.c +'\');return false;">&nbsp;</span> ' + bibx.d.fromJSON();					
					li.id = "bib_" + bibx.c;
					fragment.appendChild(li.cloneNode(true));
				}
			}
			
			$('#lsSelezionate li').remove();
			$('#lsSelezionate ul').append(fragment);
		},
		
		removeBibl: function (val) {
			var sel = $ID('PoloBiblio').options;

			for (i = 0; i < sel.length; i++) {
				if(sel[i].value==val) {
					sel[i].selected = false;	
				}
			}
			var idLista = document.formBiblioSel.idLista.value;
			cfgBibliotecheNew.biblioteche[val].s[idLista] = false;
			
			BIBSEL.checkBibl();
		}		
	};
})();

OS = (function () {
  var count = 1;
  
  return {
    init: function(data) {
      $ID(data.name).innerHTML = data.html;
			OS.rExecute(data);
    },
    
    execute: function(data) {
      var terminata = true;
      var nDoc = 0;

      for(i=0; i<data.ricerche.length; i++) {
        var ricerca = data.ricerche[i];
        
        if(ricerca.ndoc==-1) {
          $("#fedndoc_" + ricerca.cdRisorsa + " a").html('<img width="15" src="sebinayou/temi/common/img/wanime_spacer.gif" alt="immagine caricamento" id="wimageZone"/>');
          terminata = false;
        } else if (ricerca.ndoc==-2) {
          // risorsa in errore
          $("#fedndoc_" + ricerca.cdRisorsa + " a").html("0");
        }  else {
          if(data.accorpa) {
            nDoc += ricerca.ndoc;
            $("#wopensearchaccorpa a").html("" + nDoc);
          } else {
            $("#fedndoc_" + ricerca.cdRisorsa + " a").html("" + ricerca.ndoc);
            $("#fedndoc_" + ricerca.cdRisorsa + " a").attr("href",ricerca.urlScheda);            
          }
        }
      }

      if(!terminata) {
        setTimeout(function(){
					W.d230(OS.rExecute);
				}, 1000 * ++count);
      } else {
        if(data.accorpa) {
          $("#wopensearchaccorpaincorso").hide();
        }
      }
    },
    
    rExecute: function (data) {
      var jsData = data.data;
      if(jsData!==null && jsData.ricerche!==null) {
        OS.execute(jsData);  
      }      
    }
  };
})();

GBOOK = (function () {
  var books = {};
  var countBlock = -1;
  
  function setCover(book) {
    $("img[data='" + book.bib_key + "'][!analyzed]").each(function() {
      $(this).attr("analyzed", "true");
      if(book.thumbnail_url !== null) {
        $(this).attr("src", book.thumbnail_url);  
      }
    });
  }
  
  function setService(book) {
    $(".googleBooks[isbn='" + book.bib_key + "']").each(function() {
      if($(this).attr("service")==="preview" && book.preview!="noview") {
        $(this).html("<a title='" + i18n.js_gbook_preview + "' href='" + book.preview_url + "' target='_blank'><img src='http://www.google.com/intl/en/googlebooks/images/gbs_preview_sticker1.png'/></a>");
        $(this).show();
      }
      if($(this).attr("service")==="info") {
        $(this).html("<a title='" + i18n.js_gbook_info + "' href='" + book.info_url + "' target='_blank'>Google Book</a>");
        $(this).show();
      }
    });
  }
  
  function call(gBookElements, fn) {
    if (gBookElements.length === 0) {
      return;
    }
    
    var lsIsbn = "";
    gBookElements.each(function() {
      if(fn=="GBOOK.replyService") {
        var book = books[$(this).attr("isbn")];
        if(book === undefined) {
          lsIsbn += $(this).attr("isbn") + ",";
        } else {
          setService(book);
        }
      } else if(fn=="GBOOK.replyCover") {
        var book = books[$(this).attr("data")];
        if(book === undefined) {
          lsIsbn += $(this).attr("data") + ",";
        } else {
          setCover(book);
        }
      }      
    });  

    if(lsIsbn !== "") {
      var jsonScript = document.getElementById("GoogleBooksearch_" + (++countBlock));
      if (jsonScript) {
        jsonScript.parentNode.removeChild(jsonScript);
      }
          
      var scriptElement = document.createElement("script");
      scriptElement.setAttribute("id", "GoogleBooksearch_" + countBlock);
      scriptElement.setAttribute("src", "http://books.google.com/books?bibkeys=" + lsIsbn + "&jscmd=viewapi&callback=" + fn);
      scriptElement.setAttribute("type", "text/javascript");
    
      document.documentElement.firstChild.appendChild(scriptElement);
      
      if(countBlock == 20) {
        countBlock = -1;
      }
      
    } else {
      eval(fn + "();");
    }

  }
  
  return {
    initService: function() {
      call($(".googleBooks"), "GBOOK.replyService");
    },
    
    initCover: function() {
      call($("img[from='google'][!analyzed]"), "GBOOK.replyCover");
    },

    replyCover: function(booksInfo) {
      for (i in booksInfo) {
        var book = booksInfo[i];
        books[book.bib_key] = book;
        setCover(book);
      }
      
      $("img[from='google'][analyzed='true']").each(function(i) {
        var src = $(this).attr("src");
        if(src.isEmpty()) {
           UTIL.purgeNode(this);
        } 
      });
    },

    replyService: function(booksInfo) {
      for (i in booksInfo) {
        var book = booksInfo[i];
        books[book.bib_key] = book;
        setService(book);
      }
    }

  };
})();

RENDERING = (function (){

	/** genera la barra di navigazione fra pagine */
	function generaPageNavigator(pageNavigator){
	  var t = '';
	  if(pageNavigator.length>0){
	    t = t + '<table width="100%" style="border-collapse: collapse;">';
	    t = t + '<tr><td class="pagenavigator"><table><tr><td>';
	    if($.browser.msie || $.browser.mozilla) {
	      t = t + '<img src="sebinayou/img/icon_separator.gif" /> <span><a href="#" onclick="history.back();return false;">&laquo;</a></span> <img src="sebinayou/img/icon_separator.gif" />';    
	    }
	    for(i=0;i<pageNavigator.length;i++){
	      if(pageNavigator[i]!==null){
	        t = t + '<img src="sebinayou/img/icon_separator.gif" /> <span><a href="#" onclick="' + pageNavigator[i].action + ';return false;">' + pageNavigator[i].label + '</a></span> <img src="sebinayou/img/icon_separator.gif" />';      
	      } 
	    }
	    t = t + '</td></tr></table></td></tr></table>';
	  } else {
	    t = t + '&nbsp';
	  }
	  var elem = $ID('pagenavigator');
	  if(elem.firstChild){
	    UTIL.purgeNode(elem.firstChild);
	  }
	  elem.innerHTML=t;
	}
		
	return {
		html: function(data, f) {
		  if (data.error) {
	      if (i18n[data.error]) {
          HINT.error(i18n[data.error]);
        } else {
          HINT.error(data.error);
        }
		  }

      if(data.idDom) {
        var node = $ID(data.idDom);
		    if(!node) return;

	      node.innerHTML = data.html;

        setPostProcessing(data);
		  }

		  TIMEOUT.updateSess();
		  if (typeof f == "function") { f(); };
		},
		
    widget: function(data) {
      w01m00(data);
    },
		
		rBody: function(data, f) {
		  STATUS.store(data,"RENDERING.rBody");
		  RENDERING.body(data, f);			
		},
		
		body: function(data, f) {
		  if (data.error) {
	      if (i18n[data.error]) {
	        HINT.error(i18n[data.error]);
	      } else {
	        HINT.error(data.error);
	      }
        return;
		  } else if(data.html) {
	      UTIL.purgeNode($ID('pagecentercontent').firstChild);
	      $ID('pagecentercontent').innerHTML = data.html;  
      }
      
	    WIDGET.genera('pageleftcontent', data.widgetLeft);
	    WIDGET.genera('pagerightcontent', data.widgetRight);

	    if(data.pageNavigator) {
	      generaPageNavigator(data.pageNavigator);
	    }
	    
      GBOOK.initService();
			
      BOL.checkImages();

		  TIMEOUT.updateSess();
		  
		  if (data.alert) {
	      if (i18n[data.alert]) {
	        HINT.info(i18n[data.alert], { hideTime: 8000 });
	      } else {
	        HINT.info(data.alert, { hideTime: 8000 });
	      }
		  }
		  
		  if (typeof f == "function") {f();}
		}
  };
})();	

/** 
 * @deprecated usare RENDERING.html(data) 
 */
function htmlRendering(data) {
	RENDERING.html(data);
}

/** 
 * @deprecated usare RENDERING.rBody(data,func) 
 */
function rBodyRendering(data, func){
	RENDERING.rBody(data, func);
}

/** 
 * @deprecated usare RENDERING.body(data) 
 */
function bodyRendering(data){
	RENDERING.body(data);
}

PSEARCH = (function () {
  return {
    testoRicerca: function(){
      return document.ricerca.frase.value;
    },

    /** inizializza la sezione pagesearch */
    init: function(){
      TIMEOUT.updateSess();
      oSplitButton1 = new YAHOO.widget.Button("splitbutton1", { 
                                                type: "split",   
                                                menu: "splitbutton1select",
                                                title: null }); 
      
      if ($ID("splitbutton1")) {
        oSplitButton1.on("selectedMenuItemChange", function(e) {
          oSplitButton1.set("label", e.newValue.srcElement.innerHTML);
        });
      }
      
      $E.on(document.ricerca, "submit", preventDefault);    
      YAHOO.widget.Button.addHiddenFieldsToForm(document.ricerca);
      if($ID("linkbibliosel")!==null){    
        if(BIBSEL.biblioradios[0]){
          $ID("linkbibliosel").innerHTML = i18n.js_pagesearch_bibliotecheselezionate + " (" + BIBSEL.count + ")";
        } else {
          $ID("linkbibliosel").innerHTML = i18n.js_pagesearch_selezionabiblioteche;    
        }
      }
    
      $(".canaleunico").hover(function(){ $(".canaleunico").addClass("canaleunico_attivo"); },
          function() { $(".canaleunico").removeClass("canaleunico_attivo"); });
      $(".canaleunico").autocomplete({ 
          source: returnTerms,
          minChars: 3,
          multiple: true,
          multipleSeparator: " ",
          selectFirst: false,
          parse: parseArray,
          scroll: false,
          delay: 490
      });
      
      // Selezione singola per le biblioteche
      var biblioss = $("#pagesearch .biblioss");
      if (biblioss.size() == 0) return;
        
      var conf = BIBSEL.getConf();
      var biblioteche = conf.biblioteche;
      var sistemi = conf.sistemi;
      
      var input = biblioss.find("input[type='text']");
      var btn = biblioss.find("input[type='button']");
      
      input.autocomplete({ 
        source: function (terms) {
          var result = new Array();
          
          for (code in biblioteche) {
            var biblioteca = biblioteche[code];
            
            if (!biblioteca.d) continue;
            var des = biblioteca.d.toLowerCase();
            if (des.indexOf(terms.toLowerCase()) >= 0) {
              result.push({
                label: biblioteca.d,
                value: biblioteca.c
              });
            }
          }

          result.sort(function(bib1, bib2) {
            bib1 = biblioteche[bib1.c];
            bib2 = biblioteche[bib2.c];
            
            if ((!bib1 || !bib1.o) 
                && (!bib2 || !bib2.o)) { 
              return 0;
            } else if (!bib1 || !bib1.o) {
              return -1;
            } else if (!bib2 || !bib2.o) {
              return 1
            } else if (bib1.o > bib2.o) {
              return 1;
            } else if (bib1.o < bib2.o) {
              return -1;
            } else {
              return 0;
            }
          });                
          
          return result;
        },
        minChars: 3,
        multiple: true,
        multipleSeparator: " ",
        selectFirst: false,
        parse: PSEARCH.parse,
        scroll: false,
        delay: 490
      }).focus(function() {
        this.className = "active";
        if (this.value == i18n.js_pagesearch_tuttelebiblioteche) {
          this.value = "";
        }
      }).blur(function() {
        this.className = "";
        if ($.trim(this.value) == "") {
          this.value = i18n.js_pagesearch_tuttelebiblioteche;
          W.d61([], 0);
        }
      }).bind("result", function(e, p) {
        $(this).val(p[0]);
        W.d61([p[1]], 0);
        return false;
      });

      $(document).ready(function() {
        // Genera il markup
        
        var containerDIV = document.createElement("DIV");
        var sistemiUL = document.createElement("UL");
  
        for(var i=0; i<sistemi.length; i++) {
          var sistema = sistemi[i];
  
          if (sistema.c == "sistemi_tutti") {
            if (!conf.sistemitutti) {
              continue;
            } else if (!Strings.isBlank(i18n.js_sistemi_tutti)) {
              sistema.d = i18n.js_sistemi_tutti;
            }            
          }
          
          var sistemaLI = document.createElement("LI");
          var sistemaA = document.createElement("A");
          sistemaA.setAttribute("idSis", sistema.c);
          sistemaA.href = "#";
          sistemaA.innerHTML = sistema.d;
          sistemaLI.appendChild(sistemaA);
  
          sistemiUL.appendChild(sistemaLI);
          
          sistema.bib.sort(function(bib1, bib2) {
            bib1 = biblioteche[bib1.c];
            bib2 = biblioteche[bib2.c];
            
            if ((!bib1 || !bib1.o) 
                && (!bib2 || !bib2.o)) { 
              return 0;
            } else if (!bib1 || !bib1.o) {
              return -1;
            } else if (!bib2 || !bib2.o) {
              return 1
            } else if (bib1.o > bib2.o) {
              return 1;
            } else if (bib1.o < bib2.o) {
              return -1;
            } else {
              return 0;
            }
          });   
  
          var bibliotecheUL = document.createElement("UL");
          for(var j=0; j<sistema.bib.length; j++) {
            var bibSistema = sistema.bib[j];
            
            var biblioteca = biblioteche[bibSistema.c];
            if (!biblioteca) continue;
            
            var bibliotecaLI = document.createElement("LI");
            var bibliotecaA = document.createElement("A");
            bibliotecaA.setAttribute("idBib", bibSistema.c);
            bibliotecaA.href = "#";
            bibliotecaA.innerHTML = biblioteca.d;
            bibliotecaLI.appendChild(bibliotecaA);
            
            bibliotecheUL.appendChild(bibliotecaLI);
          }
  
          sistemaLI.appendChild(bibliotecheUL);
        }
        containerDIV.appendChild(sistemiUL);
  
        var testoSistemi = "<a href='#' onclick='return PSEARCH.cleanBSS()'>";
        testoSistemi += i18n.js_pagesearch_tuttiisistemi + "</a>";
  
        var m = btn.menu({
          content: containerDIV.innerHTML,    
          width: 250,
          maxHeight: 250,
          crossSpeed: 200,
          crumbDefaultText: testoSistemi,
          topLinkText: i18n.js_pagesearch_sistemi,
          backLink: false,
          showSpeed: 300
        });
        
        $(m.getContainer()).bind("select", function(e, p) {
          var input = $("#pagesearch .biblioss input[type='text']");
          input.val(p.text());
          
          var idBib = p.attr("idBib");
          if (idBib) {
            var lista = new Array();
            lista.push(idBib);
            W.d61(lista, 0);
          }
        });
      });
      
    },
    
    cleanBSS: function() {
      var input = $("#pagesearch .biblioss input[type='text']");
      input.val("");
      input.blur();
    },
    
    parse: function(data) {
      var parsed = new Array();;
      if (data != null) {
        for (var i=0; i < data.length; i++) {
          parsed.push({
            data: [data[i].label, data[i].value],
            value: data[i].label,
            result: data[i].value
          });
        }
      }
      return parsed;
    },    
    
    /** testa se il valore immesso nel canale di ricerca è valido */
    testFrase: function(){
      if(document.ricerca.frase.value.length===0){
        HINT.help(i18n.js_void);
        return false;
      }
      return true;
    },
    
    /** action da eseguire quando viene premuto il bottone per la ricerca su OpenSearch */
    risorseinreteSUBMIT: function(url){
      if(document.ricerca.frase.value.indexOf(":")>=0){
        HINT.help(i18n.js_pagesearch_os_warncampi);
        return false;
      }
      W.m03(document.ricerca.frase.value,null);
      var url_sysb = url.split("?");
      var sysb = "sysb=";
      if(url_sysb.length>0) {
        sysb = url_sysb[1];
      }
      var str = url_sysb[0] + "/risorse.do?" + sysb + "&from=mainsimple&valore=" + document.ricerca.frase.value + "&campo=parolechiave&ricerca=ricerca";
      for(i = 0;i<document.ricerca.terminilist.length;i++){
        if(document.ricerca.terminilist[i].checked){
        str += "&risorsa=" + document.ricerca.terminilist[i].value;
        }
      }
      window.open(str,'SebinaOpenSearch','scrollbars=yes,resizable=yes,width=800,height=600,status=no,location=yes,toolbar=no');
    },
    
    /** action da eseguire quando viene premuto il bottone per la ricerca sulle risorse web */
    risorsewebSUBMIT: function(){
      var r = document.ricerca;
      YAHOO.widget.Button.addHiddenFieldsToForm(r);
      if(r.risorsa===null) {
        HINT.help(i18n.js_pagesearch_web_selrisorse);
      } else if(r.frase.value.length===0){
        HINT.help(i18n.js_pagesearch_web_campivuoti);
      } else {
        var risorsa = r.risorsa.value;
        var valore = r.frase.value;
        W.m03(valore,null);
        var str = risorsa.replace("$val",valore);
        window.open(str,'RisorseWeb','scrollbars=yes,resizable=yes,width=800,height=600,status=no,location=yes,toolbar=no');
      }
    },
    
    setClump: function(key, value) {
      $("#clump").show();
      var cdCtx = $("#idCanale").val();
      var ctxLbl = ($("#ps_" + cdCtx + " b span").html());
      $("#clumpCtx").html(ctxLbl);      
      $("#clumpKey").html(i18n["js_clump_" + key]);
      $("#clumpValue").html(value);
    },
    
    resetClump: function() {
      $("#clumpKey").html("");
      $("#clumpValue").html("");
      $("#clump").hide();      
    }
  };
})();

CLUMP = (function () {
  var field;
  
  return {
    display: function(idField) {
      field = idField;
      W.d240(idField, CLUMP.render);
    },
    
    render: function(data) {
      
      var handleCancel = function() {
        DIALOG.close(dialog);
      };  
        
      var buttons = [{ text:i18n.js_btn_annulla, handler:handleCancel }];
      var dialog = DIALOG.open({
        id: "d-clump",
        html: data,
        buttons: buttons,
        width: "800px"
      });

      DIALOG.show(dialog);
    },
    
    search: function(value, desc) {
      DIALOG.close("d-clump");
      PSEARCH.setClump(field,desc);
      A.a10m16(field, value, r10);
    },
    
    reset: function() {
      W.d241(PSEARCH.resetClump());
    },
    
    refine: function(value) {
      W.d242(value, field, function(data){
          $('#clumpListContainer').html(data.html);
          DIALOG.refresh();
        });
    },
    
    showWidget: function() {
      $("#liwclump").show();      
    },
    
    hideWidget: function() {
      $("#liwclump").hide();      
    }    
    
  };
})();

UTIL = (function () {
  /** INUTILIZZATO Di norma non è possibile in js recuperare lo stile di un elemento se non è inline */
  function getRule(elm, cssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
      strValue = document.defaultView.getComputedStyle(elm, "").getPropertyValue(cssRule);
    } else if(elm.currentStyle){
      try{
        cssRule = cssRule.replace(/\-(\w)/g, function (strMatch, p1){
          return p1.toUpperCase();
        });
        strValue = elm.currentStyle[cssRule];
      } catch(e){
        // Errore ie5
      }
    }
    return strValue;
  }

  /** INUTILIZZATO riporta le coordinate reali dell'elemento */ 
  function findPosById(idElm) {
    var obj = $ID(idElm);
    var curleft = curtop = 0;
    if (obj.offsetParent) {
      do {
        curleft += obj.offsetLeft;
        curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
      return [curleft,curtop];
    }
  }

  return {
    /** imposta lo stile dell'elemento */
    setRule: function(elm, cssRule, value) {
      elm.style[cssRule] = value;
    },

    /** riporta le coordinate reali dell'elemento */
    findPos: function(elm) {
      var curleft = curtop = 0;
      if (elm.offsetParent) {
        do {
          curleft += elm.offsetLeft;
          curtop += elm.offsetTop;
        } while (elm = elm.offsetParent);
        return [curleft,curtop];
      }
    },

    /** modifica il valore dell'attributo della classe css passata (solo per gli elementi già presenti nella pagina) */
    modifyClassAttribute: function(className,attribute,value) {
      var allHTMLTags=document.getElementsByTagName("*");
      for (i=0; i<allHTMLTags.length; i++) {
        if (allHTMLTags[i].className==className) {
          allHTMLTags[i].style[attribute]=value;
        }
      }
    },

    /** modifica il valore dell'attributo html della classe css passata (solo per gli elementi già presenti nella pagina) */
    modifyHtmlAttribute: function(className,attribute,value) {
      var allHTMLTags=document.getElementsByTagName("*");
      for (i=0; i<allHTMLTags.length; i++) {
        if (allHTMLTags[i].className==className) {
          allHTMLTags[i].setAttribute(attribute,value);
        }
      }
    },

    /** aggiunge un option ad un select */
    addOption: function(selectElement,newOption) {
      // First try the DOM2 method ...
      try {
        selectElement.add(newOption,null);
      }
      // ... And if that doesn't work use the IE-only method
      catch (e) {
        selectElement.add(newOption,selectElement.length);
      }
    },
    
    /** ritorna il primo elemento figlio di quello passato. Esiste la funzione 
      "firstChild" ma Firefox la interpreta male quindi e' stata creata questa */
    getFirstChild: function(element){
      for (j=0; j<element.childNodes.length; j++){
        if (element.childNodes[j].nodeType != 1){
          continue;
        }
        return element.childNodes[j];
      } 
    },
    
    isIE6: function(){
      if (navigator.appVersion.indexOf("MSIE")!=-1){
        var s=navigator.appVersion.split("MSIE");
        var ver=parseFloat(s[1]);
        if(ver<=6){
          return true;
        }
      }
      return false;
    },
    
    /** inserisce un nodo "script" nella sezione head (e' usato da alcuni reply di dwr */
    createScriptNode: function(str,id){
      var head = document.getElementsByTagName('head')[0];
      var oldElement = $ID(id);
      if(oldElement){
        head.removeChild(oldElement);
      }
      var e=document.createElement("script");
      e.id = id;
      e.type = "text/javascript";
      if("text" in e)e.text=str;
      else if("textContent" in e)e.textContent=str;
      else if("innerHTML" in e)e.innerHTML=str;
      else e.appendChild(document.createTextNode(str));
      head.appendChild(e);
      return e;
    },
    
    purgeNode: function(node){
      if (typeof node == 'string')
        node = document.getElementById(node);
              
      if (!node) return;

      $E.purgeElement(node, true);

      if (node.parentNode)
        node.parentNode.removeChild(node);

      if (node.clearAttributes)
        node.clearAttributes();

      try {
        if (node.outerHTML)
          node.outerHTML = '';
      } catch(e) {
        // Chrome bug
      }

      node = null;  
    },
    
    purgeChilds: function(node) {
      if (typeof node == 'string')
        node = document.getElementById(node);
              
      if (node) {
        for(var i=0; i<node.childNodes.length; i++) {
          UTIL.purgeNode(node.childNodes[i]);  
        }
      } 
    }    

  };  
})();

/** carica il js all'indirizzo "sScriptSrc" e a caricamento avvenuto esegue "callbackfunction" */
loadScript = function (sScriptSrc,callbackfunction) {
  var oHead = document.getElementsByTagName('head')[0];
  if(oHead) { 
    var oScript = document.createElement('script');

    // --> IE
    var loadFunction = function() {
      if (this.readyState == 'complete' || this.readyState == 'loaded') {
        callbackfunction(); 
      }
    };
    oScript.onreadystatechange = loadFunction;
    // <-- IE

    // Firefox
    oScript.onload = callbackfunction;

    oScript.setAttribute('src',sScriptSrc + "&" + (new Date().getTime( ).toString( )));
    oScript.setAttribute('type','text/javascript');
    oScript.setAttribute('id','casScript');
    
    var oldScript = $ID("casScript");
    if (oldScript) {
      UTIL.purgeNode(oldScript);
    }
    
    var oldScript = $ID("casScript");
    if(oldScript) {
      LOG.info("replace");
      oldScript.parentNode.replaceChild(oScript,oldScript);
    } else {
      oHead.appendChild(oScript);
    }
    
  }
};

/** crea nella sezione head un elemento style con il contenuto passato.
    presuppone che ci sia solo un elemento style (rimuove il precedente e
    imposta il nuovo) */
function setStyle(cssStr){
  var style = document.createElement("style");
  style.setAttribute("type", "text/css");
  if(style.styleSheet){// IE
    style.styleSheet.cssText = cssStr;
  } else {// w3c
    var cssText = document.createTextNode(cssStr);
    style.appendChild(cssText);
  }
  var head = document.getElementsByTagName('head')[0];
  var el = document.getElementsByTagName('style')[0];
  head.removeChild(el);
  head.appendChild(style);
  
  ROLLBANNER.start();
}

function reviewsHtmlRendering(data) {
  RENDERING.html(data);
  setReviews();
}

function setReviews() {
	/** $NAME('reviewPage').length non funziona con IE, perciò sono costretta a fare questo pezzetto... 
	var contatoreReviews = 0;
	var reviewPages = document.getElementById("reviews").getElementsByTagName("div");
  for (i = 0; i < reviewPages.length; i++) {
    if (reviewPages[i].getAttribute("name") == "reviewPage") {
      contatoreReviews++;
    }
  }
  */
  
  var contatoreReviews = $("#reviews div[name='reviewPage']").size();
  
	/** fine conteggio recensioni */
  YAHOO.sebyou.reviews = YAHOO.util.Dom.get('reviews'); 
	YAHOO.sebyou.reviews.paginator = new YAHOO.widget.Paginator({ 
    rowsPerPage : 1 , 
    totalRecords : contatoreReviews , 
    containers : 'paging' ,
    firstPageLinkLabel : '&lt;&lt;' , 
    previousPageLinkLabel : '&lt;' , 
    nextPageLinkLabel : '&gt;' ,
    lastPageLinkLabel : '&gt;&gt;' 
	}); 
	YAHOO.sebyou.reviews.handlePagination = function (state) { 
    YAHOO.sebyou.reviews.className = 'page' + state.page; 
    YAHOO.sebyou.reviews.paginator.setState(state); 
    $ID('myReviewActions').style.display=state.page==1?'':'none';
	}; 
  $E.on('cancellaReview', 'click', function() {
    var reviewDialog = DIALOG.simple({
      title: i18n.js_review_delete_title,
      message: i18n.js_review_delete,
      handler: function() {
        A.a20m13(reviewsHtmlRendering);
        if (YAHOO.util.Dom.get('reviews').paginator.getTotalRecords()==1) {
          removeActiveTabDocument();
        }
        $ID('newReview').style.display='';
        DIALOG.close(reviewDialog);
      }
    });
  });
	YAHOO.sebyou.reviews.paginator.subscribe('changeRequest', YAHOO.sebyou.reviews.handlePagination); 
	YAHOO.sebyou.reviews.paginator.render(); 
  $ID('paging').style.display=YAHOO.sebyou.reviews.paginator.getTotalRecords()>1?'':'none';
  if (YAHOO.sebyou.reviews.paginator.getTotalRecords()==0) {
    removeActiveTabDocument();
  }
}

function renderHtmlEditor(id) {
  if (typeof id == "undefined") id = "editor";
  
  A.a20m11(function(data) {
    RENDERING.html(data);
  
    $('#' + id).tinymce({
      script_url : 'sebinayou/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
      theme : "advanced",
      plugins : "safari,spellchecker,layer,table,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras",
      theme_advanced_buttons1 : "fullscreen,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,link,unlink,anchor,image,media",
      theme_advanced_buttons2 : "formatselect,fontselect,fontsizeselect,|,bold,italic,underline",
      theme_advanced_buttons3 : "justifyleft,justifycenter,justifyright,justifyfull,|,outdent,indent,|,bullist,numlist,|,forecolor,backcolor",
      theme_advanced_toolbar_location : "top",
      theme_advanced_toolbar_align : "left",
      theme_advanced_statusbar_location : "bottom",
      theme_advanced_resizing : true,
      language : "it",
      width : "100%"
    });
    
    $('#confermaEditor').click(function(e) {
      A.a20m12($('#' + id).tinymce().getContent(), reviewsHtmlRendering);
    });
    
    $('#annullaEditor').click(function(e) {
      A.a20m12('', reviewsHtmlRendering);
      if ($('#userReview').size() == 0) {
        $('#newReview').show();
      }
    });
  });
}

function addReview(docCur, tabLabel) {
  addTabDocument(tabLabel, 'tabreview'); 
  $ID('newReview').style.display='none'; 
  renderHtmlEditor(); 
}

function removeActiveTabDocument() {
  var tabView = new YAHOO.widget.TabView('tabdocument');
  tabView.removeTab(tabView.get('activeTab'));
  tabView.set('activeIndex', 0); 
}

function addTabDocument(tabLabel, tabContentId) {
  var tabView = new YAHOO.widget.TabView('tabdocument');
  var tabHRef = "#" + tabContentId;
  if (!$ID(tabContentId)) {
    var tabContent = '<div id="' + tabContentId + '"></div>';
    myTab = new YAHOO.widget.Tab({ label: tabLabel, content: tabContent, href: tabHRef, active: true }) ;
    tabView.addTab(myTab);
  } else {
    for (var i = 0; i < tabView.get('tabs').length; i++) { 
      if (tabView.get('tabs')[i].get('href') == tabHRef) { 
        tabView.set('activeIndex', i); 
        break; 
      } 
    } 
  }
}

/** commenti documento: accende-spegne le stelline a seconda del rating scelto */
function refreshStars(voto) {
  $("#idRating").val(voto);
  for(var i=1; i<=5; i++) {
    if (voto >= i) {
      $("#idStar"+i).attr("src", "sebinayou/temi/common/img/star-on.png");
    } else {
      $("#idStar"+i).attr("src", "sebinayou/temi/common/img/star-off.png");
    }	
  }  
}

/** lista risultati: mostra tutte le localizzazioni */
function mostraTutteLocalizzazioni(progrDoc, numLoc, numVis){
  for(i=numVis;i<numLoc;i++){
    $ID("loc_" + progrDoc + "_" + i).style.display = '';
  }
  $ID("loc_" + progrDoc + "_" + numLoc).style.display = 'none';
}

/** action da eseguire quando viene premuto il bottone per la ricerca dal bollettino novità */
function bollettinoSUBMIT(){
    var searchParamMap = new Object();
    for(i=0;i<document.formBollettino.elements.length;i++){
      if(document.formBollettino.elements[i].value!='' && document.formBollettino.elements[i].name!='submit'){
        searchParamMap[document.formBollettino.elements[i].name] = document.formBollettino.elements[i].value;
      }
    }
    A.a10m04(searchParamMap,getCheckedValue(document.ricerca.biblioradio),r10);
}

function getKindOfList(){
  YAHOO.widget.Button.addHiddenFieldsToForm(document.ricerca);
  if(document.ricerca.kindOfList==null) {
    HINT.help(i18n.js_pagesearch_liste_selezionalista);
    return '';
  }
  return document.ricerca.kindOfList.value;
}

/** ritorna il valore di un oggetto radio */
function getCheckedValue(radioObj) {
  if(!radioObj)
    return "";
  var radioLength = radioObj.length;
  if(radioLength == undefined)
    if(radioObj.checked)
      return radioObj.value;
    else
      return "";
  for(var i = 0; i < radioLength; i++) {
    if(radioObj[i].checked) {
      return radioObj[i].value;
    }
  }
  return "";
}

/** nasconde/visualizza le colonne laterali */
function showhideColumn(e){
  if (!document.getElementById) return;
  if (UTIL.isIE6()) return;
  
  var $e = $("#" + e);
  var $o = $('#pagenavigator, #pagecentercontent'); 
  
  if ($e.css("display") == "none") {
    if (e == 'pageleftcontent') {
      if (typeof leftMargin == "undefined") return;
      $e.show("drop", { direction: 'left' }, 200, function() {
        $o.animate( { marginLeft: leftMargin } );
        UTIL.getFirstChild($ID('LeftArrowColumn')).className="bottonefrecciasinistra";
      });
   } else if(e == 'pagerightcontent') {
      if (typeof rightMargin == "undefined") return;
      $e.show("drop", { direction: 'right' }, 200, function() {
        $o.animate( { marginRight: rightMargin } );
        UTIL.getFirstChild($ID('RightArrowColumn')).className="bottonefrecciadestra";
     });
   }
   
  } else {
    if (e == 'pageleftcontent') {
      leftMargin = $o.css("marginLeft");
      $e.hide("drop", { direction: 'left' }, 200, function() {
        $o.animate( { marginLeft: '12px' } );
        UTIL.getFirstChild($ID('LeftArrowColumn')).className="bottonefrecciadestra";    
      });      
    } else if (e == 'pagerightcontent') {
      rightMargin = $o.css("marginRight");
      $e.hide("drop", { direction: 'right' }, 200, function() {
        $o.animate( { marginRight: '12px' } );
        UTIL.getFirstChild($ID('RightArrowColumn')).className="bottonefrecciasinistra";
      });
    }
  }
}

/** 
* Mostra una colonna dei widget
* c = elemento DOM della colonna
*  
*/
function showColumn(column,view){
  var $e = $("#" + column);
  if (view == false && $e.css("display") != "none") {
    showhideColumn(column);
  } else if (view == true && $e.css("display") == "none") {
    showhideColumn(column);
  }
}

function showhide(value){
	$this = $("#"+value + " .corpo");
    $this.parents("li:eq(0)").css("overflow", "hidden");
	var dsp = ($this.css("display")); 
	var ldn = ($this.attr("loading"));
	
	if (dsp == "none" || dsp == '') {
        if (ldn == "true") return;
        var h = $this.attr("or_height");
        $this.attr("loading", "true")
            .animate( { height: h+"px" }, "slow", function() {
        	   $this
        	   .css("display", "block")
        	   .removeAttr("loading")
        	   .removeAttr("or_height");
        });
	} else {
		if (ldn == "true") return;
		$this.attr("or_height", $this.height())
            .attr("loading", "true")
            .animate( { height: "0px" }, "slow", function() {
                $this.css("display", "none")
                .removeAttr("loading");
            });
	} 
    $("#"+value + "titolo").toggleClass("bottoneridimensionapiu");
}

function showhide2(value){
  if (document.getElementById){
   target = $ID("det" + value);
     if (target.style.display == "none"){
       target.style.display = "block";
     } else {
       target.style.display = "none";
     }
  }
  return false;
}

function showhidetab(scheda,record){
  if (document.getElementById){
   target = document.getElementById("det" + value);
     if (target.style.display == "none"){
       target.style.display = "block";
     } else {
       target.style.display = "none";
     }
  }
  return false;
}

function showhidetop(value1,value2){
  if (document.getElementById){
   target = document.getElementById(value1);
     if (target.style.display == "none"){
       target.style.display = "block";
     } else {
       target.style.display = "none";
     }
  }

   target = document.getElementById(value2);
     if (target.style.display == "none"){
       target.style.display = "block";
     } else {
       target.style.display = "none";
     }

   target = document.getElementById("tab" + value1 + "act");
   target.style.display = "inline";
   target = document.getElementById("tab" + value1);
   target.style.display = "none";

   target = document.getElementById("tab" + value2 + "act");
   target.style.display = "none";
   target = document.getElementById("tab" + value2);
   target.style.display = "inline";
}

function lightBox(elements) {
    $(elements).picBox({ attributes: {
      imagePath: "href",
      imageTitle: "ititle",
      imageDescription: "idesc" },
      missing: i18n.js_immagine_mancante });
}

function changeListType(kind) {
  var $lr = $("#listarisultati");
  var $lt_normal = $lr.find(".lt_normal");
  var $lt_extended = $lr.find(".lt_extended");
  var $lt_image = $lr.find(".lt_image");
  var $lt_changer = $("#lt_changer a");

  if (!oldListType) {
    oldListType = $lt_changer.attr("old");
  }

  if (!kind) return;
  switch (kind) {
    case "normal":
      $lt_normal.show();
      $lt_extended.hide();
      $lt_image.hide();
      listType = 'normal';
      $lt_changer.attr("onclick", "changeListType('" + oldListType + "'); return false;");
      break;

    case "extended":
      $lt_normal.show();
      $lt_extended.show();
      $lt_image.show();
      listType = "extended";
      oldListType = "extended";
      $lt_changer.attr("onclick", "changeListType('normal'); return false;");
      break;

    case "images":
      $lt_normal.find("> div:not(.lt_image)").hide();
      $lt_normal.filter(".copertina,.servizi").hide();
      
      $lt_extended.hide();
      $lt_image.show();
      if ($lt_changer.size() > 0) {
        $lt_changer.remove();
      }
      lightBox(".oggettiDigitali a");
      break;
  }
}

/* override del comportamento di default per oggetti YUI */
function preventDefault(p_oEvent) {
  $E.preventDefault(p_oEvent);
}

function returnTerms(terms) {
	var r;
  W.d130(terms, { async: false, callback: function(s) {
    r = s;
  }});	
  return r;	
}

function parseArray(data) {
  var parsed = [];
	if (data != null) {
    for (var i=0; i < data.length; i++) {
      var row = $.trim(data[i]);
      if (row) {
        row = [data[i], data[i]];
        parsed[parsed.length] = {
          data: row,
          value: row[0],
          result: row[0]
        };
      }
    }
	}
  return parsed;
}

/** ---- MURO --------------------------------------------------------------- */

WallMsg = function() {

  var r = new Object();
  var nMsg = false;
  var $insLink;
  var $insForm;

  function _init(id) {
    $insLink = $("#ilmurolinkinserimento");
    $insForm = $("#ilmuroforminserimento");

    if (id != null && id > 0) { 
      if (r[id] == undefined) {
        r[id] = new Object();
      }
      r[id].$li = $("#wall_head_" + id).parents("li");
      if (r[id].$li.size() > 0) {
        r[id].$titolo = r[id].$li.find(".wall_title_entry");
        r[id].$commento = r[id].$li.find(".wall_comm_entry");
        r[id].$links = r[id].$li.find(".wall_comm_links");
      }
      return r[id];
    }
  }  

  function _insert(titolo, commento) {
    _init();
    if(titolo.length > 0 || commento.length > 0){
      A.a40m01(titolo,commento, function(data){
        
        var result = eval('(' + data + ')');
        if(result != undefined) {
          if (result.err != undefined) {
              HINT.error(result.err);
          } else {
              var id = result.id;
              var li = "<li s='new'>"
                  + "<div id='wall_head_"+id+"' class='wall_head_entry'>"
                  + "<img src=\"sebinayou/temi/common/img/icon_mymessage.png\" onclick=\"WallMsg.edit('"+id+"');\"/>&nbsp;"
                  + "<span class='wall_title_entry'>" + titolo + "</span>&nbsp;"
                  + "<span class='wall_date_entry'>(" + new Date().format("dd-MM-yyyy HH:mm") + ")</span>"
                  + "</div><div class='wall_body_entry'>"
                  + "<div class='wall_comm_entry'>" + commento + "</div>"
                  + "<div class='wall_comm_links'>"
                  + i18n.js_wall_miomessaggio + "&nbsp;"
                  + "<a href='#' onclick=\"WallMsg.edit('"+id+"'); return false;\">" + i18n.js_wall_modifica + "</a>"
                  + "&nbsp;" + i18n.js_wall_miomessaggio2 + "&nbsp;"
                  + "<a href='#' onclick=\"WallMsg.remove('"+id+"'); return false;\">" + i18n.js_wall_cancella + "</a>"
                  + "&nbsp;" + i18n.js_wall_miomessaggio3;
              if (result.stato == "NEW") {
                  li += i18n.js_wall_inapprovazione;
              }    
              li += "</div></div></li>";
              
              $(li).prependTo("#listamuro");
              HINT.info(result.out);
              nMsg = true;
              _clear();
          }        
        } else LOG.error("WallMsg.insert()");
      });
    } else {
      HINT.help(i18n.js_wall_campivuoti);
    }
  }
    
  function _clear(id) {
    if (id != null) {
      var p = _init(id);
      p.$li.removeAttr("edit");
      p.$titolo.html(p.titolo);
      p.$commento.html(p.commento);
      p.$li.find("p").remove();
      p.$links.show();        
    } else {
      if (nMsg == null || nMsg == false) {
        $insLink.show();
      } else if (nMsg == true) {
        $insLink.hide();
      }
      $insForm.hide();
      $insForm.find("input").val("");
      $insForm.find("textarea").val(""); 
    }
  }
    
  function _remove(id) {
    var dialog = DIALOG.simple({
      title: i18n.js_wall_delete_title,
      message: i18n.js_wall_delete,
      handler: function() {
        var p = _init(id);
      
        if (p != null) {
          A.a40m06(id, function(data) {
            var result = eval("("+data+")");
            if (result != undefined) {
                if (result.err != undefined) {
                    HINT.error(result.err);
                } else {
                    var id = result.id;
                    if (p.$li.attr("s") == "new") {
                      nMsg = false;
                      $insLink.show();
                    }
                    p.$li.remove();
                    HINT.info(result.out);
                }
            } else LOG.error("WallMsg.remove()");
          });
        }
        DIALOG.close(dialog);
      }
    });
  }    

  function _edit(id) {
    var p = _init(id);
            
    if (p.$li.size() > 0 && p.$li.attr("edit") == undefined) {
        p.$li.attr("edit", "true")
          .wrap("<form></form>");
        p.titolo = $.trim(p.$titolo.text());
        p.commento = $.trim(p.$commento.text());
        
        p.$titolo.empty().append($("<input type='text'></input>")
          .val(escapeHTML(p.titolo))
          .css("width", "60%"));
        
        p.$commento.empty().append($("<textarea rows=6></textarea>")
          .val(escapeHTML(p.commento))
          .css("width", "90%"))
          .after($("<p></p>")
            .append($("<button type='button'></button>")  
              .addClass("std_btn")
              .text(i18n.js_btn_conferma)
              .click(function(e) { _confirm(id); }))
            .append($("<button type='button'></button>")
              .addClass("std_btn")
              .text(i18n.js_btn_esci)
              .click(function(e) { _clear(id); }))
            .append($("<button type='button'></button>")
              .addClass("std_btn")
              .text(i18n.js_btn_cancella)
              .click(function(e) { _remove(id); })))
            .after($("<p></p>")
              .text($("#wall_help").text()));
            
        p.$links.hide();            
    }
  }
  
  function _confirm(id) {
    var p = _init(id);    
    var titolo = $.trim(p.$li.find("input[type='text']").val());
    var commento = $.trim(p.$li.find("textarea").val());
    
    A.a40m05(id, titolo, commento, function(data) {
      var result = eval("("+data+")");
      if (result != undefined) {
        var q = r[result.id];
        if (result.err != undefined) {
          HINT.error(result.err);
        } else {    
          q.$titolo.html(titolo);
          q.$commento.html(commento);
          q.$li.removeAttr("edit")
            .find("p").remove();
          HINT.info(result.out);
        }
      } else LOG.error("WallMsg.edit()");
      p.$links.show();
    });
  }
  
  function _mark(id) {
    var dialog = DIALOG.simple({
      title: i18n.js_wall_segnala_title,
      message: i18n.js_wall_segnala,
      handler: function() {
        A.a40m03(id, function(data) {
          var data = eval('(' + data + ')');
          $('#wall_segnala_'+data.id).html(data.out + "&nbsp;&nbsp;");
          $('#wall_head_'+data.id)
            .attr('class', 'wall_head_entry_segn')
            .attr('className', 'wall_head_entry_segn');
          $('#wall_body_'+data.id).attr('class', 'wall_body_entry_segn')
            .attr('className', 'wall_body_entry_segn');
          $('#wall_comm_'+data.id).attr('class', 'wall_comm_entry_segn')
            .attr('className', 'wall_comm_entry_segn'); 
        });
        DIALOG.close(dialog);
      }
    });
  }
  
  return {
    
    add: function() { 
     _init();     
     $insLink.hide();
     $insForm.show();
    },
    
    cancelAdd: function() {
      _clear();
    },
    
    insert: function(titolo, commento) {
      _insert(titolo, commento);
    },

    remove: function(id) {
      _remove(id);
    },
    
    edit: function(id) {
      _edit(id);
    },
    
    mark: function(id) {
      _mark(id);
    }
    
  };
}();

/** leggi un commento segnalato nel muro */
function leggiWallSegnalato(id){
  var head = $ID('wall_head_'+id);
  var body = $ID('wall_body_'+id);
  var comm = $ID('wall_comm_'+id);   
  head.setAttribute('class', 'wall_head_entry');
  body.setAttribute('class', 'wall_body_entry');
  comm.setAttribute('class', 'wall_comm_entry');
  head.setAttribute('className', 'wall_head_entry');
  body.setAttribute('className', 'wall_body_entry');
  comm.setAttribute('className', 'wall_comm_entry');
  $ID('leggicommento_'+id).style.display="none";
}

/** ---- FINE MURO ---------------------------------------------------------- */


NEWS = (function () {
  var DIALOG_NAME = "d-news"
  var curListPage = 1;
  var update = false;
  var rollTimer;
  oldNews = -1;
  
  return {
    openDialog: function() {
      A.a100m01(NEWS.renderDialog);
    },
    
    renderDialog: function(data) {
      var handleReset = function() {
        $('#formNews')[0].reset();
      }

      var handleExit = function() {
        DIALOG.close(this);
      }
      
      var handleConfirm = function() {
        $form = $('#formNews');
        
        var p = new Object();
        
        if(data.data) {
          update = true;
          p.id = data.data;
        } else {
          update = false;
        }
        
        var errore = false;
        $form.find("input[type='text'], textarea, select").each(function() {
           var text = $(this).val();
          if (typeof text == "string" && !text.isBlank()) {
            p[this.name] = text;
          } else if (this.name == "TITOLO" || this.name == "DS") {
            $(this).parent("td").addClass("error");
            errore = true;
          }
        });
      
      if (errore) {
        HINT.error(i18n.js_campimancanti);
        return;
      }
        
        A.a100m02(p, function(data) {
          if(data.error !=null) {
            HINT.error(data.error);
          } else {
            HINT.info(i18n.js_news_inserimento_ok);
            DIALOG.close(DIALOG_NAME);
            if(update) {
              NEWS.goToPage(curListPage);  
            } else {
              W.m00("wnews", w01m00);
            }
            
          }
        });
      }
      
      var dialog = DIALOG.open({
        id: DIALOG_NAME,
        html: data,
        buttons: [{ text: i18n.js_btn_conferma, handler: handleConfirm, isDefault: true },
                  { text: i18n.js_btn_reset, handler: handleReset },
                  { text: i18n.js_btn_esci, handler: handleExit }],
        width: "750px",
        visible: false
      });
      
      DIALOG.show(dialog);
      
      var dataObj = new Date();
      $("input[name$='DATADA']").datepicker({
        dateFormat: "dd/mm/yy",
        showOptions: { 
          direction: "up" 
        },
        yearRange: '1910:'+dataObj.getFullYear()+10
      });
      
      $("input[name$='DATAA']").datepicker({
        dateFormat: "dd/mm/yy",
        showOptions: { 
          direction: "up" 
        },
        yearRange: '1910:'+dataObj.getFullYear()+10
      }); 

      $("textarea[name$='TEXT']").tinymce({
        script_url : 'sebinayou/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
        theme : "advanced",
        plugins : "safari,spellchecker,layer,table,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras",
        theme_advanced_buttons1 : "fullscreen,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,link,unlink,anchor,image,media",
        theme_advanced_buttons2 : "formatselect,fontselect,fontsizeselect,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull",
        theme_advanced_buttons3 : "bullist,numlist,|,forecolor,backcolor",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : false,
        language : "it",
        width : "600px"
      });
    },
    
    edit: function(id) {
      A.a100m05(id,NEWS.renderDialog);
    },
    
    list: function() {
      curListPage = 1;
      A.a100m00(rBodyRendering);
    },
    
    goToPage: function(page) {
      curListPage = page;
      A.a100m03(page,rBodyRendering)
    },
    
    detail: function(id) {
      A.a100m04(id,curListPage,rBodyRendering)
    },
    
    del: function(id) {
      DIALOG.simple({
        title: i18n.js_news_dialog,
        message: i18n.js_news_confirmdelete,
        handler: function() {
          A.a100m06(id,rBodyRendering)
          DIALOG.close(this);
        }
      });      
    },
    
    roll: function() {
      var listNews = $("#listNews > div");
      if(listNews.size() > 1) {
        currentNews = (oldNews + 1) % listNews.size();
        if(oldNews>=0) {
          $("#listNews > div:eq(" + oldNews + ")").fadeOut("slow",function(){$("#listNews > div:eq(" + currentNews + ")").fadeIn("slow");});
        } else {
          $("#listNews > div:eq(" + currentNews + ")").show();
        }
        
        oldNews = currentNews
        window.clearTimeout(rollTimer);
        rollTimer = window.setTimeout("NEWS.roll()", 5000);        
      } else {
        $("#listNews > div:eq(0)").show();
      }

    }

  };
})();


/* ---------------------------------------------------  */
/* reply a chiamate DWR  */
/* --------------------------------------------------- */

R = (function () {
  return {
    b01: function(data){
      STATUS.store(data,"R.b01");
      UTIL.createScriptNode(data.script,"js01");
      js01();
      RENDERING.body(data);
      homeTabView = new YAHOO.widget.TabView('htab');
    },

    b12: function(data){
      STATUS.store(data,"R.b12");
      firstDocList = null;
      RENDERING.body(data);

      if(data.mieListe!=null && data.mieListe.length>0){
        var dat = eval('(' + data.mieListe + ')');
        if(dat.l.length>0){
          firstDocList = dat.l[0].id;
        }  
        for(i=0;i<dat.l.length;i++){
          $ID("l_" + dat.l[i].id).innerHTML = LISTMANIA.show(dat.l[i].id,dat.l[i].liste);
        }
        if(LISTMANIA.last==null){
          UTIL.modifyClassAttribute("addListmania","display","none");
        } else {
          LISTMANIA.enableAdd();
          for(n=0;n<cfgMieListe.liste.length;n++){
            if(LISTMANIA.last==cfgMieListe.liste[n].id){
              UTIL.modifyClassAttribute("addListmania","color","" + cfgMieListe.liste[n].color.replace(";",""));
              UTIL.modifyHtmlAttribute("addListmania","title","premi qui per inserire il documento in: " + cfgMieListe.liste[n].ds);
            }
          }    
        }
      }
      window.scroll(0,0);  
    },

    b13: function(data){
      STATUS.store(data,"R.b13");
      r10(data);
      changeListType("images");
    },

    a90: function(result){
      var commento = eval("(" + result.data + ")");
      $ID('comm_utiletot_'+commento.id).innerHTML=commento.out;
      $ID('comm_utile_'+commento.id).innerHTML="";
    },
    
    a91: function(result) {
      var commento = eval("(" + result.data + ")");
      $ID('comm_utile_'+commento.id).innerHTML="";
      $ID('comm_segnala_'+commento.id).innerHTML=commento.out;
      $ID('comm_segnala_'+commento.id).setAttribute('class', 'commentosegnalato');
    },

    a100: function(result) {
      var data = eval("(" + result.data + ")");
      $ID('fasc_'+data.id).innerHTML=data.out;
      $ID('fasc1_'+data.id).innerHTML=data.out2;
      showFasc(data.id);
    },
    
    a101: function(result) {
      if (result.error) {
        HINT.error(result);
      } else if (result.html 
          && result.data) {
        var config = eval("(" + result.data + ")");

        var handleSubmit = function() {
          DIALOG.close(this);
          W.d101(config.polobiblio, config.tipoMovi, config.inv, true, R.a101);          
        }
        
        var handleCancel = function() {
          DIALOG.close(this);                    
        }
        
        var buttons = [ { text: i18n.js_btn_conferma, handler: handleSubmit },
          { text: i18n.js_btn_annulla, handler: handleCancel, isDefault: true } ] 
        
        var dialog = DIALOG.open({
          id: "d-confermaprestito",
          html: result,
          buttons: buttons,
          width: "600px"
        });

      } else {
        DIALOG.simple({
          html:result.data,
          width:'550px'
        });
      }
    },
    
    a102: function(result) {
      $ID(result.idDom).innerHTML=result.html;
      showDivId(result.idDom + '_chiudi');
      showDivId(result.idDom);
      hideDivId(result.idDom + '_apri');
    },
    
    a103: function(result) {
      DIALOG.simple({
        title:result.data,
        message:result.html
      });
    },

    a104: function(result) {
      DIALOG.simple({
        html:result.data,
        width:'550px'
      });
    },

    a105: function(result) {
      DIALOG.simple({
        html:result.data,
        width:'550px'
      });
    },
    
    /* risponde all'azione per mostrare tutto il set faccette di un gruppo (solo se non sono già state caricate) */
    a110: function(result){
      $ID("facet_" + result.name + "_allbtn").onclick = function() {facetShowAll(result.name);};
      $ID("facet_" + result.name).style.display="none";
      $ID("facet_" + result.name + "_all").innerHTML = result.html;
      $ID("facet_" + result.name + "_all").style.display="block";
    },
  
    w01: function(data){
      $ID('pagesearch').innerHTML=data.html;
      PSEARCH.init();

      var dat = eval('(' + data.data + ')');
      if(dat !== null && dat.clump) {
        CLUMP.showWidget();
        W.m00("wclump",w01m00);
      } else {
        CLUMP.hideWidget();
      }

      if(dat != null && dat.listatermini) {
        A.a11m00(PSEARCH.testoRicerca(),getKindOfList(),'',rBodyRendering);
      }

      var cdCanale = $ID("idCanale").value; 
      if (cdCanale == "galleria") {
        shiftTab("galleria");
      } else if (cdCanale == "where") {
        shiftTab("maps");
      }
    },
    
    w02: function(data){
      setStyle(data.style);
    }

  };
})();

COMMENTI = function() {
  return {
    insert: function(idCommento) {
      A.a20m03(idCommento, RENDERING.html);
      return false;      
    },
    edit: function(idCommento) {
      var titolo = $('#idTitolo').val();
      var commento = $('#idCommento').val();
      var rating = $('#idRating').val();
      
      if (!DIALOG.Strings.isBlank(commento)) {
        if (titolo.length > 100) {
          HINT.warn(i18n.js_commento_titolotroppolungo);
          return false;
        } else if (commento.length > 4000) {
          HINT.warn(i18n.js_commento_troppolungo);
          return false;
        }
        
        A.a20m04(idCommento, titolo, commento, rating, function(data) {
          if (data.error) {
            HINT.error(data);
          } else {
            RENDERING.html(data);
          }              
        });
      } else {
        HINT.warn(i18n.js_commento_obbligatorio);
      }
      return false;
    }
  }
}();

function w01m00(data){
  var nodo;
  if(data.name!=null){
    nodo = $ID(data.name);
  }
  
  if(data.style!=null){
    setStyle(data.style);
  }

  if(nodo && data.html != null && data.visible == true) {
    if(nodo.parentNode.getAttribute('showload') != null 
      && nodo.parentNode.getAttribute('showload') == 'N'){
      nodo.parentNode.style.display='block';
    }

    nodo.innerHTML=data.html;
    if(data.name=="pagesearch"){
      PSEARCH.init();
    } else if(data.name=="wsuggread"){
      div_suggread = new TextScroll('div_suggread', 'suggread_box', 'suggread_up', 'suggread_down');
    } else if(data.name=="wopensearch") {
      OS.init(data);
    } else if(data.name=="whometab") {
      if (data.idDom && data.idDom == "tabmaps") {
        GMUtils.open(data, HOMEMAPS.open);
      }
    } else if(data.name=="wnews") {
      NEWS.roll();
    }
    
  } else {
		eval(data.script);
  }

  if (nodo && data.visible == false) {
    nodo.parentNode.style.display='none';
  }  
  
  BOL.checkImages();
}

function r10(data){
  if(data.ndoc == 0) { // se data.ndoc == 0 significa che provengo dalla scheda del documento e non dalla lista
    r20(data);
    return;
  }
  STATUS.store(data,"r10");

  firstDocList = null;

  if(data.error) {    
  HINT.error(i18n[data.error]);
  } else if(data.ndoc == 1) {    
    A.a20m00('0',null,null,r20);
    return;
  } else {
    //UTIL.createScriptNode(data.script,"js10");
    //js10(data.docs,data.navigator,data.ordinamento);
    RENDERING.body(data);
  
    if (listType=="normal" || listType=="extended") {
      changeListType(listType);
    } else if (listType==undefined) {
      changeListType("normal");
    }
    
    // Aggiunta per rimuovere le icone materiale ove le copertine siano presenti
    // questo controllo non è fattibile lato server
    $("img[alt='copertina']").load(function() {
        if ($(this).height() < 75) $(this).parents("td").removeClass().addClass("lt_normal copertina");
        $(this).unbind("load"); 
    });
    
    if(data.mieListe!=null && data.mieListe.length>0){
      var dat = eval('(' + data.mieListe + ')');
      if(dat.l.length>0){
        firstDocList = dat.l[0].id;
      }
      for(i=0;i<dat.l.length;i++){
        $ID("l_" + dat.l[i].id).innerHTML = LISTMANIA.show(dat.l[i].id,dat.l[i].liste);
      }
      if(LISTMANIA.last==null){
        UTIL.modifyClassAttribute("addListmania","display","none");
      } else {
        LISTMANIA.enableAdd();
        for(n=0;n<cfgMieListe.liste.length;n++){
          if(LISTMANIA.last==cfgMieListe.liste[n].id){
            UTIL.modifyClassAttribute("addListmania","color","" + cfgMieListe.liste[n].color.replace(";",""));
            UTIL.modifyHtmlAttribute("addListmania","title","premi qui per inserire il documento in: " + cfgMieListe.liste[n].ds);
          }
        }    
      }
    }

    GBOOK.initService();

    window.scroll(0,0);
  }
}

function r20(data){
  STATUS.store(data,"r20");
  RENDERING.body(data);
  var tabView = new YAHOO.widget.TabView('tabdocument');
  
  setPostProcessing(data);
  
  if(data.mieListe!=null){
    var dat = eval('(' + data.mieListe + ')');
    for(i=0;i<dat.l.length;i++){
      $ID("l_" + dat.l[i].id).innerHTML = LISTMANIA.show(dat.l[i].id,dat.l[i].liste);
      firstDocList = dat.l[i].id;
    }
    
    if(LISTMANIA.last==null){
      UTIL.modifyClassAttribute("addListmania","display","none");
    } else {
      LISTMANIA.enableAdd();
      for(n=0;n<cfgMieListe.liste.length;n++){
        if(LISTMANIA.last==cfgMieListe.liste[n].id){
          UTIL.modifyClassAttribute("addListmania","color","" + cfgMieListe.liste[n].color.replace(";",""));
          UTIL.modifyHtmlAttribute("addListmania","title","premi qui per inserire il documento in: " + cfgMieListe.liste[n].ds);
        }
      }    
    }  
  }
  
  // Aggiunta per rimuovere le icone materiale ove le copertine siano presenti
  // questo controllo non è fattibile lato server
  $("img[alt='copertina']").load(function() {
    if ($(this).height() < 75) $(this).parents("td").removeClass().addClass("lt_normal copertina");
  });
  
  window.scroll(0,0);
  
  GBOOK.initService();
}

function showFasc(contatore) {
  showDivId('fasc_'+contatore);
  hideDivId('fasc1_'+contatore);
}

function hideFasc(contatore) {
  hideDivId('fasc_'+contatore);
  showDivId('fasc1_'+contatore);
}

function switchDiv(toShow, toHide) {
  showDivId(toShow);
  hideDivId(toHide);
}

function showDivId(divId) {
  $ID(divId).style.display="";
}

function hideDivId(divId) {
  $ID(divId).style.display="none";
}

CLICCATI = function() {
  return {
    openDoc: function(titoloBaseId) {
      A.a20m02(titoloBaseId, null, null, r20);
      return false;
    }
    
  };
}();


BOL = {
  checkImage: function(e) {
    var $div = $("<div/>")
      .css({ "position": "absolute", "left": "-999px" })
      .appendTo("body")
      .append(e.cloneNode(true));
    
    var l = $div.width();
    $div.remove();
    UTIL.purgeNode($div.get(0));
    delete $div;
    return l > 1;
  },

  checkImages: function() {
      GBOOK.initCover();
  
    var $images = $("img[alt='copertina']:not(img[bol])");
    $images.attr("bol", true);
    
    $images.each(function(i) {
      $(this).load(function() {
        var $this = $(this);
        $this.unbind("load");
        if (BOL.checkImage(this)) return;

        UTIL.purgeNode(this);
      });
    });
  } 

}

/* risponde all'azione per mostrare solo il set ristretto di faccette di un gruppo */
function facetHideAll(idFacet){
  $ID("facet_" + idFacet + "_all").style.display="none";
  $ID("facet_" + idFacet).style.display="block";  
}

/* risponde all'azione per mostrare tutto il set faccette di un gruppo (se sono già state caricate) */
function facetShowAll(idFacet){
  $ID("facet_" + idFacet).style.display="none";
  $ID("facet_" + idFacet + "_all").style.display="block";  
}

S = (function (){
  function getContesti() {
    var s = "";
      var filtri = document.getElementById("ap_dd_fv").getElementsByTagName("LI");
      for(var i=0; i < filtri.length; i++) {
          s = s + filtri.item(i).getAttribute("ID") + ",";
      }
      return s.substr(0, s.length -1);
  }

  function getGenerali() {
    var opzioni = new Array();
    var g = document.generali;
    opzioni[0] = g.ap_numdoc.value > 100 ? 100 : g.ap_numdoc.value;
    opzioni[1] = g.ap_orddoc.options[g.ap_orddoc.selectedIndex].value;
    opzioni[2] = g.ap_isbd.checked.toString();
    opzioni[3] = g.ap_numcom.value > 40 ? 40 : g.ap_numcom.value;
    opzioni[4] = "";
      
    if ($ID("ap_selezione_lingua") != null) {
      var lng = $ID("ap_selezione_lingua").getElementsByTagName("input");
      for(var i=0; i<lng.length; i++) {
        if (lng[i].checked) opzioni[4] = lng[i].value;
      }
    }
      
    return opzioni;
  }

  function getWidgets() {
  
    var $yc = $("#ap_widgets .yui-content"); 
    var result = new Object();
    $yc.find("div").each(function(index) {
      
      var $this = $(this);
      var pageId = $this.attr("class");
      var lWidgets = "";
      var rWidgets = "";
          
      $this.find(".ap_widgets_left").find("li").each(function() {
          lWidgets += $(this).attr("name") + ",";
      });
      
      if (lWidgets.length > 0) {
          result[pageId+".SX"] = lWidgets.substr(0, lWidgets.length - 1);
      } else { result[pageId+".SX"] = ""; }
      
      $this.find(".ap_widgets_right").find("li").each(function() {
          rWidgets += $(this).attr("name") + ",";
      });
      
      if (rWidgets.length > 0) {
          result[pageId+".DX"] = rWidgets.substr(0, rWidgets.length-1);
      } else { result[pageId+".DX"] = ""; }
      
    });

    return result;
  }

  return {
    /** fa la submit del form di login */
    login: function(){
      $ID('lt').value=_flowExecutionId;
      if(LOG.getLevel().length>0) {
        document.myLoginForm.service.value = document.myLoginForm.service.value + "&log=" + LOG.getLevel();
      }
      document.myLoginForm.submit();
    },

    /** dialog per la scelta dei temi */
    rd10: function(data){
    
      var handleSubmit = function() {
        W.d10m01(getCheckedValue(document.formTema.tema), function(data) {
          $ID('codicetema').innerHTML = data.name;
          DIALOG.close(dialog);
        });
      };

      var handleCancel = function() {
        W.d10m00(document.formTema.temacorrente.value, R.w02);
        $ID('codicetema').innerHTML = document.formTema.temacorrente.value;
        DIALOG.close(dialog);
      };  
        
      var buttons = [ { text: i18n.js_btn_conferma, handler: handleSubmit, isDefault: true },
        { text: i18n.js_btn_annulla, handler: handleCancel } ] 
        
      var dialog = DIALOG.open({
        id: "d-sceltatema",
        html: data,
        buttons: buttons,
        width: "400px"
      });
    },
    
    /** dialog per lo usemode */ 
    rd20: function(data){
    
      var handleSubmit = function() {
        W.d20m00(getCheckedValue(document.formUsemode.usemode), function(data) {
          if (data) 
            window.location.href = window.location.href;
          else LOG.error('data è null');
        });
      };
      
      var handleCancel = function() {
        DIALOG.close(dialog);
      };  
      
      var buttons = [{ text:i18n.js_btn_conferma, handler:handleSubmit, isDefault:true },
        { text:i18n.js_btn_annulla, handler:handleCancel } ]
        
      var dialog = DIALOG.open({
        id: "d-usemode",
        html: data,
        buttons: buttons,
        width: "400px"
      });
    },

    // Dialog Altre Preferenze
    rd120: function(data){
      
      var handleCancel = function() {
        $("#ap_numdoc").unbind("change");
        $("#ap_numcom").unbind("change");
        DIALOG.close(this);
      }; 
      
      var handleConfirm = function() {
        var error = 0;
        if (parseInt($("#ap_numdoc").val(), 10) > 100) {
          $("#ap_numdoc").val("100");
          error = 1;
        }

        if (parseInt($("#ap_numcom").val(), 10) > 40) {
          $("#ap_numcom").val("40");
          error += 2;
        }
        
        if (error == 1) {
          HINT.error(i18n.js_ap_numdoc_maxvalue);
        } else if (error == 2) {
          HINT.error(i18n.js_ap_numcom_maxvalue);
        } else if (error == 3) {
          HINT.error(i18n.js_ap_numdoc_maxvalue+"<br/>"+i18n.js_ap_numcom_maxvalue);
        }
        
        if (error > 0) return;
        
        DIALOG.simple({
          title: i18n.js_apsave_title,
          message: i18n.js_apsave,
          handler: function() {
            W.d121(getGenerali(), getContesti(), getWidgets(), function (res) { 
                W.m01(res,document.ricerca.frase.value,R.w01);
                window.location.href=window.location.href;
            });
            $("#ap_numdoc").unbind("change");
            $("#ap_numcom").unbind("change");            
            DIALOG.close(this);
          }
        });
      }

      var buttons = [{ text:"Conferma", handler:handleConfirm, isDefault:true },
        { text:"Annulla", handler:handleCancel, isDefault:false }];
      
      var dialog = DIALOG.open({
        id: "d-personalizza",
        html: data,
        buttons: buttons,
        width: "800px",
        visible: false
      });
      
      TIMEOUT.updateSess();
      
      var apTabs = new YAHOO.widget.TabView("ap_tabset"); 
      
      /* CONTESTI DI RICERCA */ 
      
      var mouseEnter = function(event) {
        var e = YAHOO.util.Event.getTarget(event, true);

        if (e && e.nodeName == "LI") {
          if (helpCtx.childNodes.length > 0)
            UTIL.purgeChilds(helpCtx); 
          helpCtx.innerHTML = e.getAttribute("help");
        }
        
//        if (event)
//          $E.stopPropagation(event);
      }
      
      var mouseLeave = function(event) {
        if (event) {
          var e = YAHOO.util.Event.getTarget(event, true);
          if (e.nodeName != "TD") return false;
        }

        if (helpCtx.childNodes.length > 0)
          UTIL.purgeChilds(helpCtx); 
        helpCtx.innerHTML = helpCText;

//        if (event)
//          $E.stopPropagation(event);
      }

      var mouseUp = function(event, e) {
        e = e.getEl();
        
        // Non ho modo di sapere se è iniziato o no il drag and drop, testando la visibilità
        // dell'oggetto sorgente posso sapere se l'evento startDrag è in corso o no.
        if (e.style.visibility == "") {
          if (e.parentNode.id == "ap_dd_fd") {
            document.getElementById("ap_dd_fv").appendChild(e);
          } else if (e.parentNode.id == "ap_dd_fv") {
            document.getElementById("ap_dd_fd").appendChild(e);
          }
        }
      }
      
      var helpCtx = document.getElementById("ap_contesti_help");
      var helpCText = helpCtx.getAttribute("help"); 
      mouseLeave();
                
      var apddfd = document.getElementById("ap_dd_fd");
      $E.addListener(apddfd, "mouseover", mouseEnter);
      $E.addListener(apddfd.parentNode, "mouseout", mouseLeave);
      new YAHOO.util.DDTarget(apddfd);

      var apddfv = document.getElementById("ap_dd_fv");
      $E.addListener(apddfv, "mouseover", mouseEnter);
      $E.addListener(apddfv.parentNode, "mouseout", mouseLeave);
      new YAHOO.util.DDTarget(apddfv);
      
      var selContesti = document.getElementById("ap_selezione_contesti"); 
      var contesti = selContesti.getElementsByTagName("li");

      for(var i = 0; i < contesti.length; i++) {
        var DDcontesto = new YAHOO.sebyou.DDList(contesti[i]);
        $E.addListener(contesti[i], "mouseup", mouseUp, DDcontesto);
      }
      
      /* WIDGETS             */ 
      
      var cfgWidgets = eval("(" + data.script + ")");
      
      var activePage = 0;
      var helpWText = $("#ap_widgets_tabset .yui-content").attr("help");
    
      var mousewEnter = function(event) {
        var e = YAHOO.util.Event.getTarget(event);
        if (e.nodeName != "LI") return false;
        
        var pageId = e.parentNode.id;
        var help;
        if (typeof pageId == "string" && !pageId.isBlank()) {
          var page = pageId.substring(0, pageId.indexOf("_"));
          help = document.getElementById(page + "_help");
        } else return false;

        if (help && help.childNodes.length > 0)
          UTIL.purgeChilds(help);
          
        help.innerHTML = e.getAttribute("help");
      }
      
      var mousewLeave = function(event, pageId) {
        if (event) {
          var e = YAHOO.util.Event.getTarget(event);
          if (e.nodeName != "TD") return false;

          for(var i = 0; i < e.childNodes.length; i++) {
            if (e.childNodes[i].nodeType != 1) continue;
  
            var s = e.childNodes[i].id;
            if (typeof s == "string" && !s.isBlank())
              pageId = s.substring(0, s.indexOf("_"));
          }
        }
        
        if (pageId) {
          var help = document.getElementById(pageId + "_help");
  
          if (help && help.childNodes.length > 0)
            UTIL.purgeChilds(help);
  
          help.innerHTML = helpWText;              
        }
      }      
    
      var pagesContainer = $("#ap_widgets .yui-content").get(0);
      $E.addListener(pagesContainer, "mouseover", mousewEnter)
      $E.addListener(pagesContainer, "mouseout", mousewLeave);
    
      var pages = $("#ap_widgets .yui-content div").get(); 
      for(var i = 0; i < pages.length; i++) {
        var page = pages[i];
        var pageId = page.className;
        
        if (pageId == data.data) activePage = i;
        
        new YAHOO.util.DDTarget(pageId + "_left");
        new YAHOO.util.DDTarget(pageId + "_center");
        new YAHOO.util.DDTarget(pageId + "_right");
    
        mousewLeave(null, pageId);
    
        var widgets = $(page).find(".ap_widget").get();
        for(var j = 0; j < widgets.length; j++) {
        	var widget = widgets[j];
          var id = widget.getAttribute("name");
          
          if (!DIALOG.Strings.isBlank(cfgWidgets[id].ds)) {
            widget.innerHTML = cfgWidgets[id].ds;
          }
          
          if (!DIALOG.Strings.isBlank(cfgWidgets[id].tooltip)) {
            widget.setAttribute("help", cfgWidgets[id].tooltip);
          }
                        
          if (!DIALOG.Strings.isBlank(cfgWidgets[id].nt) 
              && cfgWidgets[id].nt == "disabled") {
            widget.className = "disabled";
          }
          
          // Disabilitiamo il widget login nella home
          if (id == "wlogin" && pageId == "home") {
            widget.className += " disabled";
            var ul = widget.parentNode;
            if (ul.className == "ap_widgets_center")
              widget.insertBefore(ul.nextSibling.firstChild);
          }
           
          new YAHOO.sebyou.DDList(pageId + "_" + id);
        }
      }
      
      var apWTabs = new YAHOO.widget.TabView("ap_widgets_tabset", { orientation: "left", activeIndex: activePage });
      
      DIALOG.show(dialog);
    }
  };
})();

/** dialog per la ricerca avanzata */
function rd30(data){

  var handleSubmit = function() {
    var searchParamMap = new Object();
    var l = 0;
    for(i=0;i<document.formAvanzata.elements.length;i++){
      if(document.formAvanzata.elements[i].value!=''){
      	l = l + 1;
        searchParamMap[document.formAvanzata.elements[i].name] = document.formAvanzata.elements[i].value;
      }
    }
    if (l == 0) {
   	    HINT.help(i18n.js_avanzata_nessuncampo);
    } else {
        DIALOG.close(this);
        A.a10m04(searchParamMap,getCheckedValue(document.ricerca.biblioradio),r10);
    }
  };
  
  var handleCancel = function() {
    DIALOG.close(this);
  };  
    
  var buttons = [{ text:i18n.js_btn_conferma, handler:handleSubmit, isDefault:true },
    { text:i18n.js_btn_annulla, handler:handleCancel }]; 

  var dialog = DIALOG.open({
    id: "d-avanzata",
    html: data.html,
    buttons: buttons,
    width: "500px",
    visible: false });
    
  $("#formAvanzata input").each(function() {
    var field = $(this).attr("name");
    $(this).autocomplete({ 
      source: function (terms) {
        var result;
        W.d131(terms.normWhiteSpace(), field, { async: false, 
          callback: function(data){
            result = data;
          }
        });
        return result;
      },
      minChars: 3,
      multiple: true,
      multipleSeparator: " ",
      selectFirst: false,
      parse: parseArray,
      scroll: false,
      delay: 490
    });
  });
  
  DIALOG.show(dialog);
}

/* dialog per la cronologia ricerche */
function rd40(data){

  var handleCancel = function() {
    DIALOG.close(dialog);
  };  
  
  var handleClear = function() {
	  W.d41(function(data){
	    if(data==0){
	      DIALOG.setBody(dialog, i18n.js_chronology_nessunaricerca);
	    }
	  });
  };    
  
  var buttons = [{ text: i18n.js_chronology_reset, handler:handleClear },
  { text: i18n.js_btn_annulla, handler:handleCancel, isDefault:true }];
    
  var dialog = DIALOG.open({
    id: "d-cronologia",
    html: data.html,
    buttons: buttons,
    width: "600px" });
}

/** dialog per selezione delle risorse di OpenSearch */
function rd50(data){

  var handleCancel = function() {
    DIALOG.close(dialog);
  };  
  
  var handleConfirm = function() {
    for(i = 0;i<document.formRisorseos.rer.length;i++){
      for(n = 0;n<document.ricerca.terminilist.length;n++){
        if(document.ricerca.terminilist[n].value==document.formRisorseos.rer[i].value.toUpperCase()){
          if(document.formRisorseos.rer[i].checked){
            document.ricerca.terminilist[n].checked = true;
          } else {
            document.ricerca.terminilist[n].checked = false;            
          }
          break;
        }
      }   
    }   
    DIALOG.close(dialog);
  };
  
  var buttons = [{ text:i18n.js_btn_conferma, handler:handleConfirm },
    { text:i18n.js_btn_annulla, handler:handleCancel, isDefault:true }];
  
  var dialog = DIALOG.open({
    id: "d-opensearch",
    html: data.html,
    buttons: buttons,
    width: "450px"
  });
  
  if(document.formRisorseos.rer!=null){
    for(i = 0;i<document.formRisorseos.rer.length;i++){
      for(n = 0;n<document.ricerca.terminilist.length;n++){
        if(document.ricerca.terminilist[n].value==document.formRisorseos.rer[i].value.toUpperCase()){
          if(document.ricerca.terminilist[n].checked){
            document.formRisorseos.rer[i].checked = true;
          } else {
            document.formRisorseos.rer[i].checked = false;            
          }
          break;
        }
      }   
    }    
  }
    
  DIALOG.show(dialog);
}

/** help dei widget */
function rd80(data){
  DIALOG.info({
    html: data
  });
}

/** fa l'escape html di val */
function escapeHTML(val){
  var div = document.createElement('div');
  var text = document.createTextNode(val);
  div.appendChild(text);
  return div.innerHTML;
}

function lz(numero, cifre) {
  n = String(numero);
  while (n.length<cifre) { 
    n="0"+n;
  }
  return n;
}

/** formatta la "data" nel "formato" */
Date.prototype.format = function (formato) {
  var giorni = new Array(i18n.js_gg_do,i18n.js_gg_lu,i18n.js_gg_ma,i18n.js_gg_me,i18n.js_gg_gi,i18n.js_gg_ve,i18n.js_gg_sa);
  var mesi = new Array(i18n.js_mm_01,i18n.js_mm_02,i18n.js_mm_03,i18n.js_mm_04,i18n.js_mm_05,i18n.js_mm_06,i18n.js_mm_07,i18n.js_mm_08,i18n.js_mm_09,i18n.js_mm_10,i18n.js_mm_11,i18n.js_mm_12);

// preparo la data...  verificare di passarla corretta!
  var adesso = this; 
  var anno = adesso.getFullYear();
  var mese = adesso.getMonth()+1;
  var giorno = adesso.getDate();
  var settim = adesso.getDay();
  var ore = adesso.getHours();
  var minuti = adesso.getMinutes();
  var secondi = adesso.getSeconds();

// preparo la stringa di risposta
  var rVal = '';

  if (formato.length==0) { 
// assenza del secondo parametro
    return String(adesso); 
  } else {

  // inizio loop
    while (formato.length>0) {

  // verifico se c'e' qualche separatore e lo aggiungo
      while (formato.length>0 && String("ymdphnst").indexOf(formato.charAt(0).toLowerCase())<0) {
        rVal += formato.charAt(0);
        formato = formato.substr(1);
      }


  // Separo il gruppo
      if (formato.length>0) {
        ff = formato.charAt(0);
        formato = formato.substr(1);
        while (formato.length>0 && formato.charAt(0).toLowerCase()==ff.charAt(0).toLowerCase()) {
          ff += formato.charAt(0);
          formato = formato.substr(1);
        }

  // espando il formato nella stringa corrispondente
        ff = ff.toLowerCase();   // operazione preliminare... tutto in minuscolo
        switch (ff)   { 
          case "yy" : 
            rVal += String(anno).substr(2); 
            break; 
          case "yyyy" : 
            rVal += String(anno); 
            break; 
          case "m" : 
            rVal += String(mese); 
            break; 
          case "mm" : 
            rVal += lz(mese,2);
            break; 
          case "mmm" : 
            rVal += mesi[mese-1].substr(0,3);
            break; 
          case "mmmm" : 
            rVal += mesi[mese-1];
            break; 
          case "d" : 
            rVal += String(giorno); 
            break; 
          case "dd" : 
            rVal += lz(giorno,2); 
            break; 
          case "ddd" : 
            rVal += giorni[settim].substr(0,3);
            break; 
          case "dddd" : 
            rVal += giorni[settim];
            break; 
          case "p" : 
            var inizio = new Date(anno, 0, 0); 
            rVal += Math.floor((adesso - inizio) / 86400000);
            break; 
          case "ppp" : 
            var inizio = new Date(anno, 0, 0); 
            rVal += lz(Math.floor((adesso - inizio) / 86400000),3);
            break; 
          case "h" : 
            rVal += String(ore); 
            break; 
          case "hh" : 
            rVal += lz(ore,2); 
            break; 
          case "n" : 
            rVal += String(minuti); 
            break; 
          case "nn" : 
            rVal += lz(minuti,2); 
            break; 
          case "s" : 
            rVal += String(secondi); 
            break; 
          case "ss" : 
            rVal += lz(secondi,2); 
            break; 
          case "t" : 
            rVal += lz(ore,2)+":"+lz(minuti,2)+":"+lz(secondi,2); 
            break; 
          default :  // il numero dei caratteri del formato non e' permesso
            rVal += ff.replace(/./gi,"?");
        } 

      }

    } // fine loop principale

    return rVal;
  }
};

/** GESTIONE DIV CON SCROLL */
function TextScroll(scrollname, div_name, up_name, down_name) {
  this.div_name = div_name;
  this.name = scrollname;
  this.scrollCursor = 0;
  this.speed = 5;
  this.timeoutID = 0;
  this.div_obj = null;
  this.up_name = up_name;
  this.dn_name = down_name;

  {
    if (document.getElementById) {
      div_obj = document.getElementById(this.div_name);
      if (div_obj) {
        this.div_obj = div_obj;
        this.div_obj.style.overflow = 'hidden';
      }
      div_up_obj = document.getElementById(this.up_name);
      div_dn_obj = document.getElementById(this.dn_name);
      if (div_up_obj && div_dn_obj) {
        div_up_obj.onmouseover = function() { eval(scrollname + ".scrollUp();") };
        div_up_obj.onmouseout = function() { eval(scrollname + ".stopScroll();") };
        div_dn_obj.onmouseover = function() { eval(scrollname + ".scrollDown();") };
        div_dn_obj.onmouseout = function() { eval(scrollname + ".stopScroll();") };
      }
    }
  }

  this.stopScroll = function() {
    clearTimeout(this.timeoutID);
  }

  this.scrollUp = function() {
    if (this.div_obj) {
      this.scrollCursor = (this.scrollCursor - this.speed) < 0 ? 0 : this.scrollCursor - this.speed;
      this.div_obj.scrollTop = this.scrollCursor;
      this.timeoutID = setTimeout(this.name + ".scrollUp()", 60);
    }
  }

  this.scrollDown = function() {
    if (this.div_obj) {
      this.scrollCursor += this.speed;
      this.div_obj.scrollTop = this.scrollCursor;
      if (this.div_obj.scrollTop == this.scrollCursor) {
        this.timeoutID = setTimeout(this.name + ".scrollDown()", 60);
      } else {
        this.scrollCursor = this.div_obj.scrollTop;
      }
    }
  }

  this.resetScroll = function() {
    if (this.div_obj) {
        this.div_obj.scrollTop = 0;
        this.scrollCursor = 0;
    }
  }

}

/** Ajax loader */
function useLoadingImage(imageSrc) {
  dwr.engine.setPreHook(function() {
    LOADER.call(imageSrc);
  });
  dwr.engine.setPostHook(function() {
    LOADER.dismiss();
  });  
}

LOADER = function(){
  var overlay = $("#disabledImageZone");
  var image = overlay.find("#imageZone");
  var binded = false;
  
  function _call(imageSrc) {
    if (!imageSrc) imageSrc = "ajax-loader.gif";
    if (overlay.size() == 0 && image.size() == 0) {
      _createDOM();
    }
    overlay.show();
    image.attr("src", imageSrc)
      .show();
    _refresh();
    if (!binded) {
      $(window).bind("resize scroll", _refresh);
      binded = true;
    }  
  }

  function _dismiss() {
    overlay.hide();
    image.hide();
    if (binded) {
      $(window).unbind("resize scroll", _refresh);
      binded = false; 
    }  
  }
  
  function _refresh() {
    var css = {
        "top": $(document).scrollTop(),
        "left": $(document).scrollLeft(),
        "width": $(window).width(),
        "height": $(window).height()
    };
    overlay.css(css);
    image.css(css);
  }
  
  function _createDOM() {
      overlay = $("<div/>")
        .attr("id", "disabledImageZone")
        .appendTo("body");
      image = $("<img/>")
        .attr("id", "imageZone")
        .appendTo("body");
  }

  return {
    refresh: function() {
      _refresh();
    },
    call: function(imageSrc) {
      _call(imageSrc);
    },
    dismiss: function() {
      _dismiss();
    }    
  };
}();


/* Sezione per YUI Drag and Drop */
YAHOO.namespace("sebyou");
YAHOO.sebyou.DDList = function(id, sGroup, config) {
    YAHOO.sebyou.DDList.superclass.constructor.call(this, id, sGroup, config);

    UTIL.setRule(this.getDragEl(), "opacity", "0.67");
    
    this.goingUp = false;
    this.lastY = 0;
};

YAHOO.extend(YAHOO.sebyou.DDList, YAHOO.util.DDProxy, {
	
    startDrag: function(x, y) {
        var dragEl = this.getDragEl();
        var srcEl = this.getEl();
        UTIL.setRule(srcEl, "visibility", "hidden");
        
        dragEl.innerHTML = srcEl.innerHTML;
        dragEl.setAttribute("class", srcEl.getAttribute("class")); 
        dragEl.style.zIndex = DIALOG.getLastZIndex() + 1;
                
        UTIL.setRule(dragEl, "border", "1px dotted #999999");
    },

    endDrag: function(e) {
        var srcEl = this.getEl();
        var proxy = this.getDragEl();
        
        UTIL.setRule(proxy, "visibility", "");
        UTIL.setRule(srcEl, "visibility", "visible");
        
        var elm_pos = UTIL.findPos(srcEl);
        
        var a = new YAHOO.util.Motion( 
            proxy, { 
                top: { 
                    to: elm_pos[1]
                },
                left: {
                    to: elm_pos[0]
                }
            }, 
            0.2, 
            YAHOO.util.Easing.easeOut 
        );
        
        var proxyid = proxy.id;
        var thisid = this.id;

        a.onComplete.subscribe(function() {
                UTIL.setRule($ID(proxyid), "visibility", "hidden");
                UTIL.setRule($ID(thisid), "visibility", "");
            });
        a.animate();
        
        $("#"+proxyid).find("div").remove();
        
        $(srcEl.parentNode).trigger("endDrag");
        $(srcEl).trigger("endDrag");
    },

    onDragDrop: function(e, id) {
        var DDM = YAHOO.util.DragDropMgr;

        if (DDM.interactionInfo.drop.length === 1) {
            var pt = DDM.interactionInfo.point; 
            var region = DDM.interactionInfo.sourceRegion; 
            if (!region.intersect(pt)) {
                var destEl = $ID(id);
                var destDD = DDM.getDDById(id);
                destEl.appendChild(this.getEl());
                destDD.isEmpty = false;
                DDM.refreshCache();
            }
        }
    },

    onDrag: function(e) {
        var y = $E.getPageY(e);
        if (y < this.lastY) {
            this.goingUp = true;
        } else if (y > this.lastY) {
            this.goingUp = false;
        }
        this.lastY = y;
    },

    onDragOver: function(e, id) {
        var DDM = YAHOO.util.DragDropMgr;
    
        var srcEl = this.getEl();
        var destEl = $ID(id);

        if (destEl.nodeName.toLowerCase() == "li") {
            var orig_p = srcEl.parentNode;
            var p = destEl.parentNode;

            if (this.goingUp) {
                p.insertBefore(srcEl, destEl); 
            } else {
                p.insertBefore(srcEl, destEl.nextSibling); 
            }

            DDM.refreshCache();
        } 
    }
});

function bolDialog() {
  var html = "<div class='bolbox'>" +
      "<a href='http://www.bol.it/jp/sebinayou'>"
      + i18n.js_boldialog 
      + "</a></div>";

  var dialog = DIALOG.info({ html: html });

  $(".bolbox").wrap("<a href='http://www.bol.it/jp/sebinayou' style='color: black'></a>")
      .css( { "background": "white url(sebinayou/temi/common/img/bol.jpg) no-repeat top center",
              "padding": "1em",
              "padding-top": "10em" } );
}

function browserDialog() {
  DIALOG.simple({
    message: i18n.js_browsers_text,
    width: "400px"
  });
}

// Funzione di ritorno apertura dialog chiedi all'esperto
function rd140(data) {

  var handleCancel = function() {
    DIALOG.close(dialog);
  }; 
  
  var handleConfirm = function() {
      d141(dialog);
  };
  
  var buttons = [{ text:"Conferma", handler:handleConfirm, isDefault:true },
    { text:"Annulla", handler:handleCancel }];

  var dialog = DIALOG.open({
    id: "d-chiediesperto",
    html: data.html,
    visible: false,
    buttons: buttons,
    width: "815px"
  });
  
  $(".allegato").upBox().bind("success", insertNewUpload);
    
  $("#dialog textarea, #dialog input").keydown(function(e) {
    if (e.which == 13) {
      $(this).val($(this).val() + "\n");
      return false;
    }
  });
  
  DIALOG.show(dialog);
}

function insertNewUpload() {
  $(this).unbind("success");
  $("<input class='allegato' type='file'/>").insertAfter($(this))
    .upBox()
    .bind("success", insertNewUpload);
}

// Salvataggio dialog chiedi all'esperto
function d141(dialog, fn) {

  var errore = false;
  $form = $("#form_problema");
  $form.find("*").removeClass("error");

  function reqEMail($elm) {
    var email = /^.{3,}@.{3,}[.]\w{2,}/;
    var value = $form.find("#email").val();

    if (!email.test(value)) {
      $elm.parent().addClass("error");            
      errore = true;
    } else {
      return $elm.val();
    }
  }
    
  function req($elm) {
    if ($elm.size() == 0 || $elm.val().length == 0) {
      $elm.parent().addClass("error");            
      errore = true;
    } else {
      return $elm.val();
    }
  }
    
  var problema = {
    "ds": req($form.find("#ds")),
    "email": reqEMail($form.find("#email")),
    "telefono": $form.find("#telefono").val(),
    "motRichiesta": $form.find("#motivo").val(),

    // Modifica da tipoRichiesta a idTipoRichiesta solo per la 2.2
    "idTipoRichiesta": $form.find("#tipo").val(),
    "nt": $form.find("#nt").val()
  };

	if (errore) {
	  LOG.dir(problema);
    HINT.error(i18n.js_formproblema_campimancanti);
    return;
	}

	var allegati = new Array();
	var s = $(dialog).find("input[name='delete']");
	for(var i=0; i<s.size(); i++) {
    allegati[i] = {
      dslPath: s[i].getAttribute("value")
    };
	}

	W.d141(problema, allegati, function(data) {
    if (data == true) {   
      HINT.help(i18n.js_formproblema_inserimentook);
    } else {
      HINT.error(i18n.js_formproblema_inserimentoko);
    }
    
    if (dialog) DIALOG.close(dialog);
    if (fn) fn();
	});	
}

// Virtual Shelf
function rd150(data) {

    var handleCancel = function() {
        DIALOG.close(dialog);
    }; 
  
    var buttons = [{ text:i18n.js_btn_esci, handler:handleCancel, isDefault:false }];

    var dialog = DIALOG.open({
      id: "d-scaffale",
      html: data,
      buttons: buttons,
      width: "800px"
    });
    
    // Imposta gli spostamenti in pixel dello scaffale, s1-3 sono i div a sinistra, gli altri a destra
    var speed = new Object();
    speed["s1"] = 10;
    speed["s2"] = 5;
    speed["s3"] = 2;
    speed["s4"] = -10;
    speed["s5"] = -5;
    speed["s6"] = -2;
    aSpeed = 0;
    mWidth = 0;
    
    docsToLoad = 20;
    
    // Imposta i colori possibili per le copertine di sfondo
    var colori = new Object();
    colori[0] = "blue";
    colori[1] = "red";
    colori[2] = "green";
    colori[3] = "gray";
    colori[4] = "teal";
    colori[5] = "yellow";
    
    // Semafori per il caricamento differito dei documenti
    var leftlight = false;
    var rightlight = false;
    
    // Contenitori per i settori precaricati
    var after;
    var before;
    
    // Elemento selezionato
    var idSelection;
    
    // Altezza scaffale
    var vsHeight = 240;

    // Funzione che si occupa di scrollare lo scaffale
    $("#scaffale").find(".slice").hover(function(e) {
        id = $(this).attr("id");
        aSpeed = speed[id];
        clearInterval(moveTimer);
        moveTimer = window.setTimeout(moveMe, 6);
        e.stopPropagation();
    }, function(e) {
        clearInterval(moveTimer);
        e.stopPropagation();
    });
    
    var moveMe = function() {
        left = $("#libri").css("left");
        if (left == "auto") left = 0;
        var newLeft = parseInt(left) + parseInt(aSpeed);
        var totalWidth = mWidth*(docsToLoad*2);
        var margins = mWidth*5;
        var rM = margins / 1.4;

        if (newLeft >= 0 || newLeft <= -totalWidth) return;
        $("#libri").css("left", newLeft + "px");

//        $("#scaffale").find(".btitolo").html(left);
//        $("#scaffale").find(".bautore").html(-totalWidth);

        if (parseInt(left) > -margins && !leftlight) {
            if (before == "STOP") return;
            leftlight = true;
            r152b();
            $("#libri").css("left", parseInt(left)-((totalWidth / 2) + rM));
            leftlight = false;
        }
        
        if (parseInt(left) < -(totalWidth - margins) && !rightlight) {
            if (after == "STOP") return;
            rightlight = true;
            r151b();
            $("#libri").css("left", parseInt(left)+((totalWidth / 2) + rM));
            rightlight = false;
        }
        
        moveTimer = window.setTimeout(moveMe, 6);
    };

    // Funzione che si occupa di effettuare il parsing degli elementi LI all'interno dello scaffale
    var parseMe = function(from, to) {
        
        if (from != null && from > 0) {
            $toParse = $("#scaffale").find("li:gt("+from+")");
            to = null; 
        } else if (to != null && to > 0) {
            $toParse = $("#scaffale").find("li:lt("+to+")");
            from = null;   
        } else {
            $toParse = $("#scaffale").find("li");
        }
        $toParse.each(function(index) {
            var $a = $(this).find("a");
            var $li = $(this);
            var $img = $a.find("img");
            var $cover = $li.find(".background");
            var $back = $li.find(".cover_center");
            var $cont = $li.find(".content");
            var $foot = $li.find(".footnote");
            
            if ($li.attr("collinv") == "STOP") {
                $li.css("background", "none");
                return;
            }
            
            // Sezione per la randomizzazione del colore del libro
            var colore = colori[Math.floor(Math.random()*6)];
            var ctop = $cover.find(".cover_top");
            var ccenter = $cover.find(".cover_center");
            var cbottom = $cover.find(".cover_bottom");
            ctop.css("backgroundImage", ctop.css("backgroundImage").replace("colore", colore));
            ccenter.css("backgroundImage", ccenter.css("backgroundImage").replace("colore", colore));
            cbottom.css("backgroundImage", cbottom.css("backgroundImage").replace("colore", colore));
            
            // Gestisce la mutabilità dell'altezza della copertina, impostare a 0 per disattivare.
            var altezza = Math.floor(Math.random()*20);
            
            // Sezione per il dimensionamento corretto di ogni elemento
            var titolo = $a.attr("title");
            $("<p class='vs_titolo'>"+escapeHTML(titolo)+"</p>").prependTo($a);
            
            // Inserimento nel footer dei codici di collocazione e inventario            
            
            var collinv = $li
              .attr("collinv")
              .split(/\t/);
              
            if (collinv.length > 5) {
              $foot.html(collinv[2] + " " 
                + collinv[3] + " "
                + collinv[4] + "<br/>"
                + collinv[5]);
            } else if (collinv.length == 5) {
              $foot.html(collinv[2] + " " 
                + collinv[3] + "<br/>"
                + collinv[4]);
            }           
           
            $cont.css("top", "-" + (110 + parseInt(altezza)) + "px");
            $cont.css("height", parseInt($cover.height()) - 40 + altezza);
            $foot.css("top", -(parseInt($cover.height()) - 46 + altezza)); // era 60
                
            hli = vsHeight - parseInt($cover.height()) - altezza;
            $li.css("margin-top", hli);
            $li.css("height", parseInt($cover.height())+70+altezza); // era 15
            
            $back.height($back.height() + altezza);
            
            if ($img.attr("src") == "" || $img.attr("src") == "null") $img.remove();
            
            // Sezione per il caricamento differito delle immagini
            $(this).find("img").load(function() {
    
                    var $a = $(this).parents("a");
                    var $img = $(this);
                    var $li = $(this).parents("li");
                    var $back = $li.find(".cover_center");
                    var $cover = $li.find(".background");
                    var $cont = $li.find(".content");
                
                    // Se l'immagine è piccola o assente è inutile lasciare il tag
                    if ($img.width() <= 1) {
                
                        $a.find("img").remove();
                
                    } else if ($img.width() > 1) {
                
                        $a.find("p").remove();
                        var h = $img.height();
                        $back.height((h - 45)+"px");
                        $cont.css("top", "-" + (h + 6) + "px");
                        $cont.css("height", h + "px");
                        $foot.css("top", -(parseInt($cover.height()) - 20)); // era 35
                    }
                
                    hli = vsHeight - parseInt($cover.height());
                    $li.css("margin-top", hli);
                    $li.css("height", parseInt($cover.height())+70); // era 15
                });
            
            // mWidth del singolo LI
            mWidth = parseInt($(this).width());
                
        }); 
    };
        
    // Inserimento di una sezione nel titolo del dialog per la visualizzazione della collocazione
    $("<span class='hdp'></span>").appendTo(".hd");    
    var bindMe = function(from, to) {
        if (from != null && from > 0) {
            $toParse = $("#libri").find("li:gt("+from+")");
            to = null; 
        } else if (to != null && to > 0) {
            $toParse = $("#libri").find("li:lt("+to+")");
            from = null;   
        } else {
            $toParse = $("#libri").find("li");
        }
        
        $toParse.each(function(index) {
            
            if ($(this).attr("collinv") == "STOP") return;
            
            $(this).hover(function(e) {
                // Il mouse è sopra l'elemento LI
                clearTimeout(onTimer);
                $this = $(this);
                onTimer = window.setTimeout(function() {
                    $("#scaffale").find(".btitolo").html(escapeHTML($this.find("a").attr("title")));
                    $("#scaffale").find(".bautore").html("<a href='#'>"+escapeHTML($this.find("a").attr("name"))+"</a>");
                    
                    $(".focus").find("a").click(function() {
                        var s = new Object();
                        s["AU"] = $this.find("a").attr("name");
                        A.a10m04(s, getCheckedValue(document.ricerca.biblioradio), r10);
                        DIALOG.close(dialog);
                        return false;
                    });
                    $("#libri").find("li").removeClass("select");
                    $("#libri").find(".footnote").removeClass("select");
                    $this.addClass("select");
                    $this.find(".footnote").addClass("select");
                    idSelection = $this.attr("collinv");
                }, 200);
                e.stopPropagation();
            }, function(e) {
                // Il mouse lascia l'elemento LI
                clearTimeout(onTimer);
                e.stopPropagation();
            }).click(function() {
                // Ricerca per singolo documento
                var s = new Object();
                s["ID"] = $(this).find("a").attr("id");
                A.a20m09(s["ID"],$(this).attr("collinv"),$("#dsbiblshelf").html(),r20);
                DIALOG.close(dialog);
                return false;
            });
            
            // Selezione in movimento
            if ($(this).attr("collinv") == idSelection) {
                $(this).mouseover();
            }
        });
    };
    
    // Sposta la biblioteca nel titolo del dialog
    $(".hdp").html($(".hdp").html() + $(".biblioteca").html());
    $(".biblioteca").remove();
    
    // Effettua il parsing degli elementi
    parseMe();
    bindMe();
    
    // Posiziona lo scaffale al centro mostrando il documento da cui siamo partiti
    $("#libri").css("left", -(mWidth*(docsToLoad*2) / 1.9) + "px");
    
    // Gestione ombra opaca sotto il titolo in caso di mouse hover
    $("#scaffale .focus").hover(function() {
      $(this).addClass("enlarge"); 
    }, function() {
      $(this).removeClass("enlarge");
    });
    
    // Selezione del libro di partenza
    var ci = $("#scaffale").find("ul").attr("id");
    $("#libri").find("li").each(function() {
        if ($(this).attr("collinv") == ci) {
             $(this).trigger("mouseenter");
        }
    });
    
    // Binding eventi tasto
    $(window).keypress(function(e) {
        if (e.keyCode == 37) {
            var left = parseInt($("#libri").css("left")); 
            $("#libri").css("left", left + speed["s1"]);     
        } else if (e.keyCode == 39) {
            var left = parseInt($("#libri").css("left")); 
            $("#libri").css("left", left + speed["s4"]);     
        }
    });
    
    // Precaricamento dei settori
    var firstCollInv = $("#libri").find("li:first").attr("collinv");
    var lastCollInv = $("#libri").find("li:last").attr("collinv");
    W.d151(lastCollInv, r151);
    W.d152(firstCollInv, r152);
    
    // Funzioni per la movimentazione iniziale dei settori precaricati
    // Settori successivi
    function r151(data) {
        if (data == "stop") {
            after = "stop";
            return;
        }            
        var obj = eval(data);
        var str = "";
        for(var i=0; i<obj.length; i++) {
            str += struct(obj[i]);
        }
        after = str;
    }
    // Settori precedenti
    function r152(data) {
        if (data == "stop") {
            before = "stop";
            return;
        }            
        var obj = eval(data);
        var str = "";
        for(var i=0; i<obj.length; i++) {
            str += struct(obj[i]);
        }
        before = str;
    }
    // Funzioni per la movimentazione successiva dei settori precaricati
    function r151b() {
        if (after == "STOP") return;
        
        var toParse = true;
        if (after.indexOf("parsed:") == 0) {
            toParse = false;
            after = after.substr(7);            
        }
        
        $(after).appendTo($("#libri").find("ul"));
        before = "parsed:";
        $("#libri").find("li:lt("+docsToLoad+")").each(function(index) {
           before += "<li collinv='" + $(this).attr("collinv")
            + "' style='"+$(this).attr("style")+"'>"
            + $(this).html()+"</li>";
        });
        $("#libri").find("li:lt("+docsToLoad+")").remove();
        
        if (toParse) parseMe(docsToLoad-1,0);
        bindMe(docsToLoad-1,0);
        var lastCollInv = $("#libri").find("li:last").attr("collinv");
        if (lastCollInv == "STOP") {
            after = "STOP";
            $("#libri").find("li").each(function(index) {
               if ($(this).attr("collinv") == "STOP") $(this).remove(); 
            });
            return;
        }
        W.d151(lastCollInv, r151);
    }
    function r152b() {
        
        if (before == "STOP") return;
        
        var toParse = true;
        if (before.indexOf("parsed:") == 0) {
            toParse = false;
            before = before.substr(7);            
        }

        $(before).insertBefore($("#libri").find("li:first"));
        after = "parsed:";
        $("#libri").find("li:gt("+((docsToLoad*2)-1)+")").each(function(index) {
           after += "<li collinv='"+$(this).attr("collinv")+"' style='"+$(this).attr("style")+"'>"
            +$(this).html()+"</li>";
        });
        $("#libri").find("li:gt("+((docsToLoad*2)-1)+")").remove();
        
        if (toParse) parseMe(0,docsToLoad);
        bindMe(0,docsToLoad);
        var firstCollInv = $("#libri").find("li:first").attr("collinv");
        if (firstCollInv == "STOP") {
            before = "STOP";
            return;
        }
        W.d152(firstCollInv, r152);
    }
    function struct(d) {
      return '<li collinv="'+ d.collinv + '">'
          + '<div class="background"><table cellspacing=0 cellpadding=0>'
          + '<tr><td class="cover_top"></td></tr>'
          + '<tr><td class="cover_center"></td></tr>'
          + '<tr><td class="cover_bottom"></td></tr>'
          + '</table></div>'
          + '<div class="content"><a href="#" title="' + escapeHTML(d.titolo) + '" '
          + 'id="' + d.idtitolo + '" name="' + escapeHTML(d.autore) + '">'
          + (d.copertina != null && d.copertina != "" ? '<img src="' + d.copertina + '" alt=""/>' : "")
          + '</a></div><div class="footnote"></div></li>';
    }
    
}

function rd161(data) {
    $("#wnavigator").html(data.html);
}

PWD = {
  
  // Ho dimenticato la mia password  
  openForgot: function(userName) {
    W.d200(userName, PWD.rd200);
  },

  question: function() {
    var userName = $("form#forgotpwd input").val();
    if (userName.isBlank()) {
      HINT.error(i18n.js_password_fp_userempty);
    } else {
      W.d201(userName, PWD.reply);
    }
  },
  
  answer: function(userName) {
    var answer = $("form#forgotpwd input").val();
    if (answer.isBlank()) {
      HINT.error(i18n.js_forgotpwd_1_noanswer);
    } else {
      W.d202(userName, answer, PWD.reply);
    }
  },
  
  reply: function(data) {
    DIALOG.replace("d-changepassword", data);
  },
  
  // Cambia la mia password
  openChange: function() {
    W.d210(PWD.rd200);
  },
  
  close: function() {
    DIALOG.close("d-changepassword");
  },

  change: function() {
    var error;
    var f = new Object();

    var $this = $("form#changepwd");
    f.oldpwd = $this.find("#oldpwd").val();
    f.newpwd = $this.find("#newpwd").val();
    f.cnewpwd = $this.find("#cnewpwd").val();
    f.domanda = $this.find("#domanda").val();                  
    f.risposta = $this.find("#risposta").val();

    $.each(f, function() {
    	if (this.isBlank())
    	  error = "js_password_campivuoti";
    });
    
    if (f.oldpwd == f.newpwd) {
      error = "js_password_OLDPWD_NOT_EQUAL";   
    } else if (f.newpwd != f.cnewpwd) {
      error = "js_password_NEWPWD_NOT_EQUAL";
    } 

    if (error != null) {
      HINT.error(i18n[error]);
    } else {
      W.d211(f.oldpwd, f.newpwd, f.cnewpwd, f.domanda, f.risposta, function(data) {
        if (data == "DONE") {
          HINT.info(i18n["js_password_DONE"]);
          DIALOG.close("d-changepassword");
        } else {
          HINT.error(i18n["js_password_" + data]);
          return;
        }
      });        
    }
  },

  rd200: function(data) {
    DIALOG.open({
      id: "d-changepassword",
      html: data,
      width: "500px"
    });
  }
};

AR = (function () {
  
  var dialog;
  
  return {
    rd170: function(data) {
    
        var handleCancel = function() {
            DIALOG.close(dialog);
        }; 
      
        var handleConfirm = function() {
            AR.d171();
        };
        
        var buttons = [{ text: "Conferma", handler: handleConfirm, isDefault: true },
          { text: "Annulla", handler: handleCancel, isDefault: false }];

        var dialog = DIALOG.open({
          id: "d-ar",
          html: data,
          buttons: buttons,
          width: "740px"
        });
        
        var dataObj = new Date();
        $("#dataNascita").datepicker({
          dateFormat: "dd/mm/yy",
          showOptions: { 
            direction: "up" 
          },
          yearRange: '1910:'+dataObj.getFullYear()
        }); 
    },
    
    d171: function() {
        var errore = false;
        var erroreData = false;
        
        function req($elm, size) {
            if (size == null) size = 1;
            var $cElm = $elm; 
            if ($elm.attr("type") == "radio") {
                $elm = $elm.parent().find(":checked");
            }
            
            if ($elm.size() == 0 || $elm.val().length < size) {
                $cElm.parent().addClass("error");
                errore = true;
                return; 
            } else {
                $cElm.parent().removeClass("error");
                return $elm.val();
            }
        }
        
        function reqData($elm) {
          var born = $elm.datepicker('getDate');
          var today = new Date();
          if (born == null || born>today) {
            $elm.parent().addClass("error");
            erroreData = true;
            return;
          } else {
            $elm.parent().removeClass("error");
            erroreData = false;
            return born;
          } 
        }
        
        $form = $("#form_registrazione");
        var ui = new Object();
        
        ui["cognome"] = req($form.find("#cognome"));
        ui["nome"] = req($form.find("#nome"));
        ui["sesso"] = req($form.find("#sesso"));
        ui["dataNascita"] = reqData($form.find("#dataNascita"));
        ui["indirizzo"] = req($form.find("#indirizzo"));
        ui["localitaCitta"] = req($form.find("#localitaCitta"));
        ui["idProvincia"] = $form.find("#idProvincia").val();
        ui["idTipoUtente"] = $form.find("#idProfessione").val();
        ui["idTitoloStudio"] = $form.find("#idTitoloStudio").val();
    
        ui["flPrivacy"] = (req($form.find("#flPrivacy")) == "s" ? true : false);
        if (ui["flPrivacy"] == false) {
            $form.find("#flPrivacy").parent().addClass("error");
            errore = true;
        }
    
        ui["username"] = req($form.find("#username"), 1);
        ui["password"] = req($form.find("#password"), 1);
        var cpassword = req($form.find("#cpassword"), 1);
        
        if (ui["password"] != cpassword) {
            $form.find("#cpassword").parent().addClass("error");
            errore = true;
        } else {
            $form.find("#cpassword").parent().removeClass("error");
        }
        
        if (errore || erroreData) {
          var msg = "";
          if (errore) msg = i18n.js_registrazione_campimancanti + "<br/>";
          if (erroreData) msg += i18n.js_registrazione_dataoltreoggi; 
          HINT.error(msg);
          return;
        }
        
        W.d171(ui, AR.rd171);
    },

    rd171: function(data) {
        
        $("#form_registrazione").find("#username").removeClass("error");
        $("#usr_err").remove();
        $("#form_registrazione").find("#password").removeClass("error");
        $("#pwd_err").remove();
        
        if (data == "OK") {
            HINT.help(i18n.js_registrazione_success);
            DIALOG.close("d-ar");
        } else if (data == "ERR:1") {
            HINT.error(i18n.js_registrazione_parseerror);
        } else if (data == "ERR:2") {
            HINT.error(i18n.js_registrazione_error);
        } else if (data == "ERR:3") {
            $elm = $("#form_registrazione").find("#username");
            $elm.parent().addClass("error");
            if ($("#usr_err").size() == 0) {
                $("<p style=\"color: red\" id=\"usr_err\">"+i18n.js_registrazione_usernameerror+"</p>").insertAfter($elm);
            }
        } else if (data == "ERR:4") {
            $elm = $("#form_registrazione").find("#password");
            $elm.parent().addClass("error");
            if ($("#pwd_err").size() == 0) {
                $("<p style=\"color: red\" id=\"pwd_err\">"+i18n.js_registrazione_passworderror+"</p>").insertAfter($elm);
            }
        }
    }    
  };
})();

IF = {

  open: function() {
    W.d220(IF.rd220);
  },
    
  close: function() {
    DIALOG.close("d-inviofile");
  },
    
  insert: function() {
    var div = $("#if");
    var ds = div.find("#if_ds").val();
    var idSezione = parseInt(div.find("#if_sezioni option:selected").val(), 10);
    var nomeFile = div.find("#uploadform input:hidden").val();
    
    if (!ds.isBlank() && idSezione > 0 && !nomeFile.isBlank()) {
      W.d221(ds, idSezione, nomeFile, IF.rd221);
    } else {
      HINT.error(i18n.js_inviofile_noncompilati);
    }
  },

  rd220: function(data) {
    DIALOG.open({
      id: "d-inviofile",
      html: data,
      buttons: [],
      width: "700px"
    });
    
    $("input#if_input").upBox();
  },
  
  rd221: function(data) {
    if (data) {
      HINT.info(i18n["js_inviofile_ok"]);
      IF.close();
    } else {
      HINT.error(i18n["js_inviofile_ko"]);        
    }
  }
}

TABLE = {
  
  getSelected: function(table) {
    var aReturn = new Array();
    var aTrs = table.fnGetNodes();

    for (var i=0; i<aTrs.length; i++ ) {
      if ( $(aTrs[i]).hasClass('row_selected') ) {
        aReturn.push( aTrs[i] );
      }
    }
    return aReturn;
  },  
  
  create: function($element, options) {
    var language = {
      "oLanguage": {
        "sProcessing": i18n.js_datatable_sProcessing,
        "sLengthMenu": i18n.js_datatable_sLengthMenu,
        "sZeroRecords": i18n.js_datatable_sZeroRecords,
        "sInfo": i18n.js_datatable_sInfo,
        "sInfoEmpty": i18n.js_datatable_sInfoEmpty,
        "sInfoFiltered": i18n.js_datatable_sInfoFiltered,
        "sInfoPostFix": i18n.js_datatable_sInfoPostFix,
        "sSearch": i18n.js_datatable_sSearch,
//        "sUrl": i18n.js_datatable_sUrl,
        "oPaginate": {
          "sFirst": i18n.js_datatable_sFirst,
          "sPrevious": i18n.js_datatable_sPrevious,
          "sNext": i18n.js_datatable_sNext,
          "sLast": i18n.js_datatable_sLast
        }
      },
      "sPaginationType": "full_numbers",
      "bPaginate": true,
      "bInfo": true,
      "bLengthChange": true
    }; 
    var extended = $.extend(true, {}, language, options);
    var table = $element.dataTable(extended);
    $element.click(function(e) {
      $(table.fnSettings().aoData).each(function (){
        $(this.nTr).removeClass('row_selected');
      });
      $(e.target.parentNode).addClass('row_selected');
    });
    return table;
  }
};

var ISBD = {
  getTitle: function(string) {
    var idx1 = string.indexOf(" / ");
    var idx2 = string.indexOf(". - ");
    
    if (idx1 >= 0) {
      if (idx2 >= 0 && idx2 < idx1) {
        string = string.substring(0, idx2);
      } else {
        string = string.substring(0, idx1);
      }
    } else if (idx2 >= 0) {
      string = string.substring(0, idx2);
    }

    return string.replace(/\*/g, "");
  },
  getSortString: function(string) {
    return string.substring(string.indexOf("*")+1).toLowerCase();
  }
}

var MYSPACE = function() {
  
  var btable;
    
  function _open(data, fn) {
    if (data.error != null) {
      if (i18n[data.error] != undefined) {
        HINT.error(i18n[data.error]);
        LOG.error(i18n[data.error]);
      } else {
        HINT.error(data.error);
        LOG.error(data.error);
      }
      return;
    }
    
    function closeHandler() {
      DIALOG.close(dialog);
    }
    
    var buttons = [{ text: i18n.js_btn_esci, handler: closeHandler }];
    
    var dialog = DIALOG.open({
      id: "d-miospazio",
      html: data,
      buttons: buttons,
      width: "800px",
      dynamicHeight: ".yui-content"
    });
    
//    $("#dialog .bd").height($(window).height() -190);
//    $("#ms_tabset .yui-content").height($(window).height() - 240);
      
    var msTabs = new YAHOO.widget.TabView("ms_tabset"); 
    
    $(".ms_biblio:visible").change(MYSPACE.changeBiblio);

    if (fn != undefined && typeof fn == "function") {
      fn();
    } else {
      var selected = $("#ms_tabset .yui-content > div:visible");
      if (selected.size() == 0) return;
      
      var tabname = selected.attr("id");
      if (!tabname) {
        return;
      } else if (tabname == "tabricerche") {
        _tabRicerche();
      } else if (tabname == "tabbibliografie") {
        bibliografie.creaTabella();
      } else if (tabname == "tabmovimenti") {
        _tabMovimenti();
      } else if (tabname == "tabrisposte") {
        _tabProblema();
      }
    }
  }
    
  function _SS_remove(row, table) {
    LOG.info(row);
    var id = table.fnGetData(row)[0];
    LOG.info("MYSPACE: deleting: " + id);
    W.d182(id, function(data) {
      if (data) {
        LOG.info("MYSPACE: saved search id: " + id + " deleted");
        table.fnDeleteRow(row);  
      } else {
        LOG.error("MYSPACE: error deleting saved search id: " + id);
      }
    });
  }
    
  function _SS_run(row, table) {
    var id = table.fnGetData(row)[0];
    LOG.info("MYSPACE: running saved search: " + id);
    A.a10m10(id, function(data) {
      if (data.error != null) {
        LOG.error(data.error);
        return;
      } else {
        r10(data);
        DIALOG.close("d-miospazio");
      }
    });
  }
  
  var suggerimenti = {
    
    apriEsterno: function() {
      
      var handleExit = function() {
        DIALOG.close(this);
      }

      W.d250(function(data) {
        var dialog = DIALOG.open({
          id: "d-suggerimentoguest",
          html: data,
          buttons: [{ text: i18n.js_btn_esci, handler: handleExit }],
          width: "700px",
          visible: false
        });
        
        var form = $(".nuovo_suggerimento");
        
        form.show().submit(function() {
          var c = $(this).attr("catalogazione");
          suggerimenti.inserisci(c);

          return false;
        });
        
        DIALOG.show(dialog);
      });
    },

    apriInterno: function(data) {
      _open(data, suggerimenti.mostra);
    },
    
    rimuovi: function(idSuggerimento) {
      var $this = $(".suggerimento[idMovimento='"+idSuggerimento+"']");
      W.d183(idSuggerimento, function(data) {
        if (data) {
          $this.remove();
          HINT.info(i18n.js_ms_suggremove_ok);
        } else {
          HINT.error(i18n.js_ms_suggremove_error);
        }        
      });
    },
    
    inserisci: function(catalogazione) {
      var fn;
      if (catalogazione == "sebina4") {
        fn = W.d184b;
      } else fn = W.d184;

      $form = $(".nuovo_suggerimento");
  
      var errore = false;
      
      var p = new Object();
      $form.find("input[type='text'], textarea, select").each(function() {
        $(this).parent("td").removeClass("error");
        
        var text = $(this).val();
        if (typeof text == "string" && !text.isBlank()) {
          p[this.name] = text;
        } else if (this.name == "TITOLO") {
          $(this).parent("td").addClass("error");
          errore = true;
        }
      });
      
      if (errore) {
        HINT.error(i18n.js_campimancanti);
        return;
      }

      fn(p, function(data) {
        if (data) {
          HINT.info(i18n.js_ms_sugginsert_ok);
          $("#ms_tabset li.selected a").click();
          DIALOG.close("d-suggerimentoguest");         
        } else {
          HINT.error(i18n.js_ms_sugginsert_error);          
        }
      });
    },
    
    mostra: function() {
      $(".nuovo_suggerimento").show()
        .get(0).reset();
      $(".link_inserimento").hide();
      $(".suggerimento").hide();  
    },
    
    annulla: function() {
      $(".nuovo_suggerimento").hide()
        .get(0).reset();
      $(".link_inserimento").show();
      $(".suggerimento").show();  
    }
    
  }
  
  function _MOV_remove(idMovimento) {
    var handler = function(data) {
      W.d186(idMovimento, function(data) {
        if (data) {
          W.d181("movimenti", _reply);
          HINT.info(i18n.js_ms_movremove_ok);
        } else {
          HINT.info(i18n.js_ms_movremove_error);
        }
        DIALOG.close(dialog);
        $("#ms_tabset li.selected a").click();
      });        
    }

    var dialog = DIALOG.simple({
      message: i18n.js_dialog_myspace_movimenti_cancella,
      handler: handler
    });
  }
  
  function _MOV_prorogate(idMovimento, idBiblioteca) {
    W.d185(idMovimento, idBiblioteca, function(data) {
      if (data) {
        W.d181("movimenti", _reply);
        HINT.info(i18n.js_ms_movprorogate_ok);
      } else {
        HINT.info(i18n.js_ms_movprorogate_error);
      }
    });
  }
  
  function _filter($e) {
    var val = $e.find("option:selected").val();
    $("#tabmovimenti .movimenti").show();
    if (val != "all") {
      $("#tabmovimenti .movimenti:not(.filtro):not(."+val+")").hide();
    }
  }
  
  function _tabRicerche() {
    var rtable = TABLE.create($("#tabricerche table"), {
      "aaSorting": [ [2,'desc'] ],
      "aoColumns": [ 
        { "bSearchable": false, // Id
          "bVisible": false },
        { "sWidth": "50%" }, // Descrizione
        { "sWidth": "25%",
          "sType": "date",
          "bUseRendered": false,
          "fnRender": function(obj) {
            var d = new Date(obj.aData[2]);
            return d.format("dd/MM/yyyy");
          } }, // Data
        { "sWidth": "20%" }, // Risultati
        { "bVisible": false }, // Origine
        { "bSearchable": false, // Cancella
          "bSortable": false,
          "sWidth": "5%" } 
        ]
    });
    
    $('#tabricerche tbody td').click(function(e) {
      var $e = e.target || e.srcElement;
      var row = rtable.fnGetPosition($e.parentNode);

      if ($(this).hasClass("delete")) {
        _SS_remove(row, rtable);
      } else {
        _SS_run(row, rtable);
      }
    });
  }
  
  function _tabMovimenti() {
    var $pregressi = $("div.pregressi");
    if ($pregressi.size() > 0) {
      movimenti.creaTabella();
    }
  }
  
  function _tabProblema() {
    $(".domanda").each(function() {
      
      var $this = $(this);
      $this.click(function() {
        $(this).find(".dettaglio").toggle("blind", {}, 500);
      });

      $this.find(".chiarimento textarea, .chiarimento button")
        .click(function(e) { e.stopPropagation(); });
    
      // Se ci sono chiarimenti a cui rispondere mostrami la domanda anche se risolta
      if ($this.find(".chiarimento textarea").size() > 0) {
        $this.show();
      }
      
      // Se gli allegati sono abilitati, crea la struttura per l'upload
      $(".allegato").upBox().bind("success", insertNewUpload);
      
    });
  }
  
  function _reply(data) {
    if (data.error != null) {
      LOG.error(data.error);
      return;
    } else
      RENDERING.html(data, function() {
        LOG.info("MYSPACE: opening " + data.idDom);
   
        // TABRICERCHE
        if (data.idDom == "tabricerche") {
          _tabRicerche();
        }
    
        //TABBIBLIOGRAFIE
        if (data.idDom == "tabbibliografie") {
          bibliografie.creaTabella();
        }
    
        //TABMOVIMENTI
        if (data.idDom == "tabmovimenti") {
          _tabMovimenti();
        }
        
        //TABPROBLEMA
        if (data.idDom == "tabrisposte") {
          _tabProblema();
        }
    
        $(".ms_biblio:visible").change(MYSPACE.changeBiblio);
      });
  }
  
  movimenti = function() {
   
    var mtable;
    
    return {
      
      cancella: function(cat, codmov, nummov, xidn, bibl, serie, ninvent, tfavo, kfavo) {
        if (cat == "sebina4") {
          var p = new Object();
          p["codmov"] = codmov;
          p["nummov"] = nummov;
          p["xidn"] = xidn;
          p["bibl"] = bibl;
          p["serie"] = serie;
          p["ninvent"] = ninvent;
          p["tfavo"] = tfavo;
          p["kfavo"] = kfavo;

          var handler = function(data) {
            W.d186b(p, function(data) {
              if (data) {
                HINT.info(i18n.js_ms_movremove_ok);
              } else {
                HINT.info(i18n.js_ms_movremove_error);
              }
              DIALOG.close(dialog);
              $("#ms_tabset li.selected a").click();
            });        
          }

          var dialog = DIALOG.simple({
            message: i18n.js_dialog_myspace_movimenti_cancella,
            handler: handler
          });
          
        } //else da muovere qui _MOV_remove
      },
      
      creaTabella: function() {
        mtable = TABLE.create($("div.pregressi").find("table"), {
          "aaSorting": [ [3,'desc'] ],
          "aoColumns": [
            { }, // Tipo movimento
            { "sClass": "dt_title" }, // Titolo
            { "sClass": "dt_title",
              "bVisible": false }, // ISBD
            { } // Data inizio 
            ]
        });
        
        var testo = " " + i18n.js_ms_biblio_isbd;
        var $linkIsbd = $("<a href='#'/>")
          .click(function() {
            if (mtable.fnSettings().aoColumns[2].bVisible == false) {
              mtable.fnSetColumnVis(2, true);
              mtable.fnSetColumnVis(1, false);
              testo = " " + i18n.js_ms_biblio_titolo;
            } else {
              mtable.fnSetColumnVis(1, true);
              mtable.fnSetColumnVis(2, false);
              testo = " " + i18n.js_ms_biblio_isbd;
            }
            $(this).text(testo);
          }).text(testo);
        
        $(".dataTables_length").append($linkIsbd);
      }
      
    }
  }();
  
  bibliografie = function() {
    
    var btable;
    var $bib;
    
    var isbd = false;
    
    function debug(msg) {
      LOG.info(msg);
    }
    
    function _getBib0() {
      return $("#bibliografie .left li.selected");
    }
    
    function _getIdBib0() {
      return _getBib0().attr("idbib");
    }
    
    function _aggiornaEventi() {
      $bib = $("#bibliografie");    
      
      $bib.find(".left li").unbind().click(function() {
        if (!$(this).hasClass("selected")) {
          bibliografie.cambiaBibliografia($(this));
        }
      }).dblclick(function() {
        bibliografie.apriDialogModifica();
      });
      
      $bib.find(".right .remove").unbind().click(function() {
        bibliografie.rimuoviDocumento(this);
        return false;
      });
      
      $bib.find("div.dataTables_wrapper .dt_title").unbind().click(function() {
        var idDoc = $(this).parent().find("span.remove").attr("idtito");
        A.a20m14(idDoc, _getIdBib0(), function(data) {
          DIALOG.close("d-miospazio");
          r20(data); 
        });
      });

      $bib.find("div.dataTables_wrapper .dt_stato").unbind().change(function() {
        bibliografie.cambiaStato(this, $(this).val());             
        return false;      
      });
  
      $bib.find(".right #altreazioni").unbind().change(function() {
        var azione = $(this).val();
        switch (azione) {
        	case "pubblica":
        		bibliografie.pubblicoPrivato();
        		break;
          case "isbd":
            bibliografie.isbdTitolo();
            break;
          case "cancella":
            bibliografie.cancellaBibliografia();
            break;
        }
        $(this).find("option:first").attr("selected", "selected");
      });
      
      if (_getBib0().find(".pubblica").size() > 0) {
        $bib.find(".right .cambiastato").text(i18n.js_ms_biblio_rendiprivata);
      } else {
        $bib.find(".right .cambiastato").text(i18n.js_ms_biblio_rendipubblica);
      }

      if (btable.fnSettings().aoColumns[2].bVisible == false) {
        $bib.find(".right .isbdtitolo").text(i18n.js_ms_biblio_isbd);
      } else {
        $bib.find(".right .isbdtitolo").text(i18n.js_ms_biblio_titolo);
      }
      
      $bib.find(".bib_pub").unbind().dblclick(function() {
        bibliografie.pubblicoPrivato();
        return false;
      });
    }
    
    return {
      
      creaTabella: function(noUpdate) {
        debug("creaTabella");        
        $bib = $("#bibliografie");
      
        jQuery.fn.dataTableExt.oSort['isbd-asc'] = function(x, y) {
          x = ISBD.getSortString(x);
          y = ISBD.getSortString(y);
          return ((x > y) ? -1 : ((x < y) ?  1 : 0));
        };
        
        jQuery.fn.dataTableExt.oSort['isbd-desc'] = function(x, y) {
          x = ISBD.getSortString(x);
          y = ISBD.getSortString(y);
          return ((x < y) ? -1 : ((x > y) ?  1 : 0));
        };
      
        btable = TABLE.create($bib.find(".right table"), {
          "oLanguage": {
            "sZeroRecords": i18n.js_myspace_bibliografie_norisultati 
          },
          "aaSorting": [ [3, "asc"], [2, "desc"] ],
          "aoColumns": [ 
            { }, // Autore
            { "sClass": "dt_title", // Titolo
              "fnRender": function ( oObj ) {
                return ISBD.getTitle(oObj.aData[2]);
              },
              "iDataSort": 2 },
            { "sClass": "dt_title", // ISBD
              "sType": "isbd",
              "bVisible": false },
            { "sWidth": "14em"}, // Data o stato
            { "bSearchable": false, // Pulsanti
              "bSortable": false } 
          ],
          "fnDrawCallback": function() {
            if (btable) _aggiornaEventi();
          }
        });
        
        if (noUpdate == true) return;  
        _aggiornaEventi(); 
      },
      
      cambiaStato: function(e, newStatus) {
        var idDoc = $(e).attr("iddoc");
        W.d189n(_getIdBib0(), idDoc, newStatus, function(data) {
          if (!data) {
            HINT.error("js_error");
          }
        });
      },
      
      // 0 privato, 1 pubblico
      pubblicoPrivato: function(stato) {
        debug("pubblicoprivato");
        var bib0 = _getBib0();
        if (typeof(stato) != "number" || stato < 0 || stato > 1) {
          if (bib0.find(".privata").size() > 0) {
            stato = 0;
          } else {
            stato = 1;
          }
        }
        
        if (stato == 0) {
          W.d189f(_getIdBib0(), false, function(data) {
            if (data.length == 0) {
              HINT.error(i18n.js_errore);
              return;
            } else if (data == "stoplist") {
              HINT.error(i18n.js_myspace_bibliografie_cdinstoplist);
              return;
            }
    
            var urlPubblico = "<a href='" + data + "' title='"
              + i18n.js_ms_biblio_urlpubblicohelp
              + "'>"
              + i18n.js_ms_biblio_urlpubblico
              + "</a>";
            bib0.find(".privata")
                  .removeClass("privata")
                  .addClass("pubblica")
                  .html(i18n.js_ms_biblio_pubblica + "&nbsp;" + urlPubblico);
            $bib.find(".right .cambiastato").text(i18n.js_ms_biblio_rendiprivata);
          });
        } else {
          W.d189f(_getIdBib0(), true, function(data) {
            if (data.length == 0) {
              HINT.error(i18n.js_errore);
              return;
            }
            
            bib0.find(".pubblica")
                  .removeClass("pubblica")
                  .addClass("privata")
                  .html(i18n.js_ms_biblio_privata);
            $bib.find(".right .cambiastato").text(i18n.js_ms_biblio_rendipubblica);
          });
        }
      },
      
      rimuoviDocumento: function(e) {
        debug("rimuoviDocumento"); 
        
        var rimuoviDialog = DIALOG.simple({
          title: i18n.js_ms_biblio_rimuovidoc_titolo,
          message: i18n.js_ms_biblio_rimuovidoc_msg,
          handler:  function() {       
            var idDoc = $(e).attr("iddoc");
            W.d189b(_getIdBib0(), idDoc, function(data) {
              if (data) {
                var row = btable.fnGetPosition(e.parentNode.parentNode);
                btable.fnDeleteRow(row);
                DIALOG.close(rimuoviDialog);
              }
            }, null);
          }
        });
      },
      
      cancellaBibliografia: function() {
        debug("cancellaBibliografia");  
        
        var cancellaDialog = DIALOG.simple({
          title: i18n.js_ms_biblio_rimuovilista_titolo,
          message: i18n.js_ms_biblio_rimuovilista_msg,
          handler: function() {          
            W.d189e(_getIdBib0(), function(data) {
              if (data) {
                var selected = _getBib0(); 
                var $p = selected.prev();
                var $n = selected.next();
        
                var idBib = _getIdBib0();
                for(var i = 0; i < cfgMieListe.liste.length; i++) {
                  if (cfgMieListe.liste[i].id == idBib) {
                    cfgMieListe.liste.splice(i, 1);
                    
                    if (LISTMANIA.last == idBib) {
                      LISTMANIA.last = undefined;
                      $(".addListmania").parent().remove();      
                    }
                    
                    $(".lsBib0").each(function() {
                      var id = this.id.substring(this.id.lastIndexOf("_")+1);
                      if (id == idBib) $(this).remove();                      
                    });                  
                  }
                }        
        
                if ($p.size() > 0) {
                 bibliografie.cambiaBibliografia($p);
                  selected.remove();
                } else if ($n.size() > 0) {
                  bibliografie.cambiaBibliografia($n);
                } else {
                  $("#ms_tabset li.selected a").click();
                }
                
                DIALOG.close(cancellaDialog);
               }
            });
          }
        });
      },
      
      cambiaBibliografia: function($e) {
        debug("cambiaBibliografia"); 
        if ($e.size() == 0) return;
        
        W.d189a($e.attr("idbib"), function(data) {
          var mData = eval(data);

          btable.fnClearTable();
          
          if (mData && mData.length > 0) {
            btable.fnAddData(mData);
          }
          
          var $from = _getBib0();

          var fTitle = $from.attr("title");
          var tTitle = $e.attr("title");
          $from.removeClass("selected").attr("title", tTitle);
          $e.addClass("selected").attr("title", fTitle);
          
          _aggiornaEventi();
        });
      },
      
      isbdTitolo: function() {
        debug("isbdTitolo");         
        if (btable.fnSettings().aoColumns[2].bVisible == false) {
          btable.fnSetColumnVis(2, true);
          btable.fnSetColumnVis(1, false);
          $bib.find(".right .isbdtitolo").text(i18n.js_ms_biblio_titolo);          
        } else {
          btable.fnSetColumnVis(2, false);
          btable.fnSetColumnVis(1, true);
          $bib.find(".right .isbdtitolo").text(i18n.js_ms_biblio_isbd);              
        }
        btable.fnDraw();
      },
      
      apriDialogStampa: function() {
        debug("apriDialogStampa");  
        
        var handleConfirm = function() {
          MYSPACE.bibliografie.stampa();
        }

        var handleCancel = function() {
          DIALOG.close(this);   
        }
        
        var buttons = [{ text: i18n.js_btn_conferma, handler: handleConfirm, isDefault: true },
        { text: i18n.js_btn_esci, handler: handleCancel }];
           
        W.d189i(function(data) {
          DIALOG.simple({
            html: data,
            buttons: buttons,
            width: "600px"
          });
        });
      },
      
      apriDialogEMail: function() {
        debug("apriDialogEMail");     
        
        var handler = function() {
          MYSPACE.bibliografie.invia();
        }        
        
        W.d189m(function(data) {
          DIALOG.simple({
            html: data,
            handler: handler,
            width: "600px"
          });
        });
      },
      
      stampa: function() {
        var docs = new Array();

        var data = btable.fnGetDisplayNodes();
        for(var i = 0; i < data.length; i++) {
          var s = $(data[i]).find(".remove").attr("idtito");
          if (!DIALOG.Strings.isBlank(s)) 
            docs.push(s);            
        }
            
        if (docs.length > 0) {            
          var format = $("#printbiblio .format option:selected").val();
          var layout = $("#printbiblio .layout option:selected").val();
          W.d189h(_getIdBib0(), docs, format, layout, null, function(data) {
            window.open(data);
          });
        }
      },
      
      invia: function() {
        var docs = new Array();
        
        var data = btable.fnGetDisplayNodes();
        for(var i = 0; i < data.length; i++) {
          var s = $(data[i]).find(".remove").attr("idtito");
          if (!DIALOG.Strings.isBlank(s)) 
            docs.push(s);            
        }
            
        if (docs.length > 0) {                    
          var format = $("#mailbiblio .format option:selected").val();
          var layout = $("#mailbiblio .layout option:selected").val();
          var email = $("#mailbiblio .email").val();
          if (email == undefined || email.length == 0) {
            HINT.error(i18n.js_ms_biblio_noemail);
            return;
          }
          
          W.d189h(_getIdBib0(), docs, format, layout, email, function(data) {
            if (data.indexOf("error") >= 0) {
              HINT.error(i18n.js_ms_biblio_senderror);
            } else {
              HINT.info(i18n.js_ms_biblio_sendok);
            }
          });
        }
      },
      
      apriDialogModifica: function($form) {
        debug("apriDialogModifica");
                    
        W.d189l(_getIdBib0(), function(data) {
          var dialogModifica = DIALOG.simple({
            id: "modificabib0",
            html: data,
            handler: MYSPACE.bibliografie.modifica,
            width: "800px"
          });
        });
      },
      
      modifica: function() {
        debug("modifica");

        var bib0 = _getBib0();        
        var idBib0 = _getIdBib0();

        var d = $("#modificabib0");

        var newCd = d.find("input:text").val();
        var newDs = d.find("textarea").val();
        var newStato = d.find("input:radio:checked").val();
        if (newStato == "pubblico") {
          newStato = 1;
        } else if (newStato == "privato") {
          newStato = 0;
        }
        
        if (newCd.isBlank()) {
          HINT.error(i18n.js_ms_biblio_nonewcd);
          return;
        } else if (newDs.isBlank()) {
          HINT.error(i18n.js_ms_biblio_nonewds);
          return;
        } else if (newCd.length > 30) {
          HINT.error(i18n.js_ms_biblio_toolongnewcd);
          return;
        } else if (newDs.length > 1000) {
          HINT.error(i18n.js_ms_biblio_toolongnewds);
          return;
        }
        
        W.d189g(newCd, newDs, idBib0, function(data) {
          if (data == "ok") {
            bib0.find(".bib_cd").text(newCd);
            bib0.find(".bib_ds").text(newDs);
            
            if (newStato == 1 && bib0.find(".privata").size() > 0) {
              bibliografie.pubblicoPrivato(0);
            } else if (newStato == 0 && bib0.find(".pubblica").size() > 0) {
              bibliografie.pubblicoPrivato(1);
            }
            DIALOG.close("modificabib0");
            
            for(var i = 0; i < cfgMieListe.liste.length; i++) {
              var lista = cfgMieListe.liste[i];
              
              if (lista.id == idBib0) {
                lista.cd = newCd;
                lista.ds = newDs;
                
                $(".lsBib0").each(function() {
                  var id = this.id.substring(this.id.lastIndexOf("_")+1);
                  if (id == idBib0) {
                    $(this).text(" - " + newCd); 
                  }
                });                  
              }
            }                  
            
          } else if (data == "stoplist") {
            HINT.error(i18n.js_myspace_bibliografie_cdinstoplist);
          } else {
            HINT.error(i18n.js_ms_biblio_saveerror);
          }
        });
      }
    }
    
  }();

  return {

    open: function() {
      W.d180(_open);
    },
    
    openWithTab: function(tab, params) {
      W.d187(tab, params, _open);
    },
    
    changeTab: function(tab, params) {
      var $tab = $("#tab" + tab);
      if ($tab.size() > 0) {
        if (params == undefined) {
          if ($tab.attr("params") != undefined) {
            params = $tab.attr("params");
          } 
        } else {
          $tab.attr("params", params); 
        }
      }
      W.d181(tab, params, _reply);
    },
      
    createTable: function(options) {
      _newTable(options);
    },
    
    changeBiblio: function() {
      var catalogazione = $(this).attr("catalogazione");
      if (typeof catalogazione != "undefined" && catalogazione == "sebina4") {
        W.d189($(this).val(), function() {
          $("#ms_tabset li.selected a").click();
        });    
      } else {
        W.d188($(this).val(), function() {
          $("#ms_tabset li.selected a").click();
        });    
      }
    },
        
    filter: function(e) {
      _filter($(e));
    },
      
    suggerimenti: {
      nuovo: function() { // TODO appena possibile cambiare il widget suggerimenti
        suggerimenti.apriEsterno();
      },
      apriInterno: function() {
        W.d187("suggerimenti", null, suggerimenti.apriInterno);
      },
      apriEsterno: function() {
        suggerimenti.apriEsterno();
      },      
      rimuovi: function(idSuggerimento) {
        suggerimenti.rimuovi(idSuggerimento);
      },
      inserimento: {
        mostra: function() {
          suggerimenti.mostra();
        },
        annulla: function() {
          suggerimenti.annulla();
        },
        salva: function(catalogazione) {
          suggerimenti.inserisci(catalogazione);
        }
      }
    },
      
    movimenti: {
      cancella: function(cat, codmov, nummov, xidn, bibl, serie, ninvent, tfavo, kfavo) {
        return movimenti.cancella(cat, codmov, nummov, xidn, bibl, serie, ninvent, tfavo, kfavo);
      },
      proroga: function(idMovimento) {
        _MOV_prorogate(idMovimento);
      },
      rimuovi: function(idMovimento) {
        _MOV_remove(idMovimento);
      }
    },
      
    bibliografie: {
      apri: function(idBib0, params) {
        W.d187("bibliografie", params, function(data) {
          _open(data, function() {
            var $e = $(".bibliografia[idbib='"+idBib0+"']");
            bibliografie.creaTabella();
            bibliografie.cambiaBibliografia($e);
          });
        });
      },
      creaTabella: function() {
        bibliografie.creaTabella();
      },
      pubblicoPrivato: function() {
        bibliografie.pubblicoPrivato($(this));
      },
      rimuoviDocumento: function(e) {
        bibliografie.rimuoviDocumento(e);
      },
      cancellaBibliografia: function() {
        bibliografie.cancellaBibliografia();
      },
      cambiaBibliografia: function($e) {
        bibliografie.cambiaBibliografia($e);
      },
      isbdTitolo: function() {
        bibliografie.isbdTitolo();
      },
      apriDialogStampa: function() {
        bibliografie.apriDialogStampa();
      },
      apriDialogEMail: function() {
        bibliografie.apriDialogEMail();
      },
      apriDialogModifica: function() {
        bibliografie.apriDialogModifica($(this));
      },
      stampa: function() {
        bibliografie.stampa();
      },
      invia: function() {
        bibliografie.invia();
      },
      modifica: function() {
        bibliografie.modifica($(this).parents("form:eq(0)"));
      }
    },
    
    problema: {
      inserimento: {
        mostra: function() {
          $("#form_problema").show()
            .get(0).reset();
          $(".link_inserimento").hide();
          $(".domande").hide();  
        },
        cancella: function() {
          $("#form_problema").hide()
            .get(0).reset();
          $(".link_inserimento").show();
          $(".domande").show();  
        },
        salva: function() {
          d141(null, function() {
            MYSPACE.changeTab('risposte');
          });
        }
      },
      risolte: {
        toggle: function() {
          var $menu = $("#tabrisposte .movmenu");
          if (typeof $menu.attr("risolte") == "undefined") {
            $("#tabrisposte .risolta:hidden").show("blind", { }, 500);
            $menu.find("a").text(i18n.js_ms_risposte_nascondirisolte)
              .end().attr("risolte", "true");
          } else {
            $("#tabrisposte .risolta").hide("blind", { }, 500);
            $menu.find("a").text(i18n.js_ms_risposte_mostrarisolte)
              .end().removeAttr("risolte", "true");
          }
        },
        chiarisci: function() {
          var $this = $(this);
          var id = $this.attr("idchiarimento");
          var risposta = $this.find("textarea").val();
          
          W.d142(id, risposta, function(data) {
            if (data) {
              $this.replaceWith(risposta);
            } else {
              HINT.error(i18n.js_ms_risposte_errorechiarimento);              
            }
          });
        }
      }
    }
  };
}();

FAQ = function() {
  
  var flag = false;
  
  return {
    
    open: function() {
      A.a70m00(RENDERING.rBody);  
    },
    
    changeArgument: function() {
      if (this.tagName == "A") {
        A.a70m01(0, [0], RENDERING.rBody);
      } else if (this.tagName == "SELECT") {
        var $id = $(this).val();
        var ids = new Array();
        ids.push("0");
        var id;
        $("div.paths select.path").each(function(i) {
          id = parseInt($(this).find("option:selected").val(), 10);
          ids[i+1] = id;
          if ($id != undefined && $id == id) {
             return false;
          }
        });
        
        A.a70m01(id, ids, RENDERING.rBody);
      }
    },
    
    cerca: function() {
      var stringa = $(this).find("input[type='text']").val();
      var extended = $(this).find("input[type='checkbox']").is(":checked");

      if (!stringa.isBlank()) {
        A.a70m02(stringa, extended, RENDERING.rBody);
      }
    },
    
    openMe: function() {
      $(this).find("p:not(:first)").toggle();
      $(this).toggleClass("selected");
    },
    
    changePage: function(page) {
      if (flag) return;
      var $this = $(this);
      var $faqs = $("div.faqs");
      if ($this.hasClass("selected")) return;
      
      flag = true;
      $faqs.find("ul").fadeOut(function() {
        $faqs.find("li.faq").hide().end()
          .find("li.page-" + page).show().end()
          .find("ul").fadeIn(function() {
            $faqs.find("div.pager a.page").removeClass("selected").end()
              .find("div.pager a.page:contains('"+page+"')").addClass("selected");
            flag = false; 
          });
      });
    }
    
  };
}();

DOWNLOADS = function() {
    
  var flag = false;
  
  return {
    
    open: function() {
      A.a71m00(RENDERING.rBody);  
    },
    
    changeArgument: function() {
      if (this.tagName == "A") {
        A.a71m01(0, [0], RENDERING.rBody);
      } else if (this.tagName == "SELECT") {
        var $id = $(this).val();
        var ids = new Array();
        ids.push("0");
        var id;
        $("div.paths select.path").each(function(i) {
          id = parseInt($(this).find("option:selected").val(), 10);
          ids[i+1] = id;
          if ($id != undefined && $id == id) {
             return false;
          }
        });
        
        A.a71m01(id, ids, RENDERING.rBody);
      }
    },
    
    cerca: function() {
      var stringa = $(this).find("input[type='text']").val();

      if (!stringa.isBlank()) {
        A.a71m02(stringa, RENDERING.rBody);
      }
    },
    
    openMe: function() {

    },
    
    changePage: function(page) {
      if (flag) return;
      var $this = $(this);
      var $e = $("div.downloads");
      if ($this.hasClass("selected")) return;
      
      flag = true;
      $e.find("ul").fadeOut(function() {
        $e.find("li.download").hide().end()
          .find("li.page-" + page).show().end()
          .find("ul").fadeIn(function() {
            $e.find("div.pager a.page").removeClass("selected").end()
              .find("div.pager a.page:contains('"+page+"')").addClass("selected");
            flag = false; 
          });
      });
    }
    
  };
}();

ROLLBANNER = function() {
  var defaults = {
    
    rbTimer: null,
    rbInterval: 10000,
    
    currentFrame: 0,
    totalFrames: 0,
    mode: 0,
    
    $object: null
    
  };
  
  var p;
  var current = 0;
  
  function _init(params) {
    
    p = $.extend(true, {}, defaults, params);
    
    var $e = $("<b class='r_banner'/>")
      .appendTo("body");
      
    p.totalFrames = parseInt($e.css("padding-right"), 10);
    p.$object = $($e.css("font-family"));
    p.rbInterval = parseInt($e.css("padding-left"), 10) * 1000;
    p.mode = parseInt($e.css("padding-top"), 10);
    
    $("b.r_banner").remove();
    
    var $next = $("<div id='nextBackground'/>")
      .appendTo("body")
      .css( { position: "absolute",
        top: "0",
        right: "0",
        padding: "1em",
        "z-index": "99999" })
      .click(function() {
        ROLLBANNER.change();
      });
  }
  
  function _random(seed) {
    return Math.floor(Math.random()*seed)+1;         
  }
  
  return {
    
    start: function(params) {
      _init(params);
      if (p.totalFrames > 0 && p.$object.size() > 0) {
        if (p.mode > 0) {
          ROLLBANNER.change(++current);
          if (current >= p.totalFrames) {
            current = 0;
          }  
        } else {
          ROLLBANNER.change(_random(p.totalFrames));
        }

        if (p.rbInterval > 0) {
          p.rbTimer = window.setInterval("ROLLBANNER.change()", p.rbInterval);
        }        
      };
    },
    
    stop: function() {
      window.clearInterval(rbTimer);
    },
    
    change: function(frame) {
      if (typeof frame == "undefined") {
        frame = ++current;
      }
      
      p.$object.addClass("r_banner" + frame);
      for(var i = 1; i <= frame; i++) {
        if (i != frame) {
          p.$object.removeClass("r_banner" + i);
        }
      }
    }

  };
}();

$(function() {
  ROLLBANNER.start();
});

/*
  Google Maps Api v2 - preloading                                                    * 
*/
GMUtils = function() {
  
  preload = "stop";
  var dataStore;
  var timer;
  
  return {
    preload: function() {
      preload = "loading";      
      LOG.info("GMAPI: Preloading Google Maps Api 2");
      $.getScript("http://www.google.com/jsapi?key="+gmKey, function() {
        google.load("maps", "2", { "language": "it_IT", "callback": function() {
            if (!GBrowserIsCompatible()) {
              LOG.info("GMAPI: Preload complete, browser not compatible");
              preload = "broken";
            } else {
              LOG.info("GMAPI: Preload complete, browser compatible");
              preload = "complete";
            }
          }
        });
      });
    },
    
    open: function(data, fn, args) {
      if (timer)
        window.clearTimeout(timer);

      if (preload == "stop") {

        preload();
        if (dataStore == null) {
          dataStore = new Object();
          
          dataStore["data"] = data;
          dataStore["args"] = args;
        }
        timer = window.setTimeout(MAPS.open, 1000);

      } else if (preload == "loading") {

        timer = window.setTimeout(MAPS.open, 1000);

      } else if (preload == "broken") {

        HINT.error("Preload di Google Maps fallito");

      } else if (preload == "complete") {

        if (dataStore) {
          data = dataStore["data"];
          args = dataStore["args"]; 
          delete dataStore;          
        }
        
        if (fn) fn(data, args);
      }
    }
    
  }
}();

HOMEMAPS = {
  search: function(frase) {
    A.a13m00(frase, RENDERING.body);
  },
  
  page: function(page) {
    A.a13m02(page, RENDERING.body);
  },
  
  get: function(idWhere) {
    A.a13m01(idWhere, RENDERING.body);
  },
  
  get2: function(idWhere) {
    A.a13m03(idWhere, RENDERING.body);
  },
  
  input: function(e) {
    e = $(e);
    if (e.size() > 0 && !e.attr("first")) {
      e.attr("first", true);
      e.val("");
    }
  },
  
  open: function(data) {
    
    if (data.error) {
      if (i18n[data.error]) {
        HINT.error(i18n[data.error]);
      } else HINT.error(data.error);
    }
    
    if (data.script) {
      try {
        data = eval(data.script);
      } catch (e) {
        LOG.error("Errore in apertura, dati non idonei");
        return;
      }
    } else {
      LOG.error("Errore in apertura, dati non esistenti");
      return;
    }
    
    var bounds = new GLatLngBounds();
    var map = new GMap2($("#hmaps-container").get(0));
    
    for(var i = 0; i < data.length; i++) {
      var bib = data[i];
      
      var gLatLng = new GLatLng(bib.latitudine, bib.longitudine);

      var marker = new GMarker(gLatLng, { title: bib.tooltip });
      
      if (bib.prop.preview) {
        marker.bindInfoWindowHtml(bib.prop.preview);
      } 
      
      map.addOverlay(marker);
      bounds.extend(gLatLng);
    }

    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
  
    map.checkResize();
    map.setUIToDefault();
  }    
};


/*
  Google Maps Api v2                                                                 * 
*/
GMAPI = function() {

  var resets = {
    $cont: null,
    $canv: null,
    gMap: null,
    steps: 0,
    step: 0,
    def: null,
    defLat: null,
    defLng: null,
    bounds: null,
    markers: new Object(),
    infoBoxes: new Object(),
    timers: new Array(),
    unknown: new Object()
  };
  
  var r;
  var preload = false;
  var loadTimer;
  var args = null;

  function _openMapWindow() {
  
    var a = $("<a href='#' onclick='GMAPI.close(); return false;'></a>")
      .text(i18n.js_gmapi_close);
      
    r.$canv = $("<div id='map_canvas'></div>");
  
    r.$cont = $("<div id='map_container'></div>")
      .append(a)
      .append(r.$canv)
      .appendTo("body");

    _resizeMapWindow();
    $(window).bind("resize", GMAPI.resize);
    LOG.info("GMAPI: Showing map window");
  }
  
  function _resizeMapWindow() {
    r.$canv.css({ height: ($(window).height() - 145) + "px"});
    if (r.gMap != undefined) r.gMap.checkResize();                    
  }
  
  function _splitCode(code) {
    if (code != null && code.indexOf("@") >= 0) {
        return code.split("@")[0];
    } else return code;
  }
  
  function _objSize(object) {
    var count = 0;
    $.each(object, function() { count++;});
    return count;
  }
  
  function _hasLatLng(object) {
    if (object != null && object.latitudine != null && object.longitudine != null) {
      return true;
    } else {
      return false;
    }
  }
  
  function _isDefaultMarker(code, key, value) {
    if (code == r.def) {
      r.def = key;
      r.defLat = value.latitudine;
      r.defLng = value.longitudine;
    }
  }
  
  function _showDefaultMarker() {
    if (r.markers[r.def] != undefined) {
      r.markers[r.def].openInfoWindowHtml(r.infoBoxes[r.def]);
    }
  }
  
  function _setMapMarkers(args, idType) {
    
    args = Array.prototype.slice.call(args);   
    LOG.info("GMAPI: Setting map markers : args("+args.toString()+")");

    if (args.length == 0) {
      LOG.error("GMAPI: setMapMarkers arguments are empty");           
      return;
    }
    
    r.def = _splitCode(args.shift());
    LOG.info("GMAPI: Default marker : " + r.def);
      
    var fn;  
    if (!idType || idType == "idAux") {
      fn = W.d191;
    } else if (idType == "idWhere") {
      fn = W.d191b;
    }
        
    fn(args, function(data) {

      var data = eval("("+data+")");
      r.steps = _objSize(data);
      
      LOG.debug(r.steps);

      r.bounds = new GLatLngBounds();
      $.each(data, function(key, value) {
        if (_hasLatLng(value)) {
          _isDefaultMarker(value.idAux, key, value);
          _setKnownMarker(key, value);
        } else {
          _setStep();
        }
      });
    });
  }
  
  function _setMarker(key, value) {
    r.markers[key] = new GMarker(new GLatLng(value.latitudine, value.longitudine), { title: value.tooltip });
    r.markers[key].key = key;
    r.infoBoxes[key] = value.html;
    
    GEvent.addListener(r.markers[key], "click", function() {
        this.openInfoWindowHtml(r.infoBoxes[this.key]);
      });
    
    r.bounds.extend(new GLatLng(value.latitudine, value.longitudine));
  }
  
  function _setKnownMarker(key, value) {
    LOG.info("GMAPI: Setting a known position marker : (lat " + value.latitudine + " - lng " + value.longitudine + ")");
    
    _setMarker(key, value);
    _setStep();
  }

  function _setUnknownMarker(key) {
    var value = r.unknown[key];
    if (typeof value == "undefined") return;
    
    LOG.info("GMAPI: Setting an unknown position marker : (" + key + ", " + value.indirizzo + ")");
        
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(value.indirizzo, function(point) {
        if (!point) {
          LOG.error("GMAPI: Position not found : " + key);
        } else {
          W.d192(key, point.lat(), point.lng(), function(data) {
            if (!data) LOG.error("GMAPI: Position not saved : " + key);
          });

          value.latitudine = point.lat();
          value.longitudine = point.lng();
          _setMarker(key, value);

          _isDefaultMarker(key, value);
        }

       _setStep();
      });
  }
  
  function _adjustMap() {
    var point;
    var zLevel;
    r.gMap = new GMap2($("#map_canvas")[0]);

    if (r.defLat != null && r.defLng != null) {
      r.gMap.setCenter(new GLatLng(r.defLat, r.defLng), 17);
    } else {
      r.gMap.setCenter(r.bounds.getCenter(), r.gMap.getBoundsZoomLevel(r.bounds));
    }
    
    r.gMap.checkResize();
    r.gMap.setUIToDefault();

    LOG.info("end");
    LOG.dir(r.markers);
    $.each(r.markers, function(key, value) {
      r.gMap.addOverlay(value);
    });
    LOG.groupEnd("gmaps");
  }
  
  function _setStep() {
    if (r.steps == ++r.step) {
      LOG.info("GMAPI: Positioning map center and zoom");
    
      _adjustMap();      
      _showDefaultMarker();
    }
  }
  
  return {
    
    open: function() {
      LOG.group("gmaps");
      LOG.debug("open");
      GMUtils.open(arguments, GMAPI.load, "idAux");
    },
    
    openByIds: function() {
      LOG.debug("gmapi.openByIds");
      GMUtils.open(arguments, GMAPI.load, "idWhere");
    },
    
    load: function(data, idType) {
      LOG.debug("gmapi.load");
      r = $.extend(true, {}, resets);
      _openMapWindow();
      _setMapMarkers(data, idType);
    },
    
    close: function() {
      LOG.info("Closing map window");
      r.gMap.clearOverlays();
      r.$cont.remove();
      $(window).unbind("resize", GMAPI.resize);
      r = null;
    },
    
    resize: function() {
      _resizeMapWindow();
    },
    
    set: function(key) {
      _setUnknownMarker(key);
    }
  };
  
}();

SIZES = {
  viewport: {
    height: function() {
      if (typeof window.innerHeight != 'undefined') {
        return window.innerHeight;
      } else if (typeof document.documentElement != 'undefined'
          && typeof document.documentElement.clientHeight != 'undefined' 
          && document.documentElement.clientHeight != 0) {
        return document.documentElement.clientHeight;
      } else {
        return document.getElementsByTagName('body')[0].clientHeight;
      }
    },
    width: function() {
      if (typeof window.innerWidth != 'undefined') {
        return window.innerWidth;
      } else if (typeof document.documentElement != 'undefined'
          && typeof document.documentElement.clientWidth != 'undefined' 
          && document.documentElement.clientWidth != 0) {
        return document.documentElement.clientWidth;
      } else {
        return document.getElementsByTagName('body')[0].clientWidth;
      }
    }
  },
  document: {
    height: function() {
      return Math.max(
        document.body.clientHeight, document.documentElement.clientHeight
      ) + Math.max(
        document.body.scrollTop, document.documentElement.scrollTop
      );
    },
    width: function() {
      return Math.max(
        document.body.clientWidth, document.documentElement.clientWidth
      ) + Math.max(
        document.body.scrollLeft, document.documentElement.scrollLeft
      );
    }
  },
  scrollTop: function() {
    return (document.all) 
      ? document.documentElement.scrollTop
      : window.pageYOffset;
  }
};

DIALOG = function() {
  
  var standard = {
    id: "dialog",
    title: undefined,
    html: null,
    visible: true,
    modal: true,
    close: true,
    closeTimer: 0,
    buttons: [],
    keys: [],
    width: undefined,
    dynamicHeight: undefined
  }
  
  var stack = {
    dialogs: new Object(),
    modals: new Object(),
    zIndex: 0,
    moveTimer: undefined,
    closeTimer: new Object()
  }
  
  function objectCount(object) {
    if (typeof object != "object") return;

    var len = 0;
    for (var key in object) 
      len++;
    return len;
  }
  
  function setPosition(node, animate) {
    var left = SIZES.viewport.width() - $(node).width();
    left = (left < 0 ? 0 : left / 2) + "px";
    var top = SIZES.viewport.height() - $(node).height();
    top = (top < 0 ? 0 : top / 2 + SIZES.scrollTop()) + "px";

    if (animate) {
      $(node).animate({ "left": left, "top": top }); 
    } else {
      node.style.left = left;
      node.style.top = top; 
    }
  }
  
  function setModalPosition(node) {
    node.style.height = SIZES.document.height() + "px";
    node.style.width = SIZES.document.width() + "px";
  }
  
  function setResizeEvent() {
    unsetResizeEvent();
    $E.addListener(document, "keydown", DIALOG.keydown, false);
    $E.addListener(window, "resize", DIALOG.refresh, false);
    $E.addListener(window, "scroll", DIALOG.refresh, false);
  }

  function unsetResizeEvent() {
    $E.removeListener(document, "keydown", DIALOG.keydown);            
    $E.removeListener(window, "resize", DIALOG.refresh);      
    $E.removeListener(window, "scroll", DIALOG.refresh);      
  }

  function createDialog(options) {
    var p = $.extend(true, {}, standard, options);
    
    if (DIALOG.isOpen(p.id)) {
      DIALOG.close(p.id);
    }
    
    var e = document.getElementById(p.id);

    if (e) {
      UTIL.purgeNode(e);
    } 
    
    e = document.createElement("div");
    e.id = p.id;
    e.className = "syd-block";
    e.style["width"] = p.width ? p.width : $(document).width() / 3 + "px";
    e.style["display"] = "none";
    document.body.appendChild(e);
    
    e.innerHTML = "<table class='syd-table'>" + "<tr>"
    + "<td class='tl'></td>" + "<td class='tc'></td>" + "<td class='tr'></td>"
    + "</tr><tr>" + "<td class='cl'></td>" + "<td class='cc'></td>"
    + "<td class='cr'></td>" + "</tr><tr>" + "<td class='bl'></td>"
    + "<td class='bc'></td>" + "<td class='br'></td>" + "</tr>" + "</table>";

    var cc = $(e).find(".cc").get(0);

    var html = "";
    if (!DIALOG.Strings.isBlank(p.title)) {
      var lang = i18n[p.title];
      html = '<div class="hd">' + (lang ? lang : p.title) + '</div>';
    }

    if (!DIALOG.Strings.isBlank(p.message)) {
      var lang = i18n[p.message];
      html += '<div class="bd">' + (lang ? lang : p.message) + '</div>';
    }    

    cc.innerHTML = DIALOG.Strings.isBlank(p.html) ? html : p.html;
    
    if (!DIALOG.Strings.isBlank(p.dynamicHeight)) {
      var dc = $(e).find(p.dynamicHeight).get(0);
      if (!dc) return;
      dc.style.height = ($(window).height() / 1.5) + "px";
    }

    var bc = $(e).find(".bc").get(0);
    if (bc && p.buttons.length > 0) {
      for(var i=0; i<p.buttons.length; i++) {
        var button = p.buttons[i];

        var node = document.createElement("button");
        if (button.isDefault) {
          node.className = "std_btn syd-default";
        } else {
          node.className = "std_btn";
        }
        node.innerHTML = button.text;
       
        $E.addListener(node, "click", button.handler, e, e);

        bc.appendChild(node);
        
      }
    }

    stack.zIndex += 2;
    stack.dialogs[p.id] = stack.zIndex;
    e.style.zIndex = 1000 + stack.zIndex;

    if (p.modal) {
      var mId = p.id + "-modal"; 
      
      var m = document.getElementById(mId);
      if (m) {
        UTIL.purgeNode(m);
      } 

      m = document.createElement("div");
      m.id = mId;
      
      if (stack.zIndex == 2) {
        m.className = "syd-modal syd-modal-first";
      } else {
        m.className = "syd-modal";
      }
      
      setModalPosition(m);
      m.style.zIndex = 999 + stack.zIndex;
      
      document.body.appendChild(m);
      
      stack.modals[m.id] = m.style.zIndex;
    }

    if (p.close) {
      var c = document.createElement("div");
      c.className = "syd-close";
      $E.addListener(c, "click", DIALOG.x);
      e.appendChild(c);
    }

    if (p.visible) {
      show(e, false);
    }

    return e;
  }
  
  function show(node, animate) {
    if (node && node.style["display"] == "none") {
      if (animate) node.style["display"] = "";
      setPosition(node, animate);
      if (!animate) node.style["display"] = "";
      setResizeEvent(); 

      var button = $(node).find(".syd-default").get(0);
      if (button) {
        button.focus();
      } else node.focus();        
    }
  }
  
  function removeModal(nodeId) {
    var modalId = nodeId + "-modal";
    
    var m = document.getElementById(modalId);
    if (m) {
      UTIL.purgeNode(m);
      delete stack.modals[modalId];
    }
  }
  
  function getTopDialog() {
    var mx = 0;
    var nodeId;
    for (var key in stack.dialogs) {
      if (stack.dialogs[key] > mx) {
        mx = stack.dialogs[key];
        nodeId = key;
      }
    }
    return nodeId;
  }
  
  function parseNodeParam(node, childSelector) {
    if (typeof node == "string")
      node = $("#"+node).get(0);
    
    if (childSelector)
      return $(node).find(childSelector).get(0);
    return node;
  }
  
  function parseDataParam(data) {
    if (typeof data == "object") {
      if (data.error) {
        if (i18n[data.error]) {
          HINT.error(i18n[data.error]);
        } else HINT.error(data.error);
        
        return false;
      }

      return data.html;
    }
  }
  
  return {
    refresh: function() {
      clearTimeout(stack.moveTimer);
      stack.moveTimer = window.setTimeout(function() {
        for (var modalId in stack.modals) {
          var modal = document.getElementById(modalId);
          if (modal)
            setModalPosition(modal);
        }
        
        for (var nodeId in stack.dialogs) {
          var node = document.getElementById(nodeId);
          if (node)
            setPosition(node, true);
        }
      }, 200);
    },
    replace: function(node, data) {
      node = parseNodeParam(node, ".cc");
      data = parseDataParam(data);
      if (data == false) return;
          
      if (node) {
        if (node.childNodes.length > 0) {
          UTIL.purgeChilds(node);
        }
        node.innerHTML = data;
      }
    },
    setBody: function(node, data) {
      if (typeof node == "string") {
        node = $("#"+node).find(".bd").get(0);
      } else {
        node = $(node).find(".bd").get(0);
      }
      
      if (typeof data == "object") {
        if (data.error) {
          if (i18n[data.error]) {
            HINT.error(i18n[data.error]);
          } else HINT.error(data.error);
          
          return;
        }

        data = data.html;
      }
          
      if (node) {
        if (node.childNodes.length > 0) {
          UTIL.purgeChilds(node);
        }
        node.innerHTML = data;
      }
    },
    open: function(p) {
      // Gestione oggetto dwr
      if (p.html) {
        if (typeof p.html == "object") {
          var data = p.html;
          p.html = data.html;
          
          if (data.error) {
            if (i18n[data.error]) {
              HINT.error(i18n[data.error]);
            } else HINT.error(data.error);
            
            return;
          }
        }
      } else if (p.message) {
        if (typeof p.message == "object") {
          var data = p.message;
          p.message = data.html;
          
          if (data.error) {
            if (i18n[data.error]) {
              HINT.error(i18n[data.error]);
            } else HINT.error(data.error);
            
            return;
          }
        }
      }
      
      if (p.closeTimer > 0) {
        stack.closeTimer[p.id] = window.setTimeout("DIALOG.close('"+p.id+"');", p.closeTimer);
      }
      
      return createDialog(p);
    },
    x: function() {
      DIALOG.close(this.parentNode.id);
    },
    isOpen: function(node) {
      var nodeId;
      if (typeof node == "string") {
        nodeId = node; 
        node = document.getElementById(node);
      } 
       
      if (node) {
        for (stackId in stack.dialogs) {
          if (stackId == nodeId) return true;          
        }        
      }
      
      return false;
    },    
    close: function(node) {

      var nodeId;
      if (typeof node == "string") {
        nodeId = node; 
        node = document.getElementById(node);
      } 
       
      if (node) {
        if (DIALOG.Strings.isBlank(nodeId)) {
          nodeId = node.getAttribute("id");
        }
        
        delete stack.dialogs[nodeId];

        if (objectCount(stack.dialogs) == 0) {
          unsetResizeEvent(); 
          stack.zIndex = 0;
        } 

        UTIL.purgeNode(node);
        removeModal(nodeId);
        
        if (typeof stack.closeTimer[nodeId] != "undefined") {
          clearTimeout(stack.closeTimer[nodeId]);
          delete stack.closeTimer[nodeId]; 
        }
      }
    },
    show: function(node) {
      show(node);
    },
    keydown: function(e) {
      if (e.keyCode == 27) {
        DIALOG.close(getTopDialog());
        $E.preventDefault(e);
        $E.stopPropagation(e);
      } 
    },
    getLastZIndex: function() {
      return stack.zIndex + 1000;
    }
  }
}();  
  
DIALOG.Strings = {
  trim: function(s) {
    if (typeof s != "string") return null;
    return s.replace(/^\s+|\s+$/g, "");
  },
  normWhiteSpace: function(s) {
    if (typeof s != "string") return null;
    return DIALOG.Strings.trim(s.replace(/\s+/g, " "));
  },
  isEmpty: function(s) {
    if (typeof s != "string") return true;
    return (typeof s != "string" || s.length == 0);
  },
  isBlank: function(s) {
    if (typeof s != "string") return true;
    return DIALOG.Strings.isEmpty(DIALOG.Strings.trim(s)); 
  },
  merge: function(s1, s2) {
    if (!DIALOG.Strings.isBlank(s1)) return s1;
    return s2;
  },
  equals: function(s1, s2, ignorecase) {
    if (typeof ignorecase == "undefined")
      ignorecase = false;
    
    var blank = DIALOG.Strings.isBlank;
    if (blank(s1) && blank(s2)) {
      return true;
    } else if (blank(s1) || blank(s2)) {
      return false;
    } else {
      if (ignorecase && s1.toLowerCase == s2.toLowerCase) {
        return true;
      } else if (s1 == s2) {
        return true;
      } else {
        return false;
      }
    }
  }
};  
  
DIALOG.info = function(options) {
  return DIALOG.simple($.extend(true, { 
    id: "d-info",
    title: i18n.js_info 
  }, options ));
}

DIALOG.simple = function(options) {
  var handleCancel = function() {
    DIALOG.close(this);   
  }
  
  buttons = new Array();
  if (options.handler) 
    buttons.push({ text: i18n.js_btn_continua, handler: options.handler });
  buttons.push({ text: i18n.js_btn_esci, handler: handleCancel, isDefault: true });

  var dialog = DIALOG.open($.extend(true, {
    id: "d-simple",
    buttons: buttons
  }, options));
  
  return dialog;
}

HINT = {};

HINT.info = function(message) {
  if (message && message.error) {
    HINT.error(message);
    return;
  }

  DIALOG.simple({
    id: "d-infohint",
    title: i18n.js_info,
    message: message,
    closeTimer: 6000
  });
}

HINT.help = function(message) {
  HINT.warn(message);
}

HINT.warn = function(message) {
  if (message && message.error) {
    HINT.error(message);
    return;
  }

  DIALOG.simple({
    id: "d-warnhint",
    title: i18n.js_attenzione,
    message: message,
    closeTimer: 6000
  });
}

HINT.error = function(message) {
  if (message && message.error)
    message = message.error;
  
  DIALOG.simple({
    id: "d-errorhint",
    title: i18n.js_errore,
    message: message,
    closeTimer: 6000
  });
}

/*
 * jQuery extension by casph
 * for uploading files via servlet
 * using an iframe for catch
 * the server reply.
 * 
 * usage: $(fileInputElement).upBox();
 * 
 */

jQuery(function($) {
  $.fn.upBox = function(options) {    
    
    var p = $.extend({}, $.fn.upBox.defaults, options);
    var uploadTimer;
    
    function _createIFrame() {
      debug("begin: createIFrame");
      p.$iframe = $("<iframe name='uploadframe'/>")
        .attr("id", "uploadframe")
        .attr("name", "uploadframe")
        .css("position", "absolute")
        .css("visibility", "hidden")
        .appendTo("body");
      debug("end: createIFrame")      
    }
    
    function _removeIFrame() {
      debug("removeIFrame");
      p.$iframe.remove();
      p.$iframe = undefined;
    }
    
    function _createDOM($e) {
      debug("begin: createDOM");

      p.$input = $e;
      p.$form = $("<form/>").attr({
        "action": "upload",
        "method": "POST",
        "id": "uploadform",
        "enctype": "multipart/form-data",
        "encoding": "multipart/form-data",
        "target": "uploadframe" });

      $e.wrap(p.$form);
      p.$form = $e.parent("form");
         
      $e.removeAttr("id")
        .attr("name", "file")
        .attr("size", "50")
        .change(function(e) { 
          _fileUpload($(this));
        });
        
      debug("end: createDOM");      
      
      return p.$form;  
    }   

    function _fileUpload($e) {
      debug("fileUpload")
      if (p.$iframe == undefined) _createIFrame();
      
      p.$form.submit();
      uploadTimer = window.setInterval(_checkUpload, 1000);

      return false;
    }
    
    function _checkUpload() {
      debug("checkUpload");
      if (_callBack() == true) _confirmUpload();
    } 
    
    function _callBack() {
      debug("callBack");
      var $content = p.$iframe.contents().find("body");
      var response = $content.html();
      var result = false;
      if (response != undefined && response.length > 0) {
        if (response.indexOf("response: OK") >= 0) { 
          result = true;
        } else if (response.indexOf("response: KO") >= 0) {
          HINT.error(i18n.js_upload_error);
        } else if (response.indexOf("response: BIG") >= 0) {
          HINT.error(i18n.js_upload_toobig);
        } else if (response.indexOf("response: ERROR") >= 0) {
          HINT.error(i18n.js_upload_error);
        }
        $content.html("");
        clearInterval(uploadTimer);
      } 
      return result;
    }
    
    function _confirmUpload() {
      debug("begin: confirmUpload");
      p.$form.addClass("upbox confirmed");
    
      p.$remove = $("<button value='delete' class='upbox delete std_btn'/>")
        .html(i18n["js_inviofile_btn"])
        .prependTo(p.$form)
        .click(function(e) { 
            _removeUpload(); 
          });
    
      var val = p.$input.val();
      if(val.indexOf("/") >= 0) {
          val = val.substr(val.lastIndexOf("/")+1);                
      }
      if(val.indexOf("\\") >= 0) {
          val = val.substr(val.lastIndexOf("\\")+1);                
      }
    
      $("<span>"+val+"</span>").appendTo(p.$form);
      $("<input type='hidden' value='"+val+"' name='delete'/>")
        .appendTo(p.$form);
          
      p.$input.remove();
      _removeIFrame();
      debug("end: confirmUpload");
      
      p.$form.trigger("success");
    }
    
    function _removeUpload() {
      debug("begin: removeUpload");
      if (p.$iframe == undefined) _createIFrame();

      uploadTimer = window.setInterval(_checkRemove, 1000);
      p.$form.submit();
      return false;
    }
    
    function _checkRemove() {
      debug("checkRemove");      
      if (_callBack() == true) _confirmRemove();
    }

    function _confirmRemove() {
      debug("confirmRemove");       
      p.$input.val("").insertBefore(p.$form);
      p.$form.remove(); 
      _createDOM(p.$input);
      _removeIFrame();
    }
    
    return _createDOM(this);
  };
  
  $.fn.upBox.defaults = {
    uploadCounter: 0,
    $iframe: null,
    $form: null
  };
  
  function debug(msg) {
   LOG.info(msg);
  };
  
});

/*
 * jQuery extension by casph
 * lightbox similar
 * only for pics
 * 
 * usage: $(imageElements).picBox();
 * 
 */

jQuery(function($) {
  $.fn.picBox = function(options) {
    
    var o = $.extend({}, $.fn.picBox.defaults, options);
    var cache = new Array();
    var preloadTimer;
    var cacheTimer;
    var resizeTimer;
    
    function _fillCache($elements) {
      debug("fillCache");
      var i = 0;
      $elements.each(function() {
        var $this = $(this);
        
        var bImage = $this.attr(o.attributes.imagePath);
        debug("preload: " + bImage);
        if (bImage == undefined) {
          debug("preload: no image path");
          return;
        }
        
        var imageObj = new Object();
        imageObj.loaded = false;
        
        imageObj.image = new Image();
        $(imageObj.image).bind("load", i, function(e) {
          cache[e.data].loaded = true;
          cache[e.data].orHeight = cache[e.data].image.height;
          cache[e.data].orWidth = cache[e.data].image.width;
          $(cache[e.data].image).unbind("load");
          debug("preload: " + e.data + " complete");
        });
      
        if (o.attributes.imageTitle != undefined)
          imageObj.title = $("<p class='title'/>")
            .text($this.attr(o.attributes.imageTitle)); 
        if (o.attributes.imageDescription != undefined)
          imageObj.description = $("<p class='desc'/>")
            .text($this.attr(o.attributes.imageDescription)); 

        cache.push(imageObj);
        cache[i].image.src = bImage;
        i++;
      });
      _startCacheCheck();
    }    
    
    function _startCacheCheck() {
      debug("cacheCheck");
      cacheTimer = window.setTimeout(function() {
        for(var i=0; i<cache.length; i++) {
          if (!cache[i].loaded) {
            cache[i].loaded = undefined;
            debug("preload " + i + " failed");
          }
        }
      }, o.timeOut*1000);
    }

    function _buildDOM() {
      debug("buildDOM");
      if (o.modal)
        o.$modal = $("<div id='PB_modal'/>")
          .css("height", $(document).height())
          .prependTo("body");
      
      if (o.$canvas.size() == 0 || o.isNewCanvas == true) {
        o.isNewCanvas = true;
        o.$canvas = $("<div id='PB_canvas'/>")
          .hide()
          .prependTo("body")
          .bind("click", function() { return false; });
      } else o.isNewCanvas = false;
          
      o.$image = $("<div class='PB_image'/>")
        .appendTo(o.$canvas);
        
      o.$navLeft = $("<div class='PB_navleft'/>")
        .appendTo(o.$canvas);
      o.$navRight = $("<div class='PB_navright'/>")
        .appendTo(o.$canvas);
      o.$imageInfo = $("<div class='PB_imageinfo'/>")
        .appendTo(o.$canvas);
      o.$close = $("<div class='PB_close'/>")
        .appendTo(o.$canvas)
        .click(_close);        
    }
    
    function _bindKeyboard() {
      if (o.binded == undefined) { 
        $(document).bind("keyup", _onKeyboard);
        o.binded = true;
      }
      o.disableKeys = false;
      if (o.lastKey != undefined) 
        $(document).trigger("keyup");
    }
    
    function _unbindKeyboard() {
      o.disableKeys = true;
    }
    
    function _onKeyboard(e) {
      if ( e == null ) {
        keycode = event.keyCode;
      } else {
        keycode = e.keyCode;
      }
      key = String.fromCharCode(keycode).toLowerCase();

      if (o.disableKeys == true) {
        o.lastKey = keycode;
        return; 
      } else if (o.disableKeys == false && o.lastKey != undefined) {
        keycode = o.lastKey;
        o.lastKey = undefined;
      }

      if (keycode == o.keys.close) {
        _unbindKeyboard();
        _close();
      } else if ( keycode == o.keys.prev && o.current > 0) {
        _unbindKeyboard();
        _showImage(o.current-1);
      } else if (keycode == o.keys.next && o.current < (cache.length-1)) {
        _unbindKeyboard();
        _showImage(o.current+1);
      }
      return false;
    }
    
    function _calcNewSize(i, view) {
      var h = cache[i].orHeight;
      var w = cache[i].orWidth;
      
      if (h > view.height) {
        var ratio = view.height/(h/100);
        h = view.height;
        w = parseInt((w/100)*ratio, 10);
      }
      if (w > view.width) {
        var ratio = view.width/(w/100);
        w = view.width;
        h = parseInt((h/100)*ratio, 10);
      }
      return {
        height: h + "px",
        width: w + "px"
      };
    }
    
    function _resizeTimer(e) {
      clearTimeout(resizeTimer);
      if (e != undefined && e.data != undefined) {
        o.current = e.data;
      } else {
        _resizeCanvas(o.current);
        return;
      }
      resizeTimer = window.setTimeout(_resizeTimer, 500);
    }
    
    function _resizeCanvas(i, fn, infoSize) {
      debug("resizeCanvas("+i+")");
      if (!o.isNewCanvas) {
        return;
      }
      
      var view = {
        height: $(window).height() - o.margin.top - o.margin.bottom,
        width: $(window).width() - o.margin.left - o.margin.right
      };
      var image = {
        height: o.$canvas.height() + "px",
        width: o.$canvas.width() + "px"
      };
      
      if (i != undefined && cache[i].loaded) {
        
        o.$imageInfo
          .hide()
          .empty();
          
        o.$image.hide();

        // Se la funzione è stata chiamata da un evento
        if (typeof i == "object") {
          i = i.data;
        }

        if (i == NaN || i < 0 || i > cache.length) {
          i = undefined;
        } else {
          $.extend(image, _calcNewSize(i, view));
        }
      }
      
      var t = (($(window).height() - parseInt(image.height, 10)) / 2) + $(document).scrollTop();
      var l = (($(window).width() - parseInt(image.width, 10)) / 2) + $(document).scrollLeft();
      $.extend(image, {
        top: (t > o.margin.top ? t : o.margin.top) + "px",
        left: (l > o.margin.left ? l : o.margin.left) + "px"
      });
      
      o.$canvas.show().animate(image, function() {
        o.$image
          .find("img")
            .css(image)
            .end()
          .fadeIn();
        _showInfo(i, image, view);
        if (fn != undefined)
          fn(image, view);
      });
    }
    
    function _setNavigators(i) {
      debug("setNavigators");
      if (i >= cache.length-1) {
        o.$navRight.hide();
      } else {
        o.$navRight.show()
          .unbind().bind("click", i+1, function(e) {
            if (o.disableKeys == false) {
              _unbindKeyboard();
              var i = parseInt(e.data, 10);
              _showImage(i);
            }
            return false;
          });
      }
      if (i == 0) {
        o.$navLeft.hide();
      } else {
        o.$navLeft.show()
          .unbind().bind("click", i-1, function(e) {
            if (o.disableKeys == false) {
              _unbindKeyboard();
              var i = parseInt(e.data, 10);
              _showImage(i);
            }
            return false;
          });
      }       
    }
    
    function _showImage(i) {
      debug("showImage");
      o.current = i;
      var image = cache[i];

      if (o.$loading != undefined) o.$loading.remove();
      if (o.$image.find("img").size() == 0) {
        o.$image.hide().empty();
        o.$imageInfo.hide().empty();
      } else {
        o.$image.fadeOut(function() { 
          o.$image.empty();
        });
        o.$imageInfo.fadeOut(function() {
          o.$imageInfo.empty();  
        });  
      }
      window.clearTimeout(preloadTimer);
      window.clearInterval(preloadTimer);
      if (o.$missing != undefined) o.$missing.remove();

      if (image.loaded) {
        o.$imageInfo.html("").hide();
        _setNavigators(i); 
        _resizeCanvas(i, function(image, view) {
          o.$image.empty()
            .append($(cache[i].image).css(image))
            .fadeIn("slow");
        });
      } else {
        debug("notReady");
        o.$loading = $("<div class='PB_loading'/>")
          .appendTo(o.$canvas);
        _resizeCanvas(i);
        _bindKeyboard();
        _setNavigators(i);
        preloadTimer = window.setInterval(function() {
          if (image.loaded) {
            //o.$canvas.empty();
            _showImage(i);
          } else if (image.loaded == undefined) {
            clearInterval(preloadTimer);
            o.$loading.remove();
            if (o.$missing != undefined) o.$missing.remove();
            o.$missing = $("<p class='PB_missing'/>").text(o.missing)
              .appendTo(o.$canvas); 
                
            _bindKeyboard();
            _setNavigators(i);
          }
        }, 1000);        
      }
      $(window).bind("resize scroll", i, _resizeTimer);
      $(window).bind("click", _close);
    }
    
    function _showInfo(i, image, view) {
      debug("showInfo("+i+","+image+","+view+")");

      o.$imageInfo.empty();
      if (!cache[i].loaded) {
        LOG.info("showInfo not ready");
        $.extend(image, {
          height: o.minHeight+"px"
        });
      }
      
      if (i == undefined || i >= cache.length 
                         || i < 0) {
        o.$imageInfo.hide();
        return;
      }
      
      o.$imageInfo.show();
      if (cache[i].title != undefined)
        o.$imageInfo
          .append(cache[i].title);
          
      if (cache[i].description != undefined)
        o.$imageInfo
          .append(cache[i].description);
          
      var ih = parseInt(image.height, 10) + o.$imageInfo.height();
      if (ih > view.height) {
        var nh = { top: "-" + o.$imageInfo.height() + "px" };
        o.$imageInfo.css(nh).show();
        _bindKeyboard();
      } else {
        o.$imageInfo.css("top", 0);
        o.$canvas.animate({        
          top: parseInt(o.$canvas.css("top"), 10) - (o.$imageInfo.height()/2),
          height: parseInt(image.height, 10) + o.$imageInfo.height() + "px"
        }, function() {
          o.$imageInfo.fadeIn("fast", _bindKeyboard);
        });
      }
    }
    
    function _close() {
      debug("close");
      clearInterval(preloadTimer);
      $(window)
        .unbind("resize scroll", _resizeTimer)
        .unbind("click", _close);
      $(document)
        .unbind("keyup", _onKeyboard);
      o.binded = undefined;
      
      if (!o.isNewCanvas) {
        if (o.$modal != undefined) o.$modal.remove();
        o.$canvas.html("");
        return;
      }
      o.$canvas.fadeOut("slow", function() {
        if (o.$modal != undefined) o.$modal.remove();
        o.$canvas.remove();
      });
    }
    
    _fillCache(this);
    this.each(function(i) { 
      $(this)
        .attr("slide", i)      
        .bind("click", function() {
          $(this).trigger("picbox_start");
          debug("imageClick"); 
          _buildDOM();
          _showImage(parseInt($(this).attr("slide"), 10));
          return false;
      });
    });
    
    return this;    
  };
  
  $.fn.picBox.defaults = {
    $canvas: $("#PB_canvas"),
    attributes: {
      imagePath: "PB_imagePath",
      imageTitle: "PB_title",
      imageDescription: "PB_description"
    },
    margin: {
      top: 50,
      right: 50,
      bottom: 50,
      left: 50
    },
    minWidth: 200,
    minHeight: 200,
    keys: {
      next: 39,
      prev: 37,
      close: 27
    },
    timeOut: 40,
    modal: true,
    missing: "Image not found"
  };
  
  function debug(msg) {
   LOG.info(msg);
  };
  
});

var SCMS = function() {
  var bibliotecario = false;
  var dot = null;
  
  this.setGroups = new Object();
  
  function initChiSiamo() {
    var links = $ID("wchisiamozone").getElementsByTagName("li");
    SCMS.addSet("chisiamo", new LinkGroup(links, "chisiamo"));
  }
  
  return {
    init: function(isBibliotecario) {
      if (isBibliotecario) {
        bibliotecario = isBibliotecario;
        SCMS.drawDot();
      }    
    },
    drawDot: function() {
      dot = document.createElement("DIV");
      dot.id = "bibliodot";
      dot.className = "off";
      dot.title = i18n.js_cms_dottitle;
      
      $E.addListener(dot, "click", SCMS.editMode);
      document.body.appendChild(dot);    
    },  
    editMode: function(e, force) {
      if (!SCMS.isBibliotecario() || !dot) return;
      
      if (!force && dot.className == "off") {
        force = "on";
      } else if (!force && dot.className == "on") {
        force = "off";
      }
      
      if (force == "on") {
        dot.className = "on";
        initChiSiamo();
      } else if (force == "off") {
        dot.className = "off";
        SCMS.removeSet();
      }
    },
    isOn: function() {
      if (!SCMS.isBibliotecario() || !dot) return false;
      return (dot.className == "on");
    },
    isBibliotecario: function() {
      if (bibliotecario) {
        return bibliotecario;
      } else return false;
    },
    refresh: function(service, data) {
      if (!SCMS.isOn()) return;

      if (this.setGroups[service]) {
        SCMS.removeSet(service);
      }

      if (service.indexOf("chisiamo") >= 0) {
        w01m00(data);
        initChiSiamo();
      }
    },
    addSet: function(name, setGroup) {
      this.setGroups[name] = setGroup;
    },
    removeSet: function(name) {
      if (name) {
        if (!this.setGroups[name]) return;

        var set = this.setGroups[name];
        set.remove();
        set = null;
      } else {
        for (name in this.setGroups) {
          this.setGroups[name].remove();
          this.setGroups[name] = null;
        }
      }
    }
  }
}();

SCMS.utils = {
  isEmpty: function(s, def) {
    if (!s || DIALOG.Strings.isBlank(s)) {
      if (def) return def;
      return ""; 
    }
    return s;
  },
  renderMCE: function(element) {
    $(element).tinymce({
      script_url : 'sebinayou/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
      theme : "advanced",
      plugins : "safari,spellchecker,layer,table,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras",
      theme_advanced_buttons1 : "fullscreen,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,link,unlink,anchor,image,media",
      theme_advanced_buttons2 : "formatselect,fontselect,fontsizeselect,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,forecolor,backcolor",
      theme_advanced_buttons3 : "",      
      theme_advanced_toolbar_location : "top",
      theme_advanced_toolbar_align : "left",
      theme_advanced_statusbar_location : "bottom",
      theme_advanced_resizing : false,
      language : "it",
      width : "100%"
    });
  }
}

SCMS.StdBtn = function(classname, tooltip, fn, scope) {
  
  SCMS.StdBtn.prototype.remove = function() {
    if (this.button) {
      $E.removeListener(this.button, "click", this.fn);
      this.button.parentNode.removeChild(this.button);
    }
  }
  
  SCMS.StdBtn.prototype.init = function(e) {
    if (!e) return;
    
    e.appendChild(this.button);
    $E.addListener(this.button, "click", this.fn, null, scope);
    
    return this;
  }
  
  if (fn && fn.call) {
    this.button = document.createElement("button");
    this.button.className = "cms-stdbtn " + classname;
    if (tooltip) {
      this.button.setAttribute("title", tooltip)
    }

    this.fn = fn;
  }
}

SCMS.StdSet = function() {

  SCMS.StdSet.prototype.hide = function() {
    this.plateau.style["display"] = "none";
  }
  
  SCMS.StdSet.prototype.show = function(e) {
    this.plateau.style["display"] = "";
    
    var a = $(e).find("a");
    $(this.plateau).css({ left: a.width() + 20, top: 0 });
  }
  
  SCMS.StdSet.prototype.remove = function() {
    for(var i=0; i<this.buttons.length; i++) {
      this.buttons[i].remove();
    }

    this.plateau.parentNode.removeChild(this.plateau);
    
    $E.removeListener(this.element, mouseOver);
    $E.removeListener(this.element, mouseOut);
  }
  
  SCMS.StdSet.prototype.addButton = function(stdBtn) {
    if (!this.plateau) return;
    
    if (!this.buttons) 
      this.buttons = new Array();
    
    this.buttons.push(stdBtn.init(this.plateau));
    this.hide();
  }

  var mouseOver = function(event, e) {
    if (!SCMS.isOn()) return;
    
    var rel = $E.getRelatedTarget(event);
    if (rel == e || $D.isAncestor(e, rel)) return; 
    
    this.show(e);
  }
  
  var mouseOut = function(event, e) {
    if (!SCMS.isOn()) return;
    
    var rel = $E.getRelatedTarget(event);
    if (rel == e || $D.isAncestor(e, rel)) return; 

    this.hide();    
  }
  
  SCMS.StdSet.prototype.init = function(e, attributeName) {
    if (!e) return;

    this.element = e;
    this.idElement = e.getAttribute(attributeName);
    this.posn = e.getAttribute("posn");
    
    // Plateau
    this.plateau = document.createElement("div");
    this.plateau.className = "cms-plateau"
    e.appendChild(this.plateau);
    
    // MouseOver e MouseOut
    $E.addListener(this.element, "mouseover", mouseOver, e, this);
    $E.addListener(this.element, "mouseout", mouseOut, e, this);
  }
}

SCMS.LinkSet = function(e) {
  this.init(e, "idLink");
  
  this.add = function(e) {
    this.edit(e, true);  }
  
  this.edit = function(e, add) {
    var element = this.element;

    var handleConfirm = function() {
      var map = new Object();
      var form = document.cmslinkedit;
      var isEmpty = SCMS.utils.isEmpty;
      
      if (form.idlink)
        map["id"] = isEmpty(form.idlink.value);
      map["ds"] = isEmpty(form.ds.value);
      map["tooltip"] = isEmpty(form.tooltip.value);
      map["mode"] = isEmpty(getCheckedValue(form.mode));
      map["url"] = isEmpty(form.url.value);
      map["html"] = isEmpty($(form.html).html());
      map["target"] = form.toblank.checked;
      if (form.newposn)
        map["newposn"] = form.newposn.value;
      
      W.d262(map, function(data) {
        
        if (data.error) {
          HINT.error(data);
          return;
        } else if (data.data) {
          data = data.data;
        } else return;

        // Aggiungo l'elemento
        if (data.newposn) {
          var newli = document.createElement("LI");
          
          var idLink = document.createAttribute("idLink");
          idLink.value = data.id;
          newli.setAttributeNode(idLink);
          
          var next = element.nextSibling;
            
          if (next) {
            element.parentNode.insertBefore(newli, next);
          } else {
            element.parentNode.appendChild(newli);
          }
          
          var links = element.parentNode.getElementsByTagName("LI");
          LinkGroup.reorder(links);
        } 

        // Azioni post salvataggio
        W.m00("wchisiamo", function(data) {
          RENDERING.widget(data);
          SCMS.refresh("chisiamo");
        });
        DIALOG.close("d-cms-editlink");
      });
    }
    
    var handleCancel = function() {
      DIALOG.close(this);
    }
    
    var handleClean = function() {
      document.cmslinkedit.reset();
    }
    
    var handleChange = function() {
      var shtml = $("#d-cms-editlink .section-html"); 
      var surl = $("#d-cms-editlink .section-url");
  
      if (getCheckedValue(this) == "url") {
        var surlinput = surl.find("input");
        if (surlinput.val().indexOf("A.a80m01") == 0) {
          surlinput.val("");
        }

        surl.show();
        shtml.hide();
      } else {
        shtml.show();
        surl.hide();
      }
      
      DIALOG.refresh();
    }
    
    W.d261(this.idElement, add, function(data) {
      var buttons = [{ text:i18n.js_btn_conferma, handler:handleConfirm },
        { text:i18n.js_btn_annulla, handler:handleClean },
        { text:i18n.js_btn_esci, handler:handleCancel, isDefault:true }];
      
      var dialog = DIALOG.open({
        id: "d-cms-editlink",
        html: data,
        buttons: buttons,
        width: "800px"
      });
      
      var form = document.cmslinkedit;
      $E.addListener(form.mode, "change", handleChange, null, form.mode);
      
      var mode = getCheckedValue(form.mode);
      if (mode == "url") {
        $(dialog).find(".section-html").hide();
      } else if (mode == "html"){
        $(dialog).find(".section-url").hide();
      } else {
        $(dialog)
          .find(".section-html").hide().end()
          .find(".section-url").hide();
      }
      
      SCMS.utils.renderMCE(form.html);
    });
  }

  this.del = function() {
    if (!this.idElement) return;
    var idElement = this.idElement;
    
    var handleYes = function() {
      DIALOG.close(this);
      W.d260(idElement, function(data) {
        if (data.error) {
          HINT.error(data.error);
          return;
        }
        
        W.m00("wchisiamo", function(data) {
          w01m00(data);
          SCMS.refresh("chisiamo");
        });
      });
    }

    DIALOG.simple({
      title: i18n.js_cms_deletetitle,
      message: i18n.js_cms_deletemsg,
      handler: handleYes,
      width: "400px" 
    });
  }
  
  this.addButton(new SCMS.StdBtn("editbtn", i18n.js_cms_edittooltip, this.edit, this));
  this.addButton(new SCMS.StdBtn("deletebtn", i18n.js_cms_deletetooltip, this.del, this));
  this.addButton(new SCMS.StdBtn("newbtn", i18n.js_cms_newtooltip, this.add, this));
}

var LinkGroup = function(links, groupTag) {
  
  if (!links || !links.length || links.length == 0) return;
  
  this.setCollection = new Array(links.length);

  LinkGroup.prototype.remove = function() {
    for(var i=0; i<this.setCollection.length; i++) {
    	var set = this.setCollection[i];
    	set.remove();
    }
    this.setCollection = null;    
  }
  
  for(var i=0; i<links.length; i++) {
    this.setCollection[i] = new SCMS.LinkSet(links[i]);
    
    new YAHOO.sebyou.DDList(links[i], groupTag);
    $(links[i]).bind("endDrag", function(e) {
      var links = this.parentNode.getElementsByTagName("LI");
      LinkGroup.reorder(links);
    });
  }
  
  new YAHOO.util.DDTarget(links[0].parentNode.getElementsByTagName("UL"), groupTag);
}

LinkGroup.reorder = function(links) {
  var ids= new Array();

  if (links && links.length > 0)
    for(var i=0; i < links.length; i++)
      ids[i] == links[i].getAttribute("idLink");
  
  W.d263(ids, function(data) {
    if (!data || data == false)
      HINT.error(i18n.js_cms_errore);
  }); 
}

SCMS.LinkSet.prototype = new SCMS.StdSet;

window.onbeforeunload = function() {
  W.drop();
}

function setPostProcessing(data) { 

  if(data.idDom.indexOf("galleria") >= 0) {
    GALLERY.init();
  } else if (data.idDom.indexOf("tabloca") >= 0) {
    $("#tabloca a:has(img)").picBox({attributes: { imagePath: "href" },
      missing: i18n.js_immagine_mancante });
      
    $("#tabloca .switcher").toggle(function() {
      $(this)
        .find("a")
        .text(i18n.js_scheda_localizzazioni_switcher_off)
        .end()
        .parent()
        .find(".scheda-link")
        .show();
      return false;
    }, function() {
      $(this)
        .find("a")
        .text(i18n.js_scheda_localizzazioni_switcher_on)
        .end()
        .parent()
        .find(".scheda-link")
        .hide();
      return false;
    });
  } else if (data.idDom.indexOf("taboggd") >= 0) {
    $("#taboggd a:has(img)").picBox({ attributes: { imagePath: "href" },
      missing: i18n.js_immagine_mancante });
  } else if (data.idDom.indexOf("tabreview") >= 0) {
    $("#tabreview a.picbox").picBox({ attributes: { imagePath: "href" },
      missing: i18n.js_immagine_mancante });
  } else if (data.idDom.indexOf("tabmaps") >= 0) {
    GMUtils.open(data, HOMEMAPS.open);
  }
  
  BOL.checkImages();
}

function shiftTab(tabName) {
  if (DIALOG.Strings.isBlank(tabName)) return;
  
  var tabs = $("#whometab .yui-nav li");
  for(var i=0; i<tabs.size(); i++) {
    var tab = $(tabs[i]);

    var a = tab.find("a[href*='#tab" + tabName + "']"); 
    if (a.size() == 0) 
     continue;
     
    homeTabView.set('activeIndex', i); 
    
    var content = $("#tab" + tabName);
    if (content.is(":empty")) {  
      W.m02(tabName, RENDERING.html);
    }
  }  
}

/*--- SEZIONE DIMENTICATOIO ---------*/

// Questa sezione serve a tenere da part 
// funzioni necessarie ma non più realmente utilizzate

function showHelp() {
  
}