;(function($) {

$.fn.slider = function(options) {
	var urls = this;

	// init options
	options = options || {};
	var opts = $.extend({}, $.fn.slider.defaults, options);
	opts.before_each = opts.before_each ? [opts.before_each] : [];
	opts.after_each = opts.after_each ? [opts.after_each] : [];

	// preload images
	$(urls).imagepreloader({
		after_first: function() {
			next(opts);
			window.setInterval(function() {
				next(opts);
			}, opts.slide_speed);
		}
	});

	return this;
};

/**
 * Fetches the next image,
 * Tries to restart (back to first) if there is no next image.
 * NOTE: This is not 100% ideal in the case of slow loading images. :S
 */
function next(opts) {
	var $img = $.fn.imagepreloader.pool.next();
	if (!$img) {
		// try starting again...
		$img = $.fn.imagepreloader.pool.first();
	}

	if ($img) {
		transition($img, opts);
	}
}

function transition($next, opts) {
	// fire hooks
	if (opts.before_each.length)
		opts.before_each[0].apply($next, [$next, $next, opts, true]);

	// get image and append to slider
	$next.hide();
	$('#'+opts.container_id).append($next);

	// fade it in
	$next.fadeIn(opts.transition_speed, function() {
		if (opts.after_each.length)
			opts.after_each[0].apply($next, [$next, $next, opts, true]);
	});
}

// UTILS ------------------------------------------------------------------
function debug() {
	if (window.console && window.console.log) {
		console.log.apply(window.console, arguments)
	}
}

// DEFAULTS ------------------------------------------------------------------
$.fn.slider.defaults = {
	slide_speed: 5000, // amount of time slide is shown before changing
	transition_speed: 1000, // speed of the transition between slides
	before_each: null, // run before changing each image
	after_each: null, // run before changing each image
	container_id: 'slider'
};

})(jQuery);