﻿function RotateControl(list){
	var current = -1;
	var self = this;

	this.show = function(index){
		if (list.length > 0 && index < list.length){
			list.hide();
			$(list[index]).show();
		}
	};
	
	this.next = function(){
		if (list.length > 0) {
			current = (current + 1) % list.length;
			self.show(current);
		}
	};
}

$.fn.outerHTML = function(s) {
	return (s) ? this.before(s).remove() : $('<div>').append(this.eq(0).clone()).html();
}

$.fn.Rotate = function(options){

	var defaults = {
		interval: 5000,
		fOut : 500,
		fIn : 500,
		container: ''
	};
	var settings = $.extend({}, defaults, options);
	var self = this;
	var rCtrl = new RotateControl(this);
	var timer;
	
	var container = $(settings.container);
	if (container.length === 0) {
		container = this.parent();
		this.hide();
	}
	else {
		rCtrl.show = function(index){
			if (self.length > 0 && index < self.length){
				var tmp = $(self[index]).outerHTML();
				container.html(tmp);
			}
		};
	}
	
	//當滑鼠滑入區塊停止自動播放
	container.hover(function(){
		clearTimeout(timer);
		}, function(){
			timer = setTimeout(autoShow, settings.interval);
	});

	function autoShow(){
		//container.fadeOut(settings.fOut, function(){
			rCtrl.next();
		//}).fadeIn(settings.fIn);
		
		timer = setTimeout(autoShow, settings.interval);
	}

	autoShow();
}
