/* global $, $$nav, $$log, $$error, $$legend */
/* global SB, APP_CONFIG, Player, AppAdvertisements */

(function() {
    var App = {};

    $.extend(App, {
        currentScene: null,
        scenes: {},
        progressInt: null,
        error_buf: false,
        errorBufTimer: null,
        disconnectTimer: null,
        fullCount: 10,
        full: null,
        isShown: true,
        playerState: 0,
        playerPause: false,
        startScene: 'iptv',
        modules: {},
        initialize: function() {
      			this.logGlobalErrors();

            this.$loaderProc = $('.popup-proc');
            this.$errorModal = $('#errors');
            this.$logoutModal = $('#logout-modal');
            this.$runText = $('#runtext');

            this.setEvents();

            this.loadServerConfig();

            $('#load-text').text(App.t('video_preloading'));

            // $$nav.on();

            if (APP_CONFIG.ALLNET_SUBNET_CUSTOMERS_ONLY) $.ajax({
              dataType: "json",
              url: APP_CONFIG.VIDEO_API_URL + '?method=is_allnet',
              data: {},
              success: function(data) {
                  if (!data.result[0].allnet) {
                      App.error('app_allnet_only', function() {
                          $$log('Выход!!!');
                      });
                  }
              }
          });
        },

        loadServerConfig: function () {
          $$log('IPTV_CHANNELS_UPDATES_INFO_URL:' + APP_CONFIG.IPTV_CHANNELS_UPDATES_INFO_URL);

          $.ajax({
            url: App.getApiUrl(APP_CONFIG.IPTV_CHANNELS_UPDATES_INFO_URL),
            dataType: "text",
            success : function (lastInfo) {

              $$log('Success channels updates loaded. Start load channels script.');

              var serverConfig = eval('('+lastInfo+')');

              App.setVidieoLibVisibilityFromServerConfig(serverConfig);
              App.scenes.iptv.loadChannels(serverConfig);

              AppAdvertisements.init(serverConfig);
            }
          });
        },

        setVidieoLibVisibilityFromServerConfig: function(config) {
          App.dispatch(App.appActions.setVideoLibVisibility(config.video_lib));
        },

        logGlobalErrors: function () {
          window.onerror = function (message, source, lineno, colno, error) {
            $$error('GlobalEvent :: ' + message + ' @	' + source + ':' + lineno);
          }
        },

        getApiUrl: function(url) {
          var serverName = App.scenes.settings.options.server || APP_CONFIG.SERVER_DEFAULT;

          for (var i=0; i<APP_CONFIG.SERVERS.length; i++) {
            var server = APP_CONFIG.SERVERS[i];

            if (server.name === serverName) {
              return server.url + url;
            }
          }

          return App.getDefaultServer().url + url;
        },

        getDefaultServer: function() {
          for (var i=0; i<APP_CONFIG.SERVERS.length; i++) {
            var server = APP_CONFIG.SERVERS[i];

            if (server.default) {
              return server;
            }
          }
        },

        setEvents: function() {
            this.setNavigationEvents();

			      // События для активной сцены, когда происходит навигации по верхнему меню (onMainMenuFocus)
            $('#main-menu').on('nav_focus', '.menu-item', function(e) {
              if (this.currentScene && this.currentScene.onMainMenuFocus) {
                this.currentScene.onMainMenuFocus(e);
			        }
            });
        },

        loader: function(show, source)
        {
          if (show) {
              $('#preloader').show();
          }
          else {
              $('#preloader').hide();
              if (source) {
                $$log('Disable loader. ' + source);
              }
              $('.wrap').show();
          }
        },

        loaderProc: function (proc) {
          this.$loaderProc.html(proc);
        },

        error: function(error, returnFunc) {
            App.dispatch(App.appActions.setError(error));
            $$legend.hide();
            $$nav.save();

            $('.wrap').hide();

            this.$errorModal.fadeIn(function () {
              $$nav.on(this.$errorModal);
            });

            $(".close-error").on('nav_key:enter', function(e) {
              e.stopPropagation();

              App.closeError();

              if (returnFunc) returnFunc();
            });
        },

        closeError: function() {
          this.$errorModal.hide();
          $$nav.restore();
          $('.wrap').show();
          $(".close-error").off('nav_key:enter');
        },

        confirmLogout: function(okFunction, cancelFunction) {
            $$legend.hide();
            this.$logoutModal.show();
            $$nav.save();
            $$nav.on(this.$logoutModal);

            var restoreView = function () {
              $$legend.show();
              App.$logoutModal.hide();
              $$nav.restore();
              $(".close-error").off('nav_key:enter');
            }

            // ok modal
            $(".ok-confirm").on('nav_key:enter', function(e) {
              restoreView();
              if (okFunction) okFunction();

              e.stopPropagation();
            });

            // cancel modal
            $(".cancel-confirm").on('nav_key:enter', function(e) {
              restoreView();
              if (cancelFunction) cancelFunction();

              e.stopPropagation();
            });
        },
        playError: function() {

        },
        progressStart: function()
        {
            var x = 0;
            var y = 0;
            var banner = $(".topline");
            banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');
            this.progressInt = window.setInterval(function() {
                banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
                x--;
            }, 20);
        },
        progressStop: function()
        {
            var banner = $(".topline");
            clearInterval(this.progressInt);
            banner.css('backgroundPosition', 0 + 'px' + ' ' + 0 + 'px');
        },
        confirmAndExitOrCloseConfirm: function() {
          if (this.$logoutModal.is(':visible')) {
            $(".cancel-confirm").trigger('nav_key:enter');
            return;
          }

          this.confirmLogout(function () {
            Player.exit();
          });
        },
    });

    // check allnet user

    // delay fix for volume bug ?????
    // setTimeout(function() {
        //SB.ready(_.bind(App.initialize, App));
        SB(_.bind(App.initialize, App));
    // }, 2000);

   window.App = App;
})();
