// 
// window.heroshot = new (function($j) {
// 
//     // init
//     $j(function() {
//         $j('.heroshot').each(function() {
//             var el = $j(this);
//             make_heroshot(el);
//         });
//     });
// 
//     // selectors
//     shot_selector = '.shot';
//     
//     // heroshots
//     function make_heroshot(els) {
//         var fade = els.find('input[name=fadetime]').val();
//         var pause = els.find('input[name=showtime]').val();
//         if(fade && pause) {
//             var first = els.children(shot_selector).filter(':first');
//             
//             els.children(shot_selector)
//                 .not(':first')
//                 .css('display', 'none');
//             first.show();
//             begin(first, fade, pause);
//         }
//     }
// 
//     function begin(shot, fade, pause) {
//         fade_ms = fade * 1000;
//         pause_ms = pause * 1000;
//         
//         setTimeout(function() {
//             var next = next_shot(shot);
//             shot.fadeOut(fade_ms);
//             next.fadeIn(fade_ms, function() {
//                 begin(next, fade, pause);
//             });
//         }, pause_ms);
//     }
// 
//     function next_shot(shot) {
//         var maybe = shot.next(shot_selector);
//         if(maybe.length)
//             return maybe
//         else {
//             return shot.parent()
//                 .children(shot_selector)
//                 .filter(':first');
//         }
//         
//     }
//     
// })(jQuery);

(function($){  
  var c = $('#speedcheck');
  var heroshot = $.extend(new Object(), {
    selector: '.shot',
    totalx: 0,
    scrollx: 0,
    n: 0,
    cur: 0,
    moving: false,
    dragging: false,
    widths: [],
    
    init: function(){
      this.el = $('.heroshot:first').css('overflow','hidden');
      this.el.wrapInner($('<div class="heroshot-wrap"></div>').css({position:'absolute', top:0, left:0}));
      this.wrap = $('.heroshot .heroshot-wrap');
      this.slides = this.el.find(this.selector);
      
      // Uncomment the following to use CMS-controlled values
      /* this.fadetime = (f = this.el.find('input[name=fadetime]'), f.size()) ?
                        Math.floor(parseFloat(f.val())*1000) : 982;
      this.waittime = (f = this.el.find('input[name=showtime]'), f.size()) ?
                        Math.floor(parseFloat(f.val())*1000+this.fadetime) : 9724; */
      this.fadetime = 982;
      this.waittime = 4000;
      
      var self = this;
      this.slides.each(function(i,tem){
        var kore = $(tem),
            w = kore.outerWidth() + parseInt(kore.css('margin-left')) + parseInt(kore.css('margin-right'));
        self.widths.push(w);
        kore.css({position:'absolute', left:self.totalx}).show();
        self.totalx += w;
      });
      this.slides.filter(':last').clone().css({'left':-this.widths[this.widths.length-1]}).prependTo(this.wrap);
      this.el.find(this.selector).click(function(e){ e.preventDefault(); })
                                  .mousedown(function(e){ self.dragstart.apply(self, [e]); });
      
      for(i=1;i<this.widths;i++) this.widths[i] = this.widths[0];
      
      $(document).mousemove(function(e){ self.drag.apply(self,[e]); });
      $(document).mouseup(function(e){ self.dragstop.apply(self,[e]); });
      this.interval = setInterval(function(){ self.next.apply(self,[]); }, this.waittime);
      
      return this;
    },
    
    next: function(d){
      var dir = d || 1;
      if(this.dragging) return;
      this.moving = true;
      var kore = this,
          o = this.n % this.slides.length,
          n = (a = this.n + dir, (a >= 0)) ? a % this.slides.length : a = this.slides.length - Math.abs(a) % this.slides.length,
          nu = $(this.slides[o]).clone()
                 .css('left', ((dir<0)? parseInt(this.el.find(this.selector).filter(':first').css('left')) - this.widths[n] : this.totalx));
          if(dir>0) nu.appendTo(this.wrap);
          else nu.prependTo(this.wrap);
          nu.mousedown(function(e){ kore.dragstart.apply(kore, [e]); })
            .click(function(e){ e.preventDefault(); });
      this.scrollx += this.widths[o] * dir;
      this.totalx += this.widths[n] * dir;
      var kore = this;
      this.wrap.animate({left: -this.scrollx}, this.fadetime, 'easeOutQuad', function(){
        kore.moving = false;
        if(dir > 0)
          kore.el.children(kore.selector).filter(':first').remove();
        else
          kore.el.children(kore.selector).filter(':last').remove();
        // if(kore.scrollx > 10000)
        //   kore.rewind.apply(kore,[]);
      });
      this.cur = o;
      this.n++;
    },
    
    rewind: function(){
      var n = 10000;
      this.scrollx-=n;
      this.totalx-=n;
      this.el.find(this.selector).each(function(i,tem){
        var dis = $(tem);
        dis.css({left: parseInt(dis.css('left')) - n});
      });
      this.wrap.css({left: -this.scrollx });
    },
    
    drag: function(e){
      if(! this.dragging) return;      
      e.preventDefault();
      if(this.moving) return;
      
      var diff = e.pageX - this.dragorigin;
      if(Math.abs(diff) > 0) this.hasmoved = true;
      if(diff > 470) diff = 470;
      if(diff < -1000) diff = -1000;
      this.diff = diff;
      
      this.wrap.css({left: -this.scrollorigin + diff});
      
      var kore = this;
      if(!this.dragpoints) this.speedpoints = this.dragpoints = [e.pageX, e.pageX];
      else {
        this.dragpoints.push(e.pageX);
      }
      if(!this.speedinterval)
        this.speedinterval = setInterval(function(){ kore.trackspeed.apply(kore); }, 20);
    },
    
    dragstop: function(e){
      if(! this.dragging) return;
      e.preventDefault();
      var self = this;
      this.interval = setInterval(function(){ self.next.apply(self,[]); }, this.waittime);
      this.dragging = false;
      
      if((this.speed < -20) || (this.diff < -400))
        this.next();
      else if ((this.speed > 20) || (this.diff > 400))
        this.next(-1);
      else
        this.wrap.animate({left: -this.scrollx}, 420, 'easeOutQuad');
      
      clearInterval(this.speedinterval);
      this.speedinterval = null;
      this.speedpoints = null;
      this.dragpoints = null;
      this.speed = 0;
      
      if(! this.hasmoved){
        var cur = this.slides[this.cur];
        window.location = ((e.target.tagName.match(/^a$/i)) ? 
            $(e.target) :
            $(e.target).closest(this.selector).find('a:first'))
          .attr('href') || '#';
      }
      this.hasmoved = false;
    },
    
    dragstart: function(e){
      e.preventDefault();
      this.dragorigin = e.pageX;
      this.scrollorigin = this.scrollx;
      this.dragging = true;
      clearInterval(this.interval);
      this.interval = null;
    },
    
    trackspeed: function(){
      this.speedpoints[0] = this.speedpoints[1];
      this.speedpoints[1] = this.dragpoints[this.dragpoints.length-1];
      this.speed = this.speedpoints[1] - this.speedpoints[0];
    }
    
  });
  $(document).ready(function(){
    window.HERO = heroshot.init();
  });
})(jQuery);