Ext.ns('ABCS');
ABCS.Carousel = Ext.extend(Ext.util.Observable, {
	interval: 4,
	transitionDuration: 0.5,
	transitionType: 'slide-left',
	transitionEasing: null,
	itemSelector: 'img',
	activeSlide: 0,
	autoPlay: false,
	showPlayButton: false,
	pauseOnNavigate: false,
	wrap: false,
	freezeOnHover: false,
	// constructor of control
	constructor: function(elId, config) {
		config = config || {};
		Ext.apply(this, config);
		ABCS.Carousel.superclass.constructor.call(this, config); 
		this.el = Ext.get(elId);
		this.slides = this.els = [];
		
		this.initMarkup();
        //this.initEvents();
		if(this.carouselSize > 0){
			this.els.slidesWrap.setWidth((this.carouselSize * this.slideWidth) + 'px');
		}
		
		Ext.TaskMgr.start.defer((this.interval * 1000), this,[{
			run: this.changeSlide,
			scope:this,
			interval: (this.interval * 1000)
		}]);
	},
	// create makup of control
	initMarkup: function() {
		var dh = Ext.DomHelper;
		this.carouselSize = 0;
		var items = this.el.select(this.itemSelector);
		this.els.container = dh.append(this.el, {cls: 'carousel-container'}, true);
		this.els.slidesWrap = dh.append(this.els.container, {cls: 'carousel-slides-wrap'}, true);
		// set the dimensions of the container
		this.slideWidth = this.width || this.el.getWidth(true);
		this.slideHeight = this.height || this.el.getHeight(true);
		// set container width and height
		this.els.container.setStyle({
			width: this.slideWidth + 'px',
			height: this.slideHeight + 'px'
		});
		//append items to slides wraper
		items.appendTo(this.els.slidesWrap).each(function(item) {
			// wrap each slide with stylized div
			item = item.wrap({cls: 'carousel-slide'});
			item.setWidth(this.slideWidth + 'px').setHeight(this.slideHeight + 'px');
			this.slides.push(item);
		}, this);
		// how many slides
		this.carouselSize = this.slides.length;
		// overflow main container
		this.el.clip();
	},
	// change slide by 1
	changeSlide: function() {
		var index = this.activeSlide + 1;
		//check index		
		if(index < 0) {
			index = (this.carouselSize-1);
		}
		else if(index > (this.carouselSize-1)) {
			index = 0;
		}
		if(!this.slides[index]) {
			return;
		}
		
		var offset = index * this.slideWidth;
		switch (this.transitionType) {
			case 'slide-left':
				//calc new position
				var xNew = (-1 * offset) + this.els.container.getX();
				if(Ext.isIE && xNew == this.els.container.getX()){
					xNew += 1;
				}
				
				this.els.slidesWrap.stopFx(false);
				this.els.slidesWrap.shift({
					duration: this.transitionDuration,
					x: xNew,
					easing: this.transitionEasing
				});
			break;
		}
		this.activeSlide = index;
	}
	
});
