/***********************************************/
/* by Delyan Haralanov
/***********************************************/

var Featured = new Class({
  
  Implements: [Events, Options],
  
  options: {
    //onChange: $empty,
    
    next: null,
    previous: null,
    width: 175,
    visible: 5,
		interval: 4000,
    animation: {
      duration: 500
    }
    
  },
  
  initialize: function(element, options){
    this.setOptions(options);
		this.element = $(element);
		this.children = this.element.getChildren();
		this.document = this.element.getDocument();
		this.timer = null
		this.direction = 1
		
		this.current = 0;
		
    this.children.each(function(el, index){
      el.store('visible', index > this.options.visible - 1 ? false : true)
      el.set({
        'styles': {position: 'absolute', left: index*this.options.width, display: (el.retrieve('visible') ? 'block' : 'none')},
        'morph': {duration:600, transition:'quint:out', onComplete: function(el){el.set('styles', (el.retrieve('visible') ? 'block' : 'none'))}}
      })
    }, this)
    
    $(this.options.prev).addEvent('click', this.goToPrev.bindWithEvent(this))
    $(this.options.next).addEvent('click', this.goToNext.bindWithEvent(this))
		
		this.timer = this.onTimer.periodical(this.options.interval, this)
  },
  
 	onTimer: function(){
		if(this.current == 0) this.direction = 1
		if(this.current == this.children.length - this.options.visible) this.direction = -1
		this.goTo(null, this.current + this.direction)
	},
   
  goToPrev: function(event){
		$clear(this.timer)
    this.goTo(event, this.current - 1);
  },
  
  goToNext: function(event){
		$clear(this.timer)
    this.goTo(event, this.current + 1);
  },
  
  goTo: function(event, num){
    if(num < 0) num = 0;
    if(num > this.children.length - this.options.visible - 1) num = this.children.length - this.options.visible;
    if(num == this.current) return;
    this.current = num;
    
    offset = Math.round((this.document.getWidth() - this.element.getWidth()) / 2) 
    
    this.children.each(function(el, index){
        
      if(index >= this.current && index < this.current + this.options.visible){
        if(!el.retrieve('visible'))
          el.set('styles', {left:  (index == this.current ? -offset : this.element.getWidth() + offset - this.options.width), opacity:0})
        
        el.set('styles', {display: 'block'}).store('visible', true).morph({left: (index - this.current)*this.options.width, opacity: 1})
      }else{
        if(el.retrieve('visible')){
          el.store('visible', false).morph({left: (index > this.current ? this.element.getWidth() + offset -this.options.width: -offset), opacity: 0})
        }
      }  
    }, this)
    
  }
  
 
});