/// <reference path="jquery-1.4.1-vsdoc.js" />

var timer = null;
var sliderDelay = 7500;
var sliding = false;

$(function()
{
  $('[id|=sliderPanel]').slice(1).hide();
  $('[id|=textPanel]').slice(1).hide();

  $('[id|=sliderPanel]').mouseenter(stopAdvance);
  $('[id|=sliderPanel]').mouseleave(startAdvance);
  $('[id|=textPanel]').mouseenter(stopAdvance);
  $('[id|=textPanel]').mouseleave(startAdvance);

  $('#goLeft :first-child').click(function() { stopAdvance(); advanceSlider(-1); });
  $('#goRight :first-child').click(function() { stopAdvance(); advanceSlider(1); });

  timer = setTimeout('advanceSlider(1)', sliderDelay);
});

function stopAdvance()
{
  if (timer != null)
  {
    clearTimeout(timer);
    timer = null;
  }
}

function startAdvance()
{
  timer = setTimeout('advanceSlider(1)', sliderDelay);
}

function advanceSlider(dir)
{
  if (sliding)
    return;
      
  var current = $('[id|=sliderPanel]:visible').first();
  var length = $('[id|=sliderPanel]').length;
  if (length == 0)
    return;

  if (dir == null || dir == 0)
    dir = 1;
    
  var nextIndex = $('[id|=sliderPanel]').index(current) + dir;
  if (nextIndex < 0)
    nextIndex = length - 1;
  else if (nextIndex >= length)
    nextIndex = 0;
  var next = $('[id|=sliderPanel]:eq(' + nextIndex + ')');
  
  var curId = current.attr('id').substr(12);
  var nextId = next.attr('id').substr(12);
  var l = next.width();
  if (dir < 0)
    l = -l;

  sliding = true;
  next.css('left', l + 'px');
  next.show();
  current.animate({ left: -l }, 1000, function() { $(this).hide(); });
  next.animate({ left: 0 }, 1000);

  $('#textPanel-' + curId).fadeOut(1000);
  $('#textPanel-' + nextId).fadeIn(1000, function() { sliding = false; });
  
  timer = setTimeout('advanceSlider(1)', sliderDelay);
}
