
/****
 *
 * EPOS code begin
 *
 ****/

//english, spanish, french
var text_feature0 = [["4K UHD","4X the pixel resolution of full HD.","4X the pixel resolution of full HD.","4X the pixel resolution of full HD."],
    ["4K UHD","4X la resolución de píxeles de alta definición estándar.","4X la resolución de píxeles de alta definición estándar.","4X la resolución de píxeles de alta definición estándar."],
    ["4K UHD","4X, la résolution en pixels de la pleine HD.","4X, la résolution en pixels de la pleine HD.","4X, la résolution en pixels de la pleine HD."]];
var text_feature1 = [["dbx-tv® Sound","Hear every detail from the built-in speakers.","Hear every detail from the built-in speakers.","Hear every detail from the built-in speakers."],
    ["Sonido dbx-tv®","Escuche todos los detalles en los altavoces incorporados.","Escuche todos los detalles en los altavoces incorporados.","Escuche todos los detalles en los altavoces incorporados."],
    ["Son dbx-tv®","Les haut-parleurs intégrés reproduisent les sons dans les moindres détails.","Les haut-parleurs intégrés reproduisent les sons dans les moindres détails.","Les haut-parleurs intégrés reproduisent les sons dans les moindres détails."]];
var text_feature2 = [["AquoMotion™","Get crystal clear images during fast action scenes.","Get crystal clear images during fast action scenes.","Get crystal clear images during fast action scenes."],
    ["AquoMotion™","Obtenga imágenes super claras durante las escenas de acción rápida.","Obtenga imágenes super claras durante las escenas de acción rápida.","Obtenga imágenes super claras durante las escenas de acción rápida."],
    ["AquoMotion™","Voyez les scènes d’action rapide claires comme le cristal.","Voyez les scènes d’action rapide claires comme le cristal.","Voyez les scènes d’action rapide claires comme le cristal."]];
var text_feature3 = [["Smart TV","Stream 4K content from providers including Netflix®, Amazon Instant Video® and YouTube®.","Stream 4K content from providers including Netflix® and YouTube®.","Stream 4K content from providers including Netflix® and YouTube®."],
    ["Smart TV","Reproduzca contenido 4K de proveedores como Netflix ®, Amazon Instant Video® y YouTube®.","Reproduzca contenido 4K de proveedores como Netflix ® y YouTube®.","Reproduzca contenido 4K de proveedores como Netflix ® y YouTube®."],
    ["Smart TV","Regardez des vidéos en 4K en direct de Netflix®, Amazon Video® et YouTube® et d’autres.","Regardez des vidéos en 4K en direct de Netflix®, YouTube® et d’autres.","Regardez des vidéos en 4K en direct de Netflix®, YouTube® et d’autres."]];
var checkTvSignalTimer;
var tabIndex = 0;
var panelLoopCount = 0;
var PANEL_MAX_LOOP_COUNT = 5;
var PANEL_ANIMATION_DURATION = 7000;
var EPOS_HIDE_DURATION = 30*1000;
var FEATURE_COUNT = 4;
var slide = 0;
var isDMPPlaying = false;
var lastUsb = "";
var epos_g_currentInput = 0;
var g_needRepeat = false;
var NOT_SUPPORT_FILE_FLAG = false;
var flag = false;
var playerstatus = 0;
var g_playMode = "";
var g_currBrand = "his";
var g_serviceNo = "A6100";
var g_currCountry = 80;

var mallLogoPath = "";
var g_logoPath = "";
//epos
var languageIndex = 0;
var eposStatus = "stop";
//hisense epos
var eposScrollTimer = null;
var g_allDisplayFunc = [
    {
        "name":"4K",//0
        "ic":"epos_4k_ic.png",
        "desTitle":["epos_4k_en.png","epos_4k_fr.png","epos_4k_sp.png"],
        "desInfo":["epos_4k_des_en.png","epos_4k_des_fr.png","epos_4k_des_sp.png"]
    },
    {
        "name":"HDR10",//1
        "ic":"epos_hdr10_ic.png",
        "desTitle":["epos_hdr10_en.png","epos_hdr10_fr.png","epos_hdr10_sp.png"],
        "desInfo":["epos_hdr10_des_en.png","epos_hdr10_des_fr.png","epos_hdr10_des_sp.png"]
    },
    {
        "name":"Motion Rate",//2
        "ic":"epos_mr_ic.png",
        "desTitle":["epos_mr_en.png","epos_mr_fr.png","epos_mr_sp.png"],
        "desInfo":["epos_mr_des_en.png","epos_mr_des_fr.png","epos_mr_des_sp.png"]
    },
    {
        "name":"Smart",//3
        "ic":"epos_smart_ic.png",
        "desTitle":["epos_smart_en.png","epos_smart_fr.png","epos_smart_sp.png"],
        "desInfo":["epos_smart_des_en.png","epos_smart_des_fr.png","epos_smart_des_sp.png"]
    },
    {
        "name":"Local dimming",//4
        "ic":"epos_dimming_ic.png",
        "desTitle":["epos_dimming_en.png","epos_dimming_fr.png","epos_dimming_sp.png"],
        "desInfo":["epos_dimming_des_en.png","epos_dimming_des_fr.png","epos_dimming_des_sp.png"]
    },
    {
        "name":"Alexa",//5
        "ic":"epos_alexa_ic.png",
        "desTitle":["epos_alexa_en.png","epos_alexa_fr.png","epos_alexa_sp.png"],
        "desInfo":["epos_alexa_des_en.png","epos_alexa_des_fr.png","epos_alexa_des_sp.png"]
    }

];
var g_supportFun = ["4K","HDR10","Motion Rate","Smart"];
var g_supportFunIndex = [0,1,2,3];

//sharp epos
var SHARP_ANIMATION_DURATION = 5000;
var sharpScrollTimer = null;
var g_sharpDisplayIndex = 0;
var g_sharpPathPrix = "";
var g_sharpDisFeature = [];
var g_sharpDisFun = [
    {
        "title":["epos_highlight_1_en.png","epos_highlight_1_fr.png","epos_highlight_1_sp.png"],
        "desInfo":["epos_bottom_1_en.png","epos_bottom_1_fr.png","epos_bottom_1_sp.png"]
    }
];

var signalTimer;
var tagTimer = null;


var closeTv = false;
var videoUpdating = false;
var noSignal = 1;
var eposUpdataPath = "";
var g_eposSwithStatus = 1;
var g_videoSwitchStatus = 1;

//background timer
var startBackgroudTimer = null;
var slideshowTimer = null;

//内置视频播放路径
var g_buildInVideoPath = "";

//usb info
var g_USBVideoPlayPath = "";
var g_USBVideoCount = 0;  //usb 文件数量
var m_usbIterator = null;  //读取优盘内容迭代器
var m_volumeMainIterator = null;  //读取所有挂载U盘迭代器
var g_USBVideoList = [];
var g_USBVideoListIndex = 0;
var isDTVPausing = false;//是否处于调用pauseDTV，但还没有调起播放器的状态

//静态epos重启浏览器，页面加载后直接启动原startepos（）内容
$(document).ready(function () {
    DBG_ERROR("Epos ready______");
    slide = 0;
    isDMPPlaying = false;
    lastUsb = "";
    epos_g_currentInput = 0;
    g_needRepeat = false;
    NOT_SUPPORT_FILE_FLAG = false;
    closeTv = false;
    g_playMode = "videosignal";
    initUsbVideoData();
    if(Config.tv)  {
        g_playMode = readFileFromNative('hisenseUI/eposmode.txt', 1);  //get Mode from hisenseUI browser
        DBG_ERROR("g_playMode is " + g_playMode);
        if(g_playMode == null){
            g_playMode = "videosignal";
        }
        initPlugin();
        funBrand();
        initLanguage();
        funCountry();
        g_eposSwithStatus = getEposSwitchStatus();
        g_videoSwitchStatus = getVideoSwitchStatus();
        getBuildInVideoPath();
        getMallLogoPatch();
        getEposUpdatePath();
        getDmpDevices();  //check usb
    }
    initEposData();
    getLogoPatch();

    initEposImg();

    //background load and display
    $("#slideshow").css("opacity","0");
    var num =  $("#slideshow img").length;
    $("#slideshow img").load(function() {
        num--;
        if (num == 0) {
            $("#slideshow").css("opacity","1");
            //startBackgroud();
        }
    });
    // store mode in 4k
    if(g_playMode != "video"){
        checkTvSignal();
    } else {
        pauseDTV();
    }
    $("body").css("opacity","1");
    startEposBanner();
    //15 s show
    clearInterval(tagTimer);
    tagTimer  = setInterval(function () {
        checkTagTimer();
    },15000);

    //check tv signal
    checkTvSignalTimer = setInterval(function () {
        checkTvSignal()
    }, 7000);
});
function initLanguage(){
    languageIndex = 0;
    try {
        var languageCode = model.language.getOsd();//获取当前语言
    }catch (e){
        DBG_ERROR("initLanguage:"+e.message);
        languageCode = 1;
    }
    DBG_ERROR("initLanguage:"+languageCode);
    var lanStr = "English";
    switch (languageCode) {
        case 1:
            lanStr = "English";
            languageIndex = 0;
            break;
        case 2:
            lanStr = "French";
            languageIndex = 1;
            break;
        case 4:
            lanStr = "Spanish";
            languageIndex = 2;
            break;
        default:
            lanStr = "English";
            languageIndex = 0;
            break;
    }
}
function startEposBanner(){
    openMallLogo();
    if(g_eposSwithStatus == 1){
        eposStatus = "run";
        if(g_currBrand == "his"){
            $("#hisEpos").show();
            openLogo();
            if(eposScrollTimer){
                DBG_ERROR("startEposBanner:hisense epos is playing");
                return;
            }
            clearHiEposTimer();
            eposScrollTimer =  setTimeout(function(){
                startHisBannerAnimation();
            }, 2000);
        }
        else if ('tos' === g_currBrand) {
            $('#tos_epos').css('animation', 2 === languageIndex ? 'tos_span infinite 20s' : 'tos_eng infinite 20s');
        }
        else{
            $("#sharpEpos").show();
            openLogo();
            if(sharpScrollTimer){
                DBG_ERROR("startEposBanner:sharp epos is playing");
                return;
            }
            startSharpBannerAnimation();
        }
    }else{
        stopEpos();
    }
}
// 停止动画
function stopEpos () {
    closeLogo();
    eposStatus = "stop";
    if(g_currBrand == "his"){
        $("#hisEpos").hide();
        $("#hi_3dlogo").hide();
        $("#hi_banner").hide();
        $("#hi_banner_detail").hide();
        $("#hi_contant_4").css("z-index",1);
        $("#hi_contant_1").css("z-index",100);
        clearHiEposTimer();
    }
    else if ('tos' === g_currBrand) {
        $('#tos_epos').css('animation', '');
    }
    else{
        $("#sharpEpos").hide();
        clearInterval(sharpScrollTimer);
        sharpScrollTimer = null;
        g_sharpDisplayIndex = 0;
        $("#sharp_epos_feature_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFeature[languageIndex] +"')");
        $("#sharp_epos_title_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[0].title[languageIndex] +"')");
        $("#sharp_epos_detail_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[0].desInfo[languageIndex] +"')");

        var nextImage = (g_sharpDisplayIndex + 1) % g_sharpDisFun.length;
        $("#sharp_epos_next_title_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[nextImage].title[languageIndex] +"')");
        $("#sharp_epos_next_detail_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[nextImage].desInfo[languageIndex] +"')");
    }
    //15 s show
    clearInterval(tagTimer);
    tagTimer  = setInterval(function () {
        checkTagTimer();
    },15000);

}
function clearHiEposTimer(){
    clearTimeout(eposScrollTimer);
    eposScrollTimer = null;
}
function openMallLogo(){
    if(mallLogoPath != ""){
        $("#mallLogo").show();
    }else{
        $("#mallLogo").hide();
    }
}
function closeMallLogo(){
    $("#mallLogo").hide();
}
function openLogo(){
    if(g_logoPath != "" && eposStatus == "run" && g_eposSwithStatus == 1){
        if(isDMPPlaying && g_USBVideoList.length == 0){
            $("#logo").hide();
        }else{
            $("#logo").show();
        }
    }else{
        $("#logo").hide();
    }
}
function closeLogo(){
    $("#logo").hide();
}
function initUsbVideoData(){
    g_USBVideoList = [];
    g_USBVideoListIndex = 0;
    g_USBVideoPlayPath = "";
}
function getEposSwitchStatus(){
    try{
        var storeModeEposSwitch = readFileFromNative('hisenseUI/storeModeEposSwitch.txt', 1);
        DBG_INFO("getEposSwitchStatus:"+storeModeEposSwitch);
        if(null == storeModeEposSwitch){
            DBG_ERROR("getEposSwitchStatus:not set epos switch,return 1");
            return 1;
        }else if(storeModeEposSwitch == "open"){
            return 1;
        }else{
            return 0;
        }
    }catch (ex){
        DBG_ERROR("getEposSwitchStatus:"+ex.message);
    }

}
function getVideoSwitchStatus(){
    try{
        var storeModeVideoSwitch = readFileFromNative('hisenseUI/storeModeVideoSwitch.txt', 1);
        DBG_INFO("getVideoSwitchStatus:"+storeModeVideoSwitch);
        if(null == storeModeVideoSwitch){
            DBG_ERROR("getVideoSwitchStatus:not set video switch,return 1");
            return 1;
        }else if(storeModeVideoSwitch == "open"){
            return 1;
        }else{
            return 0;
        }
    }catch (ex){
        DBG_ERROR("getVideoSwitchStatus:"+ex.message);
    }

}
function getMallLogoPatch(){
    mallLogoPath = readFileFromNative('hisenseUI/storeModeMallLogo.txt', 1);
    if(null == mallLogoPath){
        mallLogoPath = "";
    }
    DBG_INFO("mallLogoPath:"+mallLogoPath);
}
function getLogoPatch(){
    if(g_currBrand == "his" || 'tos' === g_currBrand){
        g_logoPath = "";
    }else{
        if(g_serviceNo.indexOf("A6107") > -1){
            g_logoPath = eposUpdataPath + g_sharpPathPrix+"epos_logo.png"
        }else if(g_serviceNo.indexOf("A6109") > -1){
            g_logoPath = eposUpdataPath + g_sharpPathPrix+"epos_logo.png";
        }else{
            g_logoPath = eposUpdataPath + g_sharpPathPrix+"epos_logo.png"
        }
    }
}
function getEposUpdatePath(){
    if(Hisense.File.exists("EPOS", 3)){
        eposUpdataPath = "file:///var/local/EPOS/";
    }else{
        eposUpdataPath = "";
    }
    DBG_ERROR("EPOS update exist,path is"+eposUpdataPath);
}
/**
 * 读取所有已挂载的U盘
 */
function getDmpDevices(){
    DBG_ERROR("epos getDmpDevices");
    try {
        m_volumeMainIterator = model.volume.createTableMainIterator(
            true,
            [
                {
                    field: VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_STATE,
                    condition: Model.FIELD_COND_EQUAL,
                    value: VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_STATE_CONNECTED
                }
            ],
            [
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_ID,
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_NAME,
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_TYPE,
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_STATE,
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_SUBSTATE

            ],
            [
                { field: VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_NAME, direction: 1 }
            ],
            onVolumeMainIteratorEvent.bind(this, VolumeModelDefines.SL2_TVAPI_VOLUME_FSAL2_MEDIA_TYPE_HDD)
        );
    }
    catch (e) {
        DBG_ERROR(e.message);
    }
}

/**
 * 读取所有已挂载的U盘
 */
function getDmpDevices(){
    initUsbVideoData();
    DBG_ERROR("epos getDmpDevices");
    try {
        m_volumeMainIterator = model.volume.createTableMainIterator(
            true,
            [
                {
                    field: VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_STATE,
                    condition: Model.FIELD_COND_EQUAL,
                    value: VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_STATE_CONNECTED
                }
            ],
            [
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_ID,
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_NAME,
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_TYPE,
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_STATE,
                VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_SUBSTATE

            ],
            [
                { field: VolumeModelDefines.ENUM_SL2_TVAPI_VOLUME_TABLE_FIELD_NAME, direction: 1 }
            ],
            onVolumeMainIteratorEvent.bind(this, VolumeModelDefines.SL2_TVAPI_VOLUME_FSAL2_MEDIA_TYPE_HDD)
        );
    }
    catch (e) {
        DBG_ERROR(e.message);
    }
}

/**
 * 读取优盘数量回调
 * @param deviceType
 * @param event
 */
var onVolumeMainIteratorEvent = function (deviceType, event) {
    DBG_INFO("[onVolumeMainIteratorEvent]Show all DEVICE:" + JSON.stringify(event));
    switch (event.type) {
        case TableIterator.EVENT_TYPE_ROWS_READ:
            if (deviceType == VolumeModelDefines.SL2_TVAPI_VOLUME_FSAL2_MEDIA_TYPE_HDD) {
                DBG_INFO("[onVolumeMainIteratorEvent]Show all the DLNA DEVICE:" + JSON.stringify(event.rows));
                m_volumeMainIterator.disconnect();
                if (event.rows.length > 0) {
                    var volumesList = [];
                    for (var i = 0; i < event.rows.length; i++) {
                        var tempId = event.rows[i][0];
                        var tempType = event.rows[i][2];
                        var tempName = event.rows[i][1];
                        if (!tempName) {
                            tempName = "USB" + i;
                        }
                        if (tempType == VolumeModelDefines.SL2_TVAPI_VOLUME_FSAL2_MEDIA_TYPE_HDD && tempId.indexOf("FSL2") != -1) {
                            volumesList.push({deviceId: tempId, deviceName: tempName, DiskUUID: tempId.replace("FSL2://",""),deviceType: "usb"});
                        }
                    }
                    DBG_ERROR("onVolumeMainIteratorEvent:all usb DEVICE:" + JSON.stringify(volumesList));
                    if(!!volumesList && volumesList.length > 0) {
                        readUsbDetail(volumesList[0].deviceId, "/"); //only Support the first usb
                    } else {//not exit usb,play inside video
                        playVideo();
                    }
                } else {//not exit usb,play inside video
                    playVideo();
                    DBG_ERROR("onVolumeMainIteratorEvent:usb num length less than 0.");
                }
            }
            break;
        case TableIterator.EVENT_TYPE_TOTAL_COUNT:
            DBG_ERROR("onVolumeMainIteratorEvent:event.totalCount" + event.totalCount);
            if (event.totalCount > 0) {
                m_volumeMainIterator.readNextRows(event.totalCount);
            } else {
                m_volumeMainIterator.disconnect();
                playVideo();
            }
            break;
        default :
            DBG_ERROR("onVolumeMainIteratorEvent:event.type is " + event.type);
            m_volumeMainIterator.disconnect();
            playVideo();
            break;
    }
};

/**
 * 根据usb id 读取U盘内容
 * @param id
 * @param path
 */
var readUsbDetail = function (id, path) {
    initUsbVideoData();
    DBG_ERROR("id is " + id + "path is :" + path);
    var fileCondition = [
        {
            field: DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_VOLUME_ID,
            condition: Model.FIELD_COND_EQUAL,
            value: id
        },
        {
            field: DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_ANCESTOR,
            condition: Model.FIELD_COND_EQUAL,
            value: path
        },
        {
            field: DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_TYPE,
            condition: Model.FIELD_COND_EQUAL,
            value: 4//all = 4+8+16+64
        }
    ];
    var fileResult = [
        DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_TYPE, /**< item type (e.g. tv_launcher, video, ...), see #ENUM_SL2_TVAPI_TABLE_DIRECTORY_FIELD_TYPE for different values */
        DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_LOCATOR, /**< item URL */
        DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_CAPTION, /**< add item name (no postfix type) */
        DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_DATE_NUMERIC
//            UsbModelDefines.SL2_TVAPI_USB_TABLE_FIELD_FILE_MOD_TIME,
//            UsbModelDefines.SL2_TVAPI_USB_TABLE_FIELD_FILE_URL
    ];
    try {
        m_usbIterator = model.directory.createDirectoryIterator(
            true,
            fileCondition,
            fileResult,
            [
                { field: DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_CAPTION, direction: 1 }
            ],
            onUSBIteratorEvent.bind(this, [id, path]));
        lastUsb = id;
    }
    catch (ex) {
        DBG_ERROR("model.usb.creatUSBTableMainIterator Error" + ex.message);
    }
    m_usbIterator.fetchTotalCount();


}
/**
 * U盘内容回调
 * @param param
 * @param event
 */
var onUSBIteratorEvent = function (param, event) {
    DBG_INFO("onUSBIteratorEvent and path is : " + param[0]);
    if (event.type == TableIterator.EVENT_TYPE_ROWS_READ) {
        function readUsbTable() {
            for (var i = 0; i < event.rows.length; i++) {
                var tempType = event.rows[i][0];
                var tempPath = event.rows[i][1];
                if (tempType == DirectoryModelDefines.SL2_TVAPI_TABLE_DIRECTORY_FIELD_TYPE_VIDEO) {
                    g_USBVideoList.push(tempPath);
                }
            }
            if(g_USBVideoList.length == 0){
                lastUsb = "";
            }
        }
        initUsbVideoData();
        readUsbTable();
        DBG_ERROR("video List:"+g_USBVideoList);
        m_usbIterator.disconnect();
        if(isDMPPlaying && g_USBVideoList.length > 0){
            isDMPPlaying = false;
            model.mpctrl.MpCtrlRelease(null);
        }
        g_USBVideoListIndex = 0;
        playVideo();
    } else if (event.type == TableIterator.EVENT_TYPE_TOTAL_COUNT) {
        g_USBVideoCount = event.totalCount;
        initUsbVideoData();
        DBG_INFO("FETCH TOTAL CONT ______________________________" + g_USBVideoCount);
        if (g_USBVideoCount > 0) {
            if (g_USBVideoCount > 100) {
                g_USBVideoCount = 100;
            }
            m_usbIterator.readNextRows(g_USBVideoCount);
        }
        else if (g_USBVideoCount == 0) {
            m_usbIterator.disconnect();
            playVideo();
        }
    }
    else if (event.type == TableIterator.EVENT_TYPE_SEEK_TO_ROW) {
        DBG_ERROR('seek to row index = ' + event.result);
        m_usbIterator.readNextRows(g_USBVideoCount);
    }
    else {
        DBG_INFO("other Type________________" + event.type);
    }
};
/**
 * 根据条件播放视频,其播信号
 */

var playVideo = function() {
    DBG_ERROR("playVideo:g_playMode is "+g_playMode+",g_USBVideoPlayPath is"+g_USBVideoPlayPath+",g_buildInVideoPath is "+g_buildInVideoPath);
    if(g_playMode == "video"){
        if(g_videoSwitchStatus == 1){
            if(g_USBVideoList.length > 0){
                playUsbVideo();
            } else if(g_buildInVideoPath != ""){
                playBuildInVideo();
            } else{
                startBackgroud();
            }
        }else{
            startBackgroud();
        }

    }else if(g_playMode == "videosignal"){
        if(g_videoSwitchStatus == 1){
            if(g_USBVideoList.length > 0){
                if(g_USBVideoListIndex != g_USBVideoList.length){
                    playUsbVideo();
                }else{
                    usbTimeTickResumeDTV();
                }
            }else if(g_buildInVideoPath != ""){
                playBuildInVideo();
            }else{
                usbTimeTickResumeDTV();
            }
        }else{
            usbTimeTickResumeDTV();
        }
    }
}

/**
 * 判断当前 epos是否显示，需要重写
 */
function checkTagTimer(){
    sendMessageToUI("eposCallpopAllModule");
    startEposBanner();
}

/**
 * 是否有内置视频
 */
function getBuildInVideoPath() {
    try {
        g_buildInVideoPath = "";

        var mkv_name = "video/StoreModeDemo.mkv";
        var mp4_name = "video/StoreModeDemo.mp4";
        if(g_currBrand != "his" && 'tos' !== g_currBrand){
            mkv_name = "video/Demo_Sharp.mkv";
            mp4_name = "video/Demo_Sharp.mp4";
        }
        var prefix = "file:///vddt/";
        if(Hisense.File.exists(mkv_name, 5)){
            g_buildInVideoPath = prefix + mkv_name;
            DBG_INFO("getBuildInVideoPath:mkv exist:"+getBuildInVideoPath);
        }else if(Hisense.File.exists(mp4_name, 5)){
            g_buildInVideoPath = prefix + mp4_name;
            DBG_INFO("getBuildInVideoPath mp4 exist:"+getBuildInVideoPath);
        }else{
            DBG_ERROR("getBuildInVideoPath: no build in video");
            g_buildInVideoPath = "";
        }
    }catch (ex){
        DBG_ERROR("getBuildInVideoPath:"+ex.message);
        g_buildInVideoPath = "";
    }
}

/**
 * 启动播放tv信号
 */
function usbTimeTickResumeDTV(){
    isDMPPlaying = false;
    // resumeDTV();
    startDTVPlay();
    openLogo();
    if(g_USBVideoList.length == 0 && g_buildInVideoPath == ""){
        DBG_ERROR("usbTimeTickResumeDTV: no video return");
        return;
    }
    clearTimeout(signalTimer);
    signalTimer =setTimeout(function(){
        DBG_ERROR("tv singnal timeout");
        if((g_USBVideoList.length > 0 || g_buildInVideoPath != "") && !videoUpdating){
            g_USBVideoListIndex = 0;
            playVideo();
        }else{
            startBackgroud();
        }
    },5*60*1000);
}

/**
 * 初始化,Modle 文件，注册监听事件
 */
function initPlugin() {
    try {
        DBG_ERROR("INIT PLUGIN");
        model = new Model();
        model.initialize();
        model.volume.onVstrLatestEventChaged = null;
        model.mpctrl.onMpCtrlStatchanged = null;
        model.mpctrl.onMpCtrlPlaytimeCurrentchanged = null;

        model.volume.onVstrLatestEventChaged = onUSBChanged;//USB状态监听函数
        model.mpctrl.onMpCtrlStatchanged = onEPosPlayerStateChanged;//Epos视频播放状态监听函数
        //model.mpctrl.onMpCtrlPlaytimeCurrentchanged = onEposPlayertimeChanged;//epos视频播放时间监听函数
        //model.system.onReturnlocalappFlagChaged = onRPCChanged;
        ///model.tvservice.onNoSignalMainChanged = onSignalChanged;
        //== resumeDTV();
//        model.video.setEnumPictureMode(VideoModelDefines.SL2_TVAPI_I32_VIDEO_ENUM_PICTURE_VIVID);
        DBG_ERROR("[epos] initPlugin done!");
    }catch (e){
        DBG_ERROR("[epos]initPlugin error:"+ e.message);
    }
}

/**
 * 初始化epos，内容，夏普品牌专用，
 */
function initEposImg(){
    //mallLogo
    $("#mallLogo img").css("content", "url("+ mallLogoPath + ")");
    //logo
    $("#logo img").css("content", "url("+ g_logoPath + ")");

    //background
    $("#backup0").attr("src", eposUpdataPath+"img/epos_image_1.png");
    $("#backup1").attr("src", eposUpdataPath+"img/epos_image_2.png");
    $("#backup2").attr("src", eposUpdataPath+"img/epos_image_3.png");
    $("#backup3").attr("src", eposUpdataPath+"img/epos_image_4.png");

   if ('tos' !== g_currBrand) {
       if(g_currBrand == "his") {

           $("#hi_3dlogo >img").css("content","url('"+eposUpdataPath+"img/his/epos_hi.png')");
           $("#hi_ic_logo >img").css("content","url('"+eposUpdataPath+"img/his/epos_hisense.png')");
           $("#hi_detail_logo >img").css("content","url('"+eposUpdataPath+"img/his/epos_hisense.png')");

           $("#hi_icon_contant").css("background-image","url('"+eposUpdataPath+"img/his/epos_ft_bg.png')");

           $("#icon_1").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[0]].ic +"')");
           $("#icon_2").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[1]].ic +"')");
           $("#icon_3").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[2]].ic +"')");
           $("#icon_4").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[3]].ic +"')");

           $("#hi_contant_1 .hi_icon ").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[0]].desTitle[languageIndex]+"')");
           $("#hi_contant_1 .hi_detail ").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[0]].desInfo[languageIndex]+"')");

           $("#hi_contant_2 .hi_icon ").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[1]].desTitle[languageIndex]+"')");
           $("#hi_contant_2 .hi_detail ").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[1]].desInfo[languageIndex]+"')");

           $("#hi_contant_3 .hi_icon ").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[2]].desTitle[languageIndex]+"')");
           $("#hi_contant_3 .hi_detail ").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[2]].desInfo[languageIndex]+"')");

           $("#hi_contant_4 .hi_icon ").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[3]].desTitle[languageIndex]+"')");
           $("#hi_contant_4 .hi_detail ").css("content", "url('"+eposUpdataPath+"img/his/dispalyFun/"+g_allDisplayFunc[g_supportFunIndex[3]].desInfo[languageIndex]+"')");

       } else {
           g_sharpDisplayIndex = 0;
           $("#sharp_epos_feature_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFeature[languageIndex] +"')");
           $("#sharp_epos_title_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[0].title[languageIndex] +"')");
           $("#sharp_epos_detail_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[0].desInfo[languageIndex] +"')");

           var nextImage = (g_sharpDisplayIndex + 1) % g_sharpDisFun.length;
           $("#sharp_epos_next_title_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[nextImage].title[languageIndex] +"')");
           $("#sharp_epos_next_detail_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[nextImage].desInfo[languageIndex] +"')");
       }
   }
}

/*function onMountPointChanged(value){
 DBG_ERROR("value is " + value);

 }*/
/**
 * 插拔U盘监听
 * @param value
 */
function onUSBChanged(value){
    DBG_ERROR("[ePos]onUSBChanged:"+value);//1 : add 2: remove
    if (value[1].indexOf("FSL2") != -1 ) {
        switch (value[0]) {
            case "4":
            case "1":
                DBG_ERROR("EPOS ON USB");
                if(g_USBVideoList.length != 0) {
                    DBG_ERROR("onUSBChanged: g_USBVideoList.length is "+g_USBVideoList.length);
                    return;
                }  //only play one usb
                readUsbDetail(value[1], "/");
                break;
            case "2":
                DBG_ERROR("EPOS OFF USB remove usb is "+value[1]+",lastUsb is "+lastUsb);
                if(lastUsb == value[1]){
                    if(isDMPPlaying) {
                        isDMPPlaying = false;
                        try {
                            model.mpctrl.MpCtrlRelease(null);
                        }
                        catch (e) {
                            DBG_ERROR(e.message);
                        }
                        getDmpDevices();
                    }else{
                        getDmpDevices();
                    }
                }

                break;
        }
    }
}

/*function onEposPlayertimeChanged(value) {
    DBG_ERROR("[epos]onEposPlayertimeChanged : " + value);
    var totalTime = model.mpctrl.getMpCtrlPlaytimeTotal();//获取播放总时长
//    DBG_INFO("[epos] playing video, totaltime = " + totalTime);
//    if(value >= totalTime){
//        g_needRepeat = true;
//        model.mpctrl.StopMpctrl(null);
//    }
}*/
/**
 * 播放监听
 * @param value
 */
function onEPosPlayerStateChanged(value) {
    DBG_ERROR("[epos]onEPosPlayerStateChanged state changed : "  +  value);
    if(closeTv) {
        closeTv = false;
        DBG_ERROR("[epos]onEPosPlayerStateChanged close tv ");
        return;
    }
    if(videoUpdating) {
        DBG_ERROR("[epos]onEPosPlayerStateChanged videoUpdating =" + videoUpdating);
        return;
    }
    var nState = parseInt(value[2]);
    if (nState == playerstatus &&
        (nState == MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_PREPARE_DONE ||
            nState == MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_PREPARED)) {
        DBG_INFO("drop duplicated state event" + nState);
        return;
    }
    DBG_INFO("playerstatus = " + playerstatus + " nState = " + nState);
    playerstatus = nState;
    switch (parseInt(value[2])) {
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_IDLE:
            break;
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_PREPARING:
            break;
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_PREPARED:
            //准备好后发播放命令
            model.mpctrl.setScreenPosition([0,0,3840,2160,1,0]);
            model.mpctrl.MpCtrlPlay(null);  //播放器开始播放资源
            epos_g_currentInput = model.source.getCurrentSource();
            isDMPPlaying = true;
            closeBackground();
            break;
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_PLAYING:

            break;
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_PAUSE:
            break;
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_STOP:
            break;
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_AUTO_STOP:
            isDMPPlaying = false;
            if(g_USBVideoList.length == 0 && g_playMode == "videosignal"){
                model.mpctrl.MpCtrlRelease(null);
                setTimeout(function(){
                    usbTimeTickResumeDTV();
                    //这个延时最好不要小于500，防止在调pauseDTV后再调起播放器之间的500毫秒内执行。
                },1000);
            }else{
                playVideo();
            }
            break;
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_RELEASING:
            if(getNoSignalValueForEpos() == 1  && !isDMPPlaying) {
                startBackgroud();
            }
            break;
        case MpCtrlModelDefines.SL2_TVAPI_I32_MPCTRL_ENUM_STATE_PREPARE_DONE:  //不再使用
            break;
        //todo 文件不存在的情况下显示epos贴
        case MpCtrlModelDefines.HS_PLAYER_PLAY_ERROR_AUDIO_UNPLAYABLE:
        case MpCtrlModelDefines.HS_PLAYER_PLAY_ERROR_VIDEO_UNPLAYABLE:
        case MpCtrlModelDefines.HS_PLAYER_PLAY_ERROR_NOT_SUPPORT_FILE:
        case MpCtrlModelDefines.HS_PLAYER_PLAY_ERROR_OPEN_FILE_FAIL:
        case MpCtrlModelDefines.HS_PLAYER_PLAY_ERROR_UNKNOWN:
            DBG_ERROR("Play error__NOT SUPPORT FILE");
            NOT_SUPPORT_FILE_FLAG = true;//4k内置视频播放失败后避免进入releasing处理的flag
            model.mpctrl.MpCtrlRelease(null);
            isDMPPlaying = false;
            if(g_playMode == "video"){
                startBackgroud();
                clearTimeout(signalTimer);
                signalTimer =setTimeout(function(){
                    DBG_ERROR("tv singnal timeout");
                    if((g_USBVideoList.length > 0 || g_buildInVideoPath != "") && !videoUpdating){
                        g_USBVideoListIndex = 0;
                        playVideo();
                    }else{
                        startBackgroud();
                    }
                },5*60*1000);
            }else{
                usbTimeTickResumeDTV();
            }
            break;
        default :
            break;
    }
}

function startHisBannerAnimation(){


    $("#hi_banner_detail").hide();
    $("#hi_contant_4").css("z-index",1);
    $("#hi_contant_1").css("z-index",100);

    $("#hi_3dlogo").show();
    clearHiEposTimer();
    eposScrollTimer = setTimeout(function () {
        $("#hi_3dlogo").hide();
        clearHiEposTimer();
        eposScrollTimer = setTimeout(function() {
            $("#hi_banner").show();
            clearHiEposTimer();
            eposScrollTimer = setTimeout(function() {
                $("#icon_1").show();
                clearHiEposTimer();
                eposScrollTimer = setTimeout(function() {
                    $("#icon_2").show();
                    clearHiEposTimer();
                    eposScrollTimer = setTimeout(function() {
                        $("#icon_3").show();
                        clearHiEposTimer();
                        eposScrollTimer = setTimeout(function() {
                            $("#icon_4").show();
                            clearHiEposTimer();
                            eposScrollTimer = setTimeout(function() {
                                startHisDetailAnimation();
                            },3800);
                        },800);
                    },800);
                },800);
            },600);
        },600);
        //animatePanelSimple();
    }, 2800);
}


function startHisDetailAnimation(){

    $("#hi_banner").hide();
    $("#icon_1").hide();
    $("#icon_2").hide();
    $("#icon_3").hide();
    $("#icon_4").hide();
    clearHiEposTimer();
    eposScrollTimer = setTimeout(function () {
        $("#hi_banner_detail").show();
        clearHiEposTimer();
        eposScrollTimer = setTimeout(function() {
            $("#hi_contant_2").css("z-index",100);
            $("#hi_contant_1").css("z-index",-1);
            $("#hi_contant_3").css("z-index",-1);
            $("#hi_contant_4").css("z-index",-1);
            clearHiEposTimer();
            eposScrollTimer = setTimeout(function() {
                $("#hi_contant_3").css("z-index",100);
                $("#hi_contant_1").css("z-index",-1);
                $("#hi_contant_2").css("z-index",-1);
                $("#hi_contant_4").css("z-index",-1);
                clearHiEposTimer();
                eposScrollTimer = setTimeout(function() {
                    $("#hi_contant_4").css("z-index",100);
                    $("#hi_contant_1").css("z-index",-1);
                    $("#hi_contant_2").css("z-index",-1);
                    $("#hi_contant_3").css("z-index",-1);
                    clearHiEposTimer();
                    eposScrollTimer = setTimeout(function() {
                        $("#hi_banner_detail").hide();
                        clearHiEposTimer();
                        eposScrollTimer = setTimeout(function() {
                            startHisBannerAnimation()
                        },1200);
                    },6000);
                },6000);
            },6000);
        },6000);
    }, 1200);
}


/**
 * 启动夏普动画
 */
function startSharpBannerAnimation(){
    clearInterval(sharpScrollTimer);
    sharpScrollTimer = null;
    sharpScrollTimer = setInterval(function () {
        sharpFeatureDisAnimation();
//        animatePanelSimple();
    }, SHARP_ANIMATION_DURATION);
}
function sharpFeatureDisAnimation(){

    g_sharpDisplayIndex = (g_sharpDisplayIndex + 1) % g_sharpDisFun.length;
    $("#sharp_epos_title_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[g_sharpDisplayIndex].title[languageIndex] +"')");
    $("#sharp_epos_detail_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[g_sharpDisplayIndex].desInfo[languageIndex] +"')");

    var nextImage = (g_sharpDisplayIndex + 1) % g_sharpDisFun.length;
    $("#sharp_epos_next_title_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[nextImage].title[languageIndex] +"')");
    $("#sharp_epos_next_detail_img").css("content", "url('"+eposUpdataPath+g_sharpPathPrix+g_sharpDisFun[nextImage].desInfo[languageIndex] +"')");
}

/**
 * 夏普动画内容
 */
function animatePanelSimple() {
    $('#title'+tabIndex).css("visibility","hidden");
    //tabIndex++;
    if(tabIndex == FEATURE_COUNT - 1){
        panelLoopCount++;
        if(panelLoopCount >= PANEL_MAX_LOOP_COUNT){
            panelLoopCount = 0;
            tabIndex = 0;
            clearInterval(sharpScrollTimer);
            epos_showePos(false);
            $(".epos_banner_dynamic").css("background-image", "url('img/epos_highlight_"+(tabIndex+1)+".png')");
            return;
        }
    }
    tabIndex = (tabIndex + 1) % 4;
    $('.epos_banner_static > span').text("");
    $(".epos_banner_dynamic").css("background-image", "url('img//epos_highlight_"+(tabIndex+1)+".png')");
    $('#title'+tabIndex).css("visibility","visible");

    var country = "USA";
    var countryIndex = 1;

    switch (tabIndex){
        case 0:
            switch (languageIndex){
                case 1:
                    $('.epos_banner_static > span').text(text_feature0[0][countryIndex]);
                    break;
                case 2:
                    $('.epos_banner_static > span').text(text_feature0[2][countryIndex]);
                    break;
                case 4:
                    $('.epos_banner_static > span').text(text_feature0[1][countryIndex]);
                    break;
                default:
                    $('.epos_banner_static > span').text(text_feature0[0][countryIndex]);
                    break;
            }
            break;
        case 1:
            switch (languageIndex){
                case 1:
                    $('.epos_banner_static > span').text(text_feature1[0][countryIndex]);
                    break;
                case 2:
                    $('.epos_banner_static > span').text(text_feature1[2][countryIndex]);
                    break;
                case 4:
                    $('.epos_banner_static > span').text(text_feature1[1][countryIndex]);
                    break;
                default:
                    $('.epos_banner_static > span').text(text_feature1[0][countryIndex]);
                    break;
            }
            break;
        case 2:
            switch (languageIndex){
                case 1:
                    $('.epos_banner_static > span').text(text_feature2[0][countryIndex]);
                    break;
                case 2:
                    $('.epos_banner_static > span').text(text_feature2[2][countryIndex]);
                    break;
                case 4:
                    $('.epos_banner_static > span').text(text_feature2[1][countryIndex]);
                    break;
                default:
                    $('.epos_banner_static > span').text(text_feature2[0][countryIndex]);
                    break;
            }
            break;
        case 3:
            switch (languageIndex){
                case 1:
                    $('.epos_banner_static > span').text(text_feature3[0][countryIndex]);
                    break;
                case 2:
                    $('.epos_banner_static > span').text(text_feature3[2][countryIndex]);
                    break;
                case 4:
                    $('.epos_banner_static > span').text(text_feature3[1][countryIndex]);
                    break;
                default:
                    $('.epos_banner_static > span').text(text_feature3[0][countryIndex]);
                    break;
            }
            break;
        default:
            break;
    }
}
/**
 * 显示夏普pos贴
 * @param isShow
 */
function epos_showePos(isShow) {
    if (isShow) {
        $("#sharpEpos_old").show();
        $('#title'+tabIndex).css("visibility","visible");
        $("#sharpEpos_old").animate({
            bottom: '0px'
        });

        $("#logo").animate({
            translateY: '0px'
        });
        startSharpBannerAnimation();
    } else {
        $('#title'+tabIndex).css("visibility","visible");
        clearInterval(sharpScrollTimer);
        //moveElement("sharpEpos_old",0,1113,10);
        $("#sharpEpos_old").hide();

        $("#sharpEpos_old").animate({
            bottom: '-100px'
        });

        $("#logo").animate({
            translateY: '-130px'
        });
        setTimeout("epos_showePos(1)", EPOS_HIDE_DURATION);
    }
}
function startDTVPlay() {
    //如果播放时没有处于pauseDTV状态，不能调用resumeDTV
    if (! isDTVPausing) {
        resumeDTV();
    }
}
function playUsbVideo(){
    if(g_USBVideoList.length == 0 || isDMPPlaying){
        DBG_ERROR("playUsbVideo:g_USBVideoList.length is "+g_USBVideoList.length+",isDMPPlaying is "+isDMPPlaying);
        return;
    }
    DBG_ERROR("playUsbVideo:PLAY USB VIDEO");
    closeBackground();
    var usbVideoIndex = g_USBVideoListIndex % g_USBVideoList.length;
    g_USBVideoPlayPath =  g_USBVideoList[usbVideoIndex];
    g_USBVideoListIndex ++;
    pauseDTV();
    isDTVPausing = true;
    openLogo();
    //在pauseDTV和调用播放视频的这500毫秒延时内，如果插进来执行resumeDTV会出错
    setTimeout(function() {
        //如果播放时没有处于pauseDTV状态，不能调用resumeDTV
        isDTVPausing = false;
        playMovieAction(g_USBVideoPlayPath);
    },500);
}

/**
 * 播放内置视频
 */
function playBuildInVideo(){
    if(g_buildInVideoPath == "" || isDMPPlaying) {
        DBG_ERROR("playBuildInVideo:g_buildInVideoPath is "+g_buildInVideoPath+",isDMPPlaying is "+isDMPPlaying);
        return;
    }
    closeBackground();
    pauseDTV();
    isDTVPausing = true;
    DBG_INFO("g_buildInVideoPath is: " + g_buildInVideoPath);
    setTimeout(function() {
        closeLogo();
        //如果播放时没有处于pauseDTV状态，不能调用resumeDTV
        isDTVPausing = false;
        playMovieAction(g_buildInVideoPath);
    },500);
}
function playMovieAction(path){
    DBG_ERROR("playMovieAction:"+path);
    if(!isDMPPlaying){
        isDMPPlaying = true;
        model.mpctrl.PlayMovie(path);
    }
}
function cleanAllTimer(){
    clearInterval(sharpScrollTimer);
    clearInterval(checkTvSignalTimer);
    clearTimeout(startBackgroudTimer);
    clearInterval(slideshowTimer);
    sharpScrollTimer=null;
    checkTvSignalTimer=null;
    startBackgroudTimer = null;
    slideshowTimer=null;
}

/**
 * 检查是否有信号播放、视频播放
 */
function checkTvSignal() {
    DBG_ERROR("checkTvSignal: noSignal is " + noSignal + " isDMPPlaying is " + isDMPPlaying);
    noSignal = getNoSignalValueForEpos();
    if(noSignal){
        if(g_videoSwitchStatus == 0 ||(g_USBVideoList.length == 0 && g_buildInVideoPath == "" || !isDMPPlaying)){
            startBackgroud();
        }
    }else{
        if(g_playMode != "video" && g_USBVideoList.length == 0 && g_buildInVideoPath == "" && g_videoSwitchStatus == 1){
            startDTVPlay();
            closeBackground();
        }else if(g_playMode != "video" && g_videoSwitchStatus == 0) {
            startDTVPlay();
            closeBackground();
        }else if(g_playMode!="video" && (g_USBVideoList.length !== 0 || g_buildInVideoPath !== "" ) && !isDMPPlaying){
            startDTVPlay();
            closeBackground();
        }
    }
}
function startBackgroud() {
    DBG_ERROR("startBackground");
    if(isDMPPlaying) return false;
    $('#slideshow').show();
    openLogo();
    if(startBackgroudTimer || slideshowTimer) {
        DBG_ERROR("startBackgroud is playing background return");
        return;
    }
    $('#blackCanvas').css("visibility", "visible");
    clearTimeout(startBackgroudTimer);
    startBackgroudTimer = setTimeout(function () {
        startBackgroudTimer = null;
        $('#blackCanvas').css("visibility", "hidden");
        startBackgroundImage();
    }, 2000);
}
/**
 * 启动背景图片
 */
function startBackgroundImage() {
    if(slideshowTimer) {
        clearInterval (slideshowTimer);
        slideshowTimer = null;
    }
    slideshowTimer = setInterval(function () {
        slideshowBackup();
    }, 7000);
}
/**
 * 背景图片显示
 */
function slideshowBackup() {
    $('#blackCanvas').css("visibility","hidden");
    $('#backup'+slide).css("z-index","-1");
    slide = (slide+1)%4;
    DBG_ERROR("slide is " + slide);
    $('#backup'+slide).css("z-index","100");
}
/**
 * 隐藏背景图片
 */
function closeBackground() {
    DBG_ERROR("closeBackground");
    $('#slideshow').hide();
    if(startBackgroudTimer){
        clearTimeout(startBackgroudTimer);
        startBackgroudTimer = null;
    }
    if(slideshowTimer){
        clearInterval(startBackgroudTimer);
        startBackgroudTimer = null;
    }
}
/***** Epos 关闭处理 *****/
function stopCurrSource(){
    DBG_ERROR("stop current source");
    //stop signal timer and stop timer
    if(!!signalTimer){
        clearTimeout(signalTimer);
        signalTimer = null;
    }
    // pauseDTV();
    stopDTVPlay();
    model.mpctrl.MpCtrlRelease(null);
    isDMPPlaying = false;
}

function sendMessageToUI(action) {
    var message= '{"type": "APPMessage", "target": "launcher","action":"' + action +'"}';
    opera_omi.sendPlatformMessage(message);
}
/**
 * 浏览器消息
 * @param event
 */
handlePlatformEvent = function (event) {
    var o = JSON.parse(event);
    DBG_ERROR("evet" + event);
    DBG_ERROR("handlePlatformEvent: event  is " + event + ",status "+ o.status);
    if(o.status == "keydown") {
        if(noSignal == 0 && !isDMPPlaying){ //有信号，没有播放视频
            sendMessageToUI("stopEpos");
        }
    }
    if(o.status == "eposSwitchChange"){
        g_eposSwithStatus = getEposSwitchStatus();
    }
    if(o.status == "videoSwitchChange"){
        g_videoSwitchStatus = getVideoSwitchStatus();
        if (g_videoSwitchStatus == 0 && isDMPPlaying) {
            DBG_ERROR("handlePlatformEvent:close video switch");
            model.mpctrl.MpCtrlRelease(null);
            isDMPPlaying = false;
        }else{
            DBG_ERROR("handlePlatformEvent:open video switch");
        }
        g_USBVideoListIndex = 0;
        playVideo();
    }
    stopEpos();
    if(g_playMode == o.status) {DBG_ERROR("g_playMode == o.status");return;}
    if (o.msg == "closeDMP") {
        DBG_INFO("closeDMP closeDMP closeDMP");
        try {
            DBG_ERROR("Epos stoped by handleplatformevent");
            closeTv = true;
            epos_g_currentInput = 0;
            g_needRepeat = false;
            cleanAllTimer();
            //关闭正在播放的资源
            if (isDMPPlaying) {
                DBG_INFO("model.mpctrl.StopMpctrl");
                model.mpctrl.MpCtrlRelease(null);
                isDMPPlaying = false;
            }
            try{
                Hisense.File.write("retailmode", "close", 0);//write data to /tmp/retailmode. open: running, close: stopped
            }catch(e){
                DBG_ERROR(e.message);
            }
            startEPOS = false;
        }
        catch (e) {
            DBG_ERROR(e.message);
        }
    } else {
        DBG_INFO("change current signal mode");
        if(o.status == "signal"){//视频切信号
            if(!!signalTimer){
                clearTimeout(signalTimer);
                signalTimer = null;
            }
            if (isDMPPlaying || g_playMode == "video") {
                if(isDMPPlaying) {
                    DBG_INFO("model.mpctrl.StopMpctrl");
                    model.mpctrl.MpCtrlRelease(null);
                    isDMPPlaying = false;
                }
                // resumeDTV();
                startDTVPlay();
            }
            g_playMode = "signal";
        }else if(o.status == "video"){//信号切视频
            DBG_INFO("current video mode");
            g_playMode = "video";
            if(!!signalTimer){
                clearTimeout(signalTimer);
                signalTimer = null;
            }
            g_USBVideoListIndex = 0;
            playVideo();
        }else if(o.status == "videosignal"){//切视频加信号
            DBG_INFO("current mode is videosignal");
            g_playMode = "videosignal";
            g_USBVideoListIndex = 0;
            playVideo();
        } else if(o.status == "updateVideoStart"){//切视频加信号
            DBG_ERROR("Play  updateVideoStart");
            videoUpdating = true;
            if (isDMPPlaying) {
                DBG_INFO("model.mpctrl.StopMpctrl");
                model.mpctrl.MpCtrlRelease(null);
                isDMPPlaying = false;
            }
        } else if(o.status == "updateVideoEnd"){//切视频加信号
            DBG_ERROR("Play  updateVideoEnd");
            videoUpdating = false;
            getBuildInVideoPath();
            g_USBVideoListIndex = 0;
            playVideo();
        }else if(o.status == "changeLanguage"){//改变多语言
            DBG_ERROR("change  language");
            initEposImg();
        }
    }
}

//底层通知
opera_omi.addPlatformEventListener(handlePlatformEvent);

/**
 * 处理epos获取的按键
 * @param event
 */
document.onkeydown=function(event){
    //resetPQAQ(true);
    if(noSignal == 0 && !isDMPPlaying) { //有信号，没有播放视频
        if(slideshowTimer == null) {
            sendMessageToUI("stopEposToLiveTV");
        }
    }
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if(e.keyCode == 461) {
        return;
    }else{
        DBG_ERROR("epos receive key " +e.keyCode );
        stopEpos();
        if(tagTimer) {
            clearInterval(tagTimer);
            tagTimer  = setInterval(function () {
                checkTagTimer();
            },15000);
        }
    }
}

/**
 * 获取当前通道是否有信号，有信号返回0
 * @returns {number}
 */
function getNoSignalValueForEpos() {
    try {
        if (!tv) return 0;
        signalVal = 0;
        crntSource = model.source.getCurrentSource();
        DBG_INFO("crntSource: " + crntSource);
        if (crntSource == "TV") {
            var uriMain = model.tvservice.getUriMain();
            DBG_ERROR("getNoSignalValueForEpos uriMain="+uriMain);
            if(!!uriMain && (uriMain.indexOf("external://plain/app") > -1  || uriMain.indexOf("plain/null") > -1  || uriMain.indexOf("vddt/video") > -1  || uriMain.indexOf("tmp/lo") > -1 )) {
                signalVal = 1;
            } else {
                signalVal = model.tvservice.getNoSignalMain();
            }
        }
        else {
            sourceArray = model.source.getInputName();
            DBG_INFO("sourceArray: " + objToString(sourceArray));
            var index = sourceArray.indexOf(crntSource);
            if (index > -1) {
                signalVal = (sourceArray[index + 1] == 2)? 0 : 1;  //2 有信号，1 有线连接(hdmi)无信号,0无信号
            }
            else {
                DBG_ERROR("can't find currnt source")
            }
        }
        DBG_ERROR("signalVal: " + signalVal);
        return signalVal;
    }catch (ex) {
        DBG_ERROR("getNoSignalValueForEpos: " + ex.message);
        return 0;
    }
}

function funBrand() {
    try{
        var brandName = Hisense_GetBrand();
        switch(brandName) {
            case 'Sharp':
                g_currBrand = 'shp';
                break;
            case 'TOSHIBA':
                g_currBrand = 'tos';
                break;
            default:
                g_currBrand = 'his';
                break;
        }
    }catch (ex){
        DBG_ERROR("funBrand:getCurBrand error!"+ex.message);
        g_currBrand = "his";
    }
    try{
        g_serviceNo = Hisense_GetModelName();
    }catch (ex){
        DBG_ERROR("funBrand:getCurBrand error!"+ex.message);
        g_serviceNo = "A6100";
    }
    DBG_ERROR("funBrand:g_serviceNo is : "+g_serviceNo+",g_currBrand = "+g_currBrand);
}

function funCountry() {
    try{
        g_currCountry = model.basicSetting.getTvsetLocation();
    }catch (ex){
        DBG_ERROR("funLocation:getTvsetLocation error!"+ex.message);
        g_currCountry = 80;
    }
}
function initEposData(){
    try{
        if(g_currBrand == "his"){
            if(g_serviceNo.indexOf("A6100") > -1 || g_serviceNo == "HU49K307UW" || g_serviceNo == "HU60N3500UW(1001)"){
                g_supportFun = ["4K","HDR10","Motion Rate","Smart"];
                g_supportFunIndex = [0,1,2,3];
            }else if(g_serviceNo.indexOf("A6106") > -1){
                //us
                DBG_ERROR("funBrand:country is : "+g_currCountry);
                if(g_currCountry == 80){
                    g_supportFun = ["4K","HDR10","Local dimming","Alexa"];
                    g_supportFunIndex = [0,1,4,5];
                }else{
                    //Canada & mx
                    g_supportFun = ["4K","HDR10","Local dimming","Smart"];
                    g_supportFunIndex = [0,1,4,3];
                }
            }else{
                g_supportFun = ["4K","HDR10","Motion Rate","Smart"];
                g_supportFunIndex = [0,1,2,3];
            }
        }
        else if( 'tos' === g_currBrand) {
            //英语和西班牙语的EPOS图片
            $('#tos_epos').css('animation', 2 === languageIndex ? 'tos_span infinite 20s' : 'tos_eng infinite 20s');
        }
        else{
            if(g_serviceNo.indexOf("A6109") > -1 && g_serviceNo !== "50A6109EM" && g_serviceNo !== "55A6109EM"){
                g_sharpPathPrix = "img/sharp/A6109/";
                if(g_currCountry == 80){
                    g_sharpDisFeature = ["epos_features_us_en.png","epos_features_us_fr.png","epos_features_us_sp.png"];
                    g_sharpDisFun = [
                        {
                            "title":["epos_highlight_1_en.png","epos_highlight_1_fr.png","epos_highlight_1_sp.png"],
                            "desInfo":["epos_bottom_1_en.png","epos_bottom_1_fr.png","epos_bottom_1_sp.png"]
                        },
                        {
                            "title":["epos_highlight_2_en.png","epos_highlight_2_fr.png","epos_highlight_2_sp.png"],
                            "desInfo":["epos_bottom_2_en.png","epos_bottom_2_fr.png","epos_bottom_2_sp.png"]
                        },
                        {
                            "title":["epos_highlight_3_en.png","epos_highlight_3_fr.png","epos_highlight_3_sp.png"],
                            "desInfo":["epos_bottom_3_en.png","epos_bottom_3_fr.png","epos_bottom_3_sp.png"]
                        },
                        {
                            "title":["epos_highlight_4_en.png","epos_highlight_4_fr.png","epos_highlight_4_sp.png"],
                            "desInfo":["epos_bottom_4_en.png","epos_bottom_4_fr.png","epos_bottom_4_sp.png"]
                        },
                        {
                            "title":["epos_highlight_5_us_en.png","epos_highlight_5_us_fr.png","epos_highlight_5_us_sp.png"],
                            //"desInfo":["epos_bottom_5_us_en.png","epos_bottom_5_us_fr.png","epos_bottom_5_us_sp.png"]
                            "desInfo":["epos_bottom_5_en.png","epos_bottom_5_fr.png","epos_bottom_5_sp.png"]
                        },
                        {
                            "title":["epos_highlight_6_us_en.png","epos_highlight_6_us_fr.png","epos_highlight_6_us_sp.png"],
                            //"desInfo":["epos_bottom_6_us_en.png","epos_bottom_6_us_fr.png","epos_bottom_6_us_sp.png"]
                            "desInfo":["epos_bottom_6_en.png","epos_bottom_6_fr.png","epos_bottom_6_sp.png"]
                        }
                    ];
                }else{
                    //Canada & mx

                    g_sharpDisFeature = ["epos_features_en.png","epos_features_fr.png","epos_features_sp.png"];

                    g_sharpDisFun = [
                        {
                            "title":["epos_highlight_1_en.png","epos_highlight_1_fr.png","epos_highlight_1_sp.png"],
                            "desInfo":["epos_bottom_1_en.png","epos_bottom_1_fr.png","epos_bottom_1_sp.png"]
                        },
                        {
                            "title":["epos_highlight_2_en.png","epos_highlight_2_fr.png","epos_highlight_2_sp.png"],
                            "desInfo":["epos_bottom_2_en.png","epos_bottom_2_fr.png","epos_bottom_2_sp.png"]
                        },
                        {
                            "title":["epos_highlight_3_en.png","epos_highlight_3_fr.png","epos_highlight_3_sp.png"],
                            "desInfo":["epos_bottom_3_en.png","epos_bottom_3_fr.png","epos_bottom_3_sp.png"]
                        },
                        {
                            "title":["epos_highlight_4_en.png","epos_highlight_4_fr.png","epos_highlight_4_sp.png"],
                            "desInfo":["epos_bottom_4_en.png","epos_bottom_4_fr.png","epos_bottom_4_sp.png"]
                        },
                        {
                            "title":["epos_highlight_5_en.png","epos_highlight_5_fr.png","epos_highlight_5_sp.png"],
                            "desInfo":["epos_bottom_5_en.png","epos_bottom_5_fr.png","epos_bottom_5_sp.png"]
                        }
/*                        {
                            "title":["epos_highlight_6_en.png","epos_highlight_6_fr.png","epos_highlight_6_sp.png"],
                            "desInfo":["epos_bottom_6_en.png","epos_bottom_6_fr.png","epos_bottom_6_sp.png"]
                        }*/
                    ];
                }
            }else{
                g_sharpPathPrix = "img/sharp/A6107/";
                g_sharpDisFeature = ["epos_features_en.png","epos_features_fr.png","epos_features_sp.png"];
                g_sharpDisFun = [
                    {
                        "title":["epos_highlight_1_en.png","epos_highlight_1_fr.png","epos_highlight_1_sp.png"],
                        "desInfo":["epos_bottom_1_en.png","epos_bottom_1_fr.png","epos_bottom_1_sp.png"]
                    },
                    {
                        "title":["epos_highlight_2_en.png","epos_highlight_2_fr.png","epos_highlight_2_sp.png"],
                        "desInfo":["epos_bottom_2_en.png","epos_bottom_2_fr.png","epos_bottom_2_sp.png"]
                    },
                    {
                        "title":["epos_highlight_3_en.png","epos_highlight_3_fr.png","epos_highlight_3_sp.png"],
                        "desInfo":["epos_bottom_3_en.png","epos_bottom_3_fr.png","epos_bottom_3_sp.png"]
                    },
                    {
                        "title":["epos_highlight_4_en.png","epos_highlight_4_fr.png","epos_highlight_4_sp.png"],
                        "desInfo":["epos_bottom_4_en.png","epos_bottom_4_fr.png","epos_bottom_4_sp.png"]
                    }
                ];
            }
        }

    }catch (ex){
        DBG_ERROR("funBrand:"+ex.message);
        g_currBrand = "his";
    }
}
