var SB = window.SB;
var Player = window.Player;
var jQuery = window.jQuery;
var $ = window.$;

SB.readyForPlatform('samsung', function () {
    var curAudio = 0,
        curSubtitle = 0;

    $('#root').addClass('platform-samsung');

    var safeApply = function (self, method, args) {
        try {
            switch (args.length) {
                case 0:
                    return self[method]();
                case 1:
                    return self[method](args[0]);
                case 2:
                    return self[method](args[0], args[1]);
                case 3:
                    return self[method](args[0], args[1], args[2]);
                case 4:
                    return self[method](args[0], args[1], args[2], args[3]);
                case 5:
                    return self[method](args[0], args[1], args[2], args[3], args[4]);
                case 6:
                    return self[method](args[0], args[1], args[2], args[3], args[4], args[5]);
                case 7:
                    return self[method](args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
                case 8:
                    return self[method](args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
                default:
                    break;
            }
        } catch (e) {
            throw e;
        }
    }

    Player.extend({
        usePlayerObject: true,
        _init: function () {
            var self = this;
            //document.body.onload=function(){
            if (self.usePlayerObject) {
                //self.$plugin = $('<object id="pluginPlayer" border=0 classid="clsid:SAMSUNG-INFOLINK-PLAYER" style="position: absolute; left: 0; top: 0; width: 1280px; height: 720px;"></object>');
                self.plugin = document.getElementById('pluginPlayer');
                $('body').append(self.$plugin);


            } else {
                self.plugin = sf.core.sefplugin('Player');
            }


            if (!self.plugin) {
                throw new Error('failed to set plugin');
            }

            self.plugin.OnStreamInfoReady = 'Player.OnStreamInfoReady';
            self.plugin.OnRenderingComplete = 'Player.OnRenderingComplete';
            self.plugin.OnCurrentPlayTime = 'Player.OnCurrentPlayTime';
            self.plugin.OnCurrentPlaybackTime = 'Player.OnCurrentPlayTime';
            self.plugin.OnBufferingStart = 'Player.OnBufferingStart';
            self.plugin.OnBufferingProgress = 'Player.OnBufferingProgress';
            self.plugin.OnBufferingComplete = 'Player.OnBufferingComplete';
            //self.plugin.OnConnectionFailed = 'Player.onError';
            //self.plugin.OnNetworkDisconnected = 'Player.onError';
            //self.plugin.OnAuthenticationFailed = 'Player.OnAuthenticationFailed';

            self.plugin.OnEvent = 'Player.onEvent';
            //}

        },
        seek: function (time) {
            if (time <= 0) {
                time = 0;
            }
            /*if ( this.duration <= time + 1 ) {
             this.videoInfo.currentTime = this.videoInfo.duration;
             }
             else {*/
            var jump = Math.floor(time - this.videoInfo.currentTime - 1);
            this.videoInfo.currentTime = time;

            if (jump < 0) {
                this.doPlugin('JumpBackward', -jump);
            }
            else {
                this.doPlugin('JumpForward', jump);
            }
            //  this.currentTime = time;
            //}
        },

        forward: function(seconds) {
          this.doPlugin('JumpForward', seconds);
        },

        backward: function(seconds) {
          this.doPlugin('JumpBackward', seconds);
        },

        onEvent: function (event, arg1, arg2) {
            switch (event) {
                case 9:
                    this.OnStreamInfoReady();
                    break;

                case 4:
                    //this.onError();
                    break;

                case 8:
                    this.OnRenderingComplete();
                    break;
                case 14:
                    this.OnCurrentPlayTime(arg1);
                    break;
                case 13:
                    this.OnBufferingProgress(arg1);
                    break;
                case 12:
                    this.OnBufferingComplete();
                    break;
                case 11:
                    this.OnBufferingStart();
                    break;
            }
        },
        OnRenderingComplete: function () {
            Player.trigger('complete');
        },
        OnStreamInfoReady: function () {
            var duration, width, height, resolution;

            try {
                duration = this.doPlugin('GetDuration');
            } catch (e) {
                alert('######## ' + e.message);
            }

            duration = Math.ceil(duration / 1000);
            //this.jumpLength = Math.floor(this.duration / 30);

            if (this.usePlayerObject) {
                width = this.doPlugin('GetVideoWidth');
                height = this.doPlugin('GetVideoHeight');
            } else {
                resolution = this.doPlugin('GetVideoResolution');
                if (resolution == -1) {
                    width = 0;
                    height = 0;
                } else {
                    var arrResolution = resolution.split('|');
                    width = arrResolution[0];
                    height = arrResolution[1];
                }
            }

            this.videoInfo.duration = duration;
            this.videoInfo.width = width * 1;
            this.videoInfo.height = height * 1;
            this.trigger('ready');
        },
        OnBufferingStart: function () {
          this.trigger('bufferingBegin');
        },
        OnBufferingComplete: function () {
          this.trigger('bufferingEnd');
        },
        OnCurrentPlayTime: function (millisec) {
            if (this.state == 'play') {
                this.videoInfo.currentTime = millisec / 1000;
                this.trigger('update');
            }
        },
        _play: function (options) {
            var url = options.url;
            switch (options.type) {
                case 'hls':
                    url += '|COMPONENT=HLS'
            }
            this.doPlugin('InitPlayer', url);
            this.doPlugin('StartPlayback', options.from || 0);
        },
        _stop: function () {
            this.doPlugin('Stop');
        },
        pause: function () {
          this.doPlugin('Pause');
          this.state = "pause";
          this.trigger('pause');
        },
        resume: function () {
          this.doPlugin('Resume');
          this.state = "play";
          this.trigger('resume');
        },
        doPlugin: function () {
            var result,
                plugin = this.plugin,
                methodName = arguments[0],
                args = Array.prototype.slice.call(arguments, 1, arguments.length) || [];

            if (this.usePlayerObject) {


                result = safeApply(plugin, methodName, args);

            }
            else {
                if (methodName.indexOf('Buffer') != -1) {
                    methodName += 'Size';
                }
                args.unshift(methodName);
                result = safeApply(plugin, 'Execute', args);
            }

            return result;
        },
        audio: {
            set: function (index) {
                /*one is for audio*/
                //http://www.samsungdforum.com/SamsungDForum/ForumView/f0cd8ea6961d50c3?forumID=63d211aa024c66c9
                Player.doPlugin('SetStreamID', 1, index);
                curAudio = index;
            },
            get: function () {
                /*one is for audio*/
                var len = Player.doPlugin('GetTotalNumOfStreamID', 1);

                var result = [];
                for (var i = 0; i < len; i++) {
                    result.push(Player.doPlugin('GetStreamLanguageInfo', 1, i));
                }
                return result;
            },
            cur: function () {
                return curAudio;
            }
        },
        subtitle: {
            set: function (index) {
                Player.doPlugin('SetStreamID', 5, index);
                curSubtitle = index;
            },
            get: function () {
                var len = Player.doPlugin('GetTotalNumOfStreamID', 5);

                var result = [];
                for (var i = 0; i < len; i++) {
                    result.push(Player.doPlugin('GetStreamLanguageInfo', 5, i));
                }
                return result;
            },
            cur: function () {
                return curSubtitle;
            }
        },
        exit: function () {
          sf.core.exit();
        }
    });
});


/**
 * Samsung platform
 */
!(function (window, undefined) {


    var
        document=window.document,
        /**
         * Native plugins
         * id: clsid (DOM element id : CLSID)
         * @type {{object}}
         */
            plugins = {
            audio: 'SAMSUNG-INFOLINK-AUDIO',
            pluginObjectTV: 'SAMSUNG-INFOLINK-TV',
            pluginObjectTVMW: 'SAMSUNG-INFOLINK-TVMW',
            pluginObjectNetwork: 'SAMSUNG-INFOLINK-NETWORK',
            pluginObjectNNavi: 'SAMSUNG-INFOLINK-NNAVI',
            pluginPlayer: 'SAMSUNG-INFOLINK-PLAYER'
        },
        samsungFiles = [
            '$MANAGER_WIDGET/Common/af/../webapi/1.0/deviceapis.js',
            '$MANAGER_WIDGET/Common/af/../webapi/1.0/serviceapis.js',
            '$MANAGER_WIDGET/Common/af/2.0.0/extlib/jquery.tmpl.js',
            '$MANAGER_WIDGET/Common/Define.js',
            '$MANAGER_WIDGET/Common/af/2.0.0/sf.min.js',
            '$MANAGER_WIDGET/Common/API/Plugin.js',
            '$MANAGER_WIDGET/Common/API/Widget.js',
            '$MANAGER_WIDGET/Common/API/TVKeyValue.js',
            'src/platforms/samsung/localstorage.js'
        ];

    SB.createPlatform('samsung', {

        $plugins: {},
        platformUserAgent: 'maple',

        onDetect: function () {
            // non-standart inserting objects in DOM (i'm looking at you 2011 version)
            // in 2011 samsung smart tv's we can't add objects if document is ready

            var htmlString = '';
            for (var i = 0; i < samsungFiles.length; i++) {
                htmlString += '<script type="text/javascript" src="' + samsungFiles[i] + '"></script>';
            }
            for (var id in plugins) {
                htmlString += '<object id=' + id + ' border=0 classid="clsid:' + plugins[id] + '" style="opacity:0.0;background-color:#000000;width:0px;height:0px;"></object>';
            }
            document.write(htmlString);
        },

        getNativeDUID: function () {
            return this.$plugins.pluginObjectNNavi.GetDUID(this.getMac());
        },

        getMac: function () {
            return this.$plugins.pluginObjectNetwork.GetMAC();
        },

        getSDI: function () {
            this.SDI = this.$plugins.SDIPlugin.Execute('GetSDI_ID');
            return this.SDI;
        },

        /**
         * Return hardware version for 2013 samsung only
         * @returns {*}
         */
        getHardwareVersion: function () {
            var version = this.firmware.match(/\d{4}/) || [];
            if (version[0] === '2013') {
                this.hardwareVersion = sf.core.sefplugin('Device').Execute('Firmware');
            } else {
                this.hardwareVersion = null;
            }
            return this.hardwareVersion;
        },

        setPlugins: function () {
          var self = this,
            PL_NNAVI_STATE_BANNER_NONE = 0,
            PL_NNAVI_STATE_BANNER_VOL = 1,
            PL_NNAVI_STATE_BANNER_VOL_CH = 2,
            tvKey;

            _.each(plugins, function (clsid, id) {
                self.$plugins[id] = document.getElementById(id);
            });

            this.$plugins.SDIPlugin = sf.core.sefplugin('ExternalWidgetInterface');
            this.$plugins.tvKey = new Common.API.TVKeyValue();

            var NNAVIPlugin = this.$plugins.pluginObjectNNavi,
                TVPlugin = this.$plugins.pluginObjectTV;

            this.modelCode = NNAVIPlugin.GetModelCode();
            this.firmware = NNAVIPlugin.GetFirmware();
            this.systemVersion = NNAVIPlugin.GetSystemVersion(0);
            this.productCode = TVPlugin.GetProductCode(1);

            this.pluginAPI = new Common.API.Plugin();
            this.widgetAPI = new Common.API.Widget();

            tvKey = new Common.API.TVKeyValue();
            this.productType = TVPlugin.GetProductType();

            this.setKeys();

            if(this.pluginAPI.SetBannerState){
              NNAVIPlugin.SetBannerState(PL_NNAVI_STATE_BANNER_VOL_CH);
            }

            function unregisterKey(key){
              try{
                self.pluginAPI.unregistKey(tvKey['KEY_'+key]);
              }catch(e){
                $$error(e);
              }
            }

            unregisterKey('VOL_UP');
            unregisterKey('VOL_DOWN');
            unregisterKey('MUTE');

            this.widgetAPI.sendReadyEvent();
        },

        /**
         * Set keys for samsung platform
         */
        setKeys: function () {

          this.keys = sf.key;

          document.body.onkeydown = function ( event ) {
            var keyCode = event.keyCode;

            switch ( keyCode ) {
              case sf.key.RETURN:
              //case sf.key.EXIT:
              case 147:
              case 261:
                sf.key.preventDefault();
                break;
              default:
                break;
            }
          }
        },

        /**
         * Start screensaver
         * @param time
         */
        enableScreenSaver: function (time) {
            time = time || false;
            sf.service.setScreenSaver(true, time);
        },

        /**
         * Disable screensaver
         */
        disableScreenSaver: function () {
            sf.service.setScreenSaver(false);
        },

        exit: function () {
            sf.core.exit(false);
        },

        sendReturn: function () {
            sf.core.exit(false);
        },

        blockNavigation: function () {
            sf.key.preventDefault();
        }
    });

})(this);
(function ($) {
    "use strict";



    SB.readyForPlatform('samsung', function(){
        var voiceServer;

        /**
         * Обработка нативных событий распознавания голоса
         * @param evt событие от самсунга
         */
        var handleRecognitionEvent = function (evt) {

            switch (evt.eventtype) {
                case "EVENT_VOICE_END_MONITOR":
                    //не работает в телевизоре
                    break;
                case "EVENT_VOICE_BEGIN_MONITOR":
                case "EVENT_VOICE_BTSOUND_START":
                    //this.updateVoiceKeyHelp();
                    /*if (paused) {
                        break;
                    }
                    $('body').trigger('voiceStart');
                    if (helperWasShowed < defaults.showHelperTimes) {
                        helperWasShowed++;
                        $helpBubble.html(defaults.helpText).show();
                    }*/


                    $$voice.refresh();

                    $$voice._resetVisibilityTimeout();

                    /*
                    if ($curTarget) {
                        doAll.call($curTarget, curOptions);
                    }*/
                    break;
                case "EVENT_VOICE_RECOG_RESULT":

                    var result = evt.result.toLowerCase();
                    //если не голосовой поиск
                    if (typeof voiceServer != 'function') {
                        $$voice.say(result);
                    }
                    else {
                        voiceServer(result);
                        voiceServer = false;
                        $$voice.restore();
                    }
                    break;

                default:
                  break;
            }
        };
        _.extend($$voice, {
            _init: function(){
                deviceapis.recognition.SubscribeExEvent(deviceapis.recognition.PL_RECOGNITION_TYPE_VOICE, "Smartbox", function (evt) {
                    handleRecognitionEvent(evt);
                });
                deviceapis.recognition.SetVoiceTimeout(this.voiceTimeout);
                $('body').append('<div id="voice_buble"></div><div id="help_voice_bubble"></div>');
            },
            _nativeCheckSupport: function(){
                var enabled=false;
                try {
                    enabled = deviceapis.recognition.IsRecognitionSupported();
                } catch (e) {
                }
                return enabled;
            },
            _nativeFromServer: function(title, callback){
                voiceServer = callback;
                var describeHelpbar = {
                    helpbarType: "HELPBAR_TYPE_VOICE_SERVER_GUIDE_RETURN",
                    guideText: title
                };

                deviceapis.recognition.SetVoiceHelpbarInfo(JSON.stringify(describeHelpbar));
            },
            _setVoiceHelp: function(voicehelp){
                deviceapis.recognition.SetVoiceHelpbarInfo(JSON.stringify(voicehelp));
            },
            _nativeTurnOff: function(){
                deviceapis.recognition.SetVoiceHelpbarInfo(JSON.stringify({
                    helpbarType: "HELPBAR_TYPE_VOICE_CUSTOMIZE",
                    bKeepCurrentInfo: "false",
                    helpbarItemsList: []
                }));
            }
        });
    });
})(jQuery);
