(function($) {
    $.fn.extend({
        preloadit : function(options) {
            var defaults = {
                onComplete: false,  
                onUpdate: false
            };
            
            var opts = $.extend(defaults, options);         
            
            return this.each(function(i) {
                var $images = $("img", $(this)),
                    cache = [],
                    loadedImages = [];
                $images.each(function(i) {
                    var $t = $(this);
                    var cacheImage = document.createElement('img');                 
                    
                    cache.push(cacheImage);                 
                    $(cacheImage).bind('load', function(e) {                        
                        
                        loadedImages.push(e.target);
                        $(this).unbind('load');
                        
                        //run the update function
                        if(opts.onUpdate){
                            var data = {
                                loaded:loadedImages.length,
                                total:$images.length
                            };
                            opts.onUpdate(data);    
                        }
                        
                        //run the oncomplete images function well all images loaded
                        if (loadedImages.length == $images.length) {

                            if(opts.onComplete){                        
                                opts.onComplete();
                            }
                        }
                    });
                    cacheImage.src = $t.attr('src');
                });     
            });
        }
    });
})(jQuery);
