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

    var App = window.App;
    var Keys = window.Keys;
    var _ = window._;
    var $ = window.$;
    var $$legend = window.$$legend;

    _.templateSettings.interpolate = /\{\{([\s\S]+?)\}\}/g;

    window.App.scenes.program = {
        toString: function() {
            return 'program';
        },
        current: false,
        current_name: '',
        from: 'iptv',

        init: function() {
            this.$el = $('.scene-program-content');
            _inited = true;
        },

        show: function() {
            if (!_inited) {
                this.init();
            }

            Keys.set('program');

            App.dispatch(App.legendActions.setEnter('tv_open_channel'));
            App.dispatch(App.legendActions.setMove('up_and_down'));
            App.dispatch(App.legendActions.setRet('back'));

            // this.program_name = window.App.scenes.iptv.current_program.program_name;

            this.openProgram(App.scenes.current_ch);

            this.$el.show();

            $('.menu-items').hide();
        },

        openProgram: function (channelIndex) {
          var channels = window.channels;
          var channel_name = channels[channelIndex].name;
          var currentProgram = App.scenes.iptv.getProgram(channelIndex);

          this.channel_index = channelIndex;

          if ( this.renderItems(channelIndex, currentProgram) ) {
            $('#tv-name').text(App.t('tv_channel') + ' ' + channel_name + ' - ' + App.t('tv_program_for_tooday'));
          } else {
            $('#tv-name').text(App.t('tv_channel') + ' ' + channel_name + ' - ' + App.t('tv_no_program'));
          }
        },

        openNextProgram: function () {
          var channels = window.channels;
          var nextChannelIndex = (this.channel_index + 1) % channels.length;

          this.openProgram(nextChannelIndex);
        },

        openPrevProgram: function () {
          var channels = window.channels;
          var prevChannelIndex = (this.channel_index - 1 + channels.length) % channels.length;

          this.openProgram(prevChannelIndex);
        },

        openChannel: function () {
          this.returnToBack();
          App.scenes.iptv.setNavCurrent( this.channel_index );
          App.scenes.iptv.playChannel( this.channel_index );
        },

        old: function () {
          $(document.body).on({
              'nav_key:info': function() {
                  App.scenes.program.returnToBack();
              },
              'nav_key:return': function() {
                  App.scenes.program.returnToBack();
              },
              'nav_key:green': function() {
                  // прокрутка вниз
                  if (($('.scene-program-content').height() - 20) < $('#elem-programs').height())
                  {
                      $('#tv-name').offset(function(i, val) {
                          if (val.top < tvNameTop)
                          {
                              var myTopTvName = val.top + 30;
                          }
                          else
                          {
                              var myTopTvName = val.top;
                          }
                          return {top: myTopTvName, left: val.left};
                      });
                      $('#elem-programs').offset(function(i, val) {
                          if (val.top < elemProgramsTop)
                          {
                              var myTopElemPrograms = val.top + 30;
                          }
                          else
                          {
                              var myTopElemPrograms = val.top;
                          }
                          return {top: myTopElemPrograms, left: val.left};
                      });

                  }
              },
              'nav_key:yellow': function() {
                  // прокрутка вверх
                  if (($('.scene-program-content').height() - 20) < $('#elem-programs').height())
                  {

                      $('#tv-name').offset(function(i, val) {
                          if (val.top > (tvNameTop - ($('#elem-programs').height() - $('.scene-program-content').height() + 60)))
                          {
                              var myTopTvName = val.top - 30;
                          }
                          else
                          {
                              var myTopTvName = val.top;
                          }
                          return {top: myTopTvName, left: val.left};
                      });
                      $('#elem-programs').offset(function(i, val) {
                          if (val.top > (elemProgramsTop - ($('#elem-programs').height() - $('.scene-program-content').height() + 60)))
                          {
                              var myTopElemPrograms = val.top - 30;
                          }
                          else
                          {
                              var myTopElemPrograms = val.top;
                          }
                          return {top: myTopElemPrograms, left: val.left};
                      });

                  }
              },
          });

          if (($('.scene-program-content').height() - 20) < $('#elem-programs').height())
          {
              $$legend.keys.green(App.t('scroll_up'));
              $$legend.keys.yellow('scroll_down');
          }
        },

        hide: function() {
            $$legend.keys.ret('');
            $$legend.keys.green('');
            $$legend.keys.yellow('');
            this.$el.hide();
            $('.menu-items').show();
            $$legend.keys.move(App.t('navigation'));
            $$legend.keys.enter('');
        },

        returnToBack: function()
        {
          if (this.from == 'iptv')
          {
              window.App.openScene('iptv');

              // program fix
              // $('.channel-item.focus').trigger('nav_focus');
          }
          else
          {
              App.openScene('iptv');
              Keys.set('iptv_view');
              App.modules.interfaceOverTv.hide();
              // window.App.toggleView();
          }
        },

        /** Показать список программ на день */
        renderItems: function ( index, currentProgram) {
          var channels = window.channels;
          var channel = channels[index];
        	var programs = channel.list;

    			if (!currentProgram || !programs) {
            $('#elem-programs').html('');
    				return false;
    			}

          var currentProgramIndex = currentProgram.index;

    			var programHtml = _.template('<li class="channel-item {{status}}">{{starttime}} {{title}}</li>');
          var programsList = [];

      		var oneHour = 60 * 60 * 1000;
          var oneDay = oneHour * 24;
      		var now = new Date().getTime();
          var tooday = new Date(now).getDate();
          var yesterday = new Date(now - oneDay).getDate();
          var afterTommorow = new Date(now + oneDay*2).getDate();
          var shift = (channel.shift || 0) * oneHour;

      		var program_status = 'previous_program';
          var programsListCreating = false;
          var currentProgramInListIndex = 0;

    			for (var i=0; i<programs.length; i++) {
            var checkProgram = programs[i],
                programTime = this.getTime(checkProgram.start) - shift,
                programDate = new Date( programTime ),
                programDay = programDate.getDate();

    				if (programDay === yesterday || programDay === tooday) {
    					programsListCreating = true;
    				}

            if (programDay === afterTommorow) {
    					break;
    				}

            if (!programsListCreating) {
              continue;
            }

            if (currentProgramIndex === i) {
              program_status = 'current_program';
              currentProgramInListIndex = programsList.length;
            }

    				programsList.push({
    					title: checkProgram.title,
    					starttime: this.formatTime( this.toLocalTime( programDate ) ),
              status: program_status,
    				});

            if (program_status === 'current_program') {
              program_status = 'next_program';
            }
      		}

          // Подготовка списка программ: 10 прошедших + 20 будущих (15 x 15)
          programsList = programsList.slice(currentProgramInListIndex-10, currentProgramInListIndex+20)


    			var half = programsList.length/2,
    				ul_1 = "", ul_2 = "";
    			for (var i=0; i<programsList.length; i++) {
    				if (i < half) {
    					ul_1 += programHtml(programsList[i]);
    				} else {
    					ul_2 += programHtml(programsList[i]);
    				}
    			}

          $('#elem-programs').html("<ul>"+ul_1+"</ul><ul>"+ul_2+"</ul>");

          return true;
    		},

        // Превращает формат времени присланной программы в ms
        getTime: function ( time ) {
          var year = time.slice(0,4),
              month = time.slice(4,6),
              day = time.slice(6,8),
              hour = time.slice(8,10),
              minutes = time.slice(10,12),
              // 2011-10-10T14:48:00.000+09:00
              strInDateFormat = year + "-" + month + "-" + day + "T" + hour + ":" + minutes + ":00.000" + time.slice(15,18) + ":" + time.slice(18,20),
              programTimeWithShift = new Date(strInDateFormat).getTime();

          return programTimeWithShift;
        },

        // Время с ведущим нулем (hh:mm)
        formatTime: function ( date ) {
          if (!date) {
            return '??:??'
          }
          return ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2)
        },

        // Смещение время программы на настройки локального времени
        toLocalTime: function ( date ) {
          if (!date) {
            return;
          }

          // var offset = tizen.time.getCurrentDateTime().secondsFromUTC();
          // var myDate = new Date();
          // var exp_offset = myDate.getTimezoneOffset()*60;
          // offset is equals to exp_offset.

          var dateShift = date.getTimezoneOffset() / 60 + (date.isDstObserved() ? 1 : 0);
          var settingsShift = parseInt(App.scenes.settings.options.time) || 0;

          // console.log(dateShift, settingsShift)

          return new Date(date.getTime() + (dateShift + settingsShift)*60*60*1000)
        },
    }
})();
