(function($) {
  $(document).ready(function() {
    
    var $ = jQuery;
    
    //TODO: put in $.ready()

    var items = $('#homescroller2 .box');
    var container = items.parent();
    container.css({overflow: 'hidden', position: 'relative'});

    //find the number of boxes to add.
    if(items.length % 4) {
      var num_to_add = 4 - items.length % 4;
    }

    for(var i =0; i < num_to_add; ++i) {
      container.append('<div class="box"/>');
    }

    //recollect the items.
    items = $('#homescroller2 .box');

    var BOX_WIDTH = items.width() + 21;
    var NEG_BOX_WIDTH = -1 * BOX_WIDTH;
    var SUM_BOX_WIDTHS = BOX_WIDTH * items.length;

    items.each(function(index) {
      $(this).css({position: 'absolute', left: index * BOX_WIDTH});
    });

    /**
     * Scrolls the boxes to the left
     */
    function scroll_left() {
      //don't move any more if we are alredy moving.
      if(items.queue().length) { return; }
      
      //pre position boxes
      items.each(function() {
        var left = parseInt($(this).css('left'), 10);
        if(left < 0) {
          var pos = left / NEG_BOX_WIDTH;
          var new_left = SUM_BOX_WIDTHS - (pos * BOX_WIDTH);
          $(this).css({left: new_left});
        }
      });
      
      //animate the images.
      items.animate({left: '-='+ (BOX_WIDTH * 4)});
    }

    /**
     * Scrolls the boxes to the right.
     */
    function scroll_right() {
      //don't move any more if we are alredy moving.
      if(items.queue().length) { return; }
      
      //pre position boxes
      items.each(function() {
        var left = parseInt($(this).css('left'), 10);
        if(left > BOX_WIDTH * (items.length - 5)) {
          var pos = (left - (BOX_WIDTH * (items.length - 5))) / BOX_WIDTH;
          var new_left = (5 - pos) * NEG_BOX_WIDTH;
          $(this).css({left: new_left});
        }
      });
      
      //animate the images.
      items.animate({left: '+='+ (BOX_WIDTH * 4)});
    }

    var controls = $('#homescroller2 .controls');
    controls.css({cursor: 'pointer'});

    controls.hover(
      function() { var img = $(this).find('img'); img[0].src = img[0].src.replace(/homearrow_([lr])/, 'homearrow_$1_mo'); },
      function() { var img = $(this).find('img'); img[0].src = img[0].src.replace('_mo.', '.'); }
    );

    var left = $(controls[0]);
    var right = $(controls[1]);

    right.click(scroll_left);
    left.click(scroll_right);

  });

})(jQuery);

