/* global App */
/* global $, $$nav */

(function() {
    "use strict";

    App.modules.videoLines = {
      selectFirstFilmInVideoLine: function (videoLineIndex) {
        var $li = $($('#videos-list .videos-line')[videoLineIndex || 0]).find('li').first();

        $$nav.current($li);
      },

      autoScrollHorizontal: function (event) {
        var $li = $(event.currentTarget);
        var $ul = $li.parent();
        var $lis = $ul.find('li');
        var $scroll = $ul;
        var videoItemsCount = $lis.length;
        var videoItemOutset = 10;
        var videoItemWidth = $li.width() + videoItemOutset;

        // auto append to begin
        if ($li.index() + 2 < videoItemsCount/2) {
          $ul.prepend($lis.last());

          $scroll.css({ marginLeft: this.getMarginLeft($scroll) - videoItemWidth });
        }

        // auto append to end
        if ($li.index() - 2 > videoItemsCount/2) {
          $ul.append($lis.first());
          $scroll.css({ marginLeft: this.getMarginLeft($scroll) + videoItemWidth })
        }

        var scrollLeft = this.getMarginLeft($scroll);
        var viewWidth = $scroll.parent().width();
        var videoItemLeft = $li.position().left;
        var videoItemViewRight = videoItemLeft + scrollLeft;
        var videoItemViewLeft = videoItemLeft + videoItemWidth + scrollLeft;

        // auto scroll in left
        if (videoItemViewLeft > viewWidth) {
          this.scroll($scroll, {
            marginLeft: scrollLeft - (videoItemViewLeft - viewWidth)
          });
        }

        // auto scroll in right
        if (videoItemViewRight < 0) {
          this.scroll($scroll, {
            marginLeft: scrollLeft - videoItemViewRight
          });
        }
      },

      autoScrollVertical: function (event) {
        var $li = $(event.currentTarget);
        var $ul = $li.parent();
        var $line = $ul.parent();
        var $scroll = $line.parent();
        var viewHeight = $scroll.parent().height();
        var lineViewTop = $line.position().top - 52;
        var lineViewBottom = $line.position().top + $line.height();

        // auto scroll in top
        if (lineViewTop + $scroll.position().top < 0) {
          this.scroll($scroll, {
            top: 0
          });
        }

        // auto scroll in bottom
        if (lineViewBottom + $scroll.position().top > viewHeight) {
          this.scroll($scroll, {
            top: -lineViewBottom + viewHeight
          });
        }
      },

      scroll: function ($obj, cssProp) {
        $obj.stop().animate(cssProp);
      },

      getStyle: function ($obj, style) {
        return $obj.css(style).replace('px', '') * 1 || 0;
      },

      getMarginLeft: function($obj) {
        return this.getStyle($obj, "marginLeft");
      },

      getLeft: function ($obj) {
        return this.getStyle($obj, "left");
      }
    }
})();
