/**
	Klasa do prostej prezentacji. 
	
	@version: 1.0 11:20 2009-11-09
	@autor: pio + gie
	@param changer (DOM element, lub ID) - zmieniany kontener
	@param options (obj) 
	
	@require: mootools-1.2.1-core
	
	@example
	// patrz alltravelpl
	
	@changelog
		
*/
SimplePresentation = new Class({
	Implements: [Events, Options, Chain],

	options: {
        itemClass: 'item', // klasa elementow w kontenerze        
        itemsToShow: 1, // ile elementow ma byc widoczna
		isSlideshow: 1, // czy jest slideshow
		time: 10000 // lobalny setTimeout
	},

	initialize: function(changer, options) {
        this.changer = $(changer);
        this.setOptions(options);
        this.items = this.changer.getElements('.' + this.options.itemClass);
        this.total = this.items.length;
        this.current = 0;		
        this.queue = [];
	},
    
    go: function(num, time) {
		if (num != this.current) this._change(num, time);
	}, 
	
    next: function(e, time) {
		if (e) e.stop();
    	var next = this.current + 1;
        if (next > this.total - this.options.itemsToShow) next = 0;
        this._change(next, time);
    },
    
    prev: function(e, time) {
		if (e) e.stop();
    	var prev = this.current - 1;
        if (prev < 0) prev = this.total - this.options.itemsToShow;
        this._change(prev, time);
    },
	
    slideshow: function(time) {
		if (this.timeout) $clear(this.timeout);
    	this.timeout = this.next.delay($pick(time, this.options.time), this);
    },
	
	_change: function(num, time) {
		if (num !== undefined) {
			this.queue.push({num: num, time: time, current: this.current});
			this.current = num;
		}

		if (this.queue.length == 0 || this.locked == 1) { return; }

		if (this.timeout) $clear(this.timeout);
		this.locked = 1;
		var job = this.queue.shift();
		
		this.chain(
			this.hideShowItem.bind(this, [job]),
			function() {
				this.fireEvent('change', [job.num, job.current]);
				this.locked = 0;
				if (this.queue.length > 0) {
					this._change();
				} else if (this.options.isSlideshow) {
					this.slideshow();
				}
			}.bind(this)
		);
				
		this.callChain();		
    },
	
	hideShowItem: function(job) {
		var itemcurr = this.items[job.current];
        var itemnum = this.items[job.num];

		new Fx.Tween(itemcurr).start('opacity', 0)
            .chain(function() {
                new Fx.Tween(itemnum).start('opacity', 1)
					.chain(this.callChain.bind(this));                
            }.bind(this));
	}
});
