document.viewport.getBottom = function() {
  return this.getScrollOffsets()[1] + this.getHeight();
}

document.viewport.getRight = function() {
  return this.getScrollOffsets()[0] + this.getWidth();
}

Element.addMethods({
  moveTo: function(element, x, y) {
    element = $(element);
    var originalHeight = element.getHeight();
    var originalWidth = element.getWidth();

    // reset height, width, and position
    element.setStyle({
      "top": "0",
      "right": "0",
      "bottom": "0",
      "left": "0",
      "width": originalWidth + "px",
      "height": originalHeight + "px"
    });

    if ((x + element.getWidth()) > document.viewport.getRight()) {
      x = document.viewport.getRight() - element.getWidth();
    }
    if ((y + element.getHeight()) > document.viewport.getBottom()) {
      y = document.viewport.getBottom() - element.getHeight();
    }

    return element.setStyle({"top": y + "px", "left": x + "px"});
  },

  attachToBody: function(element) {
    $$('body').first().insert($(element).remove());
  }
});


document.observe("dom:loaded", function() {
  // Turn help links into pop-ups
  $$('a.help').each(function(link) {
    link.observe('click', function(event) {
      event.stop();
      window.open(link.readAttribute('href'),'small','toolbar=no,resizable=yes,status=yes,menu=no,scrollbars=yes,width=700,height=250');
    });
  });

  // In IE events triggered by a click on a button cancel the click event for a
  // link surrounding the button. So trap the button event and trigger the link.
  $$("input[name=cancel]").each(function(element) {
    var url      = element.up("a").readAttribute("href");
    var hostname = window.location.toString().split(url)[0];
    var target   = hostname + url;

    if (!element.hasClassName('without_confirm')) {
      element.observe("click", function(event) {
        event.stop();
        if (!event.element().hasClassName('stop-default') && confirm('Do you want to cancel?')) {
          window.location = target;
        }
      });
    }
  });
});

