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;

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);

clone = function(obj) {
	return $.extend(true, {}, obj);
};

function stopPropagation(event) {
  if (event) 
    $E.stopPropagation(event);        
}    

JGLO = (function () {
  var jGloVal = "";
  
  return {
    init: function(jglo) {
      this.jGloVal = jglo;
    },
    
    getSysb: function() {
      return this.jGloVal;
    }
  };
})(); 

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_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 = "sy?action=status&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 = new function () {
  /** introdotto per evitare memory-leak (prima era richiamato come funzione anonima) */
  this.storeStatus = function() {
    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++) {
      var div = lWElements.item(i).firstChild;
      lWidgets += div.getAttribute("id");
      
      var corpo = $(div).find(".corpo");
      if (corpo.size() > 0
          && corpo.css("position") == "absolute") {
        lWidgets += "[closed]";
      }
      
      if (i < lWElements.length -1)
        lWidgets += ",";         
    }
    
    for(i=0; i < rWElements.length; i++) {
      var div = rWElements.item(i).firstChild;
      rWidgets += div.getAttribute("id");
      
      var corpo = $(div).find(".corpo");
      if (corpo.size() > 0
          && corpo.css("position") == "absolute") {
        rWidgets += "[closed]";
      }
      
      if (i < rWElements.length -1)
        rWidgets += ",";         
    }
    
    W.d122(lWidgets, rWidgets);
    return true;
  }
  
  /** inserisce nella pagina i widget necessari */
  this.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--) {
      if(!Strings.isBlank(widgets[i].id)) {
        oldWidgets.appendChild(widgets[i]);
      }
    }

    // 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.cd);
      if (oldWidget 
          && oldWidget.getAttribute('freeze') == 'Y') {
        d.appendChild(oldWidget);
      } else {
        oldWidget = document.createElement('li');
        oldWidget.id = 'li' + lsWidget.cd;
        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.cd;
        nodo.innerHTML = lsWidget.title;
        oldWidget.appendChild(nodo);
        d.appendChild(oldWidget);

        var render = new function() {
          var node = oldWidget;
          var widget = lsWidget;
          
          W.m00(widget.cd, function(data) {
            if (widget.showClosed) 
              node.style.visibility = "hidden";
            
            w01m00(data);
            
            if (widget.showClosed) {
              WIDGET.toggle(widget.cd, false);
              // in caso fosse nascosto
              node.style.visibility = "visible";
            }          
          });          
        };
      }
            
      // DDWidget
      DDWdgs[x] = new YAHOO.sebyou.DDList(oldWidget);
      DDWdgs[x].setHandleElId(lsWidget.cd + "_header");
      DDWdgs[x].on('dragDropEvent', this.storeStatus);
      // DDWidget end 

    }

    Nodes.purgeNode(oldWidgets);
    delete oldWidgets;
  }

  this.toggle = function(cd, animate) {
    
    // di default gestisco l'animazione
    if (typeof(animate) === "undefined")
      animate = true;
    
    // imposto l'overflow in modo che la riduzione/ingrandimento
    // non modifichi il contenuto del widget
    var li = $ID("li" + cd);
    if (!li) return;
    li.style.overflow = "hidden";
    
    var corpo = $(li).find(".corpo").get(0);
    if (!corpo) return;
    corpo.style.overflow = "hidden";

    if (corpo.getAttribute("loading") == "true") {
      return;
    } else 
      // blocco eventuali seconde richieste
      corpo.setAttribute("loading", "true");

    var position = corpo.style.position;

    // è translato, quindi lo rientro
    if (position == "absolute") {  
      var orHeight = corpo.offsetHeight;
      
      corpo.style.height = "0px";
      corpo.style.left = "0px";           
      corpo.style.position = "static";
      
      var after = function() {
        var titolo = $ID(cd + "titolo");
        Nodes.removeClass(titolo, "bottoneridimensionapiu");
        corpo.removeAttribute("loading");
        corpo.style.height = "auto";
        WIDGET.storeStatus();        
      }
      
      if (animate 
          && orHeight 
          && orHeight > 0) {
        $(corpo).animate({ height: orHeight }, after);
      } else 
        after();
      
      return;
    }

    // lo translo fuori        
    var after = function() {
      
      // gli setto la larghezza in modo che l'altezza sia attendibile
      corpo.style.width = $(corpo).width() + "px";
      
      corpo.style.height = "auto";
      corpo.style.left = "-9999px";
      corpo.style.position = "absolute";
      
      var titolo = $ID(cd + "titolo");
      Nodes.addClass(titolo, "bottoneridimensionapiu");
      
      corpo.removeAttribute("loading");
      WIDGET.storeStatus();
    };
    
    if (animate) {
      $(corpo).animate({ height: "0" }, after);
    } else {
      corpo.style.height = "0px";
      after();
    }
  }
};  

function showhide(value){
  return WIDGET.toggle(value);
}

GALLERY = (function () {
  return {
    query: function (query, percorso) {
      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";
      if (!Strings.isBlank(percorso)) {
        params["percorso"] = percorso;
      }
      
      A.a10m04(params, Forms.value(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);
         });
      });
    },
  
    postListaRisultati: function(data) {
      if (data.error) {
        HINT.error(data);
      } else if (data.html) {
        $("#listarisultati")
          .wrap("<div id='"+data.idDom+"'/>")
          .replaceWith(data.html);
      }
    }
  };
})();

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 + " > td");
        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.attr('class')+'" width="25%">' + copertina[0].innerHTML + '</td>';
      }
    
      data.html += '<td width="75%">';
    
      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 = Forms.value(nform.statoBib0);
          
          if (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,
        message: 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="N" name="statoBib0"/>&nbsp;' 
        + i18n.js_listmania_nuovalista_N        
        + '<br/><input type="radio" value="S" name="statoBib0" checked="checked"/>&nbsp;' 
        + i18n.js_listmania_nuovalista_S;
        
      if (firmaListe)
        html += '<br/><input type="radio" value="F" name="statoBib0"/>&nbsp;' 
          + i18n.js_listmania_nuovalista_F
        
      html += "</td></tr></table>";
      $ID('mieliste').innerHTML=html;
    },
    
    /** applica l'etichetta della nuova Bib0 al documento */
    rd71: function(idBib0, progressivoTitolo){
      Css.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)
            Css.modifyClassAttribute("addListmania","color","" + cfgMieListe.liste[n].color.replace(";",""));
          if (cfgMieListe.liste[n].ds)
            Css.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;
					Selects.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];
						Selects.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];
								Selects.addOption($ID('PoloBiblio'), opt);								
							}
						}  else {
							opt.text = bib.d.fromJSON();;
							opt.value = tmpList[i];
							opt.selected = bib.s[idLista];
							Selects.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();
		}		
	};
})();

AREABIBL = (function () {
  var bibsel = "";
  var conf;
  var biblioteche;  
  
  function confirmBib(array) {
    W.d63(array, function(data) {
      if (data.data) {
        var novita = eval("(" + data.data + ")");
        // Ricarico la pagina con il nuovo sysb
        if (!Strings.isBlank(novita.reload)) {
          window.location.href = novita.reload;
          return;
        } else {
          A.a01m00(R.b01);
        } 
      } else {
        A.a01m00(R.b01);
      }
    });
  }

  function sort() {
    var result = new Array();
    
    for (code in biblioteche) {
      var biblioteca = biblioteche[code];
      
      if (!biblioteca.d
          || !biblioteca.o
          || !biblioteca.v) 
        continue;
      
      var des = biblioteca.d.toLowerCase();
      result.push({
        label: biblioteca.d,
        value: biblioteca.c
      });
    }

    result.sort(function(bib1, bib2) {
      bib1 = biblioteche[bib1.value];
      bib2 = biblioteche[bib2.value];

      if ((!bib1 || !bib1.o)
        && (!bib2 || !bib2.o)) {
        return 0;
      } else if (!bib1 || !bib1.o) {
        return -1;
      } else if (!bib2 || !bib2.o) {
        return 1;
      }

      if (bib1.o > bib2.o) {
        return 1;
      } else if (bib1.o < bib2.o) {
        return -1;
      } else {
        return 0;
      }
    });      

    return result;
  }
  
  return {
    
	confirmBibFromMap: function(cdBiblio) {
      W.d64(cdBiblio, function(data) {
        var novita = eval("(" + data.data + ")");
        // Ricarico la pagina con il nuovo sysb
        window.location.href = novita.reload;
        return;
      });
	},
	
    render: function (data) {
      var handleCancel = function() {
        DIALOG.close(dialog);
      };  
      
      var handleConfirm = function() {
        for (var x in biblioteche) {
          biblioteche[x].s[0] = false;
        }
        biblioteche[bibsel].s[0] = true;        
        DIALOG.close(this);
        confirmBib([bibsel]);
      };
      
      var dialog = DIALOG.open({
        id: "d-areabibl",
        html: data.html,
        visible: false,
        width: "830px" });
        
      conf = BIBSEL.getConf();
      biblioteche = conf.biblioteche;
      bb = sort();

      var res = "";

      var numBibXcolonna = bb.length / 3;
      var contBibXcolonna = 0;
      var idULCorrente = 1;
      
      for(var y in bb){
        var x = bb[y].value;
        if(x === undefined) {
          continue;
        }
        if (contBibXcolonna > numBibXcolonna) {
          $("#dAreaBiblLs" + idULCorrente).html(res);
          res = "";
          contBibXcolonna = 0;
          idULCorrente = idULCorrente + 1;
        }
        var selected = "";
        if(biblioteche[x].s[0]) {
          bibsel = biblioteche[x].c;
          selected = "class='selected'";
        }
        res += "<li id='bib_" + biblioteche[x].c + "'" + selected + ">";
        res += "<a href='#' onclick='AREABIBL.checkBibl(\"" + biblioteche[x].c + "\"); return false;'>" + biblioteche[x].d.fromJSON() + "</a></li>";
        contBibXcolonna = contBibXcolonna + 1;
      }
      $("#dAreaBiblLs" + idULCorrente).html(res);

      DIALOG.show(dialog);
    },
    
    checkBibl: function(el) {
      bibsel = el;
      $("#dAreaBiblLs li").removeClass("selected");
      $("#bib_" + el).addClass("selected");
      for (var x in biblioteche) {
          biblioteche[x].s[0] = false;
      }
      biblioteche[bibsel].s[0] = true;        
      DIALOG.close("d-areabibl");
      confirmBib([bibsel]);
    },
    
    reset: function(data){
      for (var x in biblioteche) {
        biblioteche[x].s[0] = false;
      }
      confirmBib([]);
    }

  };
})();

OS = (function () {
  var count = 0;
  
  return {
    init: function(data) {
      count = 0;
      $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) {
				//console.info(500 * (count + 1));
        setTimeout(function(){
					W.d230(OS.rExecute);
				}, 500 * ++count);
      } else {
        if(data.accorpa) {
          $("#wopensearchaccorpaincorso").hide();
        }
      }
    },
    
    rExecute: function (data) {
      var jsData = data.data;
      if(jsData.hide === true) {
        $("#liwopensearch").hide();
      }
      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()) {
           Nodes.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(pageNavigators){

    var e = $ID('pagenavigator');

    Nodes.purgeChilds(e);

    if (typeOf(pageNavigators) != "array"
        || pageNavigators.length == 0)
      return;
    
    var separator = create("img");
    separator.src = "sebinayou/img/icon_separator.gif";
    
    if (($.browser.msie || $.browser.mozilla)
        && pageNavigators[0].action != "history.back();") {    
      pageNavigators.splice(0, 0, {
        action: "history.back();",
        label: i18n.js_navigation_back,
        id: "navback"
      });
    }
    
    for(i = 0; i < pageNavigators.length; i++) {
      if (pageNavigators[i] == null)
        continue;

      var a = create("a");
      a.href = "#";
      a.innerHTML = pageNavigators[i].label;

      var span = create("span");
      span.className = "pagenavigator";
      span.id = pageNavigators[i].id;
      span.appendChild(a);

      Events.on(span, "click", function(e, pageNavigator) {
        eval(pageNavigator.action);
        return false;
      }, pageNavigators[i]);
      
      e.appendChild(span);
      e.appendChild(separator.cloneNode(false));
    }
  }
    
  return {
    hasErrors: function(data) {
      if (data.error != null) {
        if (i18n[data.error]) {
          HINT.error(i18n[data.error]);
          LOG.error(i18n[data.error]);
        } else {
          HINT.error(data.error);
          LOG.error(data.error);
        }
        
        return true;
      }
      
      return false;
    },
    
    html: function(data, f) {
      if (RENDERING.hasErrors(data)) {
        return;
      }

      if(data.idDom) {
        var node = $ID(data.idDom);
        if(!node) return;
       
        node.innerHTML = data.html;

        postProcessing(data);
      }

      TIMEOUT.updateSess();
      if (typeof f == "function") { f(); };
    },
    
    widget: function(data) {
      w01m00(data);
    },
    
    rMappa: function (data, f) {
      STATUS.store(data,"RENDERING.rMappa");
      RENDERING.body(data, f);
      GMUtils.open(data, HOMEMAPS.open);
    },
    
    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) {
        Nodes.purgeNode($ID('pagecentercontent').firstChild);
        $ID('pagecentercontent').innerHTML = data.html;
        postProcessing(data);  
      }

      WIDGET.genera('pageleftcontent', data.widgetLeft);
      WIDGET.genera('pagerightcontent', data.widgetRight);

      if(data.pageNavigator) {
        generaPageNavigator(data.pageNavigator);
      }
			
      GBOOK.initService();
			
      BOL.checkImages();

      ScrollViewUtils.scanPage("pagecentercontent");

      TIMEOUT.updateSess();
      
      if (data.alert) {
        if (i18n[data.alert]) {
          HINT.info(i18n[data.alert], { hideTime: 8000 });
        } else {
          HINT.info(data.alert, { hideTime: 8000 });
        }
      }
      
      SCMS.refresh();
      
      if (f && f.call) { f(); }
      postProcessingBody(data);
    }
  };
})();  

function postProcessing(data) { 
  if (!data || !data.name) return;
  
  switch (data.name) {
    
    // Sezione per la ricerca
  	case "pagesearch":
      PSEARCH.init();  		
  		break;

    // Widget Suggerimenti di Lettura
    case "wsuggread":
      div_suggread = new TextScroll('div_suggread', 'suggread_box', 'suggread_up', 'suggread_down');
      break;

    // Widget OpenSearch
    case "wopensearch":
      OS.init(data);
      break;

    // Tabs della homepage
    case "whometab":
      postProcessingHOME(data);
      break;

    // Widget delle notizie
    case "wnews":
      NEWS.roll(data);
      SCMS.refresh("news");
      break;

    // Widget calendario delle notizie
    case "wnewscalendar":
      SCMS.refresh("news");
      break;    
    
    // Widget oggetti digitali
    case "woggettidigitali":
      OGGETTIDIGITALI.roll(data);
      break;

    // Widget chi siamo
    case "wchisiamo":
      SCMS.refresh("chisiamo");
      break;

    // Scheda del documento
    case "document":
      postProcessingA20(data);
      break;
      
    case "chisiamo":
      postProcessingRoot(data);
      break;

    case "struminfo":
      postProcessingRoot(data);
      break;
  }      
    
  BOL.checkImages();
}

function postProcessingA20(data) {
  if (!data.idDom) return;
  var idDom = data.idDom;

  switch (idDom) {
    
    // localizzazioni
    case "tabloca":
      PicBoxUtils.create($("#tabloca a:has(img)"));
        
      $("#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;
      });
      
      break;

    // oggetti digitali
    case "taboggd":
      PicBoxUtils.create("#taboggd a:has(img)");
      break;
      
    // tab immagini (sub oggetti digitali)
    case "tabimmagini":
      PicBoxUtils.create("#tabimmagini .scheda-images a");
      break;      
      
    // recensioni o deeplink        
    case "tabreview":
      PicBoxUtils.create("#tabreview a.picbox");
      break;
  }
}

function postProcessingHOME(data) {
  if (!data.idDom) return;
  var idDom = data.idDom;
  
  window.homeTabView = new YAHOO.widget.TabView('htab');

  var isValidTab = Strings.indexOf(idDom, "tab", true) == 0;

  // mappa delle biblioteche
  if (Strings.equals(idDom, "tabmaps")) {
    GMUtils.open(data, HOMEMAPS.open);
  } else if (isValidTab) {
    // per tutti gli altri tab
    var page = $ID(idDom);

    ScrollViewUtils.scanPage(page);

    var floaters = eval(data.floaters);
    var a = $(page).find("a[id]").get();
    for(var i=0; i<a.length; i++) {
      var id = a[i].getAttribute("id");
      if (!floaters[id]) continue;

      FLOATER.create(a[i], { 
        html: floaters[id] 
      });
    }
  }
  
  // galleria delle immagini
  if(idDom.indexOf("galleria") >= 0) {
    GALLERY.init();
  }
}

function postProcessingRoot(data) {
  //if (!data.idDom) return;
  //var idDom = data.idDom;

  ScrollViewUtils.scanPage("pagecentercontent");
}

function postProcessingBody(data) {
  document.title = data.headTitle;
  
  var biblioLavoro = $(".ds_biblio_lavoro"); 
  var ds = data.dsBibliotecaDiLavoro;
  if (biblioLavoro.size() > 0
      && !Strings.isBlank(ds)) {
    $.each(biblioLavoro, function() {
      $(this).text(ds); 
    });
  }
}

/** 
 * @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 {
    buttonContesto: false,
    button: false,
    
    testoRicerca: function(){
      return document.ricerca.frase.value;
    },

    /** inizializza la sezione pagesearch */
    init: function(){
      TIMEOUT.updateSess();
      
      // bottone per i contesti ( come contesto )
      var button = $("#psfiltri #combocontesti").get(0);
      if (button) {
        PSEARCH.buttonContesto = new MultiButton(button);
      }
      
      // bottone per i contesti
      button = $("#psricerca #combocontesti").get(0);
      if (button) {
        PSEARCH.button = new MultiButton(button);
      }
      
      // bottone per le liste 
      button = $ID("select:termini");
      if (button) {
        PSEARCH.button = new MultiButton(button, { 
          click: function(event, option) {
            PSEARCH.listaTerminiSUBMIT();
          }, postSelect: function(option) {
            PSEARCH.listaTerminiSUBMIT();
          }
        });
      }

      // bottone per le ricerche web 
      button = $ID("select:web");
      if (button) {
        PSEARCH.button = new MultiButton(button, { 
          click: function(event, option) {
            if (!Strings.isBlank(document.ricerca.frase.value)) {
              PSEARCH.risorsewebSUBMIT();
            }
          }, postSelect: function(option) {
            if (!Strings.isBlank(document.ricerca.frase.value)) {
              PSEARCH.risorsewebSUBMIT();
            }
          }
        });
      }
      
      // bottone per le novità 
      button = $ID("select:novita");
      if (button) {
        PSEARCH.button = new MultiButton(button, { 
          click: function(event, option) {
            PSEARCH.bollettinoSUBMIT();
          }, postSelect: function(option) {
            PSEARCH.bollettinoSUBMIT();
          }
        });
      }
      
      $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;    
        }
      }
    
      MultiSelect(
        $(".canaleunico").get(0), {
          suggest: function(term, o) {
            var suggest = this;
            W.d130(term, o.pageSize, { noLoader: true,
              callback: function(result) {
                suggest.receive(term, result);
              }
            });
          }
        });
      
      // 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
                || !biblioteca.o) 
              continue;
            
            var des = biblioteca.d.toLowerCase();
            if (des.indexOf(terms.toLowerCase()) >= 0) {
              result.push({
                label: biblioteca.d.fromJSON(),
                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;
            }
            
            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;

          if ($(this).attr("oldValue") == "")
            return;
            
          $(this).attr("oldValue", ""); 
          PSEARCH.postSS([]);
        } 
      }).bind("result", function(e, p) {
        $(this).val(p[0]);
        
        if ($(this).attr("oldValue") == p[1])
          return;
        
        $(this).attr("oldValue", p[1]);
        PSEARCH.postSS([p[1]]);
        
        return false;
      });
  
      $(document).ready(function() {
        // Genera il markup
        
        var containerDIV = document.createElement("DIV");
        
        var bibSorter = 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;
          }
          
          if (bib1.o > bib2.o) {
            return 1;
          } else if (bib1.o < bib2.o) {
            return -1;
          } else {
            return 0;
          }
        }
        
        var getBibliotecheUL = function(sistema) {
          sistema.bib.sort(bibSorter);
          
          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 || !biblioteca.o) continue;
            
            var bibliotecaLI = document.createElement("LI");
            var bibliotecaA = document.createElement("A");
            bibliotecaA.setAttribute("idBib", bibSistema.c);
            bibliotecaA.href = "#";
            
            if (Strings.isBlank(biblioteca.d)) continue;
            
            bibliotecaA.innerHTML = biblioteca.d;
            bibliotecaLI.appendChild(bibliotecaA);
            
            bibliotecheUL.appendChild(bibliotecaLI);
          }
          
          return bibliotecheUL;
        }
        
        var testoSistemi = "<a href='#' onclick='return PSEARCH.cleanBSS()'>"
          + i18n.js_pagesearch_tuttiisistemi + "</a>";
        
        if (sistemi.length == 0
          || (sistemi.length == 1 && sistemi[0].c == "")) {
          
          var ulBib = getBibliotecheUL(sistemi[0]);
          var liAll = document.createElement("LI");
          liAll.innerHTML = testoSistemi;
          
          ulBib.insertBefore(liAll, ulBib.firstChild);
          containerDIV.appendChild(ulBib);
        } else {
          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);
            sistemaLI.appendChild(getBibliotecheUL(sistema));

            sistemiUL.appendChild(sistemaLI);
          }
          
          containerDIV.appendChild(sistemiUL);
        }
        
        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) {
          if (!p) return;
          
          var input = $("#pagesearch .biblioss input[type='text']");
          input.val(p.text());
          
          var idBib = p.attr("idBib");
          
          var oldValue = input.attr("oldValue");
          if (idBib && oldValue != idBib) { 
            input.attr("oldValue", idBib);
            PSEARCH.postSS([idBib]);
          }
        });
      });

    },

    postSS: function(array) {
      var e = $("#ol_pageleftcontent, #pagerightcontent")
        .find("li[id='liwbiblioteca']");

      if (array.length > 0) {

        W.d62(array, function(data) {

          var refreshTab = false;
          
          if (data.data) {
            var novita = eval("(" + data.data + ")");
            
            // Ricarico la pagina con il nuovo sysb
            if (!Strings.isBlank(novita.reload)) {
              window.location.href = novita.reload;
              return;
            } 
            
            // Focus sulla tab delle novità della biblioteca selezionata
            if (novita.focus == true) {
              HTAB.shiftTab("novitabib", { forceRefresh: true });
              refreshTab = true;
            } 
          } 
          
          if (!refreshTab) {
            HTAB.refreshTab("novitabib");
          }            
        });
        
        var tutte = $("#pagesearch .biblioss .back2tutte");
        tutte.show();
        
        // Rendering del widget biblioteca
        W.m00("wbiblioteca", function(data) {
          if (!data || !data.html) {
            e.hide(); 
            return;
          }

          RENDERING.widget(data);
          e.show();
        });

      } else {
        W.d62([], function(data) {
          
          if (!Strings.isBlank(data.data)) {
            window.location = data.data;
            return;
          }
          
          if (e.size() > 0) {
            e.hide();
          }          
          
          var input = $("#pagesearch .biblioss input[type='text']");
          input.val(i18n.js_pagesearch_tuttelebiblioteche);
          
          var tutte = $("#pagesearch .biblioss .back2tutte");
          tutte.hide();
          
          HTAB.shiftTab("novitabib", { forceRefresh: true, onlyUpdate: true });
        });        
      }
    },
    
    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(){
      var value = document.ricerca.frase.value;
      if(value.length===0 || value == '*' || value == '?'){
        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(!PSEARCH.testFrase() || Strings.isBlank(url)) return;
      
      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() {
      if(!PSEARCH.testFrase()) return;

      var risorsa = getKindOfList();
      
      if(risorsa === null) {
        HINT.help(i18n.js_pagesearch_web_selrisorse);
      } else if(Strings.isBlank(document.ricerca.frase.value)){
        HINT.help(i18n.js_pagesearch_web_campivuoti);
      } else {
        var valore = document.ricerca.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');
      }
    },
    
    listaTerminiSUBMIT: function() {
      var kindOfList = getKindOfList();
      if (kindOfList != '') {
        A.a11m00(document.ricerca.frase.value, kindOfList, null, rBodyRendering);
      }
    },
    
    listManiaSUBMIT: function() {
      var r = document.ricerca;

      if(PSEARCH.testFrase()) { 
        A.a12m00(r.frase.value, rBodyRendering);
      }
    },
    
    immaginiSUBMIT: function(idFiltro) {
      var r = document.ricerca;

      if (PSEARCH.testFrase()) {
        A.a10m13(idFiltro, Forms.value(r.biblioradio), r.frase.value,R.b13);
      }
    },
    
    bollettinoSUBMIT: function(idFiltro) {
      var r = document.ricerca;

      var kindOfList = getKindOfList();
      
      if(kindOfList != '') { 
        A.a61m01(idFiltro, kindOfList, Forms.value(r.biblioradio), r.frase.value, r10);
      }
    },
    
    whereSUBMIT: function() {
      var r = document.ricerca;

      if (PSEARCH.testFrase()) {
        HOMEMAPS.search(r.frase.value, RENDERING.body);
      }
    },
    
    searchSUBMIT: function(idFiltro, abilitaControlloFrase) {
      var r = document.ricerca;
      if(abilitaControlloFrase===-1 || PSEARCH.testFrase()) {
        var value = r.frase.value; 
        A.a10m08(idFiltro, Forms.value(r.biblioradio), value, r10);
      }
    },
    
    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);
      $("#d-clump .hd span").html(data.data);
    },
    
    search: function(value, desc) {
      DIALOG.close("d-clump");
      PSEARCH.setClump(field,desc);
      var fieldReal = field;
      if(field == "LI") {
        fieldReal = "TH_LI";
      }
      A.a10m16(fieldReal, 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();      
    }    
    
  };
})();

PRESDIST = (function () {
	var linvSerieNum;
	var ltitoloBaseId;
	var lcdbib;
	  
	  return {
		setBib: function(cdbib){
			lcdbib = cdbib;
		},  
		  
	    display: function(invSerieNum, titoloBaseId) {
	    	linvSerieNum = invSerieNum;
	    	ltitoloBaseId = titoloBaseId;
	    	W.d106(linvSerieNum, ltitoloBaseId, PRESDIST.render);
	    },
	    
	    render: function(result) {
	      if (result.error) {
            HINT.error(result);
          } else if (result.html) {
            var config = eval("(" + result.data + ")");

            var handleSubmit = function() {
              DIALOG.close(this);
              W.d107(linvSerieNum,ltitoloBaseId,lcdbib, function(){
                  DIALOG.simple({
                      html:"La richiesta di prestito è stata inoltrata con successo",
                      width:'550px'
                    });
              });
            }
            
            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-presdist",
              html: result.html,
              buttons: buttons,
              width: "800px"
            });
            
            lcdbib = $("select[name=combobibprestitodistanza] option:first").attr('selected','selected').val();
            
            DIALOG.show(dialog);

          } else {
            DIALOG.simple({
              html:result.data,
              width:'550px'
            });
          }
	    },
	    
	    render2: function(data) {
	      
	      var handleCancel = function() {
	        DIALOG.close(dialog);
	      };  
	        
	      var buttons = [{ text:i18n.js_btn_annulla, handler:handleCancel }];
	      var dialog = DIALOG.open({
	        id: "d-presdist",
	        html: data,
	        buttons: buttons,
	        width: "800px"
	      });

	      DIALOG.show(dialog);
	      $("#d-clump .hd span").html(data.data);
	    }
	    
	  };
	})();

// CAS
loadScript = function (sScriptSrc, callbackfunction) {
  sScriptSrc += "&" + (new Date().getTime().toString());
  return Ajax.loadScript(sScriptSrc, {
    id: "casScript",
    keep: false, // se serve
    callback: callbackfunction
  });
};

/** cambia il tema nella sezione style in head con titolo = "tema" */
function setStyle(cssStr){
  var style = document.createElement("style");
  style.setAttribute("type", "text/css");
  style.title = "tema";
  
  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 styles = head.getElementsByTagName('style');

  for(var i=0; i<styles.length; i++) {
  	if (Strings.equals(styles[i].title, "tema")) {
      head.removeChild(styles[i]);
      break;
  	}
  } 

  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/tiny_mce/tiny_mce.js',
      /* mode : "textareas", */
      theme : "advanced",
      relative_urls : false,
      convert_urls : false, 
      /* plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template", */
      plugins : "safari,spellchecker,layer,table,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras",
      /* extended_valid_elements : "div[width|onclick|class|id|style|title],form[action|target|accept|accept-charset|enctype|method],iframe[align|class|frameborder|height|id|longdesc|marginheight|marginwidth|name|scrolling|src|style|title|width]", */
      paste_retain_style_properties : "all",
      force_br_newlines : true,
      force_p_newlines : false,
      forced_root_block : '', // Needed for 3.x
      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,|,styleprops",
      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,Forms.value(document.ricerca.biblioradio),r10);
}

function getKindOfList(){
  if (!PSEARCH.button) {
    if (document.ricerca.kindOfList) {
      return document.ricerca.kindOfList.value; 
    }

    return '';
  }
  
  return PSEARCH.button.getCd();
}

function getFilter() {
  var select = $("#pagelistatermini select[name='filter']");
  if (select.size() > 0)
    return Forms.value(select.get(0));
  return "";
}

/** nasconde/visualizza le colonne laterali */
function showhideColumn(e){
  if (!document.getElementById) return;
  if (Utils.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 } );
        Nodes.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 } );
        Nodes.getFirstChild($ID('RightArrowColumn')).className="bottonefrecciadestra";
     });
   }
   
  } else {
    if (e == 'pageleftcontent') {
      leftMargin = $o.css("marginLeft");
      $e.hide("drop", { direction: 'left' }, 200, function() {
        $o.animate( { marginLeft: '12px' } );
        Nodes.getFirstChild($ID('LeftArrowColumn')).className="bottonefrecciadestra";    
      });      
    } else if (e == 'pagerightcontent') {
      rightMargin = $o.css("marginRight");
      $e.hide("drop", { direction: 'right' }, 200, function() {
        $o.animate( { marginRight: '12px' } );
        Nodes.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 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 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();
      }
      PicBoxUtils.create(".oggettiDigitali a", {
        proxy: { 
          parents: "td",
          element: ".titololistarisultati"
        }
      });
      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;
  var time = 0;
  oldNews = -1;
  var COLOROVER = "#ffffff";
  var COLOROUT = "transparent";
  var COLORSELECTED = "#009900";

  var NewsGroup = function(news, groupTag) {
    
    if (!news || !news.length || news.length == 0) return;
    
    this.setCollection = new Array(news.length);
  
    NewsGroup.prototype.remove = function() {
      for(var i=0; i<this.setCollection.length; i++) {
        var set = this.setCollection[i];
        set.remove();
      }
      
      this.setCollection = null;    
      
      // Post Remove
    }
    
    for(var i=0; i<news.length; i++) {
      this.setCollection[i] = new NEWS.NewsSet(news[i]);
    }
  }
  
  return {
    roll: function(data) {
      var listNews = $("#listNews > div");
      
      if (listNews.size() == 0) {
        return;
      } else if (listNews.size() == 1) {
        $("#listNews > div:eq(0)").show();
        return;        
      }
      
      if(time == 0) {
        time = data.data
      }

      currentNews = (oldNews + 1) % listNews.size();

      if(oldNews >= 0) {
        var oN = $("#listNews > div:eq(" + oldNews + ")"); 
        var nN = $("#listNews > div:eq(" + currentNews + ")");
        
        if (Strings.isBlank(newsEffect) 
            || newsEffect == 'fade') {
          oN.fadeOut("slow", function() {
            nN.fadeIn("slow");            
          });
        } else if (newsEffect == 'slide') {
          oN.slideUp("slow", function() {
            nN.slideDown("slow");
          });
        } else if (!Strings.isBlank(newsEffect)) {
          oN.hide(newsEffect, {}, "slow", function() {
            nN.show(newsEffect, {}, "slow");
          });          
        }
      } else {
        $("#listNews > div:eq(" + currentNews + ")").show();
      }
        
      oldNews = currentNews
      window.clearTimeout(rollTimer);
      rollTimer = window.setTimeout("NEWS.roll()", time*1000);   
    },
    
    list: function() {
      curListPage = 1;
      A.a100m00(RENDERING.rBody);
    },
    
    goToPage: function(page) {
      curListPage = page;
      A.a100m03(page,RENDERING.rBody)
    },
    
    detail: function(id) {
      A.a100m04(id,curListPage,RENDERING.rBody)
    },

    del: function(id) {
      DIALOG.simple({
        title: i18n.js_news_dialog,
        message: i18n.js_news_confirmdelete,
        handler: function() {
          A.a100m06(id,RENDERING.rBody)
          DIALOG.close(this);
        }
      });
    },
    
    insert: function() {
      A.a100m07(NEWS.renderEditor);
    },
    
    edit: function(id) {
      A.a100m08(id,NEWS.renderEditor);
    },
    
    renderEditor: function(data) {
      /*
        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",      
      */
      RENDERING.rBody(data);
      SCMS.utils.renderMCE($("textarea[name$='TEXT']").get(0));
      
      /*$("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 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,hr,|,fontselect,fontsizeselect",
      theme_advanced_buttons2 : "cut,copy,paste,|,search,replace,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,image,|,code,|,insertdate,inserttime,|,preview,fullscreen,|,print",
        theme_advanced_buttons3 : "",
        theme_advanced_buttons4 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
        language : "it",
        width : "auto"
      });*/

      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
      }); 
      
      $("input[name$='DATAPUBBLICAZIONE']").datepicker({
        dateFormat: "dd/mm/yy",
        showOptions: { 
          direction: "up" 
        },
        yearRange: '1910:'+dataObj.getFullYear()+10
      });
      
    },

    formSubmit: function(id) {
      $form = $('#formNews');
      
      var p = new Object();
      
      if(id != undefined) {
        update = true;
        p.id = id;
      } else {
        update = false;
      }
      
      var errore = false;
      $form.find("input[type='text'], input[type='hidden'], input[type='checkbox']:checked, input[type='radio']:checked, 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 {
          NEWS.detail(data.data);
          /*HINT.info(i18n.js_news_inserimento_ok);
          if(update) {
            NEWS.goToPage(curListPage);  
          } else {
            W.m00("wnews", w01m00);
          }*/
          
        }
      });
    },
    
    formReset: function() {
      $('#formNews')[0].reset();
    },
    
    formExit: function() {
      NEWS.list();
    },
    
    initCMS: function() {
      NEWS.refreshLinks();
                  
      var news = $(".dsnewstitle,#lista-news .news");
      if (news.size() > 0) {
        SCMS.addSet("news", new NewsGroup(news.get(), "news"));  
      }
    },
    
    refreshLinks: function() {
      $("#wnewsinsert,.news-inserisci").show();
      
      $(SCMS.dot).one("cms-off", function() {
        $("#wnewsinsert,.news-inserisci").hide();
      });
    },

    NewsSet: function(e) {
      this.init(e, "id");
      
      this.add = function(e) {
        NEWS.insert();
      }
      
      this.edit = function(e, add) {
        NEWS.edit(this.idElement);
      }
    
      this.del = function() {
        NEWS.del(this.idElement);
      }

      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));
    },

    uploadCallback: function() {
      $iconNews = $("#iconNews");
      $imageNews = $("#imageNews");
      if($iconNews.size()>0) {
        A.a100m10("newsicona",NEWS.refreshImages);  
      } else if($imageNews) {
        A.a100m10("newsimages",NEWS.refreshImages);
      }
    },

    refreshImages: function(data) {
      $iconNews = $("#iconNews");
      $imageNews = $("#imageNews");
      
      if($iconNews.size()>0) {
        $iconNews.html(data.html);  
      } else if($imageNews) {
        $imageNews.html(data.html);
      }
    },

    iconDialog: function() {
      //A.a100m01(NEWS.renderIconDialog);
      mcImageManager.browse({oninsert : function(data) {
        var thumb_url = data.focusedFile.custom.thumbnail_url;
        var image_url = data.focusedFile.url;
        NEWS.renderIcon(thumb_url, image_url);
      }}); 
    },
    
    coverDialog: function() {
      Finder.browse(function(doc) {
        var thumb_url = doc.copertina.url;
        var image_url = doc.copertina.url;

        var idOpac = $ID("news-icona-idopac");
        if (idOpac && doc.opacId) {
          idOpac.value = doc.opacId;
        }

        NEWS.renderIcon(thumb_url, image_url);
      });
    },
    
    renderIcon: function(thumb_url, image_url) {
      var icona = $ID("news-icona-img");
      var hidden = $ID("news-icona-input");
      var links = $ID("news-icona-links");
      if (!icona || !hidden || !links) {
        return;
      }

      if (Strings.isBlank(thumb_url)
          || Strings.isBlank(image_url)) {
        return;
      }
          
      icona.src = thumb_url;
      hidden.value = image_url;

      Animations.fadeIn(icona, 500);
      links.style.display = "none";
      
      Cancelable.apply(icona, NEWS.removeIcon);      
    },
    
    removeIcon: function() {
      var icona = $ID("news-icona-img");
      var hidden = $ID("news-icona-input");
      var idopac = $ID("news-icona-idopac")
      var links = $ID("news-icona-links");
      if (!icona || !hidden || !idopac || !links) {
        return;
      }
      
      hidden.value = "";
      idopac.value = "";

      icona.style.display = "none";
      icona.src = "";

      links.style.display = "block";
    },
    
    imagesDialog: function() {
      //A.a100m09(NEWS.renderImagesDialog);
      mcImageManager.browse({oninsert : function(data) {
        var thumb_url = data.focusedFile.custom.thumbnail_url;
        var image_url = data.focusedFile.url;
        NEWS.renderImage(thumb_url, image_url);
      }});       
    },

    renderImage: function(thumb_url, image_url) {
      var newsImages = $ID("news-images");
      
      var inputValue = ""; 
      for(var i=0; i<newsImages.childNodes.length; i++) {
        var img = newsImages.childNodes[i];
      	if (typeOf(img) != "element"
      	   || img.tagName != "IMG") {
      	  continue;
      	}
      	
      	if (img.src == image_url) {
      	  // non permetto duplicati
      	  HINT.warn(i18n.js_news_image_duplicated);
      	  return;
      	}
      	
      	inputValue += img.src + ",";
      }
      
      inputValue += image_url;
      
      var input = $ID("news-images-input");
      input.value = inputValue;
      
      var img = new Image();
      img.className = "news-image";
      img.src = thumb_url;
      img.alt = image_url;
      newsImages.appendChild(img);
      
      Cancelable.apply(img, NEWS.removeImage);
    },
    
    removeImage: function() {
      var input = $ID("news-images-input");
      
      var value = input.value;
      value = value.replace(this.alt, "");
      value = value.replace(",,", ",");
      value = value.replace(/^,|,$/g, "");
      input.value = value;
      
      Nodes.remove(this);
    },
    
    scadute: function(val) {
      curListPage = 1;
      A.a100m05(val, RENDERING.rBody);
    },
    
    pubblicate: function(val) {
      $ID("newsOperazioniAdmin").style.display=val?"":"none";
      curListPage = 1;
      A.a100m14(val, RENDERING.rBody);
    },
    
    figlie: function(val) {
      curListPage = 1;
      A.a100m11(val, RENDERING.rBody);
    },
    
    sort: function() {
      A.a100m12(RENDERING.rBody);
    },
    
    sortSali: function(sali, id) {
      if(!sali) return;
      
      var group = Nav.parentTag(sali, "tbody");
      if (group.className.indexOf("disabled") >= 0) {
        return;
      }
      
      var prev = Nav.prev(group); 
      if (!prev) {
        return;
      } 
      
      Nodes.insertBefore(prev, group);
      
      // controllo se può salire ancora o nascondo il pulsante
      if (!Nav.prev(group)) {
        sali.style.visibility = "hidden";
      } else {
        sali.style.visibility = "";
      }
      
      // mostro il pulsante scendi
      Nav.next(sali).style.visibility = "";
      
      var prevSali = $(prev).find(".sali").get(0);
      prevSali.style.visibility = "";
      
      if (Nav.next(prev) == null) {
        var prevScendi = $(prev).find(".scendi").get(0);
        prevScendi.style.visibility = "hidden";
      }
    },

    sortScendi: function(e, id) {
      if(!e) return;
      
      var group = Nav.parentTag(e, "tbody");
      if (group.className.indexOf("disabled") >= 0) {
        return;
      }
      
      var next = Nav.next(group);
      if (!next) {
        return;
      }
            
      Nodes.insertAfter(next, group);
      
      // controllo se può scendere ancora
      if (!Nav.next(group)) {
        e.style.visibility = "hidden";
      } else {
        e.style.visibility = "";
      }
      
      // mostro il pulsante sali
      Nav.prev(e).style.visibility = "";
      
      var prevScendi = $(next).find(".scendi").get(0);
      prevScendi.style.visibility = "";
      
      if (Nav.prev(next) == null) {
        var prevSali = $(next).find(".sali").get(0);
        prevSali.style.visibility = "hidden";
      }
    },
    
    sortPrioritario: function(td, id) {
      var group = Nav.parentTag(td, "tbody");
      if (group.className.indexOf("disabled") >= 0) {
        return;
      }
      
      if (td.className.indexOf("prioritario-on") >= 0) {
        Nodes.removeClass(td, "prioritario-on");
        Nodes.removeClass(group, "group-prioritario");
      } else {
        Nodes.addClass(td, "prioritario-on");
        Nodes.addClass(group, "group-prioritario");
      }      
    },

    sortMostraFigli: function(e) {
      var group = Nav.parentTag(e, "tbody");
      if (group.className.indexOf("disabled") >= 0) {
        return;
      }
      
      var tr = Nav.parentTag(e, "tr");
      var next = Nav.next(tr);
      if (!next) {
        return;
      }
      
      if (next.style.display == "none") {
        next.style.display = "table-row";
        var group = Nav.parent(tr);
        var groups = $("#news-sort > table > tbody").get();
        Nodes.addClass(groups, "disabled");
        Nodes.removeClass(group, "disabled");
        Nodes.addClass(group, "selected");
        Nodes.addClass(e, "figli-on");
      } else {
        next.style.display = "none";
        var groups = $("#news-sort > table > tbody").get();
        Nodes.removeClass(groups, "disabled");
        Nodes.removeClass(groups, "selected");
        Nodes.removeClass(e, "figli-on");
      }
    },

    sortSubmit: function() {
      var tables = $("#news-sort table").get();
      
      var ordinamento = new Object();
      var prioritario = new Object();
      each(tables, function(table) {
        each(Nav.childs(table), function(news, i) {
          ordinamento[news.id] = i;
          prioritario[news.id] = news.className.indexOf("prioritario") > 0;
        });
      });
      
      A.a100m13(ordinamento, prioritario, function(data) {
        if (!data) {
          HINT.error(i18n.js_errore_generico);
        }
        
        NEWS.goToPage(curListPage);        
      });
    },
    
    sortExit: function() {
      NEWS.goToPage(curListPage);        
    }    
  };
})();

Cancelable = new function() {
  this.apply = function(node, callback) {
    if (recursive(arguments)) return;
    
    if (typeOf(node) != "element"
        || typeOf(callback) != "function") {
      return;
    }
    
    Events.on(node, "mouseover", function(event, node) {
      var wrapper = node.parentNode;

      if (Nodes.isAncestor(event.relatedTarget, wrapper)) {
        return;
      }
        
      if (wrapper.className != "cancelable-wrapper") {
        wrapper = create("div");
        wrapper.className = "cancelable-wrapper";
        Nodes.wrap(this, wrapper);
      }
        
      var remove = node.nextSibling;
      if (!remove) {
        remove = create("div");
        remove.className = "remove cancelable-remove";
        wrapper.appendChild(remove);
      }
        
      Events.on(remove, "click", function(event) {
        DIALOG.simple({
          message: i18n.js_news_image_remove,
          handler: function() {
            Events.off(remove, "click");
            Nodes.remove(remove);

            Nodes.insertBefore(wrapper, node);     
            Nodes.remove(wrapper);
            Events.off(node, "mouseover, mouseout");
           
            callback.call(node); 
            DIALOG.close(this);
          }
        });
      });
      
      Animations.fadeIn(remove, 300);
    }, node);
      
    Events.on(node, "mouseout", function(event, node) {
      var wrapper = node.parentNode;
      if (Nodes.isAncestor(event.relatedTarget, wrapper)) {
        return;
      }
        
      var remove = node.nextSibling;
      Animations.fadeOut(remove, 300);
    }, node);
  }
}

NEWSCALENDAR = new function() {
  
  this.sortByDate = function(date) {
    W.d320(date, null, null, { noLoader: true, callback: RENDERING.widget});
  }
  
  this.sortByCategory = function(category) {
    W.d320(null, category, null, { noLoader: true, callback: RENDERING.widget});
  }

  this.sortByBib = function(bib) {
    W.d320(null, null, bib, { noLoader: true, callback: RENDERING.widget});
  }
  
  this.reset = function() {
    W.d320(null, null, null, { noLoader: true, callback: RENDERING.widget});
  }
};

OGGETTIDIGITALI = (function () {
  var rollTimer;
  var time = 0;
  oldElement = -1;
    
  return {
    roll: function(data){
      var listElements = $("#woggettidigitali_list > div");
      if (listElements.size() > 1) {
        if (time == 0) {
          time = data.data
        }
        currentElement = (oldElement + 1) % listElements.size();
        if (oldElement >= 0) {
          $("#woggettidigitali_list > div:eq(" + oldElement + ")").fadeOut("slow", function(){
            $("#woggettidigitali_list > div:eq(" + currentElement + ")").fadeIn("slow");
          });
        }
        else {
          $("#woggettidigitali_list > div:eq(" + currentElement + ")").show();
        }
        
        oldElement = currentElement
        window.clearTimeout(rollTimer);
        rollTimer = window.setTimeout("OGGETTIDIGITALI.roll()", time * 1000);
      }
      else {
        $("#woggettidigitali_list > div:eq(0)").show();
      }
      
    }
  };
})();

/* ---------------------------------------------------  */
/* reply a chiamate DWR  */
/* --------------------------------------------------- */

R = (function () {
  
  return {
    b01: function(data){
      STATUS.store(data,"R.b01");
      Nodes.createScriptNode(data.script,"js01");
      js01();
      RENDERING.body(data);
      //var hTab = 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){
          Css.modifyClassAttribute("addListmania","display","none");
        } else {
          LISTMANIA.enableAdd();
          for(n=0;n<cfgMieListe.liste.length;n++){
            if(LISTMANIA.last==cfgMieListe.liste[n].id){
              Css.modifyClassAttribute("addListmania","color","" + cfgMieListe.liste[n].color.replace(";",""));
              Css.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, config.idn, config.nat, true, R.a101);
          A.a20m00(config.iddoc, 'tabloca', config.polobiblio, r20);          
        }
        
        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") {
        HTAB.shiftTab("galleria");
      } else if (cdCanale == "where") {
        HTAB.shiftTab("maps");
      }
    },
    
    w02: function(data){
      setStyle(data.style);
    },
    
    a130m01: function(data) {
      if (data.error) {
        HINT.error(data.error);
      } else if (data.data) {
        HINT.info(data.data);
        A.a01m00(R.b01);
      }
    }

  };
})();

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 (!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;
    
    postProcessing(data);
  } else {
    if (data.script)
		  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 {
    //Nodes.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){
        Css.modifyClassAttribute("addListmania","display","none");
      } else {
        LISTMANIA.enableAdd();
        for(n=0;n<cfgMieListe.liste.length;n++){
          if(LISTMANIA.last==cfgMieListe.liste[n].id){
            Css.modifyClassAttribute("addListmania","color","" + cfgMieListe.liste[n].color.replace(";",""));
            Css.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');
  
  postProcessing(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){
      Css.modifyClassAttribute("addListmania","display","none");
    } else {
      LISTMANIA.enableAdd();
      for(n=0;n<cfgMieListe.liste.length;n++){
        if(LISTMANIA.last==cfgMieListe.liste[n].id){
          Css.modifyClassAttribute("addListmania","color","" + cfgMieListe.liste[n].color.replace(";",""));
          Css.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 = new function() {
  
  var div;

  function buildDom() {
    div = document.createElement("div");
    div.style.position = "absolute";
    div.style.left = "-9999px";
    document.body.appendChild(div);
  }
  
  function removeClasses(e) {
    if(!e)return;
    var c = e.className;
    if (Strings.isBlank(c)) return "";
    
    c = c.split(" ");
    e.className = "";
    for(var i=0; i < c.length; i++) {
    	if (Strings.isBlank(c[i])
    	   || Strings.startWith(c[i], "tnat", true)
    	   || Strings.startWith(c[i], "tdoc", true)
    	   || Strings.startWith(c[i], "tmat", true)) {
    	  continue;
    	}
    	
    	e.className += c[i] + " ";
    }
  }
  
  function load() {
    this.onload = null;

    if (BOL.checkImage(this)) {
      var p = $(this).parents(".copertina").get(0);
      removeClasses(p);
    } else {
      this.parentNode.removeChild(this);
    } 
  }
  
  this.checkImage = function(e) {
    if (!div) buildDom();
    
    var p = $(e).parents(".materiale")
    if (p.size() == 0) {
      return true;
    }
    
    var classi = p.attr("class");
    p.attr("class", "");

    var width = e.offsetWidth;

    p.attr("class", classi);
    
    if (width > 1) { 
      return true;
    }
    return false;
  }
  
  this.checkImages = function(e) {
    GBOOK.initCover();
    
    if (!div) buildDom();

    var covers = $("img[alt='copertina']:not(img[bol])").get();
    for(var i = 0; i < covers.length; i++) {
      covers[i].onload = load;
    }
  }
};

/* 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 (this.className.indexOf("closed") >= 0)
          lWidgets += "[closed]";
        lWidgets += ",";
      });
      
      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 (this.className.indexOf("closed") >= 0)
          rWidgets += "[closed]";
        rWidgets += ",";
      });
      
      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(Forms.value(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(Forms.value(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) { 
              	//sapere il contesto di ricerca non serve più, automatica la selezione sui rimanenti
                  //W.m01(res,document.ricerca.frase.value,false,R.w01);
              	var hrefloc = window.location.href;
              	if(hrefloc.indexOf("KAS=")<0){
              		hrefloc = hrefloc + ((hrefloc.indexOf("?")>0)? '&' : '?')+'KAS=true';
              	}
              	window.location.href = hrefloc;
              });
              $("#ap_numdoc").unbind("change");
              $("#ap_numcom").unbind("change");            
              DIALOG.close(this);
            }
          });
      }

      var buttons = [{ text:i18n.js_btn_conferma, handler:handleConfirm, isDefault:true },
        { text:i18n.js_btn_annulla, handler:handleCancel, isDefault:false }];
      
      var dialog = DIALOG.open({
        id: "d-personalizza",
        html: data,
        buttons: buttons,
        width: "800px",
        maximize: true,
        visible: false
      });
      
      TIMEOUT.updateSess();
      
      var apTabs = new YAHOO.widget.TabView("ap_tabset"); 
      apTabs.addListener("activeTabChange", function() {
        DIALOG.refresh();
      });
      
      
      /* 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)
            Nodes.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)
          Nodes.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)
          Nodes.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)
            Nodes.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 (!Strings.isBlank(cfgWidgets[id].ds)) {
            widget.innerHTML = cfgWidgets[id].ds;
          }
          
          if (!Strings.isBlank(cfgWidgets[id].tooltip)) {
            widget.setAttribute("help", cfgWidgets[id].tooltip);
          }
                        
          if (!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";
          }
           
          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 fields = Forms.fields(document.formAvanzata);
    for (key in fields) {
      var field = fields[key];      
      if (Strings.isBlank(field.name)
          || Strings.isBlank(field.value))
        continue;
        
      if (field.name == "mostraCodici")
        continue;
      
      searchParamMap[field.name] = field.value;
    }    

    if (Objects.size(searchParamMap) == 0) {    
 	    HINT.help(i18n.js_avanzata_nessuncampo);
 	    return;
    }
    
    DIALOG.close(this);
     
    var idFiltro = $("#psfiltri .selected");
     
    var fn = r10;
    if (idFiltro.size() > 0 
        && idFiltro.attr("id") == "ps_galleria") {
      fn = R.b13;
    }
      
    A.a10m04(searchParamMap, Forms.value(document.ricerca.biblioradio), fn);
  };
  
  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: "600px",
    visible: false 
  });
  
  $(dialog).bind("close", function() {
      // aggiunto per rimuovere i floater
    for(var i=0; i<ms.length; i++)
      ms[i].clearDOM();
  });
  
  var addFilter = function(result) {
    if (this.dom.select)
      return;

    var select = create("select");
    this.dom.select = select;
    this.dom.floater.appendChild(select);
    
    Events.on(select, "click", function(e) {
      e.halt();
    });
    
    Events.on(select, "change", function(e) {
      this.filter = Forms.value(e.target);
      this.browse();
      e.halt();         
    }, null, this);
    
    for (cd in result.filter) {
      var option = create("option");
      option.setAttribute("value", cd);
      
      if (result.defaultFilter
          && cd == result.defaultFilter) {
        option.setAttribute("selected", "selected");  
        this.filter = cd;  
      }
      
      option.innerHTML = result.filter[cd];
      select.appendChild(option);
    }
  }
  
  var elements = $("#formAvanzata input[suggest]").get(); 

  // last result cache  
  var result;
  
  var ms = MultiSelect(
    elements, {
      pageSize: 20,   
      zIndex: DIALOG.getLastZIndex() + 1,   
      i18n: {
        buttonLabel: "···"
      }, parser: function(result) {
        var terms = new Object();
        for(var i=0; i<result.terms.length; i++) {
          terms[result.terms[i].cd] = result.terms[i].ds;
        }
        return terms;
      }, suggest: function(term, o) {
        var field = this.dom.input.getAttribute("name");
        var suggest = this;
        A.a11S(term, field, null, o.pageSize, { noLoader: true, 
          callback: function(data) { 
            if (data == null) {
              result = null;
              return;
            }

            result = eval("(" + data + ")");
            suggest.receive(term, result);
          }
        });
      }, browse: {
        search: function(term, o) {
          var field = this.dom.input.getAttribute("name"); 
          var filter = this.filter;       
          A.a11S(term, field, filter || null, o.pageSize, { 
            async: false, 
            callback: function(data) { 
              if (data == null) {
                result = null;
                return;
              }
              result = eval("(" + data + ")");
            }
          });
            
          // mostro la select dei filtri
          if (result.filter)
            addFilter.call(this, result);
          
          if (result.nav.firstPage) 
            this.dom.prev.style.display = "none";
            
          if (result.nav.lastPage
              || Objects.size(result.terms) < o.pageSize)
            this.dom.next.style.display = "none";
          
          return result;
        },
        prev: function(term, o) {
          A.a11SP(o.pageSize, { 
            async: false, 
            callback: function(data) { 
              if (data == null) {
                result = null;
                return;
              }
              result = eval("(" + data + ")");
            }
          });
          
          if (result.nav.firstPage) 
            this.dom.prev.style.display = "none";
            
          return result;
        },
        next: function(term, o) {
          A.a11SN(o.pageSize, { 
            async: false, 
            callback: function(data) { 
              if (data == null) {
                result = null;
                return;
              }
              result = eval("(" + data + ")");
            }
          });
          
          if (result.nav.lastPage
              || Objects.size(result.terms) < o.pageSize)
            this.dom.next.style.display = "none";
            
          return result;
        }
      }, afterFill: function() {
        if (!result
            || !result.kindOfList) {
          return;
        }

        var field = this.dom.input.getAttribute("name");      

        var li = this.dom.list.childNodes;
        for(var i=0; i<li.length; i++) {
          // aggiungo il link ai documenti associati
          var a = create("a");
          a.href = "#";
          a.innerHTML = "&nbsp;[" + result.terms[i].freq + " doc]"; 
          
		      var cd = li[i].getAttribute("title");
          Events.on(a, "click", function(e, kindOfList, cd, filter) {
            if (Strings.startWith(kindOfList, "TH_", true)) {
              kindOfList = kindOfList.substring(3);
            }
            
            if (this.filter 
                && this.filter != "tutte") {
              cd = filter + " " + cd;
            }
                        
            A.a10m17(kindOfList, cd, r10);
            DIALOG.close("d-avanzata");
            return false;
          }, [result.kindOfList, cd, this.filter], this);
    
          li[i].appendChild(a);
        }

        if (!this.dom.hidden) {
          this.dom.hidden = {};
        }
        
        if (!this.dom.hidden[result.kindOfList]) {
          var hid = $ID(result.kindOfList); 
          if (!hid) {
            hid = create("input");
            hid.setAttribute("type", "hidden");
            hid.setAttribute("name", result.kindOfList);
            hid.id = result.kindOfList;
            hid.value = "";
            Nodes.insertAfter(this.dom.input, hid);
          }
          
          this.dom.hidden[result.kindOfList] = hid;
        }
        
        this.kindOfList = result.kindOfList;
      }, afterSelect: function(selected) {
        if (!selected
            || !this.kindOfList
            || !this.dom.hidden
            || !this.dom.hidden[this.kindOfList])
          return;
        
        var value = selected.getAttribute("title");
        if (Strings.isBlank(value))
          return;
    
        if (this.filter
            && this.filter != "tutte") {
          value = this.filter + " " + value;
        }
    
        var div = create("div");
        div.className = "avanzata-item";    
        Nodes.setText(div, value);
        Nodes.insertBefore(this.dom.input, div);
    
        // adding this to the container
        var hid = this.dom.hidden[this.kindOfList];
        if (Strings.isEmpty(hid.value)) {
          hid.value += value;
        } else
          hid.value += " OR " + value;
    
        Events.on(div, "click", function(e) {
          Nodes.remove(e.target);
          
          // remove element from hidden field
          this.value = this.value.replace(e.data, "");
          this.value = this.value.replace(/( OR ){2,}/g, " OR ");
          this.value = this.value.replace(/^( OR )|( OR )$/g, "");
        }, value, hid);
          
        // clear input after selection   
        this.dom.input.value = "";
        this.dom.input.focus();
      }
    });
  
  DIALOG.show(dialog);
}

TERMINI = {
  toggle: function() {
    var container = $CLASS("folding-container", this.parentNode);
    
    if (this.className == "folding-command-open") {
      Animations.fadeOut(container, 250);
      this.className = "folding-command-closed";
    } else {
      Animations.fadeIn(container, 250);
      this.className = "folding-command-open";
    }
  }
}

/** dialog per la ricerca sulle liste termini */
DTERMINI = new function() {
  
  var listaSelezionata = null;
  
  this.getCdListaSeleazionata = function() {
    return listaSelezionata;
  }
  
  this.d270 = function(cdLista) {
    W.d271(cdLista, function(data) {
      select(cdLista);
      RENDERING.html(data);
    });
  }
  
  this.rd270 = function(data) {
    var buttons = [
      { text:i18n.js_btn_cerca, handler:handleSubmit, isDefault:true },
      { text:i18n.js_btn_esci, handler:handleCancel } ]; 
  
    var dialog = DIALOG.open({
      id: "d-listaTermini",
      html: data.html,
      buttons: buttons,
      width: "800px"
    });
    
    if (!Strings.isBlank(listaSelezionata)) {
      select(listaSelezionata);
    } else {
      var span = $("#d-listaTermini .elenco span.selected");
      listaSelezionata = span.attr("id").substring(3); 
    }
  }
  
  var select = function(cdLista) {
    $("#d-listaTermini .elenco span")
      .removeClass("selected")
      .filter("#LT-" + cdLista)
      .addClass("selected");
      
    listaSelezionata = cdLista;
  }
  
  this.submit = function() {
    handleSubmit();
  }
  
  var handleSubmit = function() {
    var form = document.ricercaliste;
    
    var testo = form.testo.value;
    if (Strings.isBlank(testo)) {
      HINT.error(i18n.js_avanzata_nessuncampo);
      return;
    }
    
    var selected = $(this).find(".elenco span.selected");
    if (selected.size() == 0) return;
    
    var kindOfList = selected.attr("id");
    
    var filter = "";
    if (form.filter)
      filter = form.filter.value;
    
    A.a11m00(testo, kindOfList.substring(3), filter, rBodyRendering);
    
    DIALOG.close(this);
  }
  
  var handleCancel = function() {
    DIALOG.close(this);
  }  
  
}

function mostraCodiciForm(el) {
	if ($(el).is(':checked')) 
		$(".dialogavanzatacodici").show();
	else
		$(".dialogavanzatacodici").hide();
}

/* 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",
    maximize: true });
}

/** 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({
    width: "600px",
    title: "", 
    message: 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;
}

/** 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(batch) {
    var i=0;
    var l = [];
    while(batch.map["c0-param" + i] != undefined) {
      l[i] = batch.map["c0-param" + i];
      i++;
    }
    batch.map["c0-param0"] = "string:" + JGLO.getSysb();
    
    for(i=0; i < l.length; i++) {
      batch.map["c0-param" + (i+1)] = l[i];
    }
     
    if (!batch.noLoader) {
      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": Sizes.viewport.width,
        "height": $(window).height() - 10
    };
    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);

    Nodes.setRule(this.getDragEl(), "opacity", "0.67");
    
    this.goingUp = false;
    this.lastY = 0;
};

YAHOO.extend(YAHOO.sebyou.DDList, YAHOO.util.DDProxy, {
	
    startDrag: function(x, y) {
      LOG.info("startDrag");

      var srcEl = this.getEl();
      srcEl.style.display = "none";

      var dragEl = this.getDragEl();
      dragEl.style.zIndex = DIALOG.getLastZIndex() + 1;
      dragEl.style.display = "";
      dragEl.innerHTML = srcEl.innerHTML;
    },

    endDrag: function(e) {
      LOG.info("endDrag");
      
      $(".widget-block, .ap_filtro, .ap_widget")
        .removeClass("moving-down moving-up");

      $(this.getEl().parentNode).trigger("endDrag");
      $(this.getEl()).trigger("endDrag");
    },

    onDragDrop: function(e, id) {
      LOG.info("onDragDrop");
      
      var DDM = YAHOO.util.DragDropMgr;
      
      var accepted_ids = [ 
                 "ol_pageleftcontent",
                  "ol_pagerightcontent",
                  "ap_dd_fd",
                  "ap_dd_fv" ];
      
      var accepted_classes = [
                  "ap_widgets_left",
                  "ap_widgets_right",
                  "ap_widgets_center" ];

      var e = $ID(id);
      if (!e) return;

      if (Arrays.indexAt(accepted_ids, id) >= 0
          || Arrays.indexAt(accepted_classes, e.className) >= 0) {
        var destEl = $(".moving-down, .moving-up").get(0);   
        if (destEl) {
          if (this.goingUp) {
            $(".widget-block, .ap_filtro, .ap_widget")
              .removeClass("moving-down moving-up");
            Nodes.insertBefore(destEl, this.getEl());
          } else {
            $(".widget-block, .ap_filtro, .ap_widget")
              .removeClass("moving-down moving-up");
            Nodes.insertAfter(destEl, this.getEl());
          }
        } else {
          destEl = $ID(id);
          destEl.appendChild(this.getEl());
        }
      }

      this.getEl().style.display = "";      

      DDM.stopEvent(e);
      DDM.refreshCache();
    },
    
    onInvalidDrop: function(e) {
      this.getEl().style.display = "";  
      this.getDragEl().style.display = "none";
      var DDM = YAHOO.util.DragDropMgr;
      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 destEl = $ID(id);
      if (destEl.className.indexOf("widget-block") >= 0
          || destEl.className == "ap_filtro"
          || destEl.className == "ap_widget"
          || destEl.className == "ap_widget closed") {
        if (this.goingUp) {
          $(".widget-block, .ap_filtro, .ap_widget")
            .removeClass("moving-down moving-up");
          Nodes.addClass(destEl, "moving-up"); 
        } else {
          $(".widget-block, .ap_filtro, .ap_widget")
            .removeClass("moving-down moving-up");
          Nodes.addClass(destEl, "moving-down");             
        }
      }
      
    }
});

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({
    title: i18n.js_browsers_title,
    message: i18n.js_browsers_text,
    width: "400px"
  });
}

function copyrightDialog() {
  DIALOG.simple({
    title: i18n.js_copyright_title,
    message: i18n.js_copyright_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:i18n.js_btn_conferma, handler:handleConfirm, isDefault:true },
    { text:i18n.js_btn_annulla, handler:handleCancel }];

  var dialog = DIALOG.open({
    id: "d-chiediesperto",
    html: data.html,
    visible: false,
    buttons: buttons,
    width: "875px"
  });
  
  $(".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, Forms.value(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);
    BOL.checkImages();
}

function rd300m01(data) {
    $("#wscrollnavigator").html(data.html);
    BOL.checkImages();
}

function rd280(data)  {
	  var handleCancel = function() {
		    DIALOG.close(dialog);
		  };  
		  
		  var handleSubmit = function() {
			  var mailAddress = $ID("ap_abimail").value;
			  var formato = new Boolean();//false
			  if ($("#ap_formatodettaglio").is(':checked')){
				  formato = new Boolean(true);
			  }
			  W.d281(mailAddress, formato,function(bool){
				  var conferma="";
				  if (bool==true){
					  conferma = i18n.js_abimail_ok;
				  } else {
					  conferma = i18n.js_abimail_no;				  
				  }
				  DIALOG.info({
					  message: conferma
				  });
			  });
			  DIALOG.close(dialog);
		  };    
		  
		  var buttons = [{ text: i18n.js_btn_conferma, handler:handleSubmit },
		  { text: i18n.js_btn_annulla, handler:handleCancel, isDefault:true }];
		    
		  var dialog = DIALOG.open({
		    id: "d-abimail",
		    html: data.html,
		    buttons: buttons,
		    width: "600px" });
}

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"
    });
  }
};

var reCaptchaCustomTranslations = {
  instructions_visual : "Scrivi le due parole:",
  instructions_audio : "Trascrivi ci\u00f2 che senti:",
  play_again : "Riascolta la traccia audio",
  cant_hear_this : "Scarica la traccia in formato MP3",
  visual_challenge : "Modalit\u00e0 visiva",
  audio_challenge : "Modalit\u00e0 auditiva",
  refresh_btn : "Chiedi due nuove parole",
  help_btn : "Aiuto",
  incorrect_try_again : "Scorretto. Riprova."
}   

AR = (function () {
  
  var dialog;
  
  return {
    rd170: function(data) {
      if (data.error) {
        HINT.error(i18n.js_error);
        return;
      }
    
      var handleCancel = function() {
          DIALOG.close(dialog);
      }; 
    
      var handleConfirm = function() {
        AR.d171(json);
      };
      
      var buttons = [{ text: i18n.js_btn_conferma, handler: handleConfirm },
        { text: i18n.js_btn_annulla, handler: handleCancel }];

      var dialog = DIALOG.open({
        id: "d-ar",
        html: data,
        buttons: buttons,
        width: "900px"
      });
      
      $(dialog).bind("close", function() {
        if (json.recaptcha)
          Recaptcha.destroy();
      });
      
      var dataObj = new Date();
      $(dialog).find("*[name='dataNascita']").datepicker({
        dateFormat: "dd/mm/yy",
        changeMonth: true,
        changeYear: true, 
        defaultDate: "-10y",          
        maxDate: "-1y",
        minDate: "-100y",
        yearRange: '1910:' + dataObj.getFullYear()
      }); 
      
      var json = eval("(" + data.data + ")");
      if (!json) return;      
      
      if (!json.recaptcha) return;      
      Ajax.loadScript("http://api.recaptcha.net/js/recaptcha_ajax.js", {
        callback: function() {
            LOG.info("recaptcha libs loaded");
          
            Recaptcha.create(json.key,
              "recaptcha", {
              theme: "white",
              custom_translations: reCaptchaCustomTranslations,
              callback: function() { 
                LOG.info("recaptcha created");
              }
            });
          },
        keep: true
      });

    },
    
    d171: function(json) {
      var form = document.form_registrazione;      
      var fields = Forms.fields(form);

      $(form)
        .find(".error")
          .removeClass("error")
          .end()
        .find(".error-ds")
          .remove()
          .end();

      var stop = false;
      
      function err(field, msg) {
        $(field.node)
          .parent()
          .addClass("error")
          .append(msg);
          
        stop = true;
      }
      
      var newsletter = false;
      
      var ui = new Object();
      for (key in fields) {
        var field = fields[key];
        
        if (field.name == "dataNascita") {
          if (Strings.isBlank(field.value)) {
            err(field);
            continue;
          }
          
          var dataNascita = $.datepicker.parseDate("dd/mm/yy", field.value);
          if (!dataNascita 
              || isNaN(dataNascita.getDate())
              || dataNascita >= new Date()) {
            err(field);
            continue;
          }
          
          ui[field.name] = dataNascita;
          continue;
        }
        
        // recapito preferenziale
        if (field.name == "recapitopreferito") {
          if (!field.value) {
            err(field);
            continue;
          }
      
          if (field.value == 2 && fields.telefono 
              && Strings.isBlank(fields.telefono.value)) {
            err(fields.telefono);
            continue;
          } else if (field.value == 4 && fields.cellulare
              && Strings.isBlank(fields.cellulare.value)) {
            err(fields.cellulare);
            continue;
          } else if (field.value == 5 && fields.email
              && Strings.isBlank(fields.email.value)) {
            err(fields.email);
            continue;
          }
          
          ui["idRecapitoPreferenziale"] = field.value;
        }
        
        // privacy default "s"
        if (field.name == "flPrivacy") {
          if (!Strings.equals(field.value, "s")) {
            err(field, "<span class='error-ds'><br/>" + i18n.js_registrazione_datipersonali + "</span>");
          } else {
            ui["flPrivacy"] = true;
          }
          continue;
        }
        
        // password manuale
        if (field.name == "cpassword") {
          if (field.value != fields.password.value) {
            err(fields.password, "<span class='error-ds'><br/>" + i18n.js_registrazione_passwordequal + "</span>");
          }
          
          // salto il campo perchè non necessario
          continue;           
        }
        
        if (Forms.isReq(field.node)
            && Strings.isBlank(field.value)) {
          err(field);
          continue;
        }
        
        if (field.name == "newsletter") {
          newsletter = field.value;
          // non deve andare nell'oggetto uiautoregistrato
          continue;
        }
        
        ui[field.name] = field.value;
      }
      
      var cField = $("#recaptcha_challenge_field");

      if (stop) {

        if (cField.size() > 0)          
          Recaptcha.reload();

        HINT.error(i18n.js_registrazione_campimancanti);
        return;
      }
        
      if (cField.size() > 0) {
        var cValue = Recaptcha.get_challenge();
        var cResponse = Recaptcha.get_response(); 
        W.validate(cValue, cResponse, function(data) {
          if (data == false) {
            HINT.error(i18n.js_registrazione_recaptcha_fallito);
            Recaptcha.reload();
            return;              
          }
          
          W.d171(ui, newsletter, AR.rd171);
        });          
      } else {
        W.d171(ui, newsletter, AR.rd171);
      }
    },

    rd171: function(data) {
      var form = document.form_registrazione;
      
      $(form.username, form.password)
        .parent()
        .removeClass("error")
        .find(".error-ds")
        .remove();
      
      if (data == "OK") {
        HINT.help(i18n.js_registrazione_success);
        DIALOG.close("d-ar");
        return;
      } 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") {
        var msg = $("<p class='error-ds'>"+i18n.js_registrazione_usernameerror+"</p>"); 

        $(form.username)
          .parent()
          .addClass("error")
          .append(msg);
      } else if (data == "ERR:4") {
        var msg = $("<p class='error-ds'>"+i18n.js_registrazione_passworderror+"</p>"); 
      
        $(form.password)
          .parent()
          .addClass("error")
          .append(msg);
      }

      if ($("#recaptcha_challenge_field").size() > 0)  
        Recaptcha.reload();
    }    
  };
})();

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 LISTMANIA2 = {

  apriDialogStampa: function(idBib0, pageFrom) {
    var handleConfirm = function() { LISTMANIA2.stampa(idBib0); }
    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(pageFrom, function(data) { DIALOG.simple({ id: "bibliografia_stampa", html: data, buttons: buttons, width: "600px" }); });
  },
      
  apriDialogEMail: function(idBib0, pageFrom) {
    var handleConfirm = function() { LISTMANIA2.invia(idBib0); }        
    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.d189m(pageFrom, function(data) { DIALOG.simple({ id: "bibliografia_invia", html: data, buttons: buttons, width: "600px" }); });
  },
      
  stampa: function(idBib0) {
    var format = $("#bibliografia_format option:selected").val();
    var layout = $("#bibliografia_layout option:selected").val();
    var sortField = $("#bibliografia_ordinamento option:selected").val();
    W.d189h(idBib0, format, layout, sortField, null, function(data) { window.open(data); });
    DIALOG.close("bibliografia_stampa");
  },
      
  invia: function(idBib0) {
    var format = $("#bibliografia_format option:selected").val();
    var layout = $("#bibliografia_layout option:selected").val();
    var sortField = $("#bibliografia_ordinamento option:selected").val();
    var email = $("#bibliografia_email").val();
    if (email == undefined || email.length == 0) {
      HINT.error(i18n.js_ms_biblio_noemail);
      return;
    }
    W.d189hh(idBib0, format, layout, sortField, email, function(data) {
      if (data.indexOf("error") >= 0) {
        HINT.error(i18n.js_ms_biblio_senderror);
      } else {
        HINT.info(i18n.js_ms_biblio_sendok);
        DIALOG.close("bibliografia_invia");
      }
    });
  }
  
}

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",
      maximize: true,
      dynamicHeight: ".yui-content"
    });
    
    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(cdBiblio) {
      
      var handleCancel = function() {
        DIALOG.close(this);
      }

      var handleConfirm = function() {
        var form = document.nuovo_suggerimento;
        var catalogazione = form.getAttribute("catalogazione");
        suggerimenti.inserisci(catalogazione);
      }

      W.d250(cdBiblio, function(data) {
        var dialog = DIALOG.open({
          id: "d-suggerimentoguest",
          html: data,
          buttons: [
            { text: i18n.js_btn_conferma, handler: handleConfirm },          
            { text: i18n.js_btn_annulla, handler: handleCancel }
          ],
          width: "700px"
        });
      });
    },

    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;
  
      var p = new Object();
      var errore = false;

      var form = document.nuovo_suggerimento;
      Forms.fields(form, function() {
        $(this.node.parentNode).removeClass("error");
        
        if (!Strings.isBlank(this.value)) {
          p[this.name] = this.value;
        } else if (this.name == "TITOLO") {
          $(this.node.parentNode).addClass("error");
          errore = true;
        } else if (this.name == "BIBL") {
          $(this.node.parentNode).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) {
    W.d185(idMovimento, function(data) {
      if (data[0] != null) {
        W.d181("movimenti", null, _reply);
        HINT.info(i18n.js_ms_movprorogate_ok);
      } else {
        HINT.info(data[1]);
      }
    });
  }
  
  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() {

        var dateCompare = function(dateX, dateY) {
          if (!dateX && !dateY) {
            return 0;
          } else if (!dateX) {
            return -1;
          } else if (!dateY) {
            return 1;
          }

          if (dateX > dateY) {
            return 1;
          } else if (dateX < dateY) {
            return -1;
          } else if (dateX == dateY) {
            return 0;
          }
        }
        
        jQuery.fn.dataTableExt.oSort['data-asc'] = function(x, y) {
          var dateX = Dates.fromString(x, "dd/MM/yyyy"); 
          var dateY = Dates.fromString(y, "dd/MM/yyyy");
          return dateCompare(dateX, dateY);
        };

        jQuery.fn.dataTableExt.oSort['data-desc'] = function(x, y) {
          var dateX = Dates.fromString(x, "dd/MM/yyyy"); 
          var dateY = Dates.fromString(y, "dd/MM/yyyy");
          return -(dateCompare(dateX, dateY));
        };
        
        mtable = TABLE.create($("div.pregressi").find("table"), {
          "aaSorting": [ [3,'desc'] ],
          "aoColumns": [
            { }, // Tipo movimento
            { "sClass": "dt_title" }, // Titolo
            { "sClass": "dt_title",
              "bVisible": false }, // ISBD
            { "sType": "data" } // 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 _moderate(type) {
      var moderazione = $("#bibliografie").attr("moderazione");
      if (!moderazione || moderazione == "false") return false;
      
      if (!type || moderazione == type) {
        var nota = _getBib0().find("p.nota");
        if (nota.size() > 0) {
          nota.text(i18n.js_ms_biblio_NEW)
        } else {
          _getBib0().find(".content")
            .append("<p class='nota'>"+i18n.js_ms_biblio_NEW+"</p>");
        }
      };
    }
        
    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 .modify").unbind().click(function() {
        var idBib = $(this).parent().attr("idDoc");
        if (!idBib) return;
        
        bibliografie.apriDialogDocumento(idBib);      
      });
      
      $bib.find(".right .remove").unbind().click(function() {
        bibliografie.rimuoviDocumento(this);
        return false;
      });
      
      var note = $bib.find(".right .note");
      $.each(note, function() {
        FLOATER.create(this, {
          attr: "note"
        });
      });
      
      $bib.find("div.dataTables_wrapper .dt_title").unbind().click(function() {
        var idDoc = $(this).parent().find("div").attr("idtito");
        A.a20m14(idDoc, _getIdBib0(), function(data) {
          DIALOG.close("d-miospazio");
          r20(data); 
        });
      });

      $bib.find(".right #altreazioni").unbind().change(function() {
        var azione = $(this).val();
        switch (azione) {
          case "isbd":
            bibliografie.isbdTitolo();
           break;
          case "cancella":
            bibliografie.cancellaBibliografia();
            break;
        }
        $(this).find("option:first").attr("selected", "selected");
      });

      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(".dataTables_wrapper .dt_stato").unbind().change(function() {
        if (Strings.isBlank(this.value))
          return;

        var idBibliografia = this.getAttribute("iddoc");
        if (Strings.isBlank(idBibliografia))
          return;

        var result = false;
        W.d189n(idBibliografia, this.value, { 
          async: false, 
          callback: function(data) { 
            result = data; 
          } 
        });
        
        if (!result) {
          HINT.error(i18n.js_myspace_bibliografue_errorestato);
          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));
        };
      
        var columns = [
          { }, // Autore
          { "sClass": "dt_title", // Titolo
            "fnRender": function ( oObj ) {
              return ISBD.getTitle(oObj.aData[2]);
            },
            "iDataSort": 2 },
          { "sClass": "dt_title", // ISBD
            "sType": "isbd",
            "bVisible": false }];
              
        var attivazioni = $bib.find("th");
        for(var i=0; i<attivazioni.size(); i++) {
        	var th = attivazioni.get(i);
        	
        	if (th.className == "att_stato") {
            columns.push({ "bSearchable": false, "bSortable": false });
        	} else if (th.className == "att_data") {
            columns.push({ "bSearchable": false });
        	} else if (th.className == "att_editore") {
            columns.push({ });
        	}
        }

        // Pulsanti
        columns.push({ "bSearchable": false, "bSortable": false });
        
        btable = TABLE.create($bib.find(".right table"), {
          "oLanguage": {
            "sZeroRecords": i18n.js_myspace_bibliografie_norisultati 
          },
          "aaSorting": [ [3, "asc"], [2, "desc"] ],
          "aoColumns": columns,
          "fnDrawCallback": function() {
            if (btable) _aggiornaEventi();
          }
        });
        
        if (noUpdate == true) return;  
        _aggiornaEventi(); 
      },
      
      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).parent().attr("iddoc");
            W.d189b(_getIdBib0(), idDoc, function(data) {
              if (!data) {
                HINT.error("js_error");
                return;                
              }

              var row = btable.fnGetPosition(e.parentNode.parentNode.parentNode);
              btable.fnDeleteRow(row);
              DIALOG.close(rimuoviDialog);

              _moderate("full");
            }, 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);
                  selected.remove();
                } 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();
      },
      
      apriDialogModifica: function($form) {
        debug("apriDialogModifica");
                    
        W.d189l(_getIdBib0(), function(data) {
          var dialogModifica = DIALOG.simple({
            id: "modificabib0",
            html: data,
            handler: MYSPACE.bibliografie.modifica,
            width: "800px"
          });
        });
      },
      
      apriDialogDocumento: function(idDoc) {
        debug("apriDialogModifica");
                   
        var handleCancel = function() {
          DIALOG.close(this);
        }                   
                    
        var buttons = [{
          text: i18n.js_btn_conferma, 
          handler: MYSPACE.bibliografie.modificadocumento
        }, {
          text: i18n.js_btn_annulla, 
          handler: handleCancel, 
          isDefault: true
        }];                    
                    
        W.d189o(idDoc, function(data) {
          var dialogModifica = DIALOG.simple({
            id: "modificadocumento",
            html: data,
            buttons: buttons,
            width: "600px"
          });
          
          BOL.checkImages();
        });
      },
     
      modificadocumento: function() {
        var dialog = $("#modificadocumento");
        
        var note = $("#modificabib_note").val();
        if (note && note.length > 3000) {
          var error = i18n.js_myspace_bibliografie_notalunga;
          HINT.error(error.replace("%1", note.length));
          return;
        }
        
        var stato = $("#modificabib_stato").val();
        var idBib = $("#modificabib_id").val();

        W.d189p(idBib, note, stato, function(data) {
          if (!data) {
            HINT.error("js_error");
            return;
          }                 

          DIALOG.close("modificadocumento");
          
          var select = $("#tabbibliografie")
            .find("select[iddoc='"+idBib+"']").get(0);
          Selects.selectOption(select, stato);

          var noteSpan = $("#tabbibliografie")
            .find("div[iddoc='"+idBib+"']")
            .find("span.note");

          if (Strings.isBlank(note)) {
            noteSpan.attr("note", "")
              .hide();
          } else { 
            noteSpan.attr("note", escapeHTML(note))
              .show();
          }
        });        
      },
      
      modifica: function() {
        debug("modifica");

        var idBib0 = _getIdBib0();

        var form = document.modificaBibliografia;
        if (!form) return;
        
        var newCd = form.cd.value;
        var newDs = form.ds.value;
        if (Strings.isBlank(newCd)) {
          HINT.error(i18n.js_ms_biblio_nonewcd);
          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;
        }

        var newStato = Forms.value(form.stato);
        if (!newStato) newStato = "N";
        
        var newNt = form.nt.value;
        
        W.d189g(newCd, newDs, newStato, newNt, idBib0, function(data) {
          if (!Strings.isBlank(data)) {
            DIALOG.close("modificabib0");
            
            var bib0 = _getBib0();            
            bib0.find(".bib_cd").text(newCd);
            bib0.find(".bib_ds").text(newDs);
            
            if (!Strings.isBlank(newStato)) {
              bib0.find(".stato")
                .removeClass()
                .addClass("stato " + newStato)
                .html(i18n["js_ms_biblio_" + newStato]);
          
              if (newStato == "S" 
                  || newStato == "F") {    
    
                var urlPubblico = "<br/><a href='" + data + "' title='"
                  + i18n.js_ms_biblio_urlpubblicohelp
                  + "'>"
                  + i18n.js_ms_biblio_urlpubblico
                  + "</a>";
              
                bib0.find(".stato")
                  .append(urlPubblico);
              }
            }

            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); 
                  }
                });                  
              }
            }            
            
            _moderate();
          } 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(cdBiblio) { // TODO appena possibile cambiare il widget suggerimenti
        suggerimenti.apriEsterno(cdBiblio);
      },
      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();
      },
      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)"));
      },
      modificadocumento: function() {
        bibliografie.modificadocumento();                
      }
      
    },
    
    problema: {
      inserimento: {
        mostra: function() {
          $("#tabrisposte .movmenu").hide();          
          $("#form_problema").show()
            .get(0).reset();
          $(".link_inserimento").hide();
          $(".domande").hide();  
        },
        cancella: function() {
          $("#tabrisposte .movmenu").show();          
          $("#form_problema").hide()
            .get(0).reset();
          $(".link_inserimento").show();
          $(".domande").show();  
        },
        salva: function() {
          d141(null, function() {
            MYSPACE.changeTab('risposte');
            $("#tabrisposte .movmenu").show();          
          });
        }
      },
      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; 
          });
      });
    }
    
  };
}();

$(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") {

        GMUtils.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);
    GMAPI.close();
  },
  
  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);
    }
    
    var bibs;
    if (data.script) {
      try {
        bibs = 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 < bibs.length; i++) {
      var bib = bibs[i];
      
      var gLatLng = new GLatLng(bib.latitudine, bib.longitudine);

      var marker = new GMarker(gLatLng, { title: bib.tooltip });
      
      if (data.showBaloon && bib.genTooltip) {
        marker.bindInfoWindowHtml(bib.genTooltip);
      } else if (!data.showBaloon) {
        var wrapper = new function() {
          var b = bib;
          return function() {
            AREABIBL.confirmBibFromMap(b.idAux);
          }
        };
        GEvent.addListener(marker, "click", wrapper);
      } 
      
      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);

      r.bounds = new GLatLngBounds();
      
      LOG.debug(data.length);
      
      $.each(data, function(key, value) {
        if (_hasLatLng(value)) {
          if (idType == "idAux")
            _isDefaultMarker(value.idAux, key, value);
          else
            _isDefaultMarker(key, key, value);
          _setKnownMarker(key, value);
        } else {
          _setStep();
        }
      });
    });
  }
  
  function _setMarker(key, value) {
    LOG.info("GMAPI: Setting the marker: " + key + " - " + value);
    r.markers[key] = new GMarker(new GLatLng(value.latitudine, value.longitudine), { title: value.tooltip });
    r.markers[key].key = key;
    
    if (!Strings.isBlank(value.baloon)) {
      r.infoBoxes[key] = value.baloon;
    } else if (!Strings.isBlank(value.tooltip)) {
      r.infoBoxes[key] = value.tooltip;
    }
    
    if (r.markers[key]) {
      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.debug("gmapi.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");
      if (!r || !r.gMap)
        return;
      
      r.gMap.clearOverlays();
      r.$cont.remove();
      $(window).unbind("resize", GMAPI.resize);
      r = null;
    },
    
    resize: function() {
      _resizeMapWindow();
    },
    
    set: function(key) {
      _setUnknownMarker(key);
    }
  };
  
}();

/*
 * 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();
			
			if(p.type == "news") {
				$("<input type='text' name='servtype' value='news'/>")
					.hide()
        	.appendTo(p.$form);
			}			

      p.$form.submit();
      uploadTimer = window.setInterval(_checkUpload, 1000);

      return false;
    }
    
    function _checkUpload() {
      debug("checkUpload");
      if (_callBack() == true) {
				if(p.callback != null) {
					p.callback();
				} else {
					_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);
  };
  
});

var SCMS = function() {

  var dot = null;
  
  // abilitazioni possibili
  var abilitazioni = {
    cms: false,
    news: false 
  };
  
  var services = new Object();
  
  return {
    
    init: function(abilitazioniUtente) {
      abilitazioni = abilitazioniUtente;

      $.each(abilitazioni, function() {
        if (this == true) {
          dot = document.createElement("DIV");
          dot.id = "bibliodot";
          dot.className = "off";
          dot.title = i18n.js_cms_dottitle;
          
          $E.addListener(dot, "click", SCMS.switchMode);
          document.body.appendChild(dot);    
          return false;
        }
       });
    },

    isOn: function() {
      if (!dot) return false;
      
      return (Strings.equals(dot.className, "on"));
    },
    
    dot: this.dot,
    
    initServices: function() {
      $.each(abilitazioni, function(key, value) {
        if (value == true)
          SCMS.initService(key);
      });      
    },
    
    initService: function(service) {
      if (!SCMS.isOn() 
          || !abilitazioni[service])
        return false;

      $(document).ready(function() {
        switch (service) {
        	case "cms":
            var links = $("#wchisiamozone li");
            if (links.size() == 0) return;
              
            services["chisiamo"] = new LinkGroup(links.get(), "chisiamo");
        		break;

          case "news":
            if (services["news"]) {
              NEWS.refreshLinks();
            } else {
              NEWS.initCMS();
            }
            break;

        	default:
        		break;
        }
      });      
    },

    disableServices: function() {
      $.each(services, function(key, value) {
        SCMS.disableService(key);
      });      
    },
    
    disableService: function(service) {
      if (!services[service]) return;

      services[service].remove();
      services[service] = null;
    },
    
    switchMode: function(e, force) {
      if (!dot) return;
      
      if (!force && dot.className == "off") {
        force = "on";
      } else if (!force && dot.className == "on") {
        force = "off";
      }
      
      if (force == "on") {
        dot.className = "on";
        SCMS.initServices();
        
        $(dot).trigger("cms-on");
      } else if (force == "off") {
        dot.className = "off";
        SCMS.disableServices();

        $(dot).trigger("cms-off");
      }
    },

    getAbilitazioni: function() {
      return abilitazioni;
    },
    
    refresh: function(service) {
      if (!Strings.isBlank(service)) {
        SCMS.disableService(service);
        SCMS.initService(service);
      } else {
        SCMS.disableServices();
        SCMS.initServices();
      }
    },
    
    // inizializzazione esterna del set
    addSet: function(service, group) {
      if (!abilitazioni[service]) return;
      
      services[service] = group;
    },
    
    removeSet: function(service) {
      SCMS.disableService(service);
    }
    
  }
}();

SCMS.utils = {
  isEmpty: function(s, def) {
    if (!s || Strings.isBlank(s)) {
      if (def) return def;
      return ""; 
    }
    return s;
  },
  renderMCE: function(element) {
    $(element).tinymce({
      script_url : 'sebinayou/js/tiny_mce/tiny_mce.js',
      /* mode : "textareas", */
      theme : "advanced",
      relative_urls : false,
      convert_urls : false, 
      /* plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template", */
      plugins : "safari,spellchecker,layer,table,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,imagemanager",
      /* extended_valid_elements : "div[width|onclick|class|id|style|title],form[action|target|accept|accept-charset|enctype|method],iframe[align|class|frameborder|height|id|longdesc|marginheight|marginwidth|name|scrolling|src|style|title|width]", */
      paste_retain_style_properties : "all",
      force_br_newlines : true,
      force_p_newlines : false,
      forced_root_block : '', // Needed for 3.x
      theme_advanced_buttons1 : "fullscreen,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,link,unlink,anchor,image,insertimage,media,|,styleprops,|,tablecontrols",
      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);
      if(this.button.parentNode !== null) {
        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");
    // TODO piama: da rivedere $(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();
    }

    if(this.plateau.parentNode !== null) {
      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("span"); // TODO piama: da rivedere
    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(Forms.value(form.mode));
      map["url"] = isEmpty(form.url.value);
      map["html"] = isEmpty($(form.html).html());
      map["target"] = form.toblank.checked ? "_blank" : "";
      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 (Forms.value(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, "click", handleChange, null, form.mode);
      
      var mode = Forms.value(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;
NEWS.NewsSet.prototype = new SCMS.StdSet;

/* piama 25.10.2011: commentato in attesa di un metodo migliore per rilevare la chiusura della sessione
 window.onbeforeunload = function() {
  W.drop();
}*/

function shiftTab(tabName, forceRefresh, onlyRefresh) {
  return HTAB.shiftTab(tabName, forceRefresh, onlyRefresh);
}

HTAB = {
  
  lastTab: false,

  getTabs: function(visible) {
    return $("#whometab .yui-nav li" + (visible ? ":visible" : ""));
  },
  
  getCurrentTab: function() {
    var tabs = HTAB.getTabs(true);
    
    HTAB.getTab(tabs.filter(".selected"), true, tabs);
  },
  
  getFirstTab: function(visible) {
    return HTAB.getTab(1, visible);
  },
  
  getTab: function(tab, visible, tabs) {
    if (!tabs) {
      tabs = HTAB.getTabs(visible);
    }
    
    var tabName;
    if (typeof tab == "string") {
      tabName = tab;

      tab = tabs.filter(".tab" + tabName);
    } else if (typeof tab == "number") {
      tab = tabs.filter(":eq(" + tab + ")");
    } else if (!tab instanceof jQuery) {
      return;
    }
    
    if (tab.size() > 0) {
      
      if (!tabName) {
        var name = Strings.trim(tab.attr("class"));
        if (tab.hasClass(".selected")) {
          tab.name = name.substring(3, name.indexOf(" "));
        } else {
          tab.name = name.substring(3);
        }
      } else {
        tab.name = tabName;
      }
      
      tab.index = tabs.index(tab);
    } 
    
    return tab;
  },
  
  getTabBody: function(tabName) {
    if (tabName instanceof jQuery) {
      tabName = tabName.name;
    }
    
    return $("#tab" + tabName);
  },
  
  refreshTab: function(tab) {
    return shiftTab(tab, { 
        forceRefresh: true, 
        onlyUpdate: true 
      });
  },
  
  shiftTab: function(tab, options) {
    
    var o = $.extend({}, {
      forceRefresh: false,
      onlyUpdate: false
    }, options);

    if (typeof tab == "string") {
      if (Strings.isBlank(tab)) return;
      tab = HTAB.getTab(tab, false);
    } else if (!tab instanceof jQuery) {
      return;
    }
        
    if (tab.size() == 0) return;
        	
  	// Se non è richiesto il refresh e la tab è selezionata
  	// non facciamo niente
  	if (!o.forceRefresh && tab.hasClass(".selected")) {
  	  return;
  	}
  	
    var content = HTAB.getTabBody(tab.name).html();;
    if (o.forceRefresh || Strings.isBlank(content)) {
      W.m02(tab.name, function(data) {
        var firstTab = HTAB.getTab(0, true);
        
        if (!Strings.isBlank(data.html)) {
          // il tab è stato caricato correttamente
          if (tab.is(":hidden")) 
            tab.show();
            
          if (!o.onlyUpdate)
            homeTabView.set('activeIndex', tab.index);

          RENDERING.html(data);
        } else {
          tab.hide();
          
          if (tab.is(".selected")) {
            // il tab precedente ha fallito,
            // carico il primo tab e lo visualizzo
            HTAB.shiftTab(HTAB.getTab(0, true));
          } 
        } 
      });
    } else if (!o.onlyUpdate) {
      homeTabView.set('activeIndex', tab.index);
    }
  
    return false;  
  }
}

TABOGGD = (function() {

  function show(li, tab) {
    if(li.hasClass("selected")) {
      return;
    } else {
      li.parent()
        .find("li")
        .removeClass("selected");
        
      li.addClass("selected");
    }
    
    $(".syt-content").hide();
    tab.show();
  }
  
  return {  
    showImmagini: function() {
      show($(this), $("#tabimmagini"));      
    },
    showAltri: function() {
      show($(this), $("#tabaltri"));      
    }
  }
}());

SebinaStore = new function() {
  this.call = function() {
    W.getSebinaStore(function(url) {
      if (Strings.isBlank(url)) {
        HINT.error(i18n.js_dialog_problema_nonabilitatoguest);
        return;
      }
    
      window.open(url, "_blank");
    });
    
    return false;
  }
};

Finder = new function() {

  var htmlString = 
      "<div id='finder'>                             "
    + "  <div class='finder-bar'>                    "
    + "    <select id='finder-select'>               "
    + "      <option value='id'>ID</option>          "
    + "      <option value='idopac'>ID OPAC</option> " 
    + "      <option value='isbn'>ISBN</option>      "
    + "      <option value='bid'>BID</option>        "
    + "    </select>                                 "
    + "    <input id='finder-input' type='text'/>    "
    + "  </div>                                      "
    + "  <div id='finder-result'></div>              "
    + "</div>                                        ";
    
  var docString = 
      "<img id='finder-result-img' alt='' />                          "
    + "<p id='finder-result-title' class='titololistarisultati'></p>  "
    + "<p id='finder-result-author' class='autorelistarisultati'></p> ";
    
  var currentDoc;
  
  var multiButton;
    
  this.browse = function(callback) {
    
    currentDoc = null;
    
    DIALOG.simple({
      title: i18n.js_finder_title,
      message: htmlString,
      buttons: [{
          id: "finder-result-confirm",
          text: i18n.js_btn_cerca,
          handler: function() {
            if (!currentDoc
                && multiButton) {
              search(multiButton.getCd());
              return;              
            } 
            
            if (typeOf(callback) == "function") {
              callback.call(this, currentDoc);
            }
            
            DIALOG.close(this);
          }              
        }, { 
          text: i18n.js_btn_annulla, 
          handler: function() {
            DIALOG.close(this);
          }
        }
      ],
      width: "400px" 
    });
  
    multiButton = new MultiButton("finder-select", { 
      click: function(event, value) {
        search(value);
      }
    });
  }
  
  function search(field) {
    var input = $ID("finder-input");
    W.d330(field, input.value, function(doc) {
      var result = $ID("finder-result");
      Nodes.removeChilds(result);

      var button = $ID("finder-result-confirm");
      Nodes.setText(button, i18n.js_btn_cerca);

      currentDoc = null;

      if (!doc) {
        HINT.warn(i18n.js_finder_notfound);
        return;
      } else if (!doc.copertina.url) {
        HINT.warn(i18n.js_finder_nocover);
        return;
      }
      
      result.innerHTML = docString;        

      var image = $ID("finder-result-img");
      var title = $ID("finder-result-title");
      var author = $ID("finder-result-author");
      
      Nodes.setText(title, doc.title);
      Nodes.setText(author, doc.autore)
      
      image.style.display = "block";
      Events.on(image, "load", function() {
        if (image.offsetWidth > 1) {
          currentDoc = doc;
          Nodes.setText(button, i18n.js_btn_conferma);
        } else {
          HINT.warn(i18n.js_finder_nocover);
          image.style.display = "none";
        }
      });
      
      image.src = doc.copertina.url;
    });
  }
}

/*
 * Home for future facebook integrations
 */

Facebook = new function() {

  this.openBib0 = function(idBib0) {
    if (!idBib0) {
      return;
    }
    
    W.d340(idBib0, function(facebookURL) {
      if (!facebookURL) {
        return;
      }
      
      window.open(facebookURL, 'Facebook', 'height=440,width=620,scrollbars=true');      
    });
  } 
  
}

/*--- SEZIONE DIMENTICATOIO ---------*/

// Questa sezione serve a tenere da part 
// funzioni necessarie ma non più realmente utilizzate

function showHelp() {
  
}
