var totalTime = 500;
var scrollingError = "There has been an error with the scroller. All other functionality should be working fine.";

var currentSlideable = 0;
var totalSlides = 0;

var showSlideableById = function(id) {
  // the following 'substring' is based on a span id of 'slideable[0-9]+'
  var index = new Number((new String(id)).substring(9));
  showSlideable(index);
};

var showSlideable = function(index) {
  if (Number(index) == Number(currentSlideable)) return;
  var slideTime = Math.abs(totalTime / (currentSlideable - index));

  var direction = (index < currentSlideable ? -1 : 1);
  var slideOutFunction = (direction == 1 ? "SlideOutLeft" : "SlideOutRight");
  var slideInFunction = (direction == 1 ? "SlideInRight" : "SlideInLeft");

  var recursiveScroller = function(current) {
    if (current != index) {
      try {
	$($("div.slideable").get(current))[slideOutFunction](slideTime);
	$($("div.slideable").get(current + direction))[slideInFunction](slideTime, function() {
	    recursiveScroller(current + direction);
	  });
      } catch (e) {
	alert(scrollingError);
      }
    }
  };

  recursiveScroller(currentSlideable);

  currentSlideable = index;
};

var onLoadInit = function() {
  if ($("div.slideable").size() > 0) {
    totalSlides = $("div.slideable").size();
    var newSpans = "<span id=\"slidePrev\"><span>&lt;</span></span>";
    $("div.slideable").each(function(f) {
	newSpans += "<span id=\"slideable" + f + "\"><span>" + (f + 1) + "</span></span>";
      });

    newSpans += "<span id=\"slideNext\"><span>&gt;</span></span>";

    $(document.body).prepend(newSpans);
    $("div.slideable").hide();
    $("div.slideable:eq(0)").show();
    $("span[@id^='slideable']").each(function(f) {
	$(this).click(function() { showSlideableById($(this).attr("id")); })
	  .addClass("slideable");
      });
    $("span[@id='slidePrev']").click(function() { showSlideable((currentSlideable + totalSlides - 1) % totalSlides); });
    $("span[@id='slideNext']").click(function() { showSlideable((currentSlideable + totalSlides + 1) % totalSlides); });
  }
};

$(onLoadInit);
