/**
 * cMASS Scroll Ticker
 *
 * @author    Nemanja Nikolic
 * @copyright MASSVision 2011
 */
cmassScroll = {
   duration: {},
   delay: {},
   step: {},
   direction: {},
   paused: {},
   init: function(id, duration, step, delay, direction) {
      var self = this;
      this.duration[id] = duration;
      this.delay[id] = delay;
      this.step[id] = step;
      this.direction[id] = direction;
      $('#'+id).addClass('cmassScroll').find('li').each(function(index) {
         $(this).width($('#'+id).width())
                .height($('#'+id).height())
                .css(self.direction[id] == 'v' ? 'top' : 'left',
                     index ? (self.direction[id] == 'v' ? $('#'+id).height() : $('#'+id).width()) : 0)
                .find('a').each( function() {
                     $(this).hover(
                        function() { self.pause(id);  },
                        function() { self.resume(id); }
                     )
                 });
      });
      this.scrollMe(id, 0);
   },
   scrollMe: function(id, index) {
      var self = this;
      var listItems = $('#'+id).find('li').toArray();
      var prev = listItems[index > 0 ? index-1 : listItems.length-1];
      var current = listItems[index];
      var nextIndex = ++index < listItems.length ? index : 0;
      var next = listItems[nextIndex];
      var dimType = this.direction[id] == 'v' ? 'top' : 'left';
      var dimVal  = this.direction[id] == 'v' ? $('#'+id).height() : $('#'+id).width();
      $(prev).css(dimType, dimVal);
      this.animate(id, $(current), dimType, 0, -dimVal, function() { self.scrollMe(id, nextIndex); } );
      this.animate(id, $(next), dimType, dimVal, 0, null);
   },
   animate: function(id, elem, dimension, startPos, endPos, callback) {
      var self = this;
      var isOver = false;
      if (typeof(this.paused[id]) == 'undefined') {
         if (typeof(this.duration[id]) == 'undefined' || !this.duration[id])
            this.duration[id] = 100; 
         var delta = Math.floor((endPos - startPos)*this.step[id]/this.duration[id]);
         var currentPos = $(elem).position()[dimension];
         if ( (delta < 0 && currentPos + delta < endPos) || (delta > 0 && currentPos + delta > endPos) ) {
            $(elem).css(dimension, endPos);
            isOver = true;
            if (callback)
               setTimeout(callback, this.delay[id]);
         } else
            $(elem).css(dimension, currentPos + delta);
      }
      if (!isOver)
         setTimeout(function() { self.animate(id, elem, dimension, startPos, endPos, callback); }, this.step[id]);
   },
   pause: function(id) {
      this.paused[id] = true;
   },
   resume: function(id) {
      delete(this.paused[id]);
   }
}

