/**
 * @requires jquery.color.js
 */
(function($){
$.fn.extend({
	wordCloud : function(options){
		if(null === options){
			options = {}
		}
		options = $.extend({}, $.WordCloud.defaults, options);
		
		return this.each(function(index){
			new $.WordCloud(this, options);
		});
	}
});

$.WordCloud = function(list, options){
	var $list = $(list);
	var words = [];
	var animateQue = new $.WordCloud.AnimateQue(options);
	
	$list.find('li').each(function(){
		words.push(new $.WordCloud.Word(this, options));
	});
	
	var length = words.length;
	for(var i = 0; i < length; i++){
		animateQue.addToQue(words[i]);
	}
	animateQue.start();
};

$.WordCloud.defaults = {
	color: '#C0C0C0'
    ,endColor: '#6864FF'
  	,speed: 2000
};

$.WordCloud.AnimateQue = function(options){
	var $this = $(this);
	var que = [];
	var isActive = false;
	var current = 0;
	
	function startQue(){
		$this.bind('AnimateQueFinished', {}, nextQuedItem)
		nextQuedItem();
	}
	
	function nextQuedItem(e){
		$(que[current].li).animate({color: options.endColor}, options.speed, null, function(){
			$(this).animate({color: options.color}, options.speed, null, function(){
				current = Math.floor(Math.random()*que.length);
				if(false === isActive){
					$this.unBind('AnimateQueFinished');
					return null;
				}
				$this.trigger('AnimateQueFinished', {}, function(){});
			});
		});
	}
	
	function init(){
		isActive = true;
		startQue();
	}
	
	function start(){
		init();
	}
	
	function stop(){
		isActive = false;
	}
	
	return {
		addToQue: function(word){
			que.push(word);
		}
		,start: function(){
			start();
		}
		,stop: function(){
			
		}
	}
}

$.WordCloud.Word = function(li, options){
	var $li = $(li);
	
	$li.css('color', options.color);
	
	return {
		li : $li
	};
};
})(jQuery);
