Ctmol.ScrollGallery = function(delay,duration) {
    this.delay = delay || 2000;
    this.duration = duration || 300;
    this.setup();
}

Ctmol.ScrollGallery.prototype = {
    setup: function() {
        var self = this;
        self.container = $(".scroll-gallery");
        self.items = $(".gallery-items",self.container);
        if(Browser.isIE6){
          self.items.each(function(){
              var $this = $(this).find(".cmt");
              if($this.length>0){
                var span = $(document.createElement("span"))
                              .addClass("ie-bg")
                              .css("height",$this.height()+"px")
                              .appendTo($this.parent())
                $this.addClass("ie-no-bg");
                $this.hover(function(){ $(this.parentNode).find(".ie-bg").addClass("ie-no-transp");  },function(){ $(this.parentNode).find(".ie-bg").removeClass("ie-no-transp"); })
              }
          })
        }


        self.drawNavBar();
        self.goTo(1);
        self.resetTimer();
    },
    resetTimer: function() {
        var self = this;
        if (self.timer) window.clearInterval(self.timer);
        self.timer = window.setInterval(function() { self.goToNext(); }, self.delay);
    },
    drawNavBar: function() {
        var self = this;
        self.navBar = $("<div class='gallery-nav'></div>").appendTo(self.container);
        self.imageCount = 0;
        self.currentPos = 0;
        $("img",self.items).each(function(i) {
            var j = i + 1;
            if (!self.imageWidth) {
                self.imageWidth = this.width;
            }
            $("<span class='"+j+"'>"+j+"</span>").click(function() { self.goTo(this.className*1,true); }).appendTo(self.navBar);
            self.imageCount ++;
        });
        //self.items.width(self.imageWidth);
    },
    goToNext: function() {
        var self = this;
        var k = self.currentPos + 1;
        if (k > self.imageCount) {
            k = 1;
        }
        self.goTo(k);
    },
    goTo: function(k,reset) {
        var self = this;
        if (k != self.currentPos) {
            $(".active", self.navBar).removeClass("active");
            $("."+k, self.navBar).addClass("active");
            self.currentPos = k;
            self.items.stop(true,true).animate({scrollLeft: (k - 1)*self.imageWidth}, self.duration);
            if (reset) {
              self.resetTimer();
            }
        }
    }
}
