var global = this;
var THAFLOW = THAFLOW || {}; 

THAFLOW.init = function (config) {
  this.container = $(config.container);
  this.contr_container = $(config.contr_container);
  this.duration = parseInt(config.duration);
  this.transition = parseInt(config.transition);   
  this.sleep = (parseInt(config.sleep) - this.duration);    
  this.frameWidth = parseInt(this.container.parent().css("width"));
  this.slides = this.container.children();
  this.startSlide();
  this.modifier = -1;
  this.active = 0;

  // build controls
  this.slides.each(function (i, e) {
    // prak an id on the slides
    $(e).attr("id", "slide" + i);
    $("<a/>")
      .attr("href", "#")
      .attr("id", "slidebtn" + i)
      .text(i + 1)
      .click(function (e) {
        e.preventDefault();
        THAFLOW.panToSlide(i);
      })      
      .appendTo(THAFLOW.contr_container);
  });
  $("#slidebtn0", THAFLOW.contr_container).addClass("active");
};

THAFLOW.panToSlide = function (slide) {
  THAFLOW.stopSlide();
  this.container.animate({"left": (slide * this.frameWidth) * -1},
    this.transition, "linear",
    function () {
      $("a", THAFLOW.contr_container).each(function(i, e){
        $(e).removeClass('active');
      })    
      $("#slidebtn" + slide, THAFLOW.contr_container)
        .addClass("active");
      THAFLOW.active = parseInt(slide)*-1;    
      if (THAFLOW.sleepAfterPan) {
        clearInterval(THAFLOW.sleepAfterPan);
        THAFLOW.sleepAfterPan = null;
      };
      THAFLOW.sleepAfterPan = setTimeout(function () {
        THAFLOW.startSlide();
      }, THAFLOW.sleep);
      
    });
};

THAFLOW.animateSlide = function () {
  var pos = parseInt(this.container.css("left"));
  if (Math.abs(pos) === ((this.slides.length - 1) * this.frameWidth)) {
    this.modifier = 1;
  } else if (pos === 0) {
    this.modifier = -1;
  };
  this.container.animate({"left": (pos + (this.modifier * this.frameWidth))},
    this.transition, "linear",
    function () {
      THAFLOW.active += THAFLOW.modifier;
      $("a", THAFLOW.contr_container).each(function(i, e){
        $(e).removeClass('active');
      })
      $("#slidebtn" + Math.abs(THAFLOW.active), THAFLOW.contr_container)
        .addClass("active");
    });
};

THAFLOW.startSlide = function () {
  if (!this.loop) {
    // if we have more than one of these things go fubar
    this.loop = setInterval(
      function () {THAFLOW.animateSlide()}, THAFLOW.duration);
  };
}; 

THAFLOW.stopSlide = function () {
  clearInterval(this.loop);
  this.loop = null;
};


