/*
	Class:    	LazyLoad
	Author:   	David Walsh
	Website:    http://davidwalsh.name/js/lazyload
	Version:  	1.0.0
	Date:     	8/15/2009
	Built For:  MooTools 1.2.3
*/

var LazyLoad = new Class({
	
	Implements: [Options,Events],
	
	/* additional options */
	options: {
		range: 200,
		image: './img/blank.gif',
		resetDimensions: true,
		elements: 'img.lazyload',
		container: window
	},
	
	/* initialize */
	initialize: function(options) {
		
		/* vars */
		this.setOptions(options);
		this.container = $(this.options.container);
		this.elements = $$(this.options.elements);
		this.containerHeight = this.container.getSize().y;
		this.start = 0;

		/* find elements remember and hold on to */
		this.elements = this.elements.filter(function(el) {
			if(!el.hasClass('__ll_loaded') && el.get('rel') != '') {
				el.set('src',this.options.image);
				return true;
			}
		},this);

		var queue = [];
		
		/* listen for scroll */
		this.container.addEvent('scroll',this.action.bind(this));
	},

	/* create the action function */
	action: function() {

		var cpos = this.container.getScroll().y;
		if(cpos == 0 || cpos > this.start) {
			this.elements = this.elements.filter(function(el) {
				if ((this.container.getScroll().y + this.options.range + this.containerHeight) >= el.getPosition(this.container).y) {
					if(!el.hasClass('__ll_loaded') && el.get('rel') != '') {
						el.set('src',el.get('rel')).set('rel','').addClass('__ll_loaded');
						return false;
					}
				}
				return true;
			},this);
			this.start = cpos;
		}
		this.fireEvent('scroll');
		/* remove this event IF no elements */
		if(!this.elements.length) {
			this.container.removeEvent('scroll',this.action);
			this.fireEvent('complete');
		}
	}


});
