/* global App, Player */
/* global $, $$log, $$error */

(function() {
    "use strict";
    $.extend(App, {

      previousScenes: [],

      openStartScene: function () {
        this.openScene(this.startScene);
      },

      reopenScene: function(scene) {
        if (this.currentScene) {
          this.currentScene.hide();
          this.currentScene = null;
        }

        this.previousScenes = [];

        this.openScene(scene);
      },

      openScene: function(scene, isBack) {
        $$log('Open scene: "' + scene + '", currentScene: "' + this.currentScene + '"');

        if (!scene) {
          return;
        }

        if (scene === 'back') {
          App.back();
          return;
        }

        var currentScene = this.currentScene;
        var nextScene = this.scenes[scene] || scene;

        $(document.body).attr('scene', nextScene.toString());
        $(document.body).attr('class', nextScene.bodyClassName || '');

        if (currentScene === nextScene) {
          return;
        }

        if (currentScene && !isBack) {
          this.previousScenes.push(currentScene);
        }

        if (!nextScene) {
            $$error('Scene ' + scene + ' doesn\'t exist');
        } else {
            if (currentScene) {
                currentScene.hide();
            }
            nextScene.show();
            this.currentScene = nextScene;
        }
      },

      setNavigationEvents: function () {
        // click on menu item
        $('#main-menu').on('nav_key:enter', '.menu-item', function(e) {
          var scene = e.currentTarget.getAttribute('data-scene');
          if (Player.state === 'play')
          {
              Player.stop();
          }

          // сброс фильтров
          if (App.currentScene.toString() === 'videolib' && scene === 'videolib')
          {
              App.scenes.videolib.page = 1;
              App.scenes.videolib.genreId = 0;
              App.scenes.videolib.filterId = 'year';
              App.scenes.videolib.searchText = '';
              App.scenes.videolib.films();
          }

          App.openScene(scene);
        });
      },

      back: function () {
        if (!App.previousScenes.length) {
          return;
        }

        var previousScene = App.previousScenes.pop();

        App.openScene(previousScene, true);
      }
    });
})()
