/* Author:

*/

$(window).load(function() {
     $('#featured').orbit({
     animation: 'fade',                  // fade, horizontal-slide, vertical-slide, horizontal-push
     animationSpeed: 800,                // how fast animtions are
     timer: true,              // true or false to have the timer
     advanceSpeed: 3000,          // if timer is enabled, time between transitions 
     pauseOnHover: false,          // if you hover pauses the slider
     startClockOnMouseOut: false,      // if clock should start on MouseOut
     startClockOnMouseOutAfter: 1000,      // how long after MouseOut should the timer start again
     directionalNav: true,          // manual advancing directional navs
     captions: true,              // do you want captions?
     captionAnimation: 'fade',          // fade, slideOpen, none
     captionAnimationSpeed: 800,      // if so how quickly should they animate in
     bullets: true,             // true or false to activate the bullet navigation
     bulletThumbs: false,         // thumbnails for the bullets
     bulletThumbLocation: '',         // location from this file where thumbs will be
     afterSlideChange: function(){}      // empty function 
});
});

/*
$('#featured').orbit({
     animation: 'fade',                  // fade, horizontal-slide, vertical-slide, horizontal-push
     animationSpeed: 800,                // how fast animtions are
     timer: true,              // true or false to have the timer
     advanceSpeed: 4000,          // if timer is enabled, time between transitions 
     pauseOnHover: false,          // if you hover pauses the slider
     startClockOnMouseOut: false,      // if clock should start on MouseOut
     startClockOnMouseOutAfter: 1000,      // how long after MouseOut should the timer start again
     directionalNav: true,          // manual advancing directional navs
     captions: true,              // do you want captions?
     captionAnimation: 'fade',          // fade, slideOpen, none
     captionAnimationSpeed: 800,      // if so how quickly should they animate in
     bullets: true,             // true or false to activate the bullet navigation
     bulletThumbs: false,         // thumbnails for the bullets
     bulletThumbLocation: '',         // location from this file where thumbs will be
     afterSlideChange: function(){}      // empty function 
});

*/

//  --- Begin Config ---
var preloadSlides = 4;                // Number of slides to preload before showing gallery
var loadingMessageDelay = 2000;       // How long to wait before showing loading message (in ms)
var loadingMessageSpeed = 1200;       // Duration of each pulse in/out of the loading message (in ms)
var loadingMessageMinOpacity = 0.4;   // Minimum opacity of the loading message
var loadingMessageMaxOpacity = 1;     // Maximum opacity of the loading message
var leftKeyCode = 37;                 // Character code for "move left" key (default: left arrow)
var rightKeyCode = 39;                // Character code for "move right" key (default: right arrow)
var backgroundSlideOpacity = 1;     // Opacity of the slides either side of the current slide
//  --- End Config ---

var slideHorizMargin = 0;             // Number of pixels either side of each slide
var buttonHeight = 0;                 // Temporary store for the button heights
var currentSlide = 0;                 // The slide that the user is currently viewing
var totalSlides = 0;                  // Total number of slides in the gallery
var slides = new Array();             // Holds jQuery objects representing each slide image
var slideWidths = new Array();        // Holds the widths (in pixels) of each slide
var slideLoaded = new Array();        // True if the given slide image has loaded
var loading = true;                   // True if we're still preloading images prior to displaying the gallery

$( init );


// Set up the gallery once the document is ready

function init() {

  // Grab the horizontal margin between slides for later calculations
  slideHorizMargin = parseInt( $('#project-photos img').css('margin-right') );
  
  $('#leftButton').click(function(e) {
    e.preventDefault();
    moveLeft();
  });
  $('#rightButton').click(function(e) {
    e.preventDefault();
    moveRight();
  });

  // Hide the gallery and left/right buttons
  $('#project-photos').fadeTo( 0, 0 );
  $('#project-photos').css('top','-999em');
  buttonHeight = $('#leftButton').css('height');
  $('#leftButton').css('height',0);
  $('#rightButton').css('height',0);

  // If the requried number of slides haven't loaded after 'loadingMessageDelay' ms,
  // start fading in the loading message

  $('#loading').delay( loadingMessageDelay );
  fadeInLoadingMessage();

  // Bind the handleSlideLoad() handler function to each slide's load event
  $('#project-photos img').load( handleSlideLoad );

  // For each of the slide images:
  // 1. Hide the slide
  // 2. Record its serial number (0 = the first slide)
  // 3. Store it in the slides array
  // 4. Trigger the load event if the image is already cached (for IE and Opera)

  $('#project-photos img').each( function() {
    $(this).hide();
    $(this).data( 'slideNum', totalSlides );
    slides[totalSlides++] = $(this);
    if ( this.complete ) $(this).trigger("load");
    $(this).attr( 'src', $(this).attr('src') );
  } );

  // Bind the moveleft() and moveRight() functions to the
  // "move left" and "move right" keys on the keyboard

  $(document).keydown( function(event) {
    if ( event.which == leftKeyCode ) moveLeft();
    if ( event.which == rightKeyCode ) moveRight();
  } );
}

// Process each slide once it's finished loading

function handleSlideLoad() {

  // Record the slide's width in the slideWidths array
  slideWidths[$(this).data('slideNum')] = $(this).width();
  
  // Increase the gallery div's width to encompass this newly-loaded slide
  $('#project-photos').width( $('#project-photos').width() + $(this).width() + slideHorizMargin*2 + 256 );

  // Increase the gallery div's width to encompass this newly-loaded slide
  // $('#project-photos').width( $('#gallery').width() + $(this).width() + slideHorizMargin );

  // Record the fact that this slide has loaded in the slideLoaded array
  slideLoaded[$(this).data('slideNum')] = true;

  // Are we still preloading the slides?

  if ( loading ) {

    // Yes: Calculate how many slides we've now preloaded

    var preloaded = 0;

    for ( var i=0; i < preloadSlides; i++ ) {
      if ( slideLoaded[i] ) preloaded++;
    }

    // If we've preloaded enough slides, fade in the gallery and enable the left/right buttons

    if ( preloaded == preloadSlides || preloaded == totalSlides ) {
      $('#loading').clearQueue().stop().fadeTo('slow', 0 );
      $('#project-photos').css('top',0);
      $('#project-photos').fadeTo('slow', 1 );
      $('#leftButton').css('height',buttonHeight);
      $('#rightButton').css('height',buttonHeight);
      $('#leftButton').show();
      $('#rightButton').show();
      loading = false;
    }
  }
  $(this).fadeTo( 'slow', backgroundSlideOpacity );
}


// Move one slide to the left by sliding the gallery left-to-right

function moveLeft() {
  // Don't move if this is the first slide, or if we don't yet have a width for the previous slide
  if ( currentSlide == 0 ) return;
  if ( slideWidths[currentSlide-1] == undefined ) return;

  // Slide the whole gallery right so that the previous slide is now centred
  // var offset = slideWidths[currentSlide]/2 + slideHorizMargin*2 + slideWidths[currentSlide-1]/2;
  var offset = slideHorizMargin + slideWidths[currentSlide-1];
  $('#project-photos').animate( { left: '+=' + offset } );

  // Update the current slide index
  currentSlide--;
}


// Move one slide to the right by sliding the gallery right-to-left

function moveRight() {
  // Don't move if this is the final slide, or if we don't yet have a width for the next slide
  if ( currentSlide == totalSlides - 1 ) return;
  if ( slideWidths[currentSlide+1] == undefined ) return;

  // Slide the whole gallery left so that the next slide is now centred
  // var offset = slideWidths[currentSlide]/2 + slideHorizMargin*2 + slideWidths[currentSlide+1]/2;
  var offset = slideWidths[currentSlide] + slideHorizMargin;
  $('#project-photos').animate( { left: '-=' + offset } );

  // Update the current slide index
  currentSlide++
}

// Functions to pulse the loading message

function fadeInLoadingMessage() {
  $('#loading').animate( { opacity: loadingMessageMaxOpacity }, loadingMessageSpeed, 'swing', fadeOutLoadingMessage );
}

function fadeOutLoadingMessage(){
  $('#loading').animate( { opacity: loadingMessageMinOpacity }, loadingMessageSpeed, 'swing', fadeInLoadingMessage );
}
