$.widget("ui.cmCarousel", {
	int:null,
	items:null,
	cur:null,
	init: function() {
		var $this = this;
        var opts = this.options;
        var el = this.element;
    	this.cur = 0;
    	var int;
    	var car = this.items = $('.carousel-item', el);
    	if (car.length <= 1) {
    		return;
    	}
    	car.hide();
    	var links = '<div class="carousel">';
    	for(i=0;i<car.length;i++) {
    		links += '<a href="#" class="carousel-page" rel="'+i+'">'+(i+1)+'</a>';
    	}
    	links += '<a href="#" class="carousel-control pause">Pause</a>';
    	links += '</div>';
    	car.eq(0).before(links);
    	this.show(0).play();
    	$('a.carousel-page',el).click(function(){
    		$this.pause();
    		$this.show(parseInt($(this).attr('rel')));
    		return false;
    	});
    	$('a.carousel-control',el).click(function(){
    		var a = $(this);
    		if(a.hasClass('pause')) {
    			$this.pause();
    		} else {
    			$this.play();
    		}
    		return false;
    	});
	},
	play: function() {
		$('a.carousel-control', this.element).removeClass('play').addClass('pause').text('Pause');
		var $this = this;
		$this.int = setInterval(function(){
			if($this.cur+1 >= $this.items.length) {
				$this.show(0);
			} else {
				$this.show($this.cur+1);
			}
			
		}, 6000);
		this.paused = false;
	},
	pause: function() {
		$('a.carousel-control').removeClass('pause').addClass('play').text('Play');
		clearInterval(this.int);
	},
	show: function(n) {
		$('a.carousel-page',this.element).removeClass('current');
		$('a.carousel-page[rel="'+n+'"]',this.element).addClass('current');	
		var $this = this;
		this.items.eq(this.cur).fadeOut($this.options.speed, function(){
			$this.cur = n;
			$this.items.eq(n).fadeIn($this.options.speed);
		});
		return this;
	}
});
$.ui.cmCarousel.defaults = {
	int:null,
	speed:'fast'
};
