/*
 * jQuery Thead Plugin v1.1
 * http://www.asual.com/jquery/thead/
 *
 * Copyright (c) 2009-2010 Rostislav Hristov
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Date: 2010-09-26 19:36:34 +0300 (Sun, 26 Sep 2010)
 */
(function($) {

  var _agent = navigator.userAgent,
  _w = $(window),
  _d = $(document),
  _blocks = [],
  _magicNumber = 4,
  _supported = !($.browser.msie && parseFloat(_agent.substr(_agent.indexOf('MSIE') + _magicNumber)) < 7),
  _interval = null,
  _parseInt = function(value) {
	var result = parseInt(value, 10);
	return isNaN(result) ? 0 : result;
  },
  _resize = function() {
	if (_interval === null) {
	  _interval = setInterval(function() {
		if (_interval) {
		  _interval = clearInterval(_interval);
		}
		$.sticky_block.update();
	  }, 50);
	}
  },
  _scroll = function() {
	$(_blocks).each(function() {
	  var maxOffset = parseFloat(this.origin.offset().top) /*+ parseFloat(this.origin.height()) + parseFloat(this.origin.css('padding-top'))*/,
	  offset = maxOffset - (parseFloat(_d.scrollTop()) + this.deltaTop);
	  this.obj.css({
		display: (offset >= _magicNumber) ? this.origin.css('display') : 'none'
	  });
	});
  };

  $(function() {
	if (_supported) {
	  _w
	  .resize(_resize)
	  .scroll(_scroll);
	  _d.resize(_resize);
	}
  });

  $.sticky_block = (function () {
	return {
	  update: function() {
		$(_blocks).each(function() {
		  var obj = this.obj,
		  origin = this.origin;
		  obj.css({
			display : origin.css('display'),
			left: origin.offset().left - _d.scrollLeft() + 'px',
			width: origin.width() - _parseInt(obj.css('margin-left')) - _parseInt(obj.css('margin-right'))
		  });
		  this.deltaTop = parseFloat(obj.offset().top) - parseFloat(_d.scrollTop()) - + parseFloat(obj.height()) + parseFloat(obj.css('padding-top'));
		});
		_scroll();
	  }
	};
  })();

  $.fn.sticky_block = function() {
	if (_supported) {
	  $(this).each(function() {
		var origin=$(this);
		_blocks.push({
		  tagName: this.tagName.toLowerCase(),
		  origin: origin,
		  obj: origin.clone(true)
		  .addClass('sticky')
		  .css({
			position: 'fixed',
			bottom: 0,
			display: 'none'
		  })
		  .insertAfter(origin)
		});
	  });
	}
	$.sticky_block.update();
  };

})(jQuery);
