/*
    Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

    Copyright (c) 2010 Andrew Chung

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
 */
var MODS = Class.create({
  Version: '0.1.1.0',

  auto_transition: true,
  delay: 10000,                 // Time in ms to show each panel
  transition_delay: 1000,       // Time in ms the transition effects last
  transition_short: null,       // When jumping to a new panel manually, use this delay over the standard delay.  The default value is 1/2 of the transition_delay value
  content_prefix: null,         // ID prefix used by the content inside the container.  The panels shuold be named <prefix>_0, <prefix>_1, ... <prefix>_n.  The default prefix is the container ID itself
  current_panel: 1,             // Start index of the panel.  Indices start at 1
  add_anchor: false,

  _previous_panel: null,        // Internal variable keeping track of the previous panel index
  _container: '',
  _container_id: '',            // This value is passed in when the object is created
  _start_time: null,            // Time when we started our Periodical Executor
  _delay_offset: 0,             // Used when we pause so when we resume the executor it will start correctly
  _panels: null,
  _controls: null,
  _fn_click: null,
  _fn_ctrl_click: null,
  _timer_transition: null,
  _transition_effect: null,
  _state: 'UNINITIALIZED',

  initialize: function(container_id, options) {
    if (this._state != 'UNINITIALIZED') {
      return;
    }
    this._controls        = new Array();
    this._container_id    = container_id;
    this._container       = $(this._container_id);
    if (this._container == null) {throw('Unable to find container with id: '+container_id);}
    if (this.content_prefix == null || this.content_prefix == '') {this.content_prefix  = this._container_id;}
    this._panels          = this._container.immediateDescendants();
    if (this._panels == null) {throw('No content in the container found');}
    /* Event handlers */
    this._fn_click        = this._handle_click.bindAsEventListener(this);
    this._fn_ctrl_click   = this._handle_ctrl_click.bindAsEventListener(this);
    if (this.transition_short == null) {
      this.transition_short = this.transition_delay/2;
    }
    this._state = 'INITIALIZED';
  },
  start: function() {
    if (this._state == 'INITIALIZED') {
      var i;
      var mods  = this;
      var re    = new RegExp(this.content_prefix+'_(\\d+)');
      for (i = this._panels.length - 1; i >= 0; i--) {
        var match         = re.exec(this._panels[i].id);
        if (match) {
          if (this._panels[i].id != this.content_prefix+'_'+this.current_panel) {this._panels[i].hide();}
          else {this._panels[i].show();}
        }
        else { // Remove panel from the list since it is not a display panel/object
          this._panels.splice(i, 1);
        }
      }
      
      $$('a[rel~="'+this._container_id+'"]').each(function(link) {mods._add_control(link);});
      if (this.auto_transition) { // Automatically start transitioning
        this._state       = 'STOPPED';
      }
    }
    switch(this._state) {
      case 'RUNNING':
        break;
      case 'STOPPED':
        this._start_timer();
        this._state       = 'RUNNING';
        this.auto_transition  = true;
        break;
      case 'PAUSED':
        this._start_timer();
        this._state       = 'RUNNING';
        break;
      default:
        this._state       = 'STOPPED';
        break;
    }
  },
  stop: function() {
    this._stop_timer();
    this._state           = 'STOPPED';
  },
  pause: function() {
    if (this._state == 'RUNNING') {
      this._stop_timer();
      var cur_time        = new Date().getTime();
      this._delay_offset  = (cur_time - this._start_time)%(this.delay);
      this._state         = 'PAUSED';
    }
  },
  previous: function() {
    //console.log("Previous");
    this._transition(parseInt(this.current_panel) - 1, {direction: 0});
  },
  next: function() {
    //console.log("Next");
    this._transition(parseInt(this.current_panel) + 1);
  },
  jump: function(panel_number) {
    //console.log("Jump: " + panel_number);
    this._transition(parseInt(panel_number));
  },
  /*reset: function() {
  },*/
  _handle_click: function(event) {
    Event.stop(event);
    var re        = new RegExp(this.content_prefix+'=(\\d+)');
    var needle    = re.exec(Event.element(event).readAttribute('href'));
    if (needle != null) {this._transition(parseInt(needle[1]));}
  },
  _handle_ctrl_click: function(event) {
    Event.stop(event);
    //console.log("Got control click");
    var target    = Event.element(event);
    //console.log(target);

    if (target.hasClassName('play') || target.hasClassName('start')) {this.start();}
    else if (target.hasClassName('stop')) {this.stop();}
    else if (target.hasClassName('pause')) {this.pause();}    
    if (target.hasClassName('prev')) {this.previous();}
    else if (target.hasClassName('next')) {this.next();}
  },
  _handle_timeout: function() {
    this._transition(parseInt(this.current_panel) + 1, true);
    if (this._delay_offset != 0) {
      this._delay_offset  = 0;    // Reset the delay offset and start our normal period
      this._start_timer();
    }
  },
  _start_timer: function() {
    this._stop_timer();
    this._start_time          = new Date().getTime();
    if (this.auto_transition) {
      this._timer_transition  = new PeriodicalExecuter(function() {this._handle_timeout();}.bind(this), (this.delay - this._delay_offset)/1000);
    }
  },
  _stop_timer: function() {
    if (this._timer_transition == null) {return;}
    this._timer_transition.stop();
    this._timer_transition  = null;
  },
  _transition: function(new_panel_id, args) {
    /* Add error checking to make sure we have panels */
    var params= $H({skip: false, direction: 1}).update(args);
    var new_panel;
    var old_panel;
    new_panel_id        = this._wrap_panel_index(new_panel_id);
    var effect_duration = this.transition_delay/1000;

    if (this.current_panel == new_panel_id) {return;}
    if (this._transition_effect != null) {
      old_panel   = this._panels[this._previous_panel - 1];
      new_panel   = this._panels[this.current_panel - 1];
      this._transition_effect.cancel();
      old_panel.hide();
      new_panel.setStyle({left: '0px'});
      new_panel.show();
      effect_duration = this.transition_short/1000;
    }
    this._previous_panel  = this.current_panel;
    this.current_panel    = new_panel_id;
    old_panel = this._panels[this._previous_panel - 1];
    new_panel = this._panels[this.current_panel - 1];

    this._update_active_control(this.current_panel, this._previous_panel);
    if (this.add_anchor) {window.location.hash  = this.content_prefix+'='+new_panel_id;}

    new_panel.show();
    new_panel.setStyle({left: (old_panel.offsetLeft + (params.get('direction')?1:-1)*old_panel.getWidth())+'px'});
    this._transition_effect = new Effect.Parallel([
      new Effect.Move(old_panel, {x: old_panel.getWidth()*(params.get('direction')?-1:1), sync: true, mode: 'relative'}),
      new Effect.Move(new_panel, {x: new_panel.getWidth()*(params.get('direction')?-1:1), sync: true, mode: 'relative'})
    ],
    {duration: effect_duration, fps: 50, queue: {position: 'end', scope: this._container_id}, afterFinish: function() {this._transition_effect = null;}.bind(this)});

    if (!params['skip']) {
      this._delay_offset  = 0;    // Reset the delay offset and start our normal period
      this._start_timer();
    }
  },
  _update_active_control: function(n, o) {
    var control_list;
    var i;
    // Update the current active panel control
    control_list  = this._controls[n];
    if (control_list) for (i = 0; i < control_list.length; i++) {control_list[i].addClassName('active');}
    control_list  = this._controls[o];
    if (control_list) for (i = 0; i < control_list.length; i++) {control_list[i].removeClassName('active');}
    // Update the next/prev controls if available
    control_list  = this._controls['ctrl_prev'];
    if (control_list) this._update_control_url(control_list, parseInt(n) - 1);
    control_list  = this._controls['ctrl_next'];
    if (control_list) this._update_control_url(control_list, parseInt(n) + 1);
  },
  _add_control: function(link) {
    var re        = new RegExp(this.content_prefix+'=(\\d+)');
    if (link.hasClassName('prev')) {
      this._fn_ctrl_observe(link, 'ctrl_prev');
    }
    else if (link.hasClassName('next')) {
      this._fn_ctrl_observe(link, 'ctrl_next');
    }
    else if (link.hasClassName('play') || link.hasClassName('start')) {
      this._fn_ctrl_observe(link, 'ctrl_play');
    }
    else if (link.hasClassName('pause')) {
      this._fn_ctrl_observe(link, 'ctrl_pause');
    }
    else if (link.hasClassName('stop')) {
      this._fn_ctrl_observe(link, 'ctrl_stop');
    }
    else {
      var mods      = this;
      var href      = link.readAttribute('href');
      var needle    = re.exec(href);
      if (needle != null) {
        if (this._controls[needle[1]] == null) {this._controls[needle[1]] = new Array();}
        this._controls[needle[1]].push(link);
      }
      link.observe('click', mods._fn_click);
    }
  },
  _update_control_url: function(control_list, new_url_id) {
    var re = new RegExp('(.*'+this.content_prefix+'=)(\\d+)(.*)');
    for (var i = 0; i < control_list.length; i++) {
      var index = this._wrap_panel_index(new_url_id);
      var href  = control_list[i].readAttribute('href');
      control_list[i].writeAttribute('href', href.replace(re, '$1'+index+'$3'));
    }
  },
  _wrap_panel_index: function(x) {
    return((x < 1)?this._panels.length:((x > this._panels.length)?1:x));
  },
  _fn_ctrl_observe: function(link, type) {
    var mods      = this;
    if (this._controls[type] == null) {this._controls[type]  = new Array();}
    this._controls[type].push(link);
    link.observe('click', mods._fn_ctrl_click);
  }
});
