//function myal(arg){ 
//    if(Cookie.read('KT_DEBUG')){
//        alert(arg);
//    }
//}


var CarouselTango = new Class({

	Implements: [Events,Options],
	options: {
		overallContainer: null,
		elementScrolled: null,
		thumbsContainer: null,	
                viewContainer: null, 
                carouselName: null,
                itemsSelector: '.carousel_element',
		itemsVisible:3,
		elemsSlide: 1,
		itemWidth: null, 
		itemHeight: null,
		navs:{ 
                        next:'.carousel_navi_but_next',
                        prev:'.carousel_navi_but_back'
		},
		slideVertical: false, 
		showControls:0,
		transition: Fx.Transitions.linear,
		duration: 800, 
		direction: 1, 
		autoSlide: false, 
		mouseWheelNav: false, 
                autoSlideDuration:5000,
                autoHeight:false,
		startIndex: null
	},

	initialize: function(options){
		this.setOptions(options);
		this.elements = $(this.options.thumbsContainer).getElements(this.options.itemsSelector);
		this.totalElements = this.elements.length;
		if( this.totalElements == 0 ) return;
		var defaultSize = this.elements[0].getSize();

		this.elementWidth = this.options.itemWidth || defaultSize.x;
		this.elementHeight = this.options.itemHeight || defaultSize.y;
		this.currentElement = 0;
		this.direction = this.options.direction;
                this.selected=0;
                this.auto=null;
                this.height=0;
		if( this.options.elemsSlide == 1 ) this.options.elemsSlide = null;
                if( this.totalElements <= this.options.itemsVisible ) this.disableSlide=true;
		this.begin();
	}, 

	begin: function(){
                

                if(this.totalElements == 0 ) return;

                this.selected=0;
		// resizes the container div's according to the number of itemsVisible thumbnails
		this.setContainersSize();

		this.myFx = new Fx.Tween(this.options.thumbsContainer, {
			property: (this.options.slideVertical ? 'margin-top':'margin-left'),
			wait: true,
			transition: this.options.transition,
			duration: this.options.duration
		});

                this.addControls();


		/* if autoSlide is not set, scoll on mouse wheel */
		if( this.options.mouseWheelNav && !this.options.autoSlide ){
			$(this.options.thumbsContainer).addEvent('mousewheel', function(ev){
				new Event(ev).stop();
				this.slide(-ev.wheel);
			}.bind(this));
		}

		/* start index element */
		if( this.options.startIndex && this.options.startIndex > 0 && this.options.startIndex < this.elements.length ){
			for( var t = 1; t < this.options.startIndex; t++ )
				this.rearange();
		}

                if(this.totalElements>1){
                    this.setNaviDots();
                }
                

                    if( this.options.autoSlide==1 && this.elements.length > this.options.itemsVisible )
                             this.startAutoSlide(); 
                    
                


	},

	/* sets the containers width to leave visible only the specified number of elements */

	setContainersSize: function(){

		var overallSize = {};
		var scrollSize = {};
		var thumbsSize = {};


		if( this.options.slideVertical ){
			//overallSize.height = this.options.itemsVisible * this.elementHeight + 50 * this.options.showControls;
			scrollSize.height = this.options.itemsVisible * this.elementHeight;
			thumbsSize.height = this.totalElements * (this.elementHeight + 10);
		}else{
			overallSize.width = this.options.itemsVisible * this.elementWidth;
			scrollSize.width = this.options.itemsVisible * this.elementWidth;
                        scrollSize.height=this.elementHeight;
			thumbsSize.width = this.totalElements * (this.elementWidth + 10);
		}
             


		$(this.options.overallContainer).set({
			styles : overallSize
		});
		$(this.options.elementScrolled).set({
			styles : scrollSize
		});
		$(this.options.thumbsContainer).set({
			styles : thumbsSize
		});


                var offset=20;
                if(this.disableSlide){
                    offset=0;
                }

                if(this.options.autoHeight){
                    var obj=this;
                    var height=0;
                    if($$('#'+this.options.thumbsContainer+' .main_item').length){
//                        alert($$('#'+this.options.carouselName+' .main_item').length);
//                        alert('#'+this.options.carouselName+' .main_item')
                        $each($$('#'+this.options.thumbsContainer+' .main_item'),function(item){
                            height=item.getSize().y; 
                            if(height>obj.height){ obj.height=height; }
                        });

                        $(this.options.overallContainer).setStyle('height',this.height+40);
                        $(this.options.overallContainer).getParent().setStyle('height',this.height+20+offset);
                        $(this.options.elementScrolled).setStyle('height',this.height+20);
                        $$('#'+this.options.thumbsContainer+' .carousel_element').setStyle('height',this.height+10);
                    } else {
                        $each($$('#'+this.options.thumbsContainer+' .auto_height_anchor'),function(item){
                            height=item.getSize().y;  
                            if(height>obj.height){ obj.height=height; }
                        });

                        $(this.options.overallContainer).setStyle('height',this.height);
                        $(this.options.overallContainer).getParent().setStyle('height',this.height);
                        $(this.options.elementScrolled).setStyle('height',this.height);
                        $$('#'+this.options.thumbsContainer+' .carousel_element').setStyle('height',this.height);
                    }


                }

	},
	/* adds forward/back buttons */
	addControls: function(){

                if(this.elements.length>this.options.itemsVisible && this.options.showControls){
                    $$('#'+this.options.carouselName+"_navi").setStyle('display','block');
                }

                this.next = $(this.options.carouselName+"_navi").getElement(this.options.navs.next);
                this.prev = $(this.options.carouselName+"_navi").getElement(this.options.navs.prev);
                if( this.next ){
                        var obj=this;
                        this.next.addEvent('click',this.slide.pass(1, this));
                }
                if( this.prev ){
                        var obj=this;
                        this.prev.addEvent('click',this.slide.pass(-1, this));
                }

	},

        setNaviDots: function(){

            this.fdot=this.elements.length-1;

            var navi = $$('#'+this.options.carouselName+'_navi .dots');

            for (i=0;i<this.elements.length;i=i+1){
                var dot = new Element('div', {'class': 'navi_dot carousel_navi_wdot'});
                navi.grab(dot);
            }


        var dots=$$('#'+this.options.carouselName+'_navi .navi_dot');
            dots[this.fdot].set('class','navi_dot carousel_navi_bdot');

        },

        changeDot: function(direction){
//                        var nextdot=(direction == 1)? (--this.fdot):(++this.fdot);


		switch( direction ){
			/* forward */
			case 1:
				this.fdot = this.fdot == 0 ? this.totalElements-1 : this.fdot - direction;
			break;
			/* backwards */
			case -1:
				this.fdot = this.fdot >= this.totalElements-1 ? 0 : this.fdot - direction;
			break;
		}
//                        if(nextdot<0) nextdot=this.elements.length+(nextdot)%this.elements.length;

                        var dots=$$('#'+this.options.carouselName+'_navi .navi_dot');

                        $$('#'+this.options.carouselName+'_navi .carousel_navi_bdot').set('class','navi_dot carousel_navi_wdot');
                        dots[this.fdot].set('class','navi_dot carousel_navi_bdot');
        },

	/* slides elements */
	slide: function( direction,hop ){

                if( this.disableSlide ) return;

                var steps=this.options.elemsSlide;
                if(hop){
                    steps=(hop>1) ? hop:null;
                }

		if(this.started) return;

		this.direction = direction ? direction : this.direction;

		var currentIndex = this.currentIndex();

		if( steps && steps>1 && this.endingElem==null ){
			this.endingElem = this.currentElement;
			for(var i = 0; i < steps; i++ ){
				this.endingElem += direction;
				if( this.endingElem >= this.totalElements ) this.endingElem = 0;
				if( this.endingElem < 0 ) this.endingElem = this.totalElements-1;
			}
		}

		var s = new Hash();
		var fxDist = 0;
		if( this.options.slideVertical ){
//			s.include('margin-top', -this.elementHeight);
			fxDist = this.direction == 1 ? -this.elementHeight : 0;
		}else{
//			s.include('margin-left', -this.elementWidth);
			fxDist = this.direction == 1 ? -this.elementWidth : 0;
		}

		if( this.direction == -1 ){
			this.rearange();
//			$(this.options.thumbsContainer).setStyles(s);
			$(this.options.thumbsContainer).setStyle('margin-left', -this.elementWidth);
		}
		this.started = true;


		this.myFx.start( fxDist ).chain( function(){

                        if(this.totalElements>1){
                            this.changeDot(direction);
                        }
			this.rearange(true);
                            if(steps){
                                    if( this.endingElem !== this.currentElement ) this.slide(this.direction);
                                    else this.endingElem=null;
                            }
		}.bind(this)  );

		this.fireEvent('onChange', currentIndex);

	},
	/* rearanges elements for continuous navigation */
	rearange: function( rerun ){

		if(rerun) this.started = false;
		if( rerun && this.direction == -1 ) return;

		this.currentElement = this.currentIndex( this.direction );

		var s = new Hash();
		if( this.options.slideVertical ) s.include('margin-top', 0);
		else s.include('margin-left', 0);

//		$(this.options.thumbsContainer).setStyles(s);
		$(this.options.thumbsContainer).setStyle('margin-left', 0);

		if( this.currentElement == 1 && this.direction == 1 ){
			this.elements[0].injectAfter(this.elements[this.totalElements-1]);
			return;
		}
		if( (this.currentElement == 0 && this.direction ==1) || (this.direction==-1 && this.currentElement == this.totalElements-1) ){
			this.rearrangeElement( this.elements.getLast(), this.direction == 1 ? this.elements[this.totalElements-2] : this.elements[0]);
			return;
		}

		if( this.direction == 1 ) this.rearrangeElement( this.elements[this.currentElement-1], this.elements[this.currentElement-2]);
		else this.rearrangeElement( this.elements[this.currentElement], this.elements[this.currentElement+1]);
	},
	/* rearanges a single element for continuous navigation */
	rearrangeElement: function( element , indicator ){
		this.direction == 1 ? element.injectAfter(indicator) : element.injectBefore(indicator);

	},
	/* determines the current index in element list */
	currentIndex: function(){
		var elemIndex = null;
		switch( this.direction ){
			/* forward */
			case 1:
				elemIndex = this.currentElement >= this.totalElements-1 ? 0 : this.currentElement + this.direction;
			break;
			/* backwards */
			case -1:
				elemIndex = this.currentElement == 0 ? this.totalElements - 1 : this.currentElement + this.direction;
			break;
		}



		return elemIndex;
	},
	/* starts auto sliding */
	startAutoSlide: function(){
            if(!this.isRunning){
                var obj=this;
                var next = $(this.options.carouselName+"_navi").getElement(this.options.navs.next);
                this.auto = function() {
                    this.auto = (function() {
                          if($defined(next))
                            next.fireEvent('click'); 
                        }).periodical(this.options.autoSlideDuration);
                }
                this.auto();
                this.isRunning = true;
            }

                    $(this.options.overallContainer).addEvents({
                            'mouseenter':function(){
                                    $clear(this.auto);
                                    this.isRunning = false;
                            }.bind(this),
                            'mouseleave':function(){
                                    this.startAutoSlide();
                            }.bind(this)
                    })
	},

	/* resets the whole slider in case content changes */
	resetAll: function(){
            if($defined($(this.options.overallContainer)) && $defined($(this.options.elementScrolled)) && $defined($(this.options.thumbsContainer))){
                $(this.options.overallContainer).removeProperty('style');
                $(this.options.elementScrolled).removeProperty('style');
                $(this.options.thumbsContainer).removeProperty('style');
                this.stopAutoSlide();
                if($defined(this.next)){
                    this.next.dispose();
                    this.prev.dispose()
                    }
                    this.initialize()
            }

	},
	/* stops auto sliding */
	stopAutoSlide: function(){
		$clear(this.auto);
                this.auto=null;
		this.isRunning = false;
	}
})




