function editBlockTitle(title) {
  var input = Widget.input();
  input.__title = title;
  input.value = title.innerHTML;
  var dim = title.getCoordinates();
  input.setStyle({
    'position': 'absolute',
    'width': dim.width+'px',
    'height': dim.height+'px',
    'top': dim.top+'px',
    'left': dim.left+'px'
  });
  input.injectBefore(title);
  input.focus();
  input.__update = function() {
    var block = this;
    while (block) {
      if (block.id && block.id.match('__block_')) {
        var id = block.id.substr(8);
        this.__title.innerHTML = this.value;
        new Ajax(
          document.root+'?module=admin&base=blocks&action=ajax_quick_edit',
          {
            data: 'block[id]='+id+'&block[title]='+encodeURIComponent(this.value)+'&auth='+document.auth
          }
        ).request();
        break;
      }
      block = block.parentNode;
    }
    this.remove();
  };

  input.onblur = input.__update.bind(input);

  input.onkeydown = function(e) {
    var e = new Event(e);
    if (e.code == 13) {
      this.__update(this);
    }
  }.bind(input)

}

function signForm(f) {
  if (f.method.toLowerCase() != 'get') {
    if (!f.auth) {
      f.appendChild(
        Widget.input({'type': 'input', 'name': 'auth', 'style': {'display': 'none'}})
      );
    }
    f.auth.value = document.auth;
  }
}

formSubmit = function(form) {
  signForm(form);
  form = new Form(form);
  return form.__onSubmit();
}

function orderRequest(f) {
  f.style.opacity = 0.2;
  var parent = f;

  while (parent) {
    if (parent.className == 'm-notebook-content') {
      var nb = parent;
      while (nb && nb.className != 'm-notebook') {
        nb = nb.parentNode;
      }
      if (nb) {
        nb = nb.parent;
        new Ajax(
          f.action,
          {
            method: 'get',
            data: f.toQueryString(),
            onComplete: function(text) {
              this[0].updatePage(this[1].getAttribute('name'), text);
              this[0].selectPage(this[1].getAttribute('name'));
            }.bind([nb, parent])
          }
        ).request();
        return false;
      }
    }
    parent = parent.parentNode;
  }
}

function postExec(url, params) {
  var data = [];
  params['auth'] = document.auth;
  params['__ajax'] = 1;
  for (var i in params) {
    data.push(i+'='+encodeURIComponent(params[i]));
  }
  data = data.join('&');
  new Ajax(
    url,
    {
      'method': 'post',
      'data': data
    }
  ).rpc();
}

function exec_action(a) {
  var f = Widget.form();
  document.body.appendChild(f);
  f.setAttribute('method', 'post');
  f.setAttribute('action', a.getAttribute('href'));
  return formSubmit(f);
}

function link(a, rpc) {
  if (rpc) {
    new Ajax(
      $type(a) == 'element' ? a.getAttribute('href') : a,
      {
        'method': 'get',
        'onComplete': function(text) {
          new JsonRpc(text, this);
        }.bindAsEventListener(this)
      }
    ).request();
    return false;
  } else {
    var parent = a;
    while (parent) {
      if (parent.className == 'm-notebook-content') {
        var nb = parent;
        while (nb && nb.className != 'm-notebook') {
          nb = nb.parentNode;
        }
        if (nb) {
          nb.parent.updatePage(parent.getAttribute('name'), {'url': a.getAttribute('href') });
          nb.parent.selectPage(parent.getAttribute('name'));
          return false;
        }
        return true;
      }
      parent = parent.parentNode;
    }
  }
  return true;
}


function toggleFieldset(legend) {
  var fieldset = $(legend).findParentWithName('fieldset');
  if (fieldset) {
    fieldset.status = !fieldset.status;
    var labels = [];
    labels.extend(fieldset.getElementsByTagName('label'));
    labels.extend(fieldset.getElementsByClassName('wrapper'));
    for (var i = 0; i < labels.length; i++) {
      var label = labels[i];
      if (fieldset.status) {
        label.style.display = 'block';
      } else {
        label.style.display = 'none';
      }
    }
  }
}

function updateAjaxElement(el) {
  var inputs = [];
  var divs = [];

  inputs.extend(el.getElementsByTagName('input'));
  inputs.extend(el.getElementsByTagName('select'));
  inputs.extend(el.getElementsByTagName('textarea'));

  var save = {
    'input': [],
    'divs': []
  };

  for (var i = 0; i < inputs.length; i++) {
    var input = inputs[i];
    save['input'].push({
      'name':     input.name,
      'checked':  input.checked,
      'value':    input.value
    });
  }

  divs.extend(el.getElementsByTagName('div'));

  for (var i = 0; i < divs.length; i++) {
    var div = divs[i];
    save['divs'].push({
      'scrollTop': div.scrollTop,
      'scrollLeft': div.scrollLeft
    });
  }

  el.__save = save;

  el.setContent({
    'url': el.__url,
    'onComplete': function() {
      var inputs = [];
      var divs = [];

      inputs.extend(this.getElementsByTagName('input'));
      inputs.extend(this.getElementsByTagName('select'));
      inputs.extend(this.getElementsByTagName('textarea'));
      for (var i = 0; i < this.__save['input'].length; i++) {
        var input = this.__save['input'][i];
        for (var j = 0; j < inputs.length; j++) {
          var test = inputs[j];
          if (test.name == input.name && input.name) {
            if (test.name.match(/\[\]/)) {
              if (test.type == 'checkbox' && test.value == input.value && input.checked) {
                test.setAttribute('checked', 'checked');
              }
            } else {
              test.value = input.value;
            }
          }
        }
      }
      
      divs.extend(this.getElementsByTagName('div'));
      for (var i = 0; i < divs.length; i++) {
        var div = divs[i];

        div.scrollTop = 0;
        div.scrollLeft = 0;

        if (this.__save['divs'][i]) {
          div.scrollTop = this.__save['divs'][i]['scrollTop'];
          div.scrollLeft = this.__save['divs'][i]['scrollLeft'];
        }
      }

    }.bind(el)
  });
}

Meteora.onStart(
  function() {
    // signing all forms
    var len = document.forms.length;
    for (var i = 0; i < len; i++) {
      signForm(document.forms[i]);
    }
    if (typeof Editor != 'undefined') {
      
      document.editorPointer = new Array();
      
      // configuring editor button
      Editor.prototype.buttons.insertimage =  {
        
        tooltip: 'Insert',

        onAction: function() {

          this.setBookmark();
          
          var popup = new Dialog(
            {
              'url': document.root+'?module=tools&action=ajax_insert'
            },
            {
              'title': __('Insert content'),
              'onClose': Meteora.removeOverlay
            }
          );

          Meteora.overlay();
          popup.resizeTo(800, 500);
          popup.center();
          
          document.activeEditor = this;
          document.activePopup  = popup;
        }
      };

      Editor.prototype.buttons.smiley = {
      
        tooltip: 'Smileys',

        onAction: function() {

          this.setBookmark();

          if (!document.activePopup) {
            var popup = new Popup(
              __('Smileys &amp; formatting'),
              {
                'url': document.root+'?module=tools&action=ajax_emoticons'
              },
              {
                'onClose': function() { document.activePopup = null; }
              }
            );

            popup.resizeTo(500, 400);
            popup.center();
            
            document.activeEditor = this;
            document.activePopup  = popup;
          }

        }
      };
      
    }
  }
);
