YAHOO.widget.Panel.prototype.setBodyFromUrl = function(url) {
  // Make AJAX call and fetch the body
  var self = this;
  YAHOO.plugin.Dispatcher.fetch(this.body, url, {
    onChange: function(el) {
      self.setBody(el.innerHTML);
      self.center();
      self.show();
    }
  });
};

YAHOO.widget.Panel.prototype.setBodyFromString = function(content) {
  var self = this;
  YAHOO.plugin.Dispatcher.process(this.body, content, {
    onChange: function(el) {
      self.setBody(el.innerHTML);
      self.center();
      self.show();
    }
  });
};

YAHOO.widget.Panel.prototype.closeWithCallback = function(callback) {
  this.hide();
  if (typeof(callback) == "function") {
    callback();
  }
};

YAHOO.widget.Panel.prototype.open = function(content, options) {
  options = options || {};

  if (options.cleanup) {
    ModalBox.hideEvent.subscribe(function(){
      ModalBox.setBody("");
    });
  }

  if (options.modal) {
    this.cfg.setProperty("modal", true);
  } else {
    this.cfg.setProperty("modal", false);
  }

  var htmlRegExp = /<\/?[^>]+>/gi;
  if (htmlRegExp.test(content)) { // Plain HTML given as a parameter
    this.setBodyFromString(content);
  } else { // URL given as a parameter. We'll request it via Ajax
    this.setBodyFromUrl(content);
  }

  this.setHeader("<span style='visibility: hidden;'>Qype</span>");
};

YAHOO.util.Event.onDOMReady(function() {
  // build the modal box
  var anon_div = document.createElement("div");
  anon_div.innerHTML = '<div id="QypeModalBox"><div class="hd"></div><div class="bd"></div></div>';
  var modalBoxDiv = YAHOO.util.Dom.getFirstChild(anon_div);
  YAHOO.util.Dom.get('Container').appendChild(modalBoxDiv);
  anon_div = null;
  
  QYPE.layout.ModalBox = new YAHOO.widget.Panel("QypeModalBox", {visible: false, zIndex: 999});
  QYPE.layout.ModalBox.render(document.body);
  window.ModalBox = QYPE.layout.ModalBox;
  
  // Notify the listeners about ModalBox presence
  jQuery(window).trigger("modalboxReady.qype");
  
  // register click events
  YAHOO.util.Event.on(document.body, "click", function(e) {
    var el = YAHOO.util.Event.getTarget(e);
  
    // select the link outside the clicked element if itself is not a link
    if (el.nodeName.toUpperCase() != 'A' && el.parentNode && el.parentNode.nodeName.toUpperCase() == 'A') {
      el = el.parentNode;
    }
  
    // check for the data-qype-modal attribute
    if (YAHOO.util.Dom.getAttribute(el, "data-qype-modal")) {
      var use_overlay = (YAHOO.util.Dom.getAttribute(el, "data-qype-modal") == 'overlay');
      // get link from href or data-url
      var href = el.nodeName.toUpperCase() == 'A' ? YAHOO.util.Dom.getAttribute(el, "href") : YAHOO.util.Dom.getAttribute(el, "data-url");
  
      QypeModalBox.open(href, {modal: use_overlay, header: YAHOO.util.Dom.getAttribute(el, "title")});
      YAHOO.util.Event.stopEvent(e);
    }
  });
});


