(function($){
	var loading = false;

	var methods = {
		init: function(){
			return this.each(function(){
				var $this = $(this);
				var autoloader = $(this).children(".fwx-al");

				if(autoloader.length > 0 && !is_visible(autoloader)){
					$this.children(".toolbar").find("a").hide();
				}
			});
		},
		load: function(_arguments){
			if(loading == true) return this;
			loading = true;

			return this.each(function(){
				var $this = $(this);

				var page = parseInt($this.attr("data-page"))+1;
				var query = $this.attr("data-query");
				var data = {page: page, q: query};
				var url = typeof _arguments !== "undefined" && typeof _arguments["url"] !== "undefined" ? _arguments["url"] : $this.children(".toolbar").find(".more").attr("href");
				if(typeof url === "undefined") url = $this.children(".toolbar").find(".next").attr("href");

				$this.children(".toolbar").frameworkLoad({url: url+" .test, .toolbar, .fwx-al", data: data, success:
					function(){
						$this.attr("data-page", page);
					},
				error:
					function(){
						$this.children(".toolbar").remove();
						$this.find(".fwx-al").remove();
					},
				complete:
					function(){
						loading = false;
				}});
			});
		}
	};

	$.fn.autoload = function(method){
		if(methods[method]){
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		}else if(typeof method === "object" || !method){
			return methods.init.apply(this, arguments);
		}else{
			$.error("Method " +  method + " does not exist on jQuery.fader");
		}
	}

	$(window).scroll(function(){
		if(loading == true) return;

		$(".l-al").each(function(){
			var autoloader = $(this).children(".fwx-al");

			if(autoloader.length < 1) return;

			if(is_visible(autoloader)){
				autoloader.remove();
				$(this).autoload("load");
			}
		});
	});

	function is_visible(_element){
		var docViewTop = $(window).scrollTop();
		var docViewBottom = docViewTop+$(window).height();

		var elemTop = _element.offset().top;
		var elemBottom = elemTop+_element.height();

		if(((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop))){
			return true;
		}else{
			return false;
		}
	}
})(jQuery);
