var application =
{
  imageData: null,
  editOffs: null,

  renderEmail: function(a)
  {
    a = $(a);
    var m = '';
    for (var i = 1; i < application.renderEmail.arguments.length; ++i) {
      m += String.fromCharCode(application.renderEmail.arguments[i]);
    }
    a.href = 'mailto:' + m;
  },

  unameFocus: function(i)
  {
    i.style.color = '#000';
    if (i.value == 'Benutzername') {
      i.value = '';
    }
  },
  unameBlur: function(i)
  {
    i.style.color = '#888';
    if (i.value == '') {
      i.value = 'Benutzername'
    };
  },
  pwFocus: function(iTxt, iPw)
  {
    iTxt.hide();
    iPw.show();
    iPw.focus();
    iPw.style.color = '#000';
    if (iTxt.value == 'Passwort') {
      iTxt.value = '';
      iPw.value = '';
    };
  },
  pwFocusPw: function(iPw)
  {
    iPw.style.color = '#000';
  },
  pwBlur: function(iPw, iTxt)
  {
    iPw.style.color = '#888';
    iTxt.style.color = '#888';
    if (iPw.value == '') {
      iPw.value = 'Passwort';
      iTxt.value = 'Passwort';
      iTxt.show();
      iPw.hide();
    }
    else {
      iTxt.value = iPw.value;
    }
  },

  pictureDiag:
  {
    previewElem: null,
    idElem: null,
    numCols: null,
    numRows: null,
    thumbWidth: null,
    thumbHeight: null,
    deselectImageId: null,

    // Closes the picture layer
    cancel: function ()
    {
      var layer = $('pictureDlgLayer');
      layer.hide();

      return false;
    },

    paginate: function (pageNr)
    {
      var urlParams = '?page='+pageNr+
                      '&w='+this.thumbWidth+
                      '&h='+this.thumbHeight+
                      '&cols='+this.numCols+
                      '&rows='+this.numRows+
                      '&deselect='+this.deselectImageId;

      new Ajax.Request('/picdiag' + urlParams, {
        method: 'get',
        onSuccess: function (transport) {
          var layer    = $('pictureDlgLayer');
          layer.update(transport.responseText);
          layer.show();
        }
      });

      return false;
    },

    // Shows the picture layer
    show: function (prevElem, idElem, numCols, numRows, thumbWidth, thumbHeight, deselectImageId, pageNr, dir)
    {
      this.previewElem = prevElem;
      this.idElem      = idElem;

      if (typeof(numCols) == 'undefined')
      {
        numCols = 3;
      }

      this.numCols = numCols;

      if (typeof(numRows) == 'undefined')
      {
        numRows = 3;
      }

      this.numRows = numRows;

      if (typeof(thumbWidth) == 'undefined')
      {
        thumbWidth = 100;
      }

      this.thumbWidth = thumbWidth;

      if (typeof(thumbHeight) == 'undefined')
      {
        thumbHeight = 100;
      }

      this.thumbHeight = thumbHeight;

      if (typeof(deselectImageId) == 'undefined')
      {
        deselectImageId = '';
      }

      this.deselectImageId = deselectImageId;

      if (typeof(pageNr) == 'undefined')
      {
        pageNr = 0;
      }

      if (typeof(dir) == 'undefined')
      {
        dir = 'up';
      }

      var prevElem = $(prevElem);
      var layer    = $('pictureDlgLayer');

      if (prevElem)
      {
        var pos      = prevElem.cumulativeOffset();
        var dim      = prevElem.getDimensions();
        var left     = pos[0] + dim.width + 10;
        var top      = pos[1];

        layer.style.left = left + 'px';
        layer.style.top  = top + 'px';
      }

      this.paginate(0);

      return false;
    },

    // Returns the selected image ID and preview to the caller
    feedback: function (selectedId, selectedPicPath)
    {
      var idElem      = $(this.idElem);
      var previewElem = $(this.previewElem);

      if (idElem)
      {
        idElem.value = selectedId;
      }
      if (previewElem)
      {
        previewElem.src = selectedPicPath;
      }

      this.cancel();

      return false;
    }
  },

  modules:
  {
    teaser:
    {
      counts: {},
      offsets: {},
      timeouts: {},
      delays: {},

      setup: function (teaserId, count, delay)
      {
        var app = application.modules.teaser;

        app.counts['teaser' + teaserId] = count;
        app.offsets['teaser' + teaserId] = 1;
        app.delays['teaser' + teaserId] = delay;

        app.timeouts['teaser' + teaserId] =
          window.setInterval('application.modules.teaser.forward(\''+teaserId+'\');', 1000 * delay);
      },

      startstop: function (teaserId)
      {
        var app = application.modules.teaser
        if (app.timeouts['teaser' + teaserId])
        {
          window.clearTimeout(app.timeouts['teaser' + teaserId]);
          app.timeouts['teaser' + teaserId] = null;
        }
        else {
          var delay = app.delays['teaser' + teaserId];
          app.timeouts['teaser' + teaserId] =
            window.setInterval('application.modules.teaser.forward(\''+teaserId+'\');', 1000 * delay);

        }

        return false;
      },

      forward: function (teaserId)
      {
        var app = application.modules.teaser;

        // Cannot paginate this one.
        if (app.counts['teaser' + teaserId] < 2)
        {
          return;
        }

        if (app.counts['teaser' + teaserId] == app.offsets['teaser' + teaserId])
        {
          app.offsets['teaser' + teaserId] = 1;
        }
        else
        {
          app.offsets['teaser' + teaserId] = app.offsets['teaser' + teaserId] + 1;
        }

        return app.paginate(teaserId);
      },

      backward: function (teaserId)
      {

        var app = application.modules.teaser;

        // Cannot paginate this one.
        if (app.counts['teaser' + teaserId] < 2)
        {
          return;
        }
        if (1 == app.offsets['teaser' + teaserId])
        {
          app.offsets['teaser' + teaserId] = app.counts['teaser' + teaserId];
        }
        else
        {
          app.offsets['teaser' + teaserId] = app.offsets['teaser' + teaserId] -1;
        }

        return this.paginate(teaserId);
      },

      paginate: function (teaserId)
      {
        var app = application.modules.teaser;

        var pages = $$('DIV[id^=teaserpage-' + teaserId + ']');

        var curActive = null;

        if (pages)
        {
          pages.each(function (z) {
            if (z.visible())
            {
              curActive = z;
            }
          });
        }

        var id = 'teaserpage-' + teaserId + '_' + app.offsets['teaser' + teaserId];
        var obj = $(id);


        if (obj)
        {
          Effect.Fade(curActive,
              {duration:0.5, afterFinish: function() {
                  Effect.Appear(id, {duration: 0.5})
              }}
          );
        }

        var display = $('teaseroffs-' + teaserId);

        if (display)
        {
          display.innerHTML = app.offsets['teaser' + teaserId] + ' / ' + app.counts['teaser' + teaserId];
        }

        return false;
      }
    },

    reference:
    {
      editOffs: null,
      getActiveSlotImageId: function()
      {
        var input = $('id_file_' + this.editOffs);
        if (input)
        {
          return input.value;
        }
      },
      setActiveSlotImage: function(id)
      {
        var preview = $('preview_image_' + this.editOffs);
        var img     = $('refimg-' + id);
        var input   = $('id_file_' + this.editOffs);

        if (preview && img)
        {
          preview.src = img.src;
        }

        if (input)
        {
          input.value = id;
        }

        var handles = $$('DIV#imagelist A');
        var handle  = $('ref-' + id);

        if (handles)
        {
          handles.each(function (z){ z.removeClassName('active'); });
        }
        if (handle)
        {
          handle.addClassName('active');
        }

        return false;
      },
      getFilePathFromImageId: function(id)
      {
        var img = $('refimg-' + id);
        if (img)
        {
          return img.src;
        }
      },
      unfocusSlot: function(offs)
      {
        var handle = $('selector_' + offs);
        if (handle)
        {
          handle.removeClassName('active');
        }
      },
      focusSlot: function(offs)
      {
        var handle = $('selector_' + offs);
        if (handle)
        {
          handle.addClassName('active');
        }
      },
      switchImageBrowser: function(newEditOffs)
      {
        this.unfocusSlot(this.editOffs);
        this.focusSlot(newEditOffs)
        this.editOffs = newEditOffs;

        var activeImage = this.getActiveSlotImageId();
        var tmp         = 'ref-' + activeImage;
        var handle      = $(tmp);
        var handles     = $$('DIV#imagelist A');
        if (handles)
        {
          handles.each (function (h) {h.removeClassName('active'); });
        }
        if (handle)
        {
          handle.addClassName('active');
        }
        return false;
      }
    }
  },

  getNewCaptcha: function(img, input)
  {
    new Ajax.Request('/ajax/captcha', {
      method: 'get',
      onSuccess: function(t) {
        var r = t.responseText.evalJSON();
        if (r.captcha) {
          img.src = '/img/captcha/' + r.captcha + '.png';
          input.value = r.captcha;
        }
      }
    });
    return false;
  },

  attachPanelTo: function(modid, slot)
  {
    var body   = $$('body')[0];
    var module = $('module-' + modid);
    var panel  = $('editorFrame');
    var tools  = $('tools-' + modid);

    $('dummy').appendChild(panel);

    var sidebarLeft = body.hasClassName('left');

    // Size and offset of the module itself
    var msize = module.getDimensions();
    var moffs = module.cumulativeOffset();

    // Size and offset of tools panel above the module
    var tsize = tools.getDimensions();
    var toffs = tools.cumulativeOffset();

    var psize = panel.getDimensions();

    if (slot == 'content') {
      var left = moffs.left;
      var top  = moffs.top + msize.height + 10;
      panel.setStyle({'left':left+'px','top':top+'px'});
    }
    else if (slot == 'sidebar' && sidebarLeft) {
      var left = toffs.left + tsize.width + 10;
      var top = toffs.top;
      panel.setStyle({'left':left+'px','top':top+'px'});
    }
    else if (slot == 'sidebar' && !sidebarLeft) {
      var left = toffs.left - (psize.width + 10);
      var top  = toffs.top;
      panel.setStyle({'left':left+'px','top':top+'px'});
    }

    panel.scrollTo();
  },

  // Assigns an image
  assignImage: function (imageid)
  {
    var previewImg = $('img-'+this.editOffs);

    var selImgObj  = $('refimg-'+imageid);
    var selImg     = $('ref-'+imageid);

    // Unset the highlight in the upper box
    var images      = $$('DIV#imagelist A');
    if (images)
    {
      images.each(function (x) { x.removeClassName('active'); });
    }

    // Move selection border to clicked image
    if (selImg)
    {
      selImg.addClassName('active');
    }

    // Update the preview object
    if (previewImg && selImgObj)
    {
      // Switch preview image
      previewImg.src = selImgObj.src

      if (imageid != 'none')
      {
        var fnameParts = selImgObj.src.split('/');
        var fname      = fnameParts[fnameParts.length - 1];
      }
      else
      {
        var fname      = 'none';
      }
      // Update the data record
      this.imageData[this.editOffs].id = imageid;
      this.imageData[this.editOffs].path = fname;

      // Update the hidden input
      var filenameInput = $('filename'+this.editOffs);
      if (filenameInput)
      {
        filenameInput.value = fname;
      }
    }

    return false;
  },

  // Starts editing of the image with the id 'id'
  startEditing: function (id)
  {
    var preview  = $('imgsel-'+id);
    var previous = $('imgsel-'+this.editOffs);

    if (previous)
    {
      previous.removeClassName('active');
    }
    if (preview)
    {
      preview.addClassName('active');
    }

    this.editOffs = id;

    // Restore the selection in the image list for this entry
    var restoreId   = this.imageData[this.editOffs].id;

    var images      = $$('DIV#imagelist A');
    var imageListObj = $('ref-'+restoreId)

    if (images)
    {
      images.each(function (x) { x.removeClassName('active'); });
    }

    if (imageListObj)
    {
      imageListObj.addClassName('active');
    }

    return false;
  },

  selectImage: function (imageid, filename, inputType, prefix)
  {
    if (!prefix) {
      prefix = 'image';
    }
    var imageIdInput = (inputType) ? $(inputType) : $('file_id');

    if (imageIdInput) {
      var oldId        = imageIdInput.value;

      var oldAnchor    = $(prefix + '-' + oldId);
      var curAnchor    = $(prefix + '-' + imageid);

      var selectedLbl  = $('filename');

      if (oldAnchor) {
        oldAnchor.removeClassName('active');
        oldAnchor.blur();
      }
      if (curAnchor) {
        curAnchor.addClassName('active');
        curAnchor.blur();
      }

      imageIdInput.value = imageid;

      if (selectedLbl) {
        selectedLbl.innerHTML = filename;
      }
    }

    return false;
  },

  lockLayout: function ()
  {
    var sidebar = $('sideBar');
    var content = $('content');

    if (sidebar) {
      var sdim = sidebar.getDimensions();
    }
    if (content) {
      var cdim = content.getDimensions();
    }
    if (cdim && sdim) {
      var max = (cdim.height > sdim.height) ? cdim.height : sdim.height;
      content.setStyle({'height':max+'px'});
      sidebar.setStyle({'height':max+'px'});
    }
  },

  toggleDisplay: function (a, node, parent)
  {
    a = $(a);
    a.blur();
    node = $(node);
    parent = $(parent);

    if (node.visible()) {
      node.hide();
    }
    else {
      node.show();
      parent.scrollIntoView();
    }

    return false;
  }

}