/*
Script: psCarousel.js
  The Perity Studios Carousel utlizing MooTools 1.2.1

License:
  MIT-style license.

Copyright:
  Copyright (c) 2009 [Nathaniel Brown](http://nshb.net/).
*/

var psCarousel = new Class( {
  Implements : [Options], 
  
  container : false,
  scroller : false,
  gallery_holder : false,
  frames : [],
  buttons : [],
  images : {},
  in_progress : false,
  animate_effect : false,
  animate_offset : 0,
  container_width : 0,
  container_height : 0,
  
  options : {
    current_frame : 1,
    last_current_frame : 1,
    go_to_frame : false,
    total_frames : 0,
    effect_transition: Fx.Transitions.Circ.easeInOut,
    effect_duration: 1000
  },
  
  _track_click : function() {
    var gallery = $('gallery').get('gallery_title');
    var frame = this.options.current_frame;
    var url = '/ajax/gallery/' + gallery + '/' + frame;

    // Google
    try {
      pageTracker._trackPageview(url);
    } catch (e) {}
    
    // Get Clicky
    try {
      var clicky_custom = {};
      clicky_custom.href = url;
      clicky_custom.title = 'Gallery: ' + gallery + ', Frame: ' + frame;
      clicky_custom.type = 'pageview'; // outbound, download, click, pageview
      clicky.log( clicky_custom.href, clicky_custom.title, clicky_custom.type );
    } catch (e) {
    }
     
    try {
      var id = '258'; // Viewed New Gallery Page
      var revenue = '';
      clicky.goal( id, revenue );
    } catch (e) {
    }
  },
  
  initialize : function(container, scroller, options) {

    this.container = $(container);
    this.scroller = $(scroller);
    
    // Add the options embedded in the container
    var current_frame = this.container.getProperty('current');
    var go_to_frame = this.container.getProperty('go');
    
    if (current_frame) this.options.current_frame = current_frame.toInt();
    if (go_to_frame) this.options.go_to_frame = go_to_frame.toInt();
    
    this.setOptions(options);
    
    this.gallery_holder = this.container.getElement('.gallery_holder');
    
    this.gallery_holder.setStyles( { 'position': 'absolute', 'top': '0px', 'left' : '0px' } );

    this.container_width = this.container.getSize().x;
    this.container_height = this.container.getSize().y;

    // Add all buttons from the scroller
    this.add_buttons(this.scroller);
    
    // add all the frames from the gallery container
    this.add_frames(this.container);

    this.animate_effect = new Fx.Tween(this.gallery_holder, 'left', {
      transition: this.options.effect_transition,
      duration: this.options.effect_duration,
      onStart: function () { this.in_progress = true; }.bind( this ),
      onComplete: function () { this.in_progress = false; }.bind( this ),
      wait: true
    });

    // Check if we should go straight to a frame
    // Make sure it's legit and were not already on it
    if (this.options.go_to_frame && this.options.go_to_frame > 0 && this.options.go_to_frame != this.options.current_frame) {
      this.go_to(this.options.go_to_frame);
    }
  },
  
  next : function() {
    // check whether we are at the end, if so start at the beginning
    if (this.options.current_frame + 1 > this.options.total_frames) {
      // we are at the start, so start at the end
      var next_frame = 1;
    } else {
      var next_frame = this.options.current_frame + 1;
    }
    
//    alert('Next frame: ' + next_frame + ', Current Frame: ' + this.options.current_frame + ', Total Frames: ' + this.options.total_frames);
    this.options.last_current_frame = this.options.current_frame;
    this.options.current_frame = next_frame;

    this._go_to_current_frame();
  },
  
  previous : function() {
    // check whether to go back one, or cycle and start at the end
    if (this.options.current_frame - 1 < 1) {
      // we are at the start, so start at the end
      var previous_frame = this.options.total_frames;
    } else {
      var previous_frame = this.options.current_frame - 1;
    }
    
//    alert('Previous frame: ' + previous_frame + ', Current Frame: ' + this.options.current_frame + ', Total Frames: ' + this.options.total_frames);

    this.options.last_current_frame = this.options.current_frame;
    this.options.current_frame = previous_frame;

    this._go_to_current_frame();
  },
  
  go_to : function(frame) {
    frame = frame.toInt();
    
    if (frame < 1 || frame > this.options.total_frames) {
      // we are at an invalid frame, start at the beginning
      var go_to_frame = 1;
    } else {
      var go_to_frame = frame;
    }

    this.options.last_current_frame = this.options.current_frame;
    this.options.current_frame = go_to_frame;
    
    this._go_to_current_frame();
  },
  
  _go_to_current_frame : function() {
    // make sure the images and such are loaded in that frame
    this._load_current_frame();

    // update the scroller
    this._update_scroller();
    
    // after the frame is loaded, animate to it
    this._animate_to_current_frame();
    
    // track this via analytics
    this._track_click();
  },
  
  _update_scroller : function() {
    // change the button frame to active css class and remove the previous active class if there was one
    this.buttons[this.options.last_current_frame].removeClass('active').addClass('inactive');
    
    // change the new frame button to active and remove old style
    this.buttons[this.options.current_frame].addClass('active').removeClass('inactive');

    // scroll to it just in case it's not in view
    var scroll_fx = new Fx.Scroll(this.scroller).toElement(this.buttons[this.options.current_frame]);
  },
  
  _load_current_frame : function() {
    var images = this.images[this.options.current_frame];
    
    images.each(function(image) {
      tmpHref = image.getProperty('href');
      
      if( tmpHref ) {
        image.setProperty('src', tmpHref);
      }
    });
  },
  
  _animate_to_current_frame : function() { 
    if( this.options.current_frame > this.frames.length || this.options.current_frame < 0 || this.in_progress ) {
      return false;
    }
    var animate_to = ((-1 * (this.options.current_frame - 1) * this.container_width) - this.animate_offset) + 'px';
    
    this.animate_effect.start('left', animate_to);
  },
  
  add_buttons : function(obj) {
    var carousel = this;
    var frame_id = 0;
    
    obj.getElements('.button').each(function(button, frame_id) {
      frame_id += 1;
      
      // increase the total count of frames
      carousel.options.total_frames++;
      
      // add frame to internal list
      carousel.buttons[frame_id] = button;

      button.addEvent('click', function(evt) {
        evt.stop();
        carousel.go_to(frame_id);
      });
    });
  },
  
  add_frames : function(obj) {
    var carousel = this;
    var frame_id = 0;
    
    var gallery_total_width = this.container_width * this.options.total_frames;
    this.animate_offset = (-1 * (this.options.current_frame - 1)) * this.container_width;
    var frame_offset = (-1 * (this.options.current_frame - 1)) * this.container_width;
    
    this.gallery_holder.setStyle('width', gallery_total_width + 'px');
    
    obj.getElements('.frame').each(function(frame, frame_id) {
      frame_id += 1;
      carousel.images[frame_id] = [];
      
      // set the default offset
      frame.setStyles({ 'position' : 'absolute', 'top' : '0px', 'left' : frame_offset + 'px' });
      
      // preload the images into an internal array to be updated when go_to_frame is executed
      frame.getElements('img').each(function(img) {
        carousel.images[frame_id].include(img);
      });
      
      // increment the next frame the width of the container
      frame_offset += carousel.container_width;
      
      // add frame to internal list
      carousel.frames.include(frame);
    });
  }
});


window.addEvent( 'domready', function() {
  // createa a new pCarousel object with the container id
  var perity_carousel = new psCarousel(_container = $('gallery'), _frames = $('scroller'));
  
  // add the next frame button
  $$('#page_turner .direction').addEvent( 'click', function(evt) {
    evt.stop();
    if (this.hasClass('next')) perity_carousel.next();
    if (this.hasClass('previous')) perity_carousel.previous();
  });

  // Add next button to all right images
  $$('.gallery_page .image').addEvent( 'click', function(evt) {
    evt.stop();
    if (this.hasClass('right') || this.hasClass('landscape')) perity_carousel.next();
    if (this.hasClass('left')) perity_carousel.previous();
  });
});