// Definizione dell'oggetto JSiter
// -------------------------------
var JSiter = {
    alertText:"",
    debugText:"",
    errorText:"",
    successText:"",
    warningText:"",
    currentMsg:0,
    showAllMsg:true
};

// Alert FUNCTIONs
// ===============
JSiter.setAlertText = 
   function(text){
      this.alertText= text;
   }

// getAlertText FUNCTION
JSiter.getAlertText = 
   function(){
      return this.alertText;
   }

JSiter.isAlertText =
   function() {
      return this.alertText!="";
   }

// Debug FUNCTIONs
// ==================
JSiter.setDebugText = 
   function(text){
      this.debugText = text;
   }

JSiter.getDebugText = 
   function(){
      return this.debugText;
   }

JSiter.isDebugText =
   function() {
      return this.debugText!="";
   }

// Error FUNCTIONs
// ===============
JSiter.setErrorText = 
   function(text){
      this.errorText = text;
   }

// getErrorText FUNCTION
JSiter.getErrorText = 
   function(){
      return this.errorText;
   }

JSiter.isErrorText =
   function() {
      return this.errorText!="";
   }

// Success FUNCTIONs
// ===============
JSiter.setSuccessText = 
   function(text){
      this.successText = text;
   }

// getSuccessText FUNCTION
JSiter.getSuccessText = 
   function(){
      return this.successText;
   }

JSiter.isSuccessText =
   function() {
      return this.successText!="";
   }

// Warning FUNCTIONs
// ==================
JSiter.setWarningText = 
   function(text){
      this.warningText = text;
   }

JSiter.getWarningText = 
   function(){
      return this.warningText;
   }

JSiter.isWarningText =
   function() {
      return this.warningText!="";
   }

// Toggle display_mode - none 
// ==========================
JSiter.toggleDivDisplay = 
   function(iddiv, display_mode) {
      if($('#'+iddiv).css('display')==display_mode) $('#'+iddiv).css('display', 'none');
      else $('#'+iddiv).css('display', display_mode);
   }

// Bookmark URL
// ============
JSiter.bookmarkURL = 
   function(bookmark, paramUrl, valueUrl, paramTitle, valueTitle) {
      var new_url = bookmark +  paramUrl +'=' + encodeURIComponent(valueUrl) + '&'+ paramTitle +'=' + encodeURIComponent(valueTitle);
      window.open(new_url);
   }

// Add to bookmarks
// ================
JSiter.addToBookmarks =
   function(title, url){
      if (document.all)   // IE
         window.external.AddFavorite(url, title);
      else if (window.sidebar)
         window.sidebar.addPanel(title, url, "");
 }

// expandBC FUNCTION
// =================
JSiter.expand =
   function(str){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data:"jstr:expand="+str
      }).responseText;
   }

JSiter.expandString =
   function(str, mid, bcid, pauth, inline){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data:"jstr:expand="+str+"&mid="+mid+"&bcid="+bcid+"&pauth="+pauth+"&inline="+inline
      }).responseText;
   }

// expandBC FUNCTION
// =================
JSiter.expandBC =
   function(bcpath){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data:"jstr:bcexpand="+bcpath
      }).responseText;
   }

// createBC FUNCTION
// =================
JSiter.createBC = 
   function(lang, bcname, id){
      $.ajax({
         type: "GET",
         url: "?",
         data: "jstr:bcadd="+bcname+"&lang="+lang+"&return=id",
         success: function(backtxt){
            $('#jsiter_bc_'+id).html('...');
            $('#jsiter_bc_'+id).attr('bcid',backtxt);
         }
      });
   }

// updateBC FUNCTION
// =================
JSiter.updateBC = 
   function(bcpath, divid, pars){
      $.ajax({
         type: "GET",
         url: "?",
         data: "jstr:bcexpand="+bcpath+"&jstr:bctarget="+divid+(pars==''?'':'&'+pars),
         success: function(backtxt){
            $('#jsiter_bc_'+divid).html(backtxt);
         }
      });
   }

// getBC FUNCTION
// =================
JSiter.getBC = 
   function(id, pars){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data: "jstr:bcget="+id+"&"+pars
      }).responseText;
   }

// setBC FUNCTION
// =================
JSiter.setBC = 
   function(id, pars){
      return $.ajax({
         url: "?",
         type: "POST",
         async: false,
         data: "jstr:bcset="+id+"&"+pars
      }).responseText;
   }

// Framework coder FUNCTION
// ========================
JSiter.coder =
   function(coder, pars){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data: "jstr:coder="+coder+"&"+pars
      }).responseText;
   }

JSiter.modulecoder =
   function(coder, pars){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data: "jstr:modulecoder="+coder+"&"+pars
      }).responseText;
   }

JSiter.updateResource =
   function(rid, resname, ali, mid, obj){
      // Recupero dal server del FORM di edit della risorsa
      var text = JSiter.coder('edit-resource', 'res_name='+resname+'&res_inst_id='+rid+'&res_inst_ali='+ali+'&res_inst_mid='+mid);

      // Apertura del POP-UP
      $('#jstr_dyna_body').html(text);
      $('#jstr_dyna_window').fadeIn();
      DCWindow.pack();

      // Attivazione della modalità Ajax sul FORM di edit della risorsa
      $('#resource_upload_form').ajaxForm({
         dataType: 'json',
         beforeSubmit: function(a,f,o) {
            $('#resource_upload_form_status').html('<img src="./modules/h_images/loading_big.gif" alt="loading_big" />');
         },
         success: function(data) {
            $('#resource_upload_form_status').html('<div id="resource_upload_success_label">Fatto!</div>');

            // Esecuzione dello script di callback (implementato nel FORM di edit della risorsa)
            data.obj = obj;
            data.add = rid == '';
            data.tbe = obj.type == "textarea";
            res = resourceUploadCallback(data);

            if(obj.type != "textarea") return;

            // Se 'obj' è una textarea
            if(resname == "file") JSiter.tbe_file($(obj).attr('id'), res.path + res.ali);
            else if(resname == "image") JSiter.tbe_image($(obj).attr('id'), res.path + res.ali);
         }
      });
   }

// setAttribute FUNCTIONs
// ======================
JSiter.setAttribute = 
   function(aenvironment, acontext, aname, avalue){
      $.get("?",{ func:"set-attribute", envi:aenvironment, name:aname, context:acontext, value:avalue });
   }

JSiter.setRequestAttribute = 
   function(acontext, aname, avalue){
      return this.setAttribute("request", acontext, aname, avalue);
   }

JSiter.setSessionAttribute = 
   function(acontext, aname, avalue){
      return this.setAttribute("session", acontext, aname, avalue);
   }

JSiter.setUserAttribute = 
   function(acontext, aname, avalue){
      return this.setAttribute("user", acontext, aname, avalue);
   }

JSiter.setApplicationAttribute = 
   function(acontext, aname, avalue){
      return this.setAttribute("application", acontext, aname, avalue);
   }

// getAttribute FUNCTIONs
// ======================
JSiter.getAttribute = 
   function(aenvironment, acontext, aname){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data:{ func:"get-attribute", envi:aenvironment, name:aname, context:acontext }
      }).responseText;
   }

JSiter.getRequestAttribute = 
   function(acontext, aname){
      return this.getAttribute("request", acontext, aname);
   }

JSiter.getSessionAttribute = 
   function(acontext, aname){
      return this.getAttribute("session", acontext, aname);
   }

JSiter.getUserAttribute = 
   function(acontext, aname){
      return this.getAttribute("user", acontext, aname);
   }

JSiter.getApplicationAttribute = 
   function(acontext, aname){
      return this.getAttribute("application", acontext, aname);
   }

// appendAttribute FUNCTIONs
// =========================
JSiter.appendAttribute = 
   function(aenvironment, acontext, aname, avalue){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data:{ func:"append-attribute", envi:aenvironment, context:acontext, name:aname, value:avalue }
      }).responseText;
   }

JSiter.appendRequestAttribute = 
   function(acontext, aname, avalue){
      return this.appendAttribute("request", acontext, aname, avalue);
   }

JSiter.appendSessionAttribute = 
   function(acontext, aname, avalue){
      return this.appendAttribute("session", acontext, aname, avalue);
   }

JSiter.appendUserAttribute = 
   function(acontext, aname, avalue){
      return this.appendAttribute("user", acontext, aname, avalue);
   }

JSiter.appendApplicationAttribute = 
   function(acontext, aname, avalue){
      return this.appendAttribute("application", acontext, aname, avalue);
   }

// unsetAttribute FUNCTIONs
// ========================
JSiter.unsetAttribute = 
   function(aenvironment, acontext, aname){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data:{ func:"unset-attribute", envi:aenvironment, context:acontext, name:aname }
      }).responseText;
   }

JSiter.unsetRequestAttribute = 
   function(acontext, aname, avalue){
      return this.unsetAttribute("request", acontext, aname, avalue);
   }

JSiter.unsetSessionAttribute = 
   function(acontext, aname, avalue){
      return this.unsetAttribute("session", acontext, aname, avalue);
   }

JSiter.unsetUserAttribute = 
   function(acontext, aname, avalue){
      return this.unsetAttribute("user", acontext, aname, avalue);
   }

JSiter.unsetApplicationAttribute = 
   function(acontext, aname, avalue){
      return this.unsetAttribute("application", acontext, aname, avalue);
   }

// SPAZI DI ATTRIBUTI
// ==================
JSiter.setAttributeInSpace =
   function(ascope, aspace_name, aname, avalue){
      return $.ajax({
         url: "?",
         type: "POST",
         async: false,
         data:{ func:"set-attribute-in-space", scope:ascope, space_name:aspace_name, name:aname, value:avalue }
      }).responseText;
   }

JSiter.isAttributeInSpace =
   function(ascope, aspace_name, aname){
      return $.ajax({
         url: "?",
         type: "POST",
         async: false,
         data:{ func:"is-attribute-in-space", scope:ascope, space_name:aspace_name, name:aname }
      }).responseText=="OK";
   }

JSiter.removeAttributeInSpace =
   function(ascope, aspace_name, aname){
      return $.ajax({
         url: "?",
         type: "POST",
         async: false,
         data:{ func:"remove-attribute-in-space", scope:ascope, space_name:aspace_name, name:aname }
      }).responseText=="OK";
   }

JSiter.getAttributeInSpace =
   function(ascope, aspace_name, aname){
      return $.ajax({
         url: "?",
         type: "POST",
         async: false,
         data:{ func:"get-attribute-in-space", scope:ascope, space_name:aspace_name, name:aname }
      }).responseText;
   }

JSiter.getJSONAttributeInSpace =
   function(ascope, aspace_name, aname){
      return $.parseJSON(this.getAttributeInSpace(ascope, aspace_name, aname)); 
   }

JSiter.getAttributesInSpace =
   function(ascope, aspace_name){
      value = $.ajax({
         url: "?",
         type: "POST",
         async: false,
         data:{ func:"get-attributes-in-space", scope:ascope, space_name:aspace_name }
      }).responseText;  
      return $.parseJSON(value);
   }

JSiter.removeSpace =
   function(ascope, aspace_name){
      return $.ajax({
         url: "?",
         type: "POST",
         async: false,
         data:{ func:"remove-space", scope:ascope, space_name:aspace_name}
      }).responseText;
   }

// Clipboard set/is in/get/remove/reset
// ====================================
JSiter.setInClipboard = 
   function(name, value){
      return this.setAttributeInSpace("session", "com.jsiter.clipboard", name, value);
   }

JSiter.isInClipboard = 
   function(name){
      return this.isAttributeInSpace("session", "com.jsiter.clipboard", name);
   }

JSiter.getInClipboard = 
   function(name){
      return this.getAttributeInSpace("session", "com.jsiter.clipboard", name);
   }

JSiter.removeInClipboard = 
   function(name){
      return this.removeAttributeInSpace("session", "com.jsiter.clipboard", name);
   }

JSiter.resetClipboard = 
   function(){
      return this.removeSpace("session", "com.jsiter.clipboard");
   }

JSiter.getClipboard =
   function(){
      clipboard = this.getAttributesInSpace("session", "com.jsiter.clipboard");
      msg = "";
      for (var i in clipboard) msg = msg+clipboard[i];
      this.removeSpace("session", "com.jsiter.clipboard"); 
      return msg;
   }

// Dynacode editing FUNCTIONs
// ==========================
JSiter.setEditor =
   function(id, bcId, level, style, obj) {
      $('#jstr_dyna_window').replaceWith(DCWindow.getWindowCode());
      DCWindow.alive = false;
      DCWindow.init();

      docId = "jsiter_bc_" + id;

      if($(obj).attr("bcId") == '') return;
      else bcId = $(obj).attr("bcId");

      code = JSiter.getBC(bcId, '&h_level='+level);
      
      $('textarea#jstr_dynacode').attr("value", code);

      $('input#dyna_apply_command').unbind();
      $('input#dyna_apply_and_close_command').unbind();
      eval("$('input#dyna_apply_command').click(function(){ JSiter.saveDynacode(level, bcId, docId);});");
      eval("$('input#dyna_apply_and_close_command').click(function(){ JSiter.saveDynacode(level, bcId, docId); $('#jstr_dyna_window').fadeOut(); });");

      $('#jstr_dyna_window').fadeIn("def", DCWindow.pack);
   }

JSiter.saveDynacode =
   function(level, bcId, docId){
      pars = 'h_level='+level+'&h_bodycode='+Utf8.encode(encodeURIComponent($('textarea#jstr_dynacode').attr('value')));
      text = JSiter.setBC(bcId, pars);
      $('#'+docId).html(unescape(text));
   }

JSiter.getEditor =
   function(id) {
      return eval("window.jsiter_bc_"+id+".this");
   }

JSiter.gotoUrl = 
   function(url) {
      window.location.href = url;
   }

JSiter.writeStatusBar = 
   function(txt){
      window.status = txt;
      return true;
   }

JSiter.setEditorStyle =
   function(id, bgcolor) {
      obj=document.getElementById('jsiter_bc_'+id); 
      obj.oldBgBolor=obj.style.backgroundColor;
      obj.style.backgroundColor=((bgcolor=='')?'#FEE':bgcolor);
   }

JSiter.resetEditorStyle =
   function(id) {
      obj=document.getElementById('jsiter_bc_'+id);
      obj.style.backgroundColor=obj.oldBgBolor;
   }

// Dynacode IMAGE editing FUNCTIONs
// ================================
JSiter.setResourceEditorStyle =
   function(inst_id, bgcolor) {
      obj=document.getElementById(inst_id); 
      obj.oldBgBolor=obj.style.backgroundColor;
      obj.style.backgroundColor=((bgcolor=='')?'#FEE':bgcolor);
   }

JSiter.resetResourceEditorStyle =
   function(inst_id) {
      obj=document.getElementById(inst_id);
      obj.style.backgroundColor=obj.oldBgBolor;
   }

// Popup FUNCTIONs
// ===============
JSiter.popupStatus = 0;

JSiter.loadPopup = 
   function(url){
      if(this.popupStatus==0){
         // load content from server
         $("#messageArea").load(url);
         $("#backgroundPopup").css({"opacity": "0.7"});
         $("#backgroundPopup").fadeIn("slow");
         $("#popupMessage").fadeIn("slow");
         this.popupStatus = 1;
         this.centerPopup();
      }
   }

JSiter.displayPopup = 
   function(text, title){
   if(this.popupStatus==0){
      $("#messageArea").html(text).prepend('<div class="popupTitle">'+title+'</div>');
      $("#backgroundPopup").css({"opacity": "0.7"});
      $("#backgroundPopup").fadeIn("slow");
      $("#popupMessage").fadeIn("slow");
      this.popupStatus = 1;
      this.centerPopup();
   }
}

JSiter.displayAlertPopup = 
   function(text, title){
      $("div#popupMessage").attr("class", "alertPopup");
      return JSiter.displayPopup(text, title);
   }

JSiter.displayDebugPopup = 
   function(text, title){
      $("div#popupMessage").attr("class", "debugPopup");
      return JSiter.displayPopup(text, title);
   }

JSiter.displayErrorPopup = 
   function(text, title){
      $("div#popupMessage").attr("class", "errorPopup");
      return JSiter.displayPopup(text, title);
   }

JSiter.displaySuccessPopup = 
   function(text, title){
      $("div#popupMessage").attr("class", "successPopup");
      return JSiter.displayPopup(text, title);
   }

JSiter.displayWarningPopup = 
   function(text, title){
      $("div#popupMessage").attr("class", "warningPopup");
      return JSiter.displayPopup(text, title);
   }

JSiter.displayAllPopups = 
   function(){
      if(JSiter.currentMsg < 5 && JSiter.showAllMsg){

         $("#backgroundPopup").hide();
         $("#popupMessage").hide();

         switch(JSiter.currentMsg){
            case 0: if(!JSiter.isAlertText())
                       JSiter.currentMsg++;
                    else break;
            case 1: if(!JSiter.isDebugText())
                       JSiter.currentMsg++;
                    else break;
            case 2: if(!JSiter.isErrorText())
                       JSiter.currentMsg++;
                    else break;
            case 3: if(!JSiter.isSuccessText())
                       JSiter.currentMsg++;
                    else break;
            case 4: if(!JSiter.isWarningText())
                       JSiter.currentMsg++;
         }

         switch(JSiter.currentMsg){
            case 0: $("div#popupMessage").attr("class", "alertPopup");
                    JSiter.displayPopup(JSiter.getAlertText(), "Alert");
                    break;
            case 1: $("div#popupMessage").attr("class", "debugPopup");
                    JSiter.displayPopup(JSiter.getDebugText(), "Debug");
                    break;
            case 2: $("div#popupMessage").attr("class", "errorPopup");
                    JSiter.displayPopup(JSiter.getErrorText(), "Error");
                    break;
            case 3: $("div#popupMessage").attr("class", "successPopup");
                    JSiter.displayPopup(JSiter.getSuccessText(), "Success");
                    break;
            case 4: $("div#popupMessage").attr("class", "warningPopup");
                    JSiter.displayPopup(JSiter.getWarningText(), "Warning");
                    break;
         }

         JSiter.currentMsg++;
      }
   }

/*
JSiter.disablePopup =
   function(){
      //disables popup only if it is enabled
      if(this.popupStatus==1){
      $("#backgroundPopup").fadeOut("slow");
      $("#popupMessage").fadeOut("slow");
      this.popupStatus = 0;
   }
}*/

JSiter.disablePopup =
   function(){
      //disables popup only if it is enabled
      if(this.popupStatus==1){
      this.popupStatus = 0;
         $("#backgroundPopup").fadeOut("slow");
         $("#popupMessage").fadeOut("slow", this.displayAllPopups);
      }
   }

JSiter.centerPopup = 
   function(){
      var windowWidth = document.documentElement.clientWidth;
      var windowHeight = document.documentElement.clientHeight;
      var popupHeight = $("#popupMessage").height();
      var popupWidth = $("#popupMessage").width();

      $("#popupMessage").css({
         "position": "fixed",
         "top": windowHeight/2-popupHeight/2,
      	 "left": windowWidth/2-popupWidth/2
      });

      //only need force for IE6
      $("#backgroundPopup").css({
         "height": windowHeight
      });
   }

// getBC FUNCTION
// =================
JSiter.popupBC = 
   function(bc){
      this.displayPopup(this.expandBC(bc), 'Dump area');
   }

JSiter.popupImage = 
   function(src, title){
      this.displayPopup(this.expand('<'+'jstr:img src="'+src+'" />'), title);
   }

JSiter.popupText = 
   function(text, title){
      this.displayPopup(this.expand(text), title);
   }

JSiter.openPreView= 
function (path, textarea) {
    var ie4=(document.all)? true:false;

    if (ie4) width=((window.document.body.clientWidth)/3)*2;
    else width=((window.innerWidth)/3)*2;

    if (ie4) height=((window.document.body.clientHeight)/3)*2;
    else  height=((window.innerHeight)/3)*2;
    popupWin = window.open('?xpage='+path+'&func=preview&h_preview='+textarea,'preview','scrollbars=yes,toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=' + width + ',height=' + height)
}


//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
   //CLOSING POPUP
   //Click the x event!
   $("#popupClose").click(function(){JSiter.disablePopup();});

   //Click out event!
   $("#backgroundPopup").click(function(){JSiter.disablePopup();});

   //Press Escape event!
   $(document).keypress(function(e){if(e.keyCode==27 && JSiter.popupStatus==1){JSiter.disablePopup();}});
});

// Flash movies FUNCTIONS
// ======================
JSiter.createControl =
   function(DivId, CLSID, ObjectID, MOVIE, WIDTH, HEIGHT){
      var d = document.getElementById(DivId);
      d.innerHTML = 
	'<object codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0 classid=' + CLSID + ' id='+ ObjectID + ' width=' + WIDTH + ' height=' + HEIGHT +'>'+
	'<param name="movie" value=' + MOVIE +'>'+
	'<param name="quality" value="high">'+
	'<param name="wmode" value="transparent">'+
	'<param name="menu" value="false">'+
	'</object>';
   }

JSiter.createControlAtAbsolutePosition =
   function(DivId, CLSID, ObjectID, MOVIE, WIDTH, HEIGHT, TOP, LEFT){
      var d = document.getElementById(DivId);
      d.style.zIndex="10";
      d.style.position="absolute";
      d.style.top = TOP+"px";
      d.style.left = LEFT+"px";
      d.innerHTML  = 
	'<object classid=' + CLSID + ' id='+ ObjectID + ' width=' + WIDTH + ' height=' + HEIGHT +'>'+
	'<param name="movie" value=' + MOVIE +'>'+
	'<param name="quality" value="high">'+
	'<param name="wmode" value="transparent">'+
	'<param name="menu" value="false">'+
	'</object>';
   }

// Utilities per la selezione di un utente
// =======================================
JSiter.retrieveUser =
   function(obj, name, context){  
      $.ajax({
         type: "GET",
         url: "?",
         data: "jstr:coder=filter-users&stringsearch="+obj.value,
         success: function(backtxt){
            var selected="";
            var jsonObject = eval('(' + backtxt + ')');
            var items = jsonObject.items; 
            var htmlResponse = "<select name='"+name+"' id='user_selection_"+context+"' onchange=\"JSiter.writeUser(this,'"+context+"')\">";
               if(items.length>0) htmlResponse +="<option value = ''>Selezionare</option>";
               for(i = 0; i < items.length; i++) {
                  htmlResponse += "<option alt='"+items[i].description+"' value ='"+items[i].id+"'>" + items[i].item + "</option>";
               }
            htmlResponse += "</select>";

            $("#td_select_user_"+context).html(htmlResponse);
            $('#view_user').html('');
         }
      });
   }

JSiter.writeUser =
   function(obj,nome_select){
      var x=document.getElementById(nome_select).selectedIndex;
      var select = document.getElementById(nome_select);
      $('#view_user').html(select[x].alt);
   }

// ================================
// Editing tool-bar
// ================================
JSiter.tbe_bold =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd = "<strong>" + text + "</strong>";
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_italic =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd ="<i>" + text + "</i>";
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_underline =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd ="<u>" + text + "</u>";
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_paragraph =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      AddTxt="<p>" + text + "</p>";
      this.tbe_addText(AddTxt, textarea);
   }

JSiter.tbe_span =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      AddTxt="<span>" + text + "</span>";
      this.tbe_addText(AddTxt, textarea);
   }

JSiter.tbe_div =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      AddTxt="<div>" + text + "</div>";
      this.tbe_addText(AddTxt, textarea);
   }

JSiter.tbe_center =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd ='<div style="text-align:center;">' + text + '</div>';
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_left =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd ='<div style="text-align:left;">' + text + "</div>";
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_right =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd ='<div style="text-align:right;">' + text + "</div>";
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_justify =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd ='<div style="text-align:justify;">' + text + "</div>";
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_hr =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd = text +"<hr />";
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_link =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      tadd ='<a href="" target="_blank">' + text + "</a>";
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_getClipboard =
   function(textarea) {
      tadd = this.getClipboard();
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_copyToClipboard =
   function(textarea) {
      var text = this.tbe_getText(textarea);
      this.setInClipboard('010101',text);
   }

JSiter.tbe_image =
   function(textarea, mod_path) {
      mod_path = mod_path != undefined ? mod_path : "";
      var text = this.tbe_getText(textarea);
      tadd ='<jstr:img src="' + mod_path + text + '" />';
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_insertImage =
   function(textarea,mid) {
      // id, res_type, src, mod, caller_obj
      this.updateResource('', 'image', '', mid, document.getElementById(textarea));
   }

JSiter.tbe_file =
   function(textarea, mod_path) {
      mod_path = mod_path != undefined ? mod_path : "";
      var text = this.tbe_getText(textarea);
      tadd ='<jstr:file src="' + mod_path + text + '" label="download" />';
      this.tbe_addText(tadd, textarea);
   }

JSiter.tbe_insertFile =
   function(textarea, mid) {
      // id, res_type, src, mod, caller_obj
      this.updateResource('', 'file', '', mid, document.getElementById(textarea));
   }

JSiter.tbe_getText =
   function(textarea) {
      var tarea = document.getElementById(textarea);
      if(tarea == null) return "";
      if(tarea.type != "textarea") return "";
      if (tarea.createTextRange && tarea.caretPos) {
         return tarea.caretPos.text;
      } else if (typeof tarea.selectionStart != 'undefined'){
         return tarea.value.substr(tarea.selectionStart,tarea.selectionEnd-tarea.selectionStart)
      }
      return '';
   }

JSiter.tbe_addText =
   function(text, textarea) {
      var crtScrollTop;
      var crtScrollLeft;
      try {
        var tarea = document.getElementById(textarea);
        if (typeof tarea.scrollTop != 'undefined') {
            crtScrollTop = tarea.scrollTop;
            crtScrollLeft = tarea.scrollLeft;
        }
      } catch (e) {};
      var tarea = document.getElementById(textarea);
      if (typeof tarea.selectionStart != 'undefined'){ // if it supports DOM2
        start = tarea.selectionStart;
        end = tarea.selectionEnd;
        tarea.value = tarea.value.substr(0,tarea.selectionStart)
        + text+ tarea.value.substr(tarea.selectionEnd);
        tarea.focus();
        tarea.selectionStart = ((start - end) == 0) ? start + text.length : start;
        tarea.selectionEnd = start + text.length;
      } else {
        if (tarea.createTextRange && tarea.caretPos) {
            var caretPos = tarea.caretPos;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
        }
        else {
            tarea.value += text;
        }
        tarea.focus(caretPos);
      };
      try {
        var tarea = document.PostTopic.Message;
        if (typeof tarea.scrollTop != 'undefined') {
            tarea.scrollTop = crtScrollTop;
            tarea.scrollLeft = crtScrollLeft;
        }
      } catch (e) {}; 
   }

JSiter.tbe_storeCaret =
   function(ftext) {
      if (ftext.createTextRange) {
         ftext.caretPos = document.selection.createRange().duplicate();
      }
   }

/* 
 * path: <modulepath>/<code>
 */
JSiter.getModuleCode =
   function(path, pars, callback, type){
      return $.get(
            "?h_modcode="+path,   // URL
            pars,                 // data
            callback,             // callback function (called ONLY on success)
            type
         );
   }

JSiter.toJSON =
   function(inputName){
      data = $("input[name="+inputName+"]");

      okData = new Array();

      for (i=0; i < data.length; i++)
         if (data[i].checked)
            okData[i] = [data[i].id];

      return $.toJSON(okData);
   }


// ================================
// LOCALITIES FUNCTIONS
// ================================

// *** loadLocalities ***
function loadLocalities(level, prefix) {
   id = $("#"+prefix+"_"+level).attr("value");
   resetLevels(prefix, level);
   $.get("?", { h_fwcode: "get-locations", id: id }, function(data) { setSelect(prefix, level, data) });
}

// *** setSelect ***
function setSelect(prefix, level, data) {
   select = $("select#"+prefix+"_"+(level+1));
   writeOptions(select, getData(data));
}

// *** getData ***
function getData(data){
   arr = new Array();
   comma_split = data.split(",");
   for(i=0; i<comma_split.length; i++){
      name_and_value = comma_split[i].split("-");
      arr.push(new Array(name_and_value[0], name_and_value[1]));
   }
   if(arr.length == 1)
      if(arr[1] == null) arr.pop();
   return arr;
}

// *** writeOptions ***
function writeOptions(select, options){
   if(options.length >= 1){
      html_options = "";
      select.removeAttr("disabled");
      html_options += "<option value=\"0\" selected=\"selected\">[seleziona]</option>\n";
      for(i=0; i<options.length; i++){
         if(options[i][1] == null) continue;
         html_options += "<option value=\""+options[i][1]+"\">"+options[i][0]+"</option>\n";
      }
      select.html(html_options);
   }
}

// *** resetLevels ***
function resetLevels(prefix, level) {
   for(i=level+1; i<=6; i++) {
      select = $("select#"+prefix+"_"+i);
      select.html("");
      select.attr("disabled", "disabled");
   }
}

// Utilities for validation and concession
// =======================================
function setValidation(resource_id, resource_classname, icon){
      v_var = $("input#v_var_" + resource_id);
      value = v_var.attr("value");
      func_value = resource_classname+".setValidation";

      $.get("?",
      { 
         rid: resource_id,
         value: value,
         func: func_value,
         h_noexpand: "yes"
      },
      function(data){
         if(data.substring(0, 2) == "ok"){
            if(value == "1") $(icon).fadeTo(150, 1.0);
            else $(icon).fadeTo(150, 0.3);
            v_var.attr("value", value == "1"?"0":"1");
         }
         else{
            alert("Save error!");
         }
      });
}

function setConcession(resource_id, resource_classname, icon){
      c_var = $("input#c_var_" + resource_id);
      value = c_var.attr("value");
      func_value = resource_classname+".setConcession";

      $.get("?",
      { 
         rid: resource_id,
         value: value,
         func: func_value,
         h_noexpand: "yes"
      },
      function(data){
         if(data.substring(0, 2) == "ok"){
            if(value == "1") $(icon).fadeTo(150, 1.0);
            else $(icon).fadeTo(150, 0.3);
            c_var.attr("value", value == "1"?"0":"1");
         }
         else{
            alert("Save error!");
         }
      });
}
