/**
 * jQuery.scroll.loader
 * Dual licensed under MIT and GPL.
 * Date: 10/21/2009
 *
 * @description Auto load content when the user has scrolled towards the bottom
 * @author Jim Yi
 * @version 0.1
 *
 * @id jQuery.fn.scrollLoader
 * @param {Object} settings Hash of settings, loadContent (function) is required.
 * @return {jQuery} Returns the same jQuery object for chaining.
 *
 */
(function($){
	$.fn.scrollLoader = function(options) {

		var defaults = {
			ratio: .05, // how close to the scrollbar is to the bottom before triggering a load
			loadContent: function() {} // function to call when the scrollbar has reached the threshold
		};

		var options = $.extend(defaults, options);

		return this.each(function() {
			var obj = this;
			var enabled = true;

			/* bind some custom events */
			$(obj).bind("enableLoad", function() {
				enabled = true;
			});
			$(obj).bind("disableLoad", function() {
				enabled = false;
			});
			$(obj).bind("manualLoad", function() {
				options.loadContent.call();
			});

			$(obj).bind("scroll", function() {
				if (enabled) {
					var scrollHeight, scrollPosition;
					if (obj == window) {
						scrollHeight = $(document).height();
					}
					else {
						scrollHeight = $(obj)[0].scrollHeight;
					}
					scrollPosition = $(obj).height() + $(obj).scrollTop();
					if ( (scrollHeight - scrollPosition) / scrollHeight <= options.ratio) {
						options.loadContent.call();
					}
				}
			});

			return false;
		});
	};
})(jQuery);
