/**
 * @author Bruno Bornsztein <bruno@missingmethod.com>
 * @copyright 2007 Curbly LLC
 * @package Glider
 * @license MIT
 * @url http://www.missingmethod.com/projects/glider/
 * @version 0.0.3
 * @dependencies prototype.js 1.5.1+, effects.js
 */

/*  Thanks to Andrew Dupont for refactoring help and code cleanup - http://andrewdupont.net/  */

Glider = Class.create();
Object.extend(Object.extend(Glider.prototype, Abstract.prototype), {
	initialize: function(wrapper, options){
        this.handStopped = false;
	    this.scrolling  = false;
	    this.wrapper    = $(wrapper);
	    this.scroller   = this.wrapper.down('div.scroller');
	    this.sections   = this.wrapper.getElementsBySelector('div.sectionslide');
	    this.options    = Object.extend({ duration: 1.0, frequency: 3 }, options || {});
		this.direction  = 0;

	    this.sections.each( function(section, index) {
	      section._index = index;
	    });    

	    this.events = {
	      click: this.click.bind(this),
          mouseover: this.pause.bind(this),
          mouseout: this.resume.bind(this)
	    };

	    this.addObservers();
        if(this.options.initialSection) 
            this.moveTo(this.options.initialSection, this.scroller, { duration:this.options.duration });  // initialSection should be the id of the section you want to show up on load
        if(this.options.autoGlide) 
            this.start();
	  },
	
  addObservers: function() {
    this.wrapper.observe('mouseover', this.events.mouseover);
    this.wrapper.observe('mouseout', this.events.mouseout);
    
    var descriptions = this.wrapper.getElementsBySelector('div.sliderdescription');
    descriptions.invoke('observe', 'mouseover', this.makeActive);
    descriptions.invoke('observe', 'mouseout', this.makeInactive);
    
    var controls = this.wrapper.getElementsBySelector('div.slidercontrol a');
    controls.invoke('observe', 'click', this.events.click);

  },

  click: function(event) {
    var element = Event.findElement(event, 'a');
    
    if (this.scrolling) this.scrolling.cancel();
    this.moveTo(element.href.split("#")[1], this.scroller, { duration:this.options.duration });    	
    Event.stop(event);
  },

  moveTo: function(element, container, options) {
    this.current = $(element);
    Position.prepare();
    var containerOffset = Position.cumulativeOffset(container);
    var elementOffset = Position.cumulativeOffset(this.current);

    this.scrolling = new Effect.SmoothScroll(container, {
      duration:options.duration, 
      x:(elementOffset[0]-containerOffset[0]), 
      y:(elementOffset[1]-containerOffset[1])
    });
    
    if (typeof element == 'object')
        element = element.id;
        
    this.toggleControl($$('a[href="#'+element+'"]')[0]);
    
    return false;
  },
        
  next: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var nextIndex = (this.sections.length - 1 == currentIndex) ? 0 : currentIndex + 1;      
    } else var nextIndex = 1;

    this.moveTo(this.sections[nextIndex], this.scroller, { 
      duration: this.options.duration
    });

  },

  /*fadeIn: function(id){
    var target = $(id);
    if (target.style.display == "none"){
        this.current = this.getNode(id);
        target.setStyle({ 'display': 'none', 'zIndex': this.z++ });
        new Effect.Appear(target, { duration: 0.5, afterFinish:this.disarm.bindAsEventListener(this) });
        this.select(id);
    }
  },*/

  rotate: function(){
    if (this.current) {
      var currentIndex = this.current._index;
	  if (this.sections.length - 1 == currentIndex) {
		  this.direction = this.direction == 1 ? 0 : 1;
	  }else if( currentIndex == 0 )
		  this.direction = this.direction == 1 ? 0 : 1;

	  if( this.direction == 0)
		var	nextIndex = currentIndex + 1;      
	  else
		var	nextIndex = currentIndex - 1;      
	  
    } else {
		var nextIndex = 1; 
	}

    this.moveTo(this.sections[nextIndex], this.scroller, { 
      duration: this.options.duration
    });

  },
	
  previous: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var prevIndex = (currentIndex == 0) ? this.sections.length - 1 : 
       currentIndex - 1;
    } else var prevIndex = this.sections.length - 1;
    
    this.moveTo(this.sections[prevIndex], this.scroller, { 
      duration: this.options.duration
    });
  },
  
  makeActive: function(event)
  {
    var element = Event.findElement(event, 'div');
    element.addClassName('active');
  },
  
  makeInactive: function(event)
  {
    var element = Event.findElement(event, 'div');
    element.removeClassName('active');
  },
  
  toggleControl: function(el)
  {
    $$('.slidercontrol a').invoke('removeClassName', 'active');
    el.addClassName('active');
  },

	stop: function()
	{
        this.handStopped = true;
		clearTimeout(this.timer);
	},
	
	start: function()
	{
        this.handStopped = false;
		this.periodicallyUpdate();
	},
    
    pause: function()
    {
      if (!this.handStopped) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    },
    
    resume: function()
    {
      if (!this.handStopped)
        this.periodicallyUpdate();
    },
		
	periodicallyUpdate: function()
	{ 
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.rotate();
		}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency*1000);
	}

});

Effect.SmoothScroll = Class.create();
Object.extend(Object.extend(Effect.SmoothScroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext=true;
      this.element.appendChild(this.element.firstChild);
    }
   
    this.originalLeft=this.element.scrollLeft;
    this.originalTop=this.element.scrollTop;
   
    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } 
  },
  update: function(position) {   
    this.element.scrollLeft = this.options.x * position + this.originalLeft;
    this.element.scrollTop  = this.options.y * position + this.originalTop;
  }
});

var Highlights = Class.create({
  initialize: function(holder, name, loaded) {
  	this.holder = holder;
	this.name = name;
	//this.data = data;
	this.timer;
	this.loaded = loaded;
	this.length = loaded;
	//this.action = action;
	//this.section = section
	//this.apiCall(this.action);
	//(!data) ? this.apiCall(this.action) : this.create();
	this.start(0);
  },
  /*apiCall: function(action, params){
    var options = { method : 'post', parameters : 'r=feed/highlight&section='+ this.section, onSuccess: this.onComplete.bindAsEventListener(this) };
    new Ajax.Request(Loader.AJAX_PATH + 'index.php', options);
  },
  onComplete: function(transport) {
  	var json = transport.responseJSON;
  	this.data = json.items;
  	this.length = json.length;
  	this.create();
  },*/
  version: '0.0.1',
  z: 0,
  duration: 7000,
  current: -1,
  loaded: 0,
  n: 0,
  status: false,
  create: function(){
	var target = $(this.holder).update("");
	var ul_controls = new Element('ul', { 'id': this.holder + '-controls' });
	var div_images = new Element('div', { 'id': this.holder + '-images' });
	
	target.appendChild(div_images);
	target.appendChild(ul_controls);
	
	this.addImage(this.loaded);
	
	var tmp_a = new Element('a', { href: 'javascript:' + this.name + '.pause();', 'id': 'highlights-pause' }).update("");
	var play = new Element('li', { 'id': this.holder + '-control-play', 'class': 'right' }).update(tmp_a);
	ul_controls.appendChild(play);
	
	this.start(0);
  },
  
  play: function(){
	if (this.status == false){
		this.start(0);
		/*var play = $(this.holder + '-control-play').getElementsByTagName('a')[0];
		play.id = "highlights-pause";
		play.writeAttribute('href', 'javascript:'+this.name+'.pause()');
		play.update("");*/
	}
  },
  	
  pause: function(){
	this.status = false;
	clearTimeout(this.timer);
	/*var play = $(this.holder + '-control-play').getElementsByTagName('a')[0];
		play.id = "highlights-play";
	play.writeAttribute('href', 'javascript:'+this.name+'.play()');
	play.update("");*/
  },
 
  start: function(d){
	this.status = true;
	this.timer = setTimeout(this.next.bindAsEventListener(this), d);
  },
  
  next: function(){
	this.current++;
	if (this.current >= this.loaded) this.current = 0;
	this.fadeIn(this.holder + "-" + this.current);
	this.start(this.duration);
  },
 
  addImage: function(id){
	  var target = $(this.holder);
	  var div_images = $(this.holder + "-images");
	  var ul_controls = $(this.holder + "-controls");
	  var tmp_link = new Element('a', { 'href': this.data[id].link, 'target' : '_blank' });
	  var tmp_img = new Element('img', { 'id': this.holder + "-" + id });
	  tmp_img.onload = this.loader.bindAsEventListener(this);
	  tmp_img.setStyle({ 'display': 'none' });
	  tmp_link.appendChild(tmp_img)
	  div_images.appendChild(tmp_link);
	  tmp_img.src = this.data[id].image;
	  var nm = (this.data[id].ad == true) ? "A" : this.n+1;
	  if (this.data[id].ad != true) this.n++;
	  var tmp_a = new Element('a', { href: "javascript:" + this.name + ".view('" + this.holder + "-" + id + "');"}).update(nm);
	  var tmp_li = new Element('li', { 'id': this.holder + "-control-" + id }).update(tmp_a);
	  ul_controls.appendChild(tmp_li);
	  },
  
  loader: function(){
	if (this.loaded < (this.length-1)){
		this.loaded++;
		this.addImage(this.loaded);
	}
  },
  	
  view: function (id){
  	this.pause();
  	this.fadeIn(id);	
  },
  
  fadeIn: function(id){
	var target = $(id);
	if (target.style.display){
		if (target.style.display == "none"){
			this.current = this.getNode(id);
			this.disarm();
			target.setStyle({ 'display': 'none', 'zIndex': this.z++ });
			new Effect.Appear(target, { duration: 1.0, afterFinish:this.disarm.bindAsEventListener(this) });
			this.select(id);
		}
	}
  },
	
  disarm: function(){
	for (var i = 0; i < this.loaded; i++){
		var image = $(this.holder + "-" + i);
		if (this.current != i && image) image.setStyle({ 'display': 'none' });
	}
	if(this.status == false){
		this.start(this.duration);
		this.status = true;
	}
  },
  
  select: function(id){
	var n = this.getNode(id);
	for (var i = 0; i < this.loaded; i++){
		var target = $(this.holder + "-control-" + i).getElementsByTagName("a")[0];
		(i != n) ? target.removeClassName('active') : target.addClassName('active');
	}
  },
  
  getNode: function(id){
	var n = id.split("-");
	n = n[n.length-1];
	return n;
  }

});
