var currentOffset = 0;
var switchedMarginLeft = null;
var productWidth = null
var productsDivWidth = null
var maxOffset = null;

function moveHomeProducts(px) {
  currentOffset = parseInt($("#products ul").css('left').replace('px',''));
  if(px > 0) {
    if(currentOffset == 0) {
      $("#products ul").animate({left: -1 * (maxOffset - switchedMarginLeft - productWidth)}, 1000);
    } else {
      $("#products ul").animate({left: "+=" + (productsDivWidth - switchedMarginLeft)}, 1000);
    }
  } else {
    if((currentOffset + px - switchedMarginLeft) <= (-1 * maxOffset)) {
      $("#products ul").animate({left: 0}, 1000);
    } else {
      $("#products ul").animate({left: "-=" + (productsDivWidth - switchedMarginLeft)}, 1000);
    }
  }
}

function advanceMarket() {
  items = $("#market-selector a");
  numItems = items.length;
  activeItem = $("#market-selector a.active");
  activeIndex = items.index(activeItem);

  if(activeIndex == (numItems - 1)) {
    $("#market-selector a:first").click();
  } else {
    $(items[activeIndex + 1]).click();
  }
}

function setUpHomePage() {
  // Set up the homepage feature selector
  $("#market-selector a").click(function(){
    $("div.market-slide").removeClass("active");
    $("#slide-" + $(this).attr("rel")).addClass("active");
    $("#market-selector a").removeClass("active");
    $(this).addClass("active");
    return false;
  });

  // Show the first feature
  $("#market-selector a:first").click();

  // Set up a timer
  setInterval("advanceMarket()", 4000);

  productsDiv= $("#products");
  productsDivWidth = productsDiv.width();
  firstChild = $("#products li:first-child");
  var products = $("#products li");
  productsSwitched = $("#products li.switch-1");
  switchedMarginLeft = (parseInt(firstChild.css('margin-left').replace('px','')));
  productWidth = firstChild.width();
  maxOffset = (productWidth * products.length) + (productsSwitched.length * switchedMarginLeft);
  $("#products ul").css({width: maxOffset + "px"});
  $("#products a.move-left").click(function(){
    moveHomeProducts(productsDivWidth);
    return false;
  });
  $("#products a.move-right").click(function(){
    moveHomeProducts(-1 * productsDivWidth);
    return false;
  });
}

