(function($, GLOBAL) {
  var floating_thead_class = 'floating-thead';

  var border_box = 'border-box';
  var box_sizing = 'box-sizing';
  var isBorderBox = function(elem) {
      return (elem.css(box_sizing) == border_box
          || elem.css('-moz-' + box_sizing) == border_box
          || elem.css('-webkit-' + box_sizing) == border_box);
  };

  function inject_css(selector, obj, media) {
    if ( ! media) { media = 'screen'; }
    if ( ! selectors[selector]) { selectors[selector] = {}; }

    $.each(obj, function(k, v){
      selectors[selector][k] = v;
    });

    var text = "@media "+media+" {";
    $.each(selectors, function(s, obj) {
      var css = [];
      $.each(obj, function(k, v) {
        css.push( k+":"+v );
      });
      text += s+"{"+css.join(";")+"}";
    });
    text += "}";

    if ( ! inject_css.style) {
      inject_css.style = $("<style />").appendTo('body');
    }
    inject_css.style.text(text);
  };

  $.fn.fakeHead = function(klass, media) {
    var top_selector = this.selector;
    return this.each(function() {
      var scroller = $(this);

      if (scroller.find('.'+floating_thead_class).length > 0) {
        scroller.find('.'+floating_thead_class).trigger('resize');
        return false;
      }

      var original_thead = $('thead', scroller);
      var thead_html = original_thead.html();
      var clone = $('<table><thead>'+thead_html+'</thead></table>');

      clone.prependTo(scroller);
      clone.css({
        position: 'relative',
        'float': 'left',
        'z-index': 1
      });
      clone.addClass(floating_thead_class);

      if (klass) {
        clone.addClass(klass);
      }

      var height = original_thead.height();
      if (isBorderBox(original_thead)) {
        height = original_thead.outerHeight();
      }

      var css = {
        position: 'relative',
        top: height * -1 + 'px'
      };

      if (media) {
        inject_css( top_selector+" table", css, media);
      }
      else {
        $('table', scroller).css(css);
      }

      scroller.scroll(function() {
        var scrollTop = scroller.scrollTop();
        clone.css('top', scrollTop );
      });

      clone.css({ top: scroller.scrollTop() });

      scroller.on('resize', function(e) {
        e.stopPropagation();
        var cloned_th = $('th', clone);

        original_thead.find('th').each(function(i, th) {
          var $th = $(th);
          var width = $th.css('width');
          if (isBorderBox($th)) {
            width = $th.outerWidth();
          }
          $(cloned_th[i]).css('width', width);
        });
      });

      scroller.trigger('resize');
      setTimeout(function() {
        scroller.trigger('resize');
      }, 1);

      var timeout;
      $(window).on('resize', function() {
        clearTimeout(timeout);

        timeout = setTimeout(function() {
          scroller.trigger('resize');
        }, 500);
      });
    });
  };

})(jQuery, this);