(function($) {
  $.facebox = function(data, klass) {
    $.facebox.init();
    $.facebox.loading();
    $.isFunction(data) ? data.call() : $.facebox.reveal(data, klass);
  }

  $.facebox.settings = {
    close_image   : '/static/img/facebox/closelabel.png',
    image_types   : [ 'png', 'jpg', 'jpeg', 'gif' ],
    facebox_html  : '<div id="facebox" style="display: none;"><div class="popup"><div class="body"><div class="content"></div><a href="#" class="close"><img src="/static/img/lightbox/widget_close.png" title="close" class="close_image" /></a></div></div></div>'
  }

  $.facebox.loading = function() {
    $('#facebox .content').empty();
    $('#facebox').css({top: '10%'}).show();
    
    $(document).bind('keydown.facebox', function(e) {
      if (e.keyCode == 27) $.facebox.close();
    });
  }

  $.facebox.reveal = function(data, klass) {
    $('#focus').show().css('opacity', 0).fadeTo('slow', 0.75, function(){
        if (klass) $('#facebox .body').addClass(klass);
        $('#facebox .content').append(data);
        
        $('#facebox .body').show().css('opacity', 0).fadeTo(1500, 1);
        $('#focus,#focus *,#facebox .close').click($.facebox.close);
    });
  }

  $.facebox.close = function() {
    $(document).unbind('keydown.facebox');
    
    $('#facebox').fadeOut(function() {
        $('#focus').fadeOut('slow');
      $('#facebox .content').removeClass().addClass('content');
    });
    return false
  }

  $.fn.facebox = function() {
    $.facebox.init();

    var image_types = $.facebox.settings.image_types.join('|');
    image_types = new RegExp('\.' + image_types + '$', 'i');

    function click_handler() {
      $.facebox.loading(true);

      // support for rel="facebox[.inline_popup]" syntax, to add a class
      var klass = this.rel.match(/facebox\[\.([\w-_]+)\]/);
      if (klass) klass = klass[1];

      // div
      if (this.href.match(/#/)) {
        var url    = window.location.href.split('#')[0];
        var target = this.href.replace(url,'');
        $.facebox.reveal($(target).clone().show(), klass);

      // image
      } else if (this.href.match(image_types)) {
        var image = new Image();
        image.onload = function() {
          $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass);
        }
        image.src = this.href;

      // ajax
      } else {
        $.get(this.href, function(data) { $.facebox.reveal(data, klass) });
      }

      return false;
    }

    this.click(click_handler);
    return this;
  }

  $.facebox.init = function() {
    if ($.facebox.settings.inited) {
      return true;
    } else {
      $.facebox.settings.inited = true;
    }

    $('body').append($.facebox.settings.facebox_html);
  }

})(jQuery);