﻿(function ($) {
	$.fn.fixthead = function (options) {
		var defaults = {};
		if (!options) options = {};
		options = $.extend({}, defaults, options);

		return this.each(function () {
			// Only support IE 8+
			var ua = window.navigator.userAgent;
			if (ua.indexOf("MSIE") != -1) {
				if (parseFloat(ua.split("MSIE")[1]) < 8) return;
			}

			var $table = $(this);
			var $tbody = $(this).children("tbody");
			var $thead = $(this).children("thead");

			if (!$thead.length) {
				// no thead element
				return;
			}

			var $w = $(window);
			var $ths = $thead.first("tr").find("th, td");
			var $placeholder = $("<tr><td colspan='" + $ths.length + "'></td></tr>");

			// Find background color for the thead
			var trans = ["transparent", "rgba(0, 0, 0, 0)"];
			if ($.inArray($thead.css("background-color"), trans) > -1) {
				var $parent = $thead;
				var backgroundColor;

				while ($parent.length) {
					backgroundColor = $parent.css("background-color");
					if ($parent[0] == document.body || $.inArray(backgroundColor, trans) == -1) break;
					$parent = $parent.parent();
				}
				$thead.css("background-color", backgroundColor);
			}

			var original = {
				style: $thead.attr("style")
				//spacing: $table.css("border-spacing")
			};

			function revert() {
				$thead.attr("style", original.style || "");

				$ths.each(function () {
					var $th = $(this);
					var w = $th.data("original-style");
					if (w != undefined) $th.attr("style", w);
				});

				// OMG border spacing in chrome multiplies
				// http://code.google.com/p/chromium/issues/detail?id=29502
				$table.css("border-spacing", "0");
			}

			function fix() {
				var scroll = $w.scrollTop();
				var tableTop = $table.offset().top;
				var diff = scroll - tableTop;
				var thHeight = $thead.height();

				if (diff > 0) {
					if (!$placeholder.parent().length) {
						$placeholder.css("height", thHeight + "px");
						$tbody.prepend($placeholder);
					}

					$ths.each(function () {
						var $th = $(this);
						$th.data("original-style", $th.attr("style"));
						$th.css("width", $th.width() + "px");
					});

					var tableBottom = tableTop + $table.height();
					if (scroll + thHeight - tableBottom > 0) {
						$thead.css({
							position: "absolute",
							top: tableBottom - thHeight + "px"
						});
					} else {
						$thead.css({
							position: "fixed",
							top: "0px"
						});
					}
				} else {
					if ($placeholder.parent().length) {
						$placeholder.remove();
						revert();
					}
				}
			}

			$w.scroll(function () {
				fix();
			});

			$w.resize(function () {
				revert();
				fix();
			});
		});
	};
})(jQuery);
