
var JdnCarousel = new Class({

	Implements: [Events,Options],
	options: {
		overallContainer: null,/* outer container, contains fwd/back buttons and container for thumbnails */
		elementScrolled: null, /* has a set width/height with overflow hidden to allow sliding of elements */
		thumbsContainer: null,	/* actual thumbnails container */
                viewContainer: null, /* big images view container */
                carouselName: null,
		itemsSelector: null, /* css class for inner elements ( ie: .jdn_element ) */
		itemsVisible:1, /* number of elements visible at once */
		elemsSlide: 1, /* number of elements that slide at once */
		itemWidth: null, /* single element width */
		itemHeight: null, /* single element height */
		navs:{ /* starting this version, you'll need to put your back/forward navigators in your HTML */
//			fwd:'.jdn_forward', /* forward button CSS selector */
//			bk:'.jdn_back', /* back button CSS selector */
                        next:'.jdn_navi_but_next',
                        prev:'.jdn_navi_but_back'
		},
		slideVertical: false, /* vertical sliding enabled */
		showControls:0, /* show forward/back controls */
		transition: Fx.Transitions.linear, /* transition */
		duration: 800, /* transition duration */
		direction: 1, /* sliding direction ( 1: enter from left/top; -1:enter from right/bottom ) */
		autoSlide: true, /* auto slide - as milliseconds ( ie: 10000 = 10 seconds ) */
		mouseWheelNav: false, /* enable mouse wheel nav */
                autoSlideDuration:1000,
		startIndex: null
		/*onChange: $empty*/
	},

	initialize: function(options){
		this.setOptions(options);
		/* all elements are identified on CSS selector (itemsSelector) */
		this.elements = $(this.options.thumbsContainer).getElements(this.options.itemsSelector);
		this.totalElements = this.elements.length;
		if( this.totalElements == 0 ) {this.prepareView();return;}
		// width of thumbsContainer children
		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.autoSlideTotal = this.options.autoSlide + this.options.duration;
                this.selected=0;
                this.titles=$$('.jdn_item_title');
                this.titleSelected=1;
                this.auto=null;
		if( this.options.elemsSlide == 1 ) this.options.elemsSlide = null;
                if( this.totalElements <= this.options.itemsVisible ) this.disableSlide=true;
		this.begin();
	},

	begin: function(){

                this.prepareOpacity();

                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
		});

		/* if navigation is needed and enabled, add it */
		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.options.autoSlide && this.elements.length > this.options.itemsVisible )
			this.startAutoSlide();

                if(this.titles.length>1){
                    $(this.options.overallContainer).getElement('.jdn_navi_next').
                      set('html','&nbsp;&nbsp;<span class="nextLink">'+this.titles[this.titleSelected].get('html')+'</span>');
                      $$('.jdn_navi_next .titleLink').setStyles({'font-size': '12px',
                                                                 'text-decoration': 'underline'});
                    this.setNaviDots();

                } else {
                    $$('.jdn_navi').setStyle('display','none');
                }

	},

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

        prepareView: function(){
            $(this.options.overallContainer).set('text','');
            $(this.options.overallContainer).setStyle('display','none');
        },

//        sendRequestObj: function(descId){
//            var myreq = new Request.HTML({
//              method: 'get',
//              url: 'desc.php',
//              data: 'file='+descId,
//              update: $(this.options.carouselName+'_descript')
//            }).send();
//        },

        setNaviDots: function(){

            this.fdot=this.elements.length-1;
            
            var navi = $$('#'+this.options.overallContainer+' .dots');

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

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

        },

	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
		});
	},
	/* adds forward/back buttons */
	addControls: function(){


//		this.fwd = $(this.options.overallContainer).getElement(this.options.navs.fwd);
//		this.bkwd = $(this.options.overallContainer).getElement(this.options.navs.bk);
                this.next = $(this.options.overallContainer).getElement(this.options.navs.next);
                this.prev = $(this.options.overallContainer).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));
                }

//                    if( this.fwd )
//                            this.fwd.addEvent('click', this.slide.pass(1, this));
//                    if( this.bkwd )
//                            this.bkwd.addEvent('click', this.slide.pass(-1, this));
//
//		if( !this.options.showControls ) {
//                    this.fwd.destroy();
//                    this.bkwd.destroy();
//                    $(this.options.overallContainer).setStyle('padding','0px 0px 0px 0px')
//
//                }

	},


        prepareOpacity: function(){
                var size = $$('.jdn_element')[0].getSize();

                var hash = $$('#'+this.options.thumbsContainer+' .opacity_vertical_position');
                var hash_bg = $$('#'+this.options.thumbsContainer+' .opacity_vertical_position_bg')

                if(hash.length==hash_bg.length){
                    hash.each(function(value, key){

                        var pos=size.y - value.getSize().y;
                        value.setStyle('top',pos);

                        hash_bg[key].setStyles({'height':value.getSize().y,
                                                'top':pos,
                                                'display':'block'
                        });

                    });
                }
        },

        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.overallContainer+' .navi_dot');

                        $$('#'+this.options.overallContainer+' .jdn_navi_bdot').set('class','navi_dot jdn_navi_wdot');
                        dots[this.fdot].set('class','navi_dot jdn_navi_bdot');
        },

        changeTitle: function(direction){
                if(this.titles.length>1){

                     switch( direction ){
                            /* forward */
                            case 1:
                                    this.titleSelected = this.titleSelected >= this.totalElements-1 ? 0 : this.titleSelected + direction;
                            break;
                            /* backwards */
                            case -1:
                                    this.titleSelected = this.titleSelected == 0 ? this.totalElements - 1 : this.titleSelected + direction;
                            break;
                    }

//                    var next=(direction == 1)? (++this.titleSelected):(--this.titleSelected);
//                    if((next)%this.titles.length<0){
//                        next=this.titles.length+(next)%this.titles.length
//                    } else{
//                        next=(next)%this.titles.length;
//                    }
                    $(this.options.overallContainer).getElement('.jdn_navi_next').
                    set('html','&nbsp;&nbsp;<span class="nextLink">'+this.titles[this.titleSelected].get('html')+'</span>');
                    $$('.jdn_navi_next .titleLink').setStyles({
                        'font-size': '12px',
                        'text-decoration': 'underline'
                    });


                }
        },

	/* 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);   Zakomentowane w zwiazku z wprowadzeniem mootools 1.3 (DO SPRAWDZENIA)
			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(){

                        this.changeTitle(direction);

                        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).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 next = $(this.options.overallContainer).getElement(this.options.navs.next);
                this.auto = function() {
                    this.auto = (function() {
                            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(){

		$(this.options.overallContainer).removeProperty('style');
		$(this.options.elementScrolled).removeProperty('style');
		$(this.options.thumbsContainer).removeProperty('style');
		this.stopAutoSlide();
		if( $defined( this.fwd ) ){
			this.fwd.dispose();
			this.bkwd.dispose();
		}
		this.initialize();
	},
	/* stops auto sliding */
	stopAutoSlide: function(){
		$clear(this.autoSlide);
		this.isRunning = false;
	}
})




