// var TEMP_URL = "https://www.w3schools.com/html/mov_bbb.mp4";

(function() {
    "use strict";
    var _inited;

    var App = window.App;
    var Keys = window.Keys;
    var Player = window.Player;
    var $ = window.$;
    var _ = window._;
    var $$nav = window.$$nav;
    var $$log = window.$$log;
    var $$legend = window.$$legend;
    var APP_CONFIG = window.APP_CONFIG;

    _.templateSettings.interpolate = /\{\{([\s\S]+?)\}\}/g;
    // шаблон списка
    var itemHtml = _.template(
      '<li '+
        'data-imdb="{{video_data.rate_imdb}}" '+
        'data-kino="{{video_data.rate_kinopoisk}}" '+
        'data-id="{{video_data.id}}" '+
        'data-name="{{video_data.name}}" '+
        'data-year="{{video_data.year}}" '+
        'data-genre_str="{{video_data.genre_str}}" '+
        'data-country="{{video_data.country}}" '+
        'data-lenght="{{video_data.lenght}}" '+
        'data-poster="http://rudny-online.kz{{video_data.poster}}" '+
        'class="video-item nav-item navigation-item" '+
        'style="background-image: url(\'http://rudny-online.kz{{video_data.poster}}\')"'+
      '/>'
    );

    var pageHtml = _.template('<li data-page="{{page}}" class="{{classname}} nav-but">{{text}}</li>');

    App.scenes.video = {
        itemHtml: itemHtml,
        toString: function() {
            return 'video';
        },
        className: 'scene-videos',
        films: [],
        ratings: [],
        init: function() {
          this.$el = $('.scene-videos-content');
          this.$episodes = $('#video-episodes');
          this.$genreselect = $('#genre-select');
          this.$filterselect = $('#filter-select');
          this.$dateselect = $('#date-select');
          this.$details = $('#video-details');
          this.$detailsHeader = this.$details.find('.filminfo-content')

          this.dates = {
            'last': App.t('video_last'),
            'year': App.t('video_year'),
          };

          this.date = 'last';
          this.genre = 1;
          this.filterId = 'year';

          this.setSearchHeader('');

          this.selectPage(1);
          this.loadGenres();
          this.loadFilters();

          App.scenes.video.$el.on('nav_focus', '.video-item', App.scenes.video.onVideoFocus);
          App.scenes.video.$el.on('nav_key:enter', '.video-item', App.scenes.video.onVideoClick);
          App.scenes.video.$el.on('nav_key:enter', '.date-but', App.scenes.video.openDateMenu);

          _inited = true;

          this.render();
        },

        render: function() {
          this.renderDateMenu();
        },

        show: function() {
          this.isInterfaceVisible = true;

          if (!_inited) {
              this.init();
          }

          this.selectElem(true);
          this.$el.show();
  			  $('li[data-scene=video]').addClass('active');

          $$legend.hide();
          Keys.set('video');

          this.selectFirstFilm();
          this.startListenPlayer();
        },

        hide: function() {
          this.selectElem(false);
          this.$el.hide();
		      $('li[data-scene=video]').removeClass('active');

          this.stopListenPlayer();
        },

        startListenPlayer: function() {
          Player.on('bufferingBegin', App.scenes.video.onBufferingBegin);
          Player.on('bufferingEnd', App.scenes.video.onBufferingEnd);
          Player.on('update', App.scenes.video.onPlayTimeUpdate);
          Player.on('pause', App.scenes.video.onPause);
          Player.on('resume', App.scenes.video.onResume);
        },

        stopListenPlayer: function() {
          Player.off('bufferingBegin', App.scenes.video.onBufferingBegin);
          Player.off('bufferingEnd', App.scenes.video.onBufferingEnd);
          Player.off('update', App.scenes.video.onPlayTimeUpdate);
          Player.off('pause', App.scenes.video.onPause);
          Player.off('resume', App.scenes.video.onResume);
        },

        onBufferingBegin: function() {
          App.dispatch(App.playerActions.setDuration(0));
        },

        onBufferingEnd: function() {
          var duration = Player.videoInfo.duration;

          App.dispatch(App.playerActions.setDuration(duration));
        },

        onPlayTimeUpdate: function() {
          var currentTime = Player.videoInfo.currentTime;

          App.dispatch(App.playerActions.setPosition(currentTime))
        },

        onPause: function() {
          App.dispatch(App.playerActions.setPaused(true));
        },

        onResume: function() {
          App.dispatch(App.playerActions.setPaused(false));
        },

        setVideosFocusEvents: function() {
          var scene = this;

          this.$el.find('.video-item').on({
            'nav_focus': function() {
                var filmId = $(this).data('id');
                var film = scene.getFilmById(filmId);

                App.dispatch(App.legendActions.setInfo('video_more_details'));

                scene.renderVideoInfo(film);
                scene.focusedFilm = film;
            },
            'nav_blur': function() {
              App.dispatch(App.legendActions.setInfo(''));
            }
          });
        },

        openFilmDetails: function(film) {
          if (!film) {
            film = this.focusedFilm;
          }

          App.dispatch(App.videoActions.setDetailsFilm(film));
        },

        closeFilmDetails: function() {
          App.dispatch(App.videoActions.setDetailsFilm(null));
        },

        isDetailsOpened: function() {
          return this.$details.is(':visible');
        },

        isEpisodesOpened: function() {
          return this.$episodes.is(':visible');
        },

        openGenreSelect: function (event) {
          App.scenes.video.$genreselect.fadeIn(400, function() {
              // select current genre
              App.scenes.video.$genreselect.find('.genre-item[data-genre=' + App.scenes.video.genre + ']').trigger('mouseenter').trigger('nav_focus');
          });

          $(document.body).off('nav_key:return');
          $(document.body).on({
              'nav_key:return': function() {
                  $(".close-genre-select").trigger('click');
              }
          });
          App.scenes.video.selectElem(false);
          $$nav.save();
          $$nav.on(App.scenes.video.$genreselect);

          return false;
        },

        getFilmById: function(filmId) {
          return this.films[filmId];
        },

        openEpisodesPopup: function(film) {
          this.$episodes.fadeIn();
          $$nav.save();
          $$nav.on(this.$episodes);
        },

        closeEpisodesPopup: function(film) {
          this.$episodes.fadeOut();
          $$nav.restore();
        },

        onVideoClick: function(e) {
          App.scenes.video.navToButtonsBlock()
        },

        navToButtonsBlock: function () {
          $$nav.current(this.$el.find('#play-button'));
        },

        play: function(url) {
          var videoScene = this;

          this.hideInterface();
          App.loader(true);

          App.error_buf = true;
          App.errorBufTimer = setTimeout(function() {
              App.error_buf = false;
              clearTimeout(App.errorBufTimer);
              Player.stop();
              App.loader(false);
              Keys.set('video');
              videoScene.onVideoError();
          }, APP_CONFIG.VLIB_BUFFERING_TIMEOUT_ERROR_MS);

          App.playerLast = url;

          Player.play({
              url: url,
              type: 'vod',
              onerror: function () {
                videoScene.onVideoError()
              },
          });

          $('#version').hide();
        },

        hideInterface: function () {
          $('#main-menu').hide();
          $('.scene_video').hide();

          this.isInterfaceVisible = false;

          $$log('hideInterface');
        },

        showInterface: function () {
          $('#main-menu').show();
          $('.scene_video').show();

          Player.stop();

          this.isInterfaceVisible = true;

          this.hidePlayerInterface();

          $('#version').show();
        },

        showPlayerInterface: function () {
          if (this.isInterfaceVisible) {
            return;
          }

          if ($('#appPlayer').is(':visible')) {
            return;
          }

          $('#appPlayer').fadeIn();

          $$nav.save();
          $$nav.on($('#appPlayer'));
          $$nav.current($('#appPlayerPause'));

          this.waitAndHidePlayerInterface(APP_CONFIG.VIDEO_PLAYER_AOUTHIDE_MS);
        },

        waitAndHidePlayerInterface: function (ms) {
          if (this.isInterfaceVisible) {
            return;
          }

          clearTimeout(this.hidePlayerInterfaceTimer);

          this.hidePlayerInterfaceTimer = setTimeout(function () {
            App.scenes.video.hidePlayerInterface();
          }, ms);

          $('#appPlayer').off();

          $('#appPlayer').on('nav_focus', '.nav-item', function () {
              App.scenes.video.waitAndHidePlayerInterface(ms);
          });

          $('#appPlayer').on('nav_key:enter', '.nav-item', function () {
              App.scenes.video.waitAndHidePlayerInterface(ms);
          });
        },

        hidePlayerInterface: function () {
          $('#appPlayer').fadeOut();

          $$nav.restore();
        },

        onVideoError: function () {
          App.error('video_error', function(){
              window.App.scenes.video.showInterface();
          });
        },

        playFilm: function (film) {
          if (!this.isInterfaceVisible) {
            return;
          }

          if (!film) {
            film = this.focusedFilm;
          }

          App.progressBar(false);

          this.closeFilmDetails();

          if (film.files.type === 'film')
          {
              if (film.files.files === undefined)
              {
                  // фильм еще не закачался
                  App.error('video_unavailable_error', function() {

                  });
                  return;
              }

              this.playSupportedFormat(film.files.files);
              return;
          }
          else
          {
              App.scenes.video.openEpisodesPopup(film);
          }
        },

        playEpisode: function(episode) {
          if (!this.isInterfaceVisible) {
            return;
          }

          var isEpisodePlayed = this.playSupportedFormat(episode);

          if (!isEpisodePlayed) {
            App.error('video_unavailable_error');
          }
        },

        playSupportedFormat: function (filmFiles)  {
          var supportedFormats = APP_CONFIG.VIDEO_SUPPORTED_FORMATS;

          for (var i=0; i<supportedFormats.length; i++) {
            var filmFormat = supportedFormats[i];
            var filmFile = filmFiles[filmFormat];

            if (filmFile) {
              App.scenes.video.play(filmFile.url);
              return true;
            }
          }

          return false;
        },

        renderItems: function(items, params) {
            var html = [];

            for (var i = 0, len = items.length; i < len; i++) {
              html.push(itemHtml(items[i], params));
            }

            html.sort(function () {
              return Math.random() - 0.5;
            });

            this.getVideoLineByParams(params)
              .html(html.join(''));

            var isFirstLine = params.filter === 'year' && !params.genre;

            if (isFirstLine) {
              this.$el.find('#videos-list li').first().trigger('mouseenter');
            }

            this.chooseGenreId(params.genre);
            this.showAfterFilmsLoaded();
        },
        hideBeforeFilmsLoaded: function (filmsLoading) {
          this.filmsLoading = filmsLoading;

          this.$el.find('#videos-list')
            .fadeOut(0);
        },
        showAfterFilmsLoaded: function () {
          this.filmsLoading--;

          if (this.filmsLoading) {
            return;
          }

          this.$el.find('#videos-list')
            .fadeIn(400, function() {
              App.scenes.video.selectFirstFilm();
            })
        },
        getVideoLineByParams: function (params) {
          if (params.genre) {
            return $('#videos-list .by-genre .videos-line-inner');
          }

          if (
            params.filter === 'kinopoisk' ||
            params.filter === 'imdb'
          ) {
            return $('#videos-list .by-rating .videos-line-inner');
          }

          if (
            params.filter === 'last' ||
            params.filter === 'year'
          ) {
            return $('#videos-list .by-year .videos-line-inner');
          }

          return $('#videos-list .by-'+ params.filter +' .videos-line-inner');
        },
        renderVideoInfo: function(film) {
            if (!film) {
              film = this.focusedFilm;
            }

            App.dispatch(App.videoActions.focusFilm(film));
        },
        renderPageSelector: function(page, pages) {
            var html = '';
            var neighbours = 2;
            var left_neighbour = page - neighbours;
            if (left_neighbour < 1)
                left_neighbour = 1;
            var right_neighbour = page + neighbours;
            if (right_neighbour > pages)
                right_neighbour = pages;
            if (page > 3)
            {
                html += pageHtml({page: 1, classname: 'nav-item', text: 1});
                html += pageHtml({page: (page - 1), classname: 'nav-item', text: '←'});
            }
            for (var i = left_neighbour; i <= right_neighbour; i++) {
                if (i != page)
                {
                    html += pageHtml({page: i, classname: 'nav-item', text: i});
                }
                else
                {
                    html += pageHtml({page: i, classname: 'current', text: i});
                }
            }
            if (page < (pages - 2))
            {
                html += pageHtml({page: (page + 1), classname: 'nav-item', text: '→'});
                html += pageHtml({page: pages, classname: 'nav-item', text: pages});
            }

            this.$el.find('#page-select li').off('nav_key:enter');
            if (pages == 1)
            {
                this.$el.find('#page-select')
                        .empty();
            }
            else
            {
                this.$el.find('#page-select')
                        .empty()
                        .html(html);
            }

            this.$el.find('#page-select li').on('nav_key:enter', function() {
                App.scenes.video.selectPage($(this).data('page'));
                console.log('select page: ' + $(this).data('page'));
            });
        },
        api: function(param, callback) {
            $.ajax({
                dataType: "json",
                url: 'http://rudny-online.kz/api_video.php?' + param,
                data: {},
                success: function(data) {
                    callback(data.result);
                }
            });
        },
        chooseGenreId: function (genreId) {
          if (!genreId) {
            return;
          }

          this.genre = genreId;

          App.dispatch(App.videoActions.setGenreId(genreId.toString()));
        },
        loadFilters: function() {
            this.api('method=filter', function(result) {
              App.scenes.video.prepareRatingMenu(result);
              App.scenes.video.chooseRating(App.scenes.video.ratings[0]);
            });
        },
        renderDateMenu: function () {
          // exit from part select
          $(".close-date-select").click(function() {
              // return
              $(document.body).off('nav_key:return');
              $(document.body).on({
                  'nav_key:return': function() {
                      App.exit();
                  }
              });
              App.scenes.video.$dateselect.fadeOut(400);
              $$nav.restore();
          });
          // select filter
          $('.date-select').click(function() {
              App.scenes.video.chooseDate($(this).data('rating'));

              App.scenes.video.loadFilms({
                page: App.scenes.video.page,
                filter: App.scenes.video.date,
              });

              $(".close-date-select").trigger('click');
          });

          this.chooseDate(App.scenes.video.date);
        },
        openDateMenu: function (event) {
          var $dateselect = App.scenes.video.$dateselect;
          var $dateparent = $dateselect.find('ul');

          $dateselect.fadeIn(400, function() {
              // select current filter
              $dateparent.find('.filter-item[data-filter-id=' + App.scenes.video.filterId + ']').trigger('mouseenter').trigger('nav_focus');
          });
          // return
          $(document.body).off('nav_key:return');
          $(document.body).on({
              'nav_key:return': function() {
                  $(".close-date-select").trigger('click');
              }
          });
          App.scenes.video.selectElem(false);
          $$nav.save();
          $$nav.on($dateselect);

          return false;
        },
        chooseDate: function (date) {
          if (!date) {
            return;
          }

          this.date = date;

          if (!this.date) {
            return;
          }

          if (!this.dates[date])
            return;

          $('.date-but').html($('[data-rating=' + date + ']').html());
        },
        prepareRatingMenu: function (result) {
          $.each(result, function(index, value) {
            $.each(value, function(key, val) {
              if (val.indexOf('Рейтинг') < 0) {
                return;
              }

              App.scenes.video.ratings.push({ value: key, label: val });
            });
          });

          App.dispatch(App.videoActions.setRatings(App.scenes.video.ratings));
        },
        chooseRating: function (rating) {
          if (!rating) {
            return;
          }

          this.rating = rating.value;

          if (!this.ratings) {
            return;
          }

          App.dispatch(App.videoActions.setRating(rating));
        },
        loadGenres: function() {
          this.api('method=genres', function(result) {
              App.dispatch(App.videoActions.setGenres(result));
          });
        },
        loadFilms: function(params) {
            App.progressStart();
            this.api('method=films&page=' + params.page + '&genre=' + params.genre + '&filter=' + params.filter + '&search=' + this.searchText, function(result) {

                if (result[0].length > 0)
                {
                    var isFirstLine = params.filter === 'year' && !params.genre;

                    App.scenes.video.updateFilms(result[0]);
                    App.scenes.video.renderItems(result[0], params);
                    App.scenes.video.page = result[1].page;

                    if (isFirstLine) {
                      App.scenes.video.renderPageSelector(App.scenes.video.page, result[1].pages);
                    }

                    App.scenes.video.setVideosFocusEvents();
                    App.progressStop();
                }
                else
                {
                    App.error('video_search_error', function() {
                        App.progressStop();
                        App.scenes.video.loadFilms();
                    });
                }
            });
        },

        updateFilms: function (films) {
          $.each(films, function(index, film) {
            film.video_data.files = film.files;
            App.scenes.video.films[film.video_data.id] = film.video_data;
          });
        },

        selectPage: function(page) {
            this.page = page;

            this.loadFilms({page: page, genre: 0, filter: 'year'});
            this.loadFilms({page: page, genre: 0, filter: 'kinopoisk'});
            this.loadFilms({page: page, genre: this.genre, filter: 'year'});

            this.hideBeforeFilmsLoaded(3);
        },

        selectElem: function(show, text) {
            if (show)
            {
              App.dispatch(App.legendActions.setBlue('genre_selection'));
              App.dispatch(App.legendActions.setGreen('genre_selection'));
              App.dispatch(App.legendActions.setYellow('filter'));
              App.dispatch(App.legendActions.setRet(''));
            }
            else
            {
              App.dispatch(App.legendActions.setBlue(''));
              App.dispatch(App.legendActions.setGreen(''));
              App.dispatch(App.legendActions.setYellow(''));

              if (text) {
                App.dispatch(App.legendActions.setRet(text));
              } else {
                App.dispatch(App.legendActions.setRet('cancel'));
              }
            }
        },

        setSearchHeader: function (text) {
          this.searchText = text;
          // TODO..
          $('.header .search-btn .value').html(text);
        },

        onVideoFocus: function (event) {
          App.scenes.video.autoScrollVertical(event);
        },

        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({ left: "-=" + videoItemWidth})
          }

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

          var scrollLeft = $scroll.position().left;
          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) {
            $scroll.stop().animate({
              left: scrollLeft - (videoItemViewLeft - viewWidth)
            })
          }

          // auto scroll in right
          if (videoItemViewRight < 0) {
            $scroll.stop().animate({
              left: 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) {
            $scroll.stop().animate({
              top: 0
            })
          }

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

        back: function () {
          if (App.scenes.video.isEpisodesOpened()) {
            App.scenes.video.closeEpisodesPopup();
          } else if (App.scenes.video.isDetailsOpened()) {
            App.scenes.video.closeFilmDetails();
          } else if (!this.isInterfaceVisible) {
            App.scenes.video.showInterface();
          } else {
            App.back();
          }
        },

        toggleDetails: function () {
          if (App.scenes.video.isDetailsOpened()) {
            App.scenes.video.closeFilmDetails();
          } else {
            App.scenes.video.openFilmDetails();
          }
        },

        likeFilm: function(film, callback) {
          if (!film) {
            film = this.focusedFilm;
          }

          this.api('method=like_film&id='+film.id, function (film) {
            delete film.poster;
            App.dispatch(App.videoActions.updateFilm(film));
          });
        },

        delikeFilm: function(film) {
          if (!film) {
            film = this.focusedFilm;
          }

          this.api('method=delike_film&id='+film.id, function (film) {
            delete film.poster;
            App.dispatch(App.videoActions.updateFilm(film));
          });
        },

        selectFirstFilm: function () {
          $$nav.current($('#videos-list li').first());
        },

        fastForward: function() {
          var duration = Player.videoInfo.duration;

          this.forward(Math.floor(duration * APP_CONFIG.VIDEO_PLAYER_REWIND_PERCENT / 100));
        },

        fastBackward: function() {
          var duration = Player.videoInfo.duration;

          this.backward(Math.floor(duration * APP_CONFIG.VIDEO_PLAYER_REWIND_PERCENT / 100));
        },

        forward: function(seconds) {
          if (!seconds) {
            seconds = 10;
          }

          var duration = Player.videoInfo.duration;
          var currentTime = Player.videoInfo.currentTime;

          Player.forward((currentTime + seconds) < duration ? seconds : (duration - currentTime));
        },

        backward: function(seconds) {
          if (!seconds) {
            seconds = 10;
          }

          var currentTime = Player.videoInfo.currentTime;

          Player.backward(currentTime > seconds ? seconds : currentTime);
        }
    }
})();
