Initializable = {
	create : function(obj) {
		return function() {
			obj.initialize();
		};
	}
};

Function.prototype.bind = function(obj) {
	var method = this;
	var temp = function() {
		return method.apply(obj, arguments);
	}
	return temp;
}

var DeferredLoader = Initializable.create( {
	initialize : function() {
		this.window = $(window);
		$(document).ready(this.onScroll.bind(this));
	},
	onScroll : function() {
		this.check(true);
	},
	onLoad : function() {
		this.check(false);
	},
	check : function(scroll) {
		if(this.items == null) {
			this.items = $(".deferred");
		}
		
		if(this.items.size() > 0) {
			var aboveFold = new Object();
			var belowFold = [];
	
			/*if (scroll) {
				this.window.unbind("scroll", this.onScroll);
			}*/
	
			$.each(this.items, function(index, element) {
				if (scroll || this.isVisible(element)) {
					aboveFold[element.id] = $(element).attr("file");
				} else {
					belowTheFold.push(element);
				}
			}.bind(this));
			
			if (belowFold.length < this.items.length) {
				this.items = belowFold;
				this.load(aboveFold);
			}
		}
	},
	load : function(map) {
		$.ajax( {
			url : '/batch/',
			data : map,
			dataType : "json",
			success : function(result) {
				for ( var word in result) {
					$("#" + word).removeClass("loading").html(result[word]);
				}
			}
		});
	},
	isVisible : function(el) {
		return this.window.height() + this.window.scrollTop() > $(el).offset().top;
	}
});

new DeferredLoader();