// jQuery.bbrk.home.sliderPage.js

(function ($) {
  
  if (typeof $.bbrk === "undefined") {
    $.bbrk = {};
  }
  
  if (typeof $.bbrk.home === "undefined") {
    $.bbrk.home = {};
  }
  
  $.bbrk.home.sliderPage = function (data) {
    
    var $page, $image;
    
    var naturalWidth = data.card.width;
    var naturalHeight = data.card.height;
    var imageHeight = naturalHeight;
    
    var scrollTop = 0;
    
    var timer;
    
    var isPause = false;
    

    $page = $("<div>", {
      "class": "page"
    });
    
    $page.css({
      position: "relative",
      width: "100%",
      height: "100%",
      overflow: "hidden"
    });
    
    $image = $.bbrk.home.sliderImage(data.card.src, data.card.width, data.card.height);

    $page.html($image);

    
    $page.play = function () {
      
      clearTimeout(timer);
      
      isPause = false;
      
      (function loop() {
        
        ++scrollTop;
        
        if (scrollTop >= imageHeight) {
          scrollTop = 0;
        }
        
        $image.css({
          marginTop: -scrollTop
        });
        
        if (isPause) {
          return;
        }
        
        timer = setTimeout(loop, 60);

      })();
    };
    
    $page.pause = function () {
      clearTimeout(timer);
      isPause = true;
    };
    
    $page.reset = function (duration, easing) {
      
      $page.pause();
      
      scrollTop = 0;
      
      $image.stop();
      
      $image.animate({
        marginTop: -imageHeight
      }, {
        duration: duration, 
        easing: easing,
        complete: function () {
          $image.css({
            marginTop: 0
          });
        }
      });
    };
    
    $page.resize = function (width, height) {
      
      if (height < 520) {
        height = 520;
      }
      
      if (width < 980) {
        width = 980;
      }

      if (width / naturalWidth < height / naturalHeight) {
        width = height * naturalWidth / naturalHeight;
      }
      else {
        height = width * naturalHeight / naturalWidth;
      }
      
      imageHeight = height;
      
      $image.resize(width, height);

    };
    
    return $page;
  };
  
})(jQuery);

