/**
 * jQuery.bgSwitcher v0.1.1b
 * http://rewish.org/javascript/jquery_bg_switcher
 *
 * Copyright (c) 2009 Rewish (http://rewish.org/)
 *
 * Licensed under the MIT:
 * [en] http://www.opensource.org/licenses/mit-license.php
 * [ja] http://sourceforge.jp/projects/opensource/wiki/licenses%2FMIT_license
 *
 * Date:
 * 2009-04-08
 *
 **/
(function($) {
	$.fn.bgSwitcher = function(opts, callback) {

		var opts = $.extend({
			bgImages : null,
			interval : 2000,
			loopExec : true,
			fadeOut  : false,
			fadeSpeed: 1000,
			sequence : false,
			seqFirst : 1,
			seqLast  : 5,
			startNum : 1,
			random   : false
		}, opts);

		if (opts.bgImages == null) {
			return this;
		}

		if (opts.sequence) {
			var baseName = opts.bgImages[0];
			opts.bgImages = sequence(baseName, opts.seqFirst, opts.seqLast);
		}

		preload(opts.bgImages);

		callback = callback || function(elem, bg, clone) {
			if (opts.fadeOut) {
				clone.css('background-image', elem.css('background-image')).show();
				elem.css('background-image', 'url('+ bg +')');
				clone.fadeOut(opts.fadeSpeed);
			} else {
				elem.css('background-image', 'url('+ bg +')');
			}
		};

		return this.each(function(i) {
			var elem  = $(this);
			var clone = opts.fadeOut
			          ? setCSS(elem, elem.clone()).insertAfter(elem)
			          : null;
			var len = opts.bgImages.length;
			var num = opts.startNum - 1;
			var tId = setInterval(function() {
				callback(elem, opts.bgImages[num], clone);
				if (opts.random) {
					var _num = num;
					do {
						_num = random(len);
					} while (num === _num);
					num = _num;
				} else {
					num++;
					if (len === num) {
						if (opts.loopExec) num = 0;
						else clearInterval(tId);
					}
				}
			}, opts.interval);
		});
	};

	function sequence(baseName, min, max) {
		var ret = [];
		for (i = min; i <= max; i++) {
			ret.push(baseName.replace(/\.\w+$/, i + '$&'));
		}
		return ret;
	}

	function setCSS(from, to) {
		if (isNaN(from.css('z-index'))) {
			from.css('z-index', 1);
		}
		pos = from.position();
		return to.css({
			zIndex: from.css('z-index') + 10,
			position: 'absolute',
			top: pos.top,
			left: pos.left
		});
	}

	function random(max) {
		return Math.floor(Math.random() * max);
	}

	function preload(images) {
		for (var i = 0, len = images.length; i < len; ++i) {
			var image = new Image;
			image.src = images[i];
		}
	}

})(jQuery);

