if (!CFR.popup) CFR.popup = {};

CFR.popup.init = function(root) {
  $('a.popup', root).each(function(i) {

    $(this).mouseover(function(evt) {
      var anchor = this;

      this.timer = setTimeout(function() {
        var div = CFR.popup.popup(evt);

        $(div).mouseover(function() {
          if (anchor.divTimer) {
            clearTimeout(anchor.divTimer);
          }
        });

        $(div).mouseout(function() {
          anchor.divTimer = setTimeout(function() { $(div).hide(); }, 500);
        });

        evt.target.popupDiv = div;
      }, 1000)
    });

    $(this).mouseout(function(evt) {
        clearTimeout(this.timer);
        if (evt.target.popupDiv) {
          evt.target.divTimer = setTimeout(function() { evt.target.popupDiv.hide(); }, 500);
        }
    });

  });
}

CFR.popup.popup = function(evt) {
  var ajaxUrl = evt.target.getAttribute('popupUrl');
  var div = jQuery('<div class="popup"></div>');
  $(evt.target).after(div);
  jQuery.get(ajaxUrl, {}, function(data, textStatus) { div.append(data); CFR.popup.init(div); });
  return div;
}

$(document).ready(function() { CFR.popup.init($('html > body')); });
