var bannerSpeed = 10000;    // How fast the tabs will change
var timer;

/* Method to switch from one tab to another
 *  tab - (jQuery object), selected control "button"
 *  animate - (boolean), whether or not animation (fade-in/fade-out) should be used
 * Returns:
 *  false - if tab doesn't exist
 *  true - otherwise
 */
function bannerActivate(tab, animate) {
  if (timer) clearTimeout(timer);       // Reset the timer if it was set previously

  tabId = tab.find("a").attr("href");   // Get the id of the div with the tab content
  if (!tabId) {                         // If the div with such id doesn't exist
    return false;                       // Stop executing
  }

  // Deactivate all control "buttons"
  $(".banner-container .controls li").removeClass("active");

  /* If animation is enabled, fade-out the main block, copy the html-code from selected tab
   * to the main block, and fade-in the main block */
  if (animate) {
    $(".banner-container .banner").fadeOut("slow", function(event) {
      $(".banner-container .banner").html($(tabId).html());
      return false;
    }).fadeIn("slow");
  } else {                              // Otherwise simply copy the html-code
    $(".banner-container .banner").html($(tabId).html());
  }

  // Activate the control "button"
  tab.addClass("active");

  // Find the next tab to display
  nextTab = tab.next();
  if (nextTab.length == 0) {            // If the next tab doesn't exist, start from the first one
    nextTab = $(".banner-container .controls li").first();
  }

  timer = setTimeout(function() { bannerActivate(nextTab, true); }, bannerSpeed);
  return true;
}

$(document).ready(function(){
  var tab = $(".banner-container .controls li").first();
  bannerActivate(tab, false);

  $(".banner-container .controls li").click(function(){
    bannerActivate($(this), true);
    return false;
  });
});

