/*
jQuery Image Lazy-Loader
Cory O'Brien particle-liberation.org 
*/

;(function($){
    $.fn.imageloader = function(options){

        var settings = {
            container: $(window),
            imageClass: 'unloaded',
            urlAttribute: 'data-src',
            threshold: 200,
            delay: 50,
            speed: 300,
            debug: false
        },
        o = $.extend(settings, options);

        var images = [],
            loadEvent = 'loadimage',
            timer;

        var debug = function(msg){
            if (o.debug){ console.log(msg); }
        }

        o.container.bind('scroll resize', function(e){
            if (timer){
                clearTimeout(timer);
            }
            timer = setTimeout(function(){
                var top = o.container.scrollTop();
                    height = o.container.height(),
                    topLimit = (top - o.threshold);
                    bottomLimit = (top + height + o.threshold);
                    debug('Top: ' + topLimit + '\n' + 'Bottom: ' + bottomLimit);
                for (var i=0; i<images.length; i++){
                    var el = images[i];
                    if (!el.loaded){
                        if (el.offset().top <= bottomLimit && el.offset().top >= topLimit){
                            el.trigger(loadEvent);
                        }
                    }
                }
            }, o.delay);
        });

        this.each(function(){
            var el = $(this);
            el.loaded = false;
            el.bind(loadEvent, function(){
                if (el.attr(o.urlAttribute)){
                    el
                        .hide()
                        .attr('src', el.attr(o.urlAttribute))
                        .removeClass(o.imageClass)
                        .removeAttr(o.urlAttribute);
                    if ($.browser.msie){
                        el.show();
                    } else {
                        el.fadeIn(o.speed);
                    }
                    el.loaded = true;
                    debug(el.attr('src') + ' loaded');
                }
            });
            images.push(el);
        });

        o.container.trigger('resize');

        return this;
    }
})(jQuery);

