﻿/*
 * v1.0 written 3/10/2011 by Eddie Fuller
 * Code is property of Anedix Technologies, Inc 2011
 */
var holdme;

$(document).ready(function() {
  // first, we shall preload the images in our slideshow
  var images = new Array();
  
  $('.event-holder').find('img').each(function(x) {
    images[x] = $(this).attr('src');
  });
  preload(images);
  // end preload
  
  nextSlide(0);
  $('#event-slideshow').css('backgroundImage', 'none');
  $('#home-window').append('<div class="controlNav"></div>');
  var count = 0;
  $('.event-holder').each(function(i) {
    if(i == 0)
      $('.controlNav').append('<a class="active" id="nav'+i+'" href="'+i+'"></a>');
    else
      $('.controlNav').append('<a id="nav'+i+'" href="'+i+'"></a>');
    count = i + 1;
  });
  // Center the navigation based on how long the nav is
  $('.controlNav').css({'width': parseInt(25 * count)+ "px"});
  
  clearTimeout(holdme);
  if(count > 1) // no slideshow if there's only one slide
    holdme = setTimeout('nextSlide(1)', 5000);
  
  $('.event-holder').live('mouseenter mouseleave', function(e) {
    if(e.type == 'mouseenter')
    {
      clearTimeout(holdme);
    }
    else
    {
      holdme = $(this).index();
      if(count > 1) // no slideshow if there's only one slide
        holdme = setTimeout('nextSlide('+holdme+')', 5000);
    }
  });
  
  $('.controlNav a').live('click', function() {
    if($(this).hasClass('active')) return false;
    
    var clicked = parseInt($(this).attr('href'));
    clearTimeout(holdme);
    nextSlide(clicked);
    return false;
  });
});

function preload(images)
{
  $(images).each(function() {
    $('<img/>')[0].src = this;
  });
}

function nextSlide(current)
{
  var count = parseInt($('.event-holder').length - 1);
  current = parseInt(current);
  var next = current;
  var prev;
  var start = 0;
  var slide = $('div.event-holder');
  
  slide.each(function(i) {
  
    if($(this).css('display') == "none")
      ++start;
    else
      prev = i;
  });
  
  if(start == (count + 1))
  {
    slide.eq(0).fadeIn('slow');
    $('.controlNav a').removeClass('active').eq(0).addClass('active');  
    ++next;
  }
  else if(current == 0)
  {
//    slide.eq(count).fadeOut('slow', function() { 
    slide.eq(prev).fadeOut('slow', function() { 
      slide.eq(0).fadeIn('slow');
      $('.controlNav a').removeClass('active').eq(current).addClass('active');
    });
    ++next;
  }
  else
  {
    if(current == count) next = 0;
    else ++next;
    
//    slide.eq((current - 1)).fadeOut('slow', function() { 
    slide.eq(prev).fadeOut('slow', function() { 
      slide.eq(current).fadeIn('slow'); 
      $('.controlNav a').removeClass('active').eq(current).addClass('active');
    });
  }
  
  clearTimeout(holdme);
  holdme = setTimeout('nextSlide('+next+')', 5000);
}

