/*
 Copyright (c) Jean-Marc Delafont, kttp://www.ksp.fr
License:
	MIT-style license.
*/
var sodiScroller = new Class({
  Implements: [Options],
  options: {
    container_id: 'carousel',
    content_classname: '.scrollable_content',
    invoker_up_classname: '.scroll_prev_cmd',
    invoker_down_classname: '.scroll_next_cmd',
    item_classname: '.item',
    item_on_classname: 'on',
    nb_visible_elements: 8,
    step_unit: 2
  },

  initialize: function(options){
    this.setOptions(options);

    this.container = $(this.options.container_id);

    if (this.container) {
      if (this.content = this.container.getElement(this.options.content_classname)) {
        this.scroller = new Fx.Scroll(this.content, { duration: 500 });
        this.items = this.content.getElements(this.options.item_classname);
        if (selected_item = this.content.getElement('.'+this.options.item_on_classname)) {
          this.moveTo(selected_item);
        }
      } 

      if (this.container && this.content && this.scroller) {
        this.container.getElements(this.options.invoker_up_classname).each(function(item) {
          item.addEvent('click', this.moveUp.bindWithEvent(this));
        }, this);

        this.container.getElements(this.options.invoker_down_classname).each(function(item) {
          item.addEvent('click', this.moveDown.bindWithEvent(this));
        }, this);
      }
    }
  },

  moveUp: function(event) {
    event = new Event(event).stop();

    step = this.current_index.limit(0, this.options.step_unit);
    this.current_index -= step;
    this.scroller.toElement(this.items[this.current_index]);
    this.updateInvokerState();
  },

  moveDown: function(event) {
    event = new Event(event).stop();
    remain = this.items.length - this.options.nb_visible_elements - this.current_index;

    step = remain.limit(0, this.options.step_unit);

    this.current_index += step;
    this.scroller.toElement(this.items[this.current_index]);
    this.updateInvokerState();
  },

  moveTo: function(item) {
    
    this.scroller.toElement(item);

    idx = this.items.indexOf(item).limit(0, this.items.length - this.options.nb_visible_elements);
    this.current_index = idx;

    this.updateInvokerState();
  },

  buildItemCssId: function(itemId) { return itemId; }, //abstract
  getItemId: function() { return '-1'; }, //abstract

  selectItemFromId: function(itemId, hasToMove) {
    if (itemToSelect = this.container.getElementById(this.buildItemCssId(itemId))) {
      this.selectItem(itemToSelect, hasToMove);
    }
  },

  selectItem: function(itemToSelect, hasToMove) {
    if (itemToSelect) {
      this.container.getElements('.'+this.options.item_on_classname).each(function(item) {
        item.removeClass(this.options.item_on_classname);
      }.bind(this));
      itemToSelect.addClass(this.options.item_on_classname);
      if (hasToMove) this.moveTo(itemToSelect);
    }
  },

  enableUp: function() {
    this.container.getElements(this.options.invoker_up_classname).each(function(item) {
      item.removeClass('disabled');
    }, this);
  },

  disableUp: function() {
    this.container.getElements(this.options.invoker_up_classname).each(function(item) {
      item.addClass('disabled');
    }, this);
  },

  enableDown: function() {
    this.container.getElements(this.options.invoker_down_classname).each(function(item) {
      item.removeClass('disabled');
    }, this);
  },

  disableDown: function() {
    this.container.getElements(this.options.invoker_down_classname).each(function(item) {
      item.addClass('disabled');
    }, this);
  },

  updateInvokerState: function() {
    if (this.current_index > 0 && this.items.length > this.options.nb_visible_elements) { 
      this.enableUp(); 
    } else { 
      this.disableUp(); 
    }

    if (this.current_index < (this.items.length - this.options.nb_visible_elements)) { 
      this.enableDown(); 
    } else {
      this.disableDown();
    }
  },

  listener: null,
  container: null,
  content: null,
  scroller: null,
  items: [],
  current_index: 0
});

var ListScroller = new Class({
  Extends: sodiScroller,

  initialize: function() {  
    this.parent();
    this.items.each(function(item) {
      item.getElement('a').addEvent('click', this.selectFile.bindWithEvent(this, item));
    }.bind(this));
  },

  selectFile: function(event, item) {
    event = new Event(event).stop();
    if (this.filescroller) {
      this.filescroller.selectItemFromId(this.getItemId(item), true);
      this.filescroller.updatePrevNextLinks();
      this.selectItem(item, false);
    }
  },

  getCurrentItemId: function() {
    this.getItemId(this.items[this.current_index]);
  },

  getItemId: function(item) {
    var reg = /item-([a-z0-9\-]+)/;
    if (matches = item.id.match(reg)) {
      return matches[1];
    }
  },

  buildItemCssId: function(itemId) {
    return 'item-' + itemId;
  },

  getLinkFromId: function(itemId) {
    if (elt = $(this.buildItemCssId(itemId))) {
      return elt.getElement('a');
    }
  },

  filescroller: null
});

var SodiFileScroller = new Class({
  Extends: sodiScroller,

  moveDown: function(event) {
    this.parent(event);
    this.updateListScroller();
    this.updatePrevNextLinks();
  },

  moveUp: function(event) {
    this.parent(event);
    this.updateListScroller();
    this.updatePrevNextLinks();
  },

  updatePrevNextLinks: function() {
    var prevLink, nextLink;
    if (prevItem = this.items[this.current_index-1]) {
      if (prevLink = this.listscroller.getLinkFromId(this.getItemId(prevItem))) {
        this.container.getElements(this.options.invoker_up_classname).each(function(item) {
          if (lnk = item.getElement('a')) {
            lnk.href = prevLink.href;
          }
        }, this);
      }
    }

    if (nextItem = this.items[this.current_index+1]) {
      if (nextLink = this.listscroller.getLinkFromId(this.getItemId(nextItem))) {
        this.container.getElements(this.options.invoker_down_classname).each(function(item) {
          if (lnk = item.getElement('a')) {
            lnk.href = nextLink.href;
          }
        }, this);
      }
    }
  },

  updateListScroller: function() {
    if (this.listscroller) {
      this.listscroller.selectItemFromId(this.getItemId(this.items[this.current_index]), true);
    }
  },

  getItemId: function(item) {
    var reg = /file-([a-z0-9\-]+)/;
    if (matches = item.id.match(reg)) {
      return matches[1];
    }
  },

  buildItemCssId: function(itemId) {
    return 'file-' + itemId;
  },

  listscroller:null
});

var PilotFileScroller = new Class({
  Extends: SodiFileScroller,

  moveDown: function(event) {
    this.parent(event);
    this.resetPanels();
  },

  moveUp: function(event) {
    this.parent(event);
    this.resetPanels();
  },

  moveTo: function(item) {
    this.parent(item);
  },

  resetPanels: function() {
    var url;
    if (currentItem = this.items[this.current_index]) {
      if (currentLink = this.listscroller.getLinkFromId(this.getItemId(currentItem))) {
        url = currentLink.href;
      }
    }

    if (url && this.panels_manager) {
      this.panels_manager.updatePanels(url + '?panel=' + this.panels_manager.getTypeCurrentPanel());
    }
  },

  panels_manager: null
});

var PilotListScroller = new Class({
  Extends: ListScroller,

  selectFile: function(event, item) {
    this.parent(event, item);
    anchor = item.getElement('a');
    if (anchor && anchor.href) this.resetPanels(anchor.href);
  },

  resetPanels: function(url) {
    new Request.HTML({
    url: url,
    method: 'get',
    update: 'panel_container',
    evalScripts: true
    }).send();
  }
});


var sodiSelectButton = new Class({
  Implements: [Options],
  options: { 
  },

  initialize: function(element, options) {
    this.list = element.getElement('.submenu');
    this.slideFx = new Fx.Slide(this.list);
    element.addEvent('click',  function(event){
      event = new Event(event).stop();
      this.slideFx.toggle();
    }.bindWithEvent(this));

  },

  slideFx: null,
  list: null
});

String.implement({
  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
    this.slice(0, length - truncation.length) + truncation : this;
  }
});
/*
function update_panel(panel, url) {
  anchors = document.getElement('.pilot-tabs').getElements('a');
  new Request.HTML({
  url: url,
  method: 'get',
  update: 'ghost_container',
  evalScripts: true,
  onRequest: function() {
    //cursor
    document.body.style.cursor = 'wait';
    anchors.setStyles({cursor: 'wait'});
  },
  onComplete: function(){ 
    document.body.style.cursor = '';
    anchors.setStyles({cursor: ''});

    panel_content_to_display = $('ghost_container').getElement('.pilot-panel-content');
    panel_content_to_replace = $('panel_container').getElement('.pilot-panel-content');

    show_hide_panel_content($('ghost_container'), 0, false);

    fx = new Fx.Tween(panel_content_to_replace, {
      onComplete: function() {
        replace_panel_contents($('panel_container'), $('ghost_container'));
        show_hide_panel_content($('panel_container'), 1, true);
      }
    });
    fx.start('height', panel_content_to_display.getHeight());

  }
}).send();
}

function replace_panel_contents(from, to) {
  ['.pilot-panel-content', '.menu-year', '.pilot-tabs'].each(function(class_name) {
    to.getElement(class_name).replaces(from.getElement(class_name));
  });
}

function show_hide_panel_content(container, opacity, transition) {

  elt_class_name = [ '.pilot-panel-content', '.menu-year' ]
  elts_to_fade = [];
  effects = {};

  elt_class_name.each(function(item,idx) {
    if (elt = container.getElement(item)) {
      elts_to_fade.push(elt);
      effects[idx] = { opacity: opacity };
    }
  });

  if (transition) {
    return new Fx.Elements(elts_to_fade).start(effects);
  } else { 
    return new Fx.Elements(elts_to_fade).set(effects);
  }
}
*/

var PilotPanelsManager = new Class({
  Implements: [Options],
  options: {
    ghost_container_id: 'ghost_container',
    panel_container_id: 'panel_container',
    panel_content_class_name: '.pilot-panel-content',
    pilot_tabs_class_name: '.pilot-tabs',
    elts_class_name_to_fade: [ '.pilot-panel-content', '.menu-year' ],
    elts_class_name_to_replace: ['.pilot-panel-content', '.menu-year', '.pilot-tabs']
  },

  initialize: function(options){
    this.setOptions(options);
    this.ghost_container = $(this.options.ghost_container_id);
    this.panel_container = $(this.options.panel_container_id);
  },

  updatePanels: function(url) {
    anchors = document.getElement(this.options.pilot_tabs_class_name).getElements('a');
    new Request.HTML({
    url: url,
      method: 'get',
      update: this.ghost_container,
      evalScripts: true,
      onRequest: function() {
        //cursor
        document.body.style.cursor = 'wait';
        anchors.setStyles({cursor: 'wait'});
      },
      onComplete: function(){ 
        document.body.style.cursor = '';
        anchors.setStyles({cursor: ''});

        panel_content_to_display = this.ghost_container.getElement(this.options.panel_content_class_name);
        panel_content_to_replace = this.panel_container.getElement(this.options.panel_content_class_name);

        this.showHidePanelContent(this.ghost_container, 0, false);

        fx = new Fx.Tween(panel_content_to_replace, {
          onComplete: function() {
            this.replacePanelContent(this.ghost_container, this.panel_container);
            this.showHidePanelContent(this.panel_container, 1, true);
            this.ghost_container.setStyle('opacity', 0);
          }.bind(this)
        });
        fx.start('height', panel_content_to_display.getHeight());
      }.bind(this)
    }).send();
  },
  
  showHidePanelContent: function(container, opacity, transition) {
    elts_to_fade = [];
    effects = {};
    this.options.elts_class_name_to_fade.each(function(item,idx) {
      if (elt = container.getElement(item)) {
        elts_to_fade.push(elt);
        effects[idx] = { opacity: opacity };
      }
    });

    if (transition) {
      return new Fx.Elements(elts_to_fade).start(effects);
    } else { 
      return new Fx.Elements(elts_to_fade).set(effects);
    }
  },
  
  replacePanelContent: function(from, to) {
    this.options.elts_class_name_to_replace.each(function(class_name) {
      from.getElement(class_name).replaces(to.getElement(class_name));
    });
  },

  getTypeCurrentPanel: function() {
    var type = 'closed';
    this.panel_container.getElement(this.options.pilot_tabs_class_name).getElements('li').each(function(tab) {
      if (tab.hasClass('on')) {
          var reg = /tab_(results|honour|photos)/;
          if (matches = tab.id.match(reg)) {
            type = matches[1];
          }
      }
    });
    return type;
  }
});
