// Main SDBW JavaScript

var SDBW = window.SDBW || {};

// SDBW.AutoScroller
// 
//  Automatically scrolls through list of items, e.g. Twitter posts
//  Requires: jQuery 1.3+
// 

SDBW.AutoScroller = function() {
  var list_element,current_element,last_child,timeout,delay;

  var setAutoScroll = function() {
    timeout = setTimeout(function(){
      scrollTo(nextElement());
      if (current_element.attr('id') != last_child.attr('id')) {
        setAutoScroll();
      }
    }, delay);
  }

  var nextElement = function() {
    return current_element.next();
  }

  var prevElement = function() {
    return current_element.prev();
  }

  var stopAutoScroll = function() {
    window.clearTimeout(timeout); delete(timeout);
  }

  var scrollTo = function(element) {
    var element = $(element);
    if (element) {
      current_element = element;
      var elements_height = $.map(current_element.prevAll(), function(elem){
        return $(elem).outerHeight();
      });
      var scrollTop = $.sum(elements_height);
      list_element.animate({
        'scrollTop': scrollTop
      }, 500);
    }
  }

  return {
    // Options (object): id (required) & delay (optional)
    initialize: function(options) {
      var options = options || {}
      var element_id = /^#/.test(options.id) ? options.id : '#' + options.id;
      delay = options.delay || 1000;
      list_element = $(element_id);
      if (list_element) {
        current_element = $(element_id + ' > li:first-child');
        last_child = $(element_id + ' > li:last-child');
        setAutoScroll();
      }
    },
    prev: function() {
      scrollTo(prevElement());
      stopAutoScroll();
    },
    next: function() {
      scrollTo(nextElement());
      stopAutoScroll();
    }
  }
}();

jQuery.sum = function (arr){
  var sum = 0;
  for (i = 0; i < arr.length; i++) {
      sum += arr[i]
  }
  return sum;
}