// Definizione dell'oggetto JSiter
// -------------------------------
var JSiter = {
    errorText:"",
    warningText:"",
    alertText:""
};

// Error FUNCTIONs
// ===============
JSiter.setErrorText = 
   function(text){
      this.errorText = text;
   }

// getErrorText FUNCTION
JSiter.getErrorText = 
   function(){
      return this.errorText;
   }

JSiter.isErrorText =
   function() {
      return this.errorText!="";
   }

// Warning FUNCTIONs
// ==================
JSiter.setWarningText = 
   function(text){
      this.warningText = text;
   }

JSiter.getWarningText = 
   function(){
      return this.warningText;
   }

JSiter.isWarningText =
   function() {
      return this.warningText!="";
   }

// Alert FUNCTIONs
// ===============
JSiter.setAlertText = 
   function(text){
      this.alertText= text;
   }

// getAlertText FUNCTION
JSiter.getAlertText = 
   function(){
      return this.alertText;
   }

JSiter.isAlertText =
   function() {
      return this.alertText!="";
   }

// expandBC FUNCTION
// =================
JSiter.expandBC =
   function(bcpath){
      return $.ajax({
         url: "?",
         type: "GET",
         async: false,
         data:"jstr:bcexpand="+bcpath
      }).responseText;
   }

// expandString FUNCTION
// =====================
JSiter.expandString =
   function(str){
      return $.ajax({
         url: "?",
         type: "POST",
         async: false,
         data:"jstr:bcpreview="+str
      }).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;
   }

// getBC 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.updateResource =
   function(rid, resname){
      // Recupero dal server del FORM di edit della risorsa
      var text = JSiter.coder('edit-resource', 'res_name='+resname+'&res_inst_id='+rid);

      // Apertura del POP-UP
      $('#jsiter_msg_text').html(text);
      $('#jsiter_msg_outer').jqmShow();

      // 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('Submitting...');
         },
         success: function(data) {
            $('#resource_upload_form_status').append(data.result);

            // Esecuzione dello script di callback (implementato nel FORM di edit della risorsa)
            resourceUploadCallback(data); 
         }
      });   
   }

// 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);
   }

// Dynacode editing FUNCTIONs
// ==========================
JSiter.setEditor =
   function(id, bcid, level, style, obj) {
      eval("window.jsiter_bc_"+id+" = new JSiter_dyna_editor('"+id+"','"+obj.bcid+"',"+level+");");
      eval("jsiter_bc_"+id+".edit('"+style+"')");
   }

JSiter.getEditor =
   function(id) {
      alert("window.jsiter_bc_"+id+".docId");
      alert(eval("window.jsiter_bc_"+id+".docId"));
      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('<h1>'+title+'</h1>');
      $("#backgroundPopup").css({"opacity": "0.7"});
      $("#backgroundPopup").fadeIn("slow");
      $("#popupMessage").fadeIn("slow");
      this.popupStatus = 1;
      this.centerPopup();
   }
}

JSiter.disablePopup =
   function(){
      //disables popup only if it is enabled
      if(this.popupStatus==1){
      $("#backgroundPopup").fadeOut("slow");
      $("#popupMessage").fadeOut("slow");
      this.popupStatus = 0;
   }
}

JSiter.centerPopup = 
   function(){
      var windowWidth = document.documentElement.clientWidth;
      var windowHeight = document.documentElement.clientHeight;
      var popupHeight = $("#popupMessage").height();
      var popupWidth = $("#popupMessage").width();

      $("#popupMessage").css({
         "position": "absolute",
         "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');
   }


//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,nome_select){  
      $.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='"+nome_select+"' id='"+nome_select+"' onchange=\"JSiter.writeUser(this,'"+nome_select+"')\">";
               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").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);
   }


// ================================
// 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");
            
            if(value == "0")
               $("tr#list_row_"+resource_id).attr("class", $("tr#list_row_"+resource_id).attr("class") + " row_not_published");
            else
               $("tr#list_row_"+resource_id).attr("class", $("tr#list_row_"+resource_id).attr("class").replace(" row_not_published", ""));            
         }
         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!");
         }
      });
}
