﻿﻿(function($) {

	var settings = 
	{
        images: null,
        identifier: null,
        oneachimageload: null,
        burst: 1
    };
    
	var methods = 
	{	
        init: function(options) {
			
			if (options) {
				$.extend(settings, options);
			}	

    		element = $(this);
    		element.data(options);
		},
		
        loadImages : function (i, burst)
            {
				element = $(this);
				options = element.data();
            	
            	for (index = i; index < Math.min(i + burst, options.images.length); index++)
            	{	
					$('<img id="img_' + index + '"/>').load(
						function() {
							if (options.oneachimageload)
							{	
								id = $(this).attr('id');
								id = id.substring(4, id.length);
								if (!settings.oneachimageload($(this), parseInt(id) , options.identifier))
								{
									// stop on demand
									return;
								}	
							}	
						}
	    			).attr('src', options.images[index]);
            	}
            }
	    }
	
		$.fn.smartpreload = 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 
		    {
		    	throw new Exception( 'Method ' +  method + ' does not exist on jQuery.smartpreload' );
		    }    
		};
})(jQuery);
