// 
//  quicktour.js
//  bummerl-rails
//  
//  Created by Andrew Okonetchnikov on 2010-09-08.
//  Copyright 2010 okonet.ru. All rights reserved.
// 

var QTour = Class.create({
  /**
   * QTour#initialize(handlers, slides) -> QTour
   * 
   * handlers (CSS selector) and slides (CSS selector)
   * 
   **/
  initialize: function(options){
    
    this.activeHandler = null;
    this.activeItemId = null;
    this.el = $$(options['content'])[0];
    this.handlerSelector = options['handlers'];
    this.handlers = $$(this.handlerSelector);
    
    document.on('click', this.handlerSelector + '>a', function(event, link){
      event.stop();
      if(this.slideshow) this.slideshow.stop();
      this.activate(this.getIdFromLink(link));
    }.bind(this));
    
    // Activate first item
    this.activate(this.getIdFromLink(this.handlers[0].down('a[href]')));
    
    this.slideshow = new PeriodicalExecuter(this.switchToNext.bind(this), 20);
  },
  
  activate: function(id){
    var el = $(id);
    var handler = $$(this.handlerSelector + ' > a[href*="' + id + '"]')[0].up('li');
    
    if(Object.isUndefined(el)) 
      throw "Item element was not found in DOM.";

    this.el.setStyle({
      'left': -el.positionedOffset().left + 'px'
    });
    
    if(this.activeHandler) this.activeHandler.removeClassName('active');
    handler.addClassName('active');
    this.activeHandler = handler;
    this.activeItemId = id;
  },
  
  switchToNext: function(){
    if(!this.activeHandler) return;
    var next = this.activeHandler.next();
    if(!next) next = this.handlers[0];
    this.activate(this.getIdFromLink(next.down('a[href]')));
  },
  
  getIdFromLink: function(link){
    // Bulletproof method to work in IE6 & IE7
    return link.href.substring(link.href.indexOf('#')).replace('#', '');
  }
  
});
