/*
  Malgrado il nome, sembra fare delle cose tipiche di xeditor, sia in edit che non.
*/

if (Object.isUndefined(WindowOpener)) { var WindowOpener = { } }
WindowOpener = Class.create({
  initialize: function() {
    this.options = Object.extend({
      name: null,
      type: 'ajax',
      url: null,
      title: null,
      class_name: 'mac_os_x',
      width: 420,
      height: 220,
      parameters: {}
    }, arguments[0] || { });
    
    this.pageSize = WindowUtilities.getPageSize(document.body);
    this.windowScroll = WindowUtilities.getWindowScroll(document.body);
    if ($(this.options.name))
      return false
    
    eval("this.open" + this.options.type.capitalize() + "Window()");
    this.setCookie();
    this.setPosition();
    document.onkeydown = this.keyboardAction;
  },
  openIframeWindow: function() {
    win = new Window(this.options.name, {
      width:  this.options.width,
      height: this.options.height,
      title:  this.options.title,
      className: this.options.class_name,
      showEffectOptions: { duration:0.2 },
      hideEffectOptions: { duration:0.1 },
      zIndex: Windows.maxZIndex + 3,
      destroyOnClose: true,
      url: this.options.url + "?" + $H(this.options.parameters).toQueryString()
    })
    win.show();
    win.setDestroyOnClose();
    win.toFront();
  },
  openAjaxWindow: function() {
    win = new Window(this.options.name, {
      width:  this.options.width,
      height: this.options.height,
      title:  this.options.title,
      parameters: this.options.parameters,
      className: this.options.class_name,
      showEffectOptions: { duration:0.2 },
      hideEffectOptions: { duration:0.1 },
      zIndex: Windows.maxZIndex + 3,
      destroyOnClose: true
    })
    win.setAjaxContent(this.options.url, {
      method: 'post',
      asynchronous:true,
      parameters: this.options.parameters,
      evalScripts:true
    }, false, false)
    win.setDestroyOnClose();
    win.toFront();
  },
  setPosition: function() {
    win.setLocation(this.windowScroll.top, ((this.pageSize.windowWidth / 2) - (win.width / 2)));
  },
  setCookie: function() {
    date = new Date();
    date.setMonth(date.getMonth() + 3);
    win.setCookie(this.options.name, date);
  },
  keyboardAction: function(e) {
    if (e == null) { // ie
      keycode = event.keyCode; // TODO!!! Ma che e' event????
      escapeKey = 27;
    } else { // mozilla
      keycode = e.keyCode;
      escapeKey = e.DOM_VK_ESCAPE;
    }
    key = String.fromCharCode(keycode).toLowerCase();
    if (keycode == escapeKey)
      Windows.closeAll();
  }
})

/*
[{:resource_model_5821=>'231', :resource_5821=>''}, {:resource_model_2311=>'231', :resource_2311=>''}, {}]
[{:resource_model_5821=>'231', :resource_5821=>''}, {:resource_model_2311=>'231', :resource_2311=>'88031'}, {}]
*/

function setViewParamaters() {

  var params_value = $F('widget_parameters');

  $$('input.textfield').each(function(el) {
    var param_to_update = el.id.gsub(/field_/,'');
    var value = $F(param_to_update);
    var re = new RegExp(param_to_update + "=>'[^']*'", 'g');
    params_value = params_value.replace(re, param_to_update + "=>'" + value + "'");
  })
  $('widget_parameters').value = params_value;
}

// Aggiorna il campo hidden che contiene i parametri del widget per linkare una vista parametrica
function update_widget_params(dom_elem, param_to_update, value) {
  var params_value = $F(dom_elem);
  var re = new RegExp(param_to_update + "=>'[^']*'", 'g');
  $(dom_elem).value = params_value.replace(re, param_to_update + "=>'" + value + "'");
}

function paramsToQueryString(viewId, params, input) {
  var url = '/' + current_project_name + '/xform/parameters_to_querystring/' + viewId + '?input=' + input + '&parameters=' + escape(params)
  new Ajax.Request(url, {
    asynchronous:true, evalScripts:true,
    onLoading:function(request) { Element.show('loading') },
    onSuccess:function(request) { Element.hide('loading') }
  })
}

function show_search_box(treeId) {
  if ($(treeId + 'search_form_table')) {
    clear_tooltip();
    $(treeId + 'search_form_table').style.display = 'block';
    $(treeId + 'search_term').focus();
  }
  return false;
}

function initializeSearchBox(resources, treeId) {
  //alert(resources);
  var search_box_elem = new SearchBox('proviamo', {
    container: treeId + 'field_content',
    resources: resources,
    hiddenFieldID: treeID + 'search_term',
    hiddenFieldName: treeID + 'search_term',
    fieldClass: 'tf-search-above-left-tree'
  })
}

// Questa funzione aggiunge il supporto multilingua alle xform.
// * div => name del div che deve essere sostituito dalla form
// * action => action del controller translation che si intende usare
// * lang_name => lingua scelta
// * object_id => ogetto su cui lavora la form
// * partial => eventuale partial usato per renderare la form
function set_language_on_xform(div, action, lang_name, object, xform, partial, redirect_url) {

  for (xx = 0; xx < div.length; xx++) {
    if ($(div[xx])) {
      toUpdate = div[xx] // trovato!
      break
    }
  }

  var content_ids = ''
  // se viene passata la xform non sono nel caso xform_defalt quindi prelevo
  // la lista degli id delle risorse.
  if (xform != 0) {
    form = document.getElementById('xform');
    finputs = form.getElementsByTagName('input');
    finputs_ary = $A(finputs);
    id_regex = new RegExp('content_\\d+_id', "i");
    name_regex = new RegExp("content\\[\\d+\\]\\[name\\]", "i");
    id_inputs = finputs_ary.select(function(input) { return id_regex.test(input['id']); });
    name_inputs = finputs_ary.select(function(input) { return name_regex.test(input['id']); });
    contents = id_inputs.pluck('value');
    // posso tradurre solo se sono state selezionate tutte le risorse della xform, quindi controllo che
    // gli input content_id (presenti solo se la risorse viene selezionata) siano in numero uguali agli
    // input content_name (presenti sempre).
    //alert(contents.inspect());
    //alert(name_inputs.inspect());
    if (contents.size() == 0 || (contents.size() != name_inputs.size())) {
      alert('Sorry! You can translate only resources that already exist!');
      return;
    }
    content_ids = contents.join(',');
  }
  var url = '/' + current_project_name + '/translation/' + action + '/' + object + '?lang=' + lang_name + '&partial=' + partial + '&xform=' + xform + '&contents=' + content_ids + '&redirect_url=' + redirect_url
  new Ajax.Updater(toUpdate, url, {
    asynchronous:true,
    evalScripts:true
  });
}

// Per tradurre i field semplici
function get_translation_input(div, lang, field, klass) {
  var url = '/' + current_project_name + '/translation/get_translation_input/' + field['id'] + '?class=' + klass + '&lang=' + lang
  new Ajax.Updater(div, url, {
    asynchronous: true,
    evalScripts: true
  });
}

// per tradurre le cose tipo pagination
function get_translation_inputs(div, inputs, lang, field, klass) {
  var url = '/' + current_project_name + '/translation/get_translation_inputs/' + field['id'] + '?class=' + klass + '&lang=' + lang + '&inputs=' + inputs.join(',')
  new Ajax.Updater(div, url, {
    asynchronous:true,
    evalScripts:true
  });
}

// Per tradurre le cose tipo le labels
function get_translation_input_array(div, lang, field, klass) {
  var url = '/' + current_project_name + '/translation/get_translation_input_array/' + field['id'] + '?class=' + klass + '&lang=' + lang;
  new Ajax.Updater(div, url, {
    asynchronous: true,
    evalScripts: true
  });
}


function setTab(wId, vId, wTid, domElem, tab, viewParams) {
  var url = '/' + current_project_name + '/xeditor/load_selection/' + vId
  new Ajax.Updater(domElem, url, {
    asynchronous:true,
    evalScripts:true,
    parameters: { view_params: viewParams, witems: wId },
    onLoading:function(request) {
      $$('#' + $(tab).parentNode.parentNode.id + ' div.active_tab').collect(function(el) { el.className = 'tab' })
      $(tab).className = 'active_tab';
      $('tab_loading_' + wTid).show()
    },
    onSuccess:function(request) {
      $('tab_loading_' + wTid).hide()
    }
  })
}

// Aggiorna il domElem postando form per widget wId su view vId
// E' una parente stretta di setTab.
// Anzi forse la seconda potrebbe essere riscritta in termini di questa?
// ... Spostata qui perchè deve essere visibile anche senza autenticazione
function searchOnPage(wId, vId, domElem, form) {
  
  //console.debug("serializzo form: " + form);
  form_ser = $(form).serialize(true)
  //console.debug("form_ser:  %o", form_ser);
  view_params_hash = $H(form_ser);
  //console.debug("vph: %o", view_params_hash);
  view_params_json = view_params_hash.toJSON();
  witems = [wId];
  witems_json = witems.toJSON();
  // console.debug("view_params: " + view_params_json);
  // console.debug("witems: " + witems_json);
  url = '/' + current_project_name + '/xeditor/load_selection/' + vId;
  // console.debug("all'url: " + url);
  
  new Ajax.Updater(domElem, url, {
    asynchronous:true,
    evalScripts:true,
    parameters: {
      view_params: view_params_json,
      witems: witems_json
    },
    onLoading:function(request) {
        $(form + '_loader').toggle();
    },
    onSuccess:function(request) { 
        $(form + '_loader').toggle();
    }
  })
}
// Una brutta funzione per verificare se il plugin flash è installato
// Restituisce un valore booleano
// Testato su IE7, Safari 4, Mozilla 2, Mozilla 3
function detectFlashPlugin() {
  try {
      
      var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false ;
      var axo;
      var e;
      
      if (isIE)
      {
          try {
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            // alert('Flash su IE');
            return true;
          } catch (e) {
            // alert('Flash non presente su IE');
            return false;
          }
      } else {
          try {
            if (navigator.plugins["Shockwave Flash"])
            {
                // alert('Flash su Browser diverso da IE');
                return true;
            } else {
                // alert('Flash non presente su non IE');
                return false;
            }
          } catch (e) {
            return false;
          }
      }
  } catch (e) {
     return false;
  }    
}
