﻿(function ($) {
	var methods = {
		init: function (options) {
			var settings = {
				childSelector: '.switchee',
				delay: 5000,
				animationDuration: 500,
				pauseOnMouseover: true
			};

			return this.each(function () {
				if (options) {
					$.extend(settings, options);
				}

				var $source = $(this), data = $source.data('switcher');

				if (!data) {
					data = {
						timer: null,
						settings: settings,
						children: $(settings.childSelector, $source)
					}
					$source.data('switcher', data);
				}

				// Hide children
				data.children.hide();

				if (settings.pauseOnMouseover) {
					data.children.mouseover(function () {
						$source.switcher('pause');
					}).mouseout(function () {
						$source.switcher('start');
					});
				}

				// Start the switcher
				$source.switcher('start');
				// Show the first item
				$source.switcher('next');
			});
		},
		next: function () {
			return this.each(function () {
				var $source = $(this), data = $source.data('switcher');
				if (data && data.children && data.children.length > 0) {
					// Calculate the next index to display
					var nextIndex = 0;
					if (data.currIndex != undefined) {
						nextIndex = data.currIndex + 1;
					}
					if (nextIndex >= data.children.length) {
						nextIndex = 0;
					}
					else if (nextIndex < 0) {
						nextIndex = 0;
					}

					// Hide the current child
					if (data.currentChild) {
						data.currentChild.fadeOut(data.settings.animationDuration);
					}

					// Show the new one
					data.currIndex = nextIndex;
					data.currentChild = $(data.children.get(nextIndex));
					data.currentChild.fadeIn(data.settings.animationDuration);
				}
			});
		},
		pause: function () {
			return this.each(function () {
				var $source = $(this), data = $source.data('switcher');
				if (data && data.timer) {
					clearInterval(data.timer);
				}
				data.timer = null;
			});
		},
		start: function () {
			return this.each(function () {
				var $source = $(this), data = $source.data('switcher');
				if (data && !data.timer) {
					data.timer = setInterval(function () { $source.switcher('next'); }, data.settings.delay);
				}
			});
		},
		destroy: function () {
			return this.each(function () {
				var $source = $(this), data = $soure.data('switcher');
				$source.removeData('switcher');
			});
		}
	};


	$.fn.switcher = 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 {
			$.error('Method ' + method + ' does not exist on jQuery.switcher');
		}
	};
})(jQuery);

(function ($) {
	$.fn.preload = function () {
		this.each(function () {
			$('<img/>')[0].src = this;
		});
	};
})(jQuery);

