$(document).ready(function() {
  $('div.dfo-switchbox').each(function() {
    // Use css to enforce, but set the number of boxes visible at a time here
    var visibleCount = 3;
    // Declare important vars
    var box = $(this);
    var items = box.find('div.dfo-switchbox-item');
    var content = $('<div class="dfo-switchbox-content" />').appendTo(box);
    var sliderOuter = $('<div class="dfo-switchbox-slider-outer" />').appendTo(box);
    var sliderSlider = $('<div class="dfo-switchbox-slider" />').appendTo(sliderOuter);
    var sliderInner = $('<div class="dfo-switchbox-slider-inner" />').appendTo(sliderSlider);
    var sliderPanel = $('<div class="dfo-switchbox-slider-panel" />').appendTo(sliderInner);
    var boxStatus = $('<div class="dfo-switchbox-status" />').appendTo(box);

    var leftButton = $('<div class="prev" />').appendTo(sliderSlider);
    var rightButton = $('<div class="next" />').appendTo(sliderSlider);

    var currentIndex = 0;

    var greenArrow = $('<div class="dfo-switchbox-activearrow" />');

    items.find('a.video').colorbox({iframe:true, opacity: 0.5, innerWidth:650, innerHeight:400});
    items.detach();

    box.css('display', 'block');

    var insertContent = function(item) {
      content.children().detach();
      content.append(item);
    };

    // Add the items to the slider.
    items.each(function(i) {
      var t = $(this);
      sliderPanel.append(
        $('<div class="slider-item" />').append(
          $('<div class="outer-button" />').append(
            $('<div class="button" />').append(
              $('<div class="inner-button" />').append(
                $('<img />').attr('src', t.attr('button-image'))
              )
            )
          )
        )
      );
    });

    // Make clickable each item with a links-to attribute
    items.each(function(i) {
      var t = $(this);
      var linkTo = t.attr('links-to');
      if (linkTo) {
        t.click(function() {
          window.location.href = linkTo;
        }).find('*').css('cursor','pointer');
      }
    });

    var setPanelWidth = function() {
      var panelWidth = 0;
      sliderPanel.children().each(function() {
        panelWidth += $(this).width();
      });
      sliderPanel.width(panelWidth);
    }

    var setCurrentIndex = function(i) {
      // The preferred offset is how many spaces from the left the current box 'wants' to be (0 means leftmost box).
      var preferredOffset = (Math.ceil(visibleCount / 2) - 1) | 0; // bitwise operators convert operands to 32-bit integers
      // Get all the item buttons
      var itemButtons = sliderPanel.children();
      // Make sure the index is valid
      if (i < 0) {
        i = 0;
      } else if (i >= itemButtons.size()) {
        i = itemButtons.size() - 1;
      }
      // Decide which item will be leftmost.
      var leftmostIndex = i - preferredOffset;
      if (leftmostIndex < 0) {
        leftmostIndex = 0;
      } else if (leftmostIndex > itemButtons.size() - visibleCount) {
        leftmostIndex = itemButtons.size() - visibleCount;
      }
      // Display the item
      insertContent(items.eq(i));
      // Give the current item the 'current' css class.
      itemButtons.removeClass('current').eq(i).addClass('current');
      // Update the box-status
      boxStatus.text((i + 1) + " of " + itemButtons.size());
      // Make sure the panel has the correct width.
      setPanelWidth();
      // Figure out how much negative padding the slider content needs
      var leftPadding = 0;
      itemButtons.slice(0, leftmostIndex).each(function() {
        leftPadding += $(this).width();
      });
      // Set the negative margin (formerly we were trying padding)
      sliderPanel.animate({
        marginLeft: -leftPadding
      }, 'fast');
      // Set the current index variable.
      currentIndex = i;
    }

    var movePrev = function() {
      setCurrentIndex(currentIndex - 1);
    }

    var moveNext = function() {
      setCurrentIndex(currentIndex + 1);
    }

    sliderPanel.children().each(function(index) {
      $(this).click(function() {
        setCurrentIndex(index);
      });
    });

    leftButton.click(movePrev);
    rightButton.click(moveNext);

    // Set the starting item to the first one.
    setCurrentIndex(0);
    $(sliderSlider, 'img').load(function() { setCurrentIndex(0) });
  });
});

