//判断是否存在jq插件
if (typeof jQuery == 'undefined') loadScript('//cdn.bootcss.com/jquery/3.4.1/jquery.min.js',function () {});

//加载版权（这里我就想说，改归改，版权要留下）
console.group("欢迎使用天方夜谭音乐播放器：官方网站：http://www.eirds.com");
console.log(`%c 作者：`, `color: #03A9F4; font-weight: bold`, '天方夜谭');
console.log(`%c 联系QQ：`, `color: #4CAF50; font-weight: bold`, '17404785');
console.log(`%c 官方交流Q群：`, `color: #ec7259; font-weight: bold`, '592427909');
console.groupEnd();

//加载css(font-awesome.min.css)
dynamicLoadCss('//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css');

//加载css()
dynamicLoadCss('//127.0.0.1:518/ThinkPHP/Cache/At6BrD7AkZ93yTojt3ndR4U5p5pU4EWU/player1/css/player.css');

//动态加载css
function dynamicLoadCss(url) {
    var head = document.getElementsByTagName('head')[0];
    var link = document.createElement('link');
    link.type='text/css';
    link.rel = 'stylesheet';
    link.href = url;
    head.appendChild(link);
}

//动态加载js
function loadScript(url,callback) {
    var script=document.createElement("script");
    script.type="text/javascript";
    if(script.readyState){  // ie游览器
        script.onreadystatechange=function () {
            if(script.readyState=="loaded" || script.readyState=="complete"){
                script.onreadystatechange=null;
                callback();
            }
        }
    }else { //其他
        script.onload=function () {
            callback();
        }
    };
    script.src=url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

window.onload = function(){
    //全局变量
    var audio,
        autoplay,
        isFirstPlay = localStorage.qplayer == undefined? true: false;
    var music_api = 'https://cloud.xmyrs.cn/music/api.php';

    //超级缓存
    var TFYT_Cache = {};

    //储存播放器资源站
    $.data(TFYT_Cache, 'TFYT_URL', $('[ID="TFYT"]').attr('TFYT_URL'));

    //储存播放器KEY
    $.data(TFYT_Cache, 'TFYT_KEY', $('[ID="TFYT"]').attr('TFYT_KEY'));

    //储存播放器ID
    $.data(TFYT_Cache, 'TFYT_ID', $('[ID="TFYT"]').attr('TFYT_ID'));

    //移除无用的属性
    $('[ID="TFYT"]').removeAttr('TFYT_KEY');
    $('[ID="TFYT"]').removeAttr('TFYT_ID');
    $('[ID="TFYT"]').removeAttr('TFYT_URL');
    $('[ID="TFYT"]').removeAttr('ID');

    //加载天方夜谭音乐播放器
    $('body').append('<div id="TFYT-Player">\n' +
        '    <div class="TFYT-Player">\n' +
        '        <div class="TFYT-Player-background">\n' +
        '            <div class="TFYT-Player-Info">\n' +
        '                <div class="TFYT-Player-Head">\n' +
        '                    <div class="TFYT-Player-Song-Info">\n' +
        '                        <div class="TFYT-Player-Song-Name" title="歌名"><i class="fa fa-music"></i> <span>歌名</span></div>\n' +
        '                        <div class="TFYT-Player-Song-Artist" title="艺术家"><i class="fa fa-user"></i> <span>艺术家</span></div>\n' +
        '                        <div class="TFYT-Player-Song-Album" title="专辑"><i class="fa fa-info-circle"></i> <span>专辑</span></div>\n' +
        '                    </div>\n' +
        '                    <div class="TFYT-Player-Cover"><img class="TFYT-Player-Cover-img" src="https://p3.music.126.net/Wc5RGwkyzCldRQK9oD9ODA==/109951163854792864.jpg?param=300y300"></div>\n' +
        '                    <div class="TFYT-Player-Config">\n' +
        '                        <div class="TFYT-Player-Lyric-State" title="歌词：已开启"><i class="fa fa-text-width"></i> <span>歌词已开启</span></div>\n' +
        '                        <div class="TFYT-Player-Pattern-State" title="播放模式：歌单循环"><i class="fa fa-retweet"></i> 歌单循环</div>\n' +
        '                        <div class="TFYT-Player-Volume-State" title="目前音量：100%"><i class="fa fa-volume-up"></i> 音量：100</div>\n' +
        '                    </div>\n' +
        '                    <div class="TFYT-Player-Time">\n' +
        '                        <time title="播放进度"><i class="fa fa-clock-o"></i> <span>00:00</span></time>\n' +
        '                        <time title="播放总进度"><i class="fa fa-clock-o"></i> <span>04:29</span></time>\n' +
        '                    </div>\n' +
        '                </div>\n' +
        '                <div class="TFYT-Player-Foot">\n' +
        '                    <div class="TFYT-Player-Control">\n' +
        '                        <div class="TFYT-Player-Backward" title="上一首"><i class="fa fa-step-backward"></i></div>\n' +
        '                        <div class="TFYT-Player-Play" title="点击播放"><i class="fa fa-play-circle"></i></div>\n' +
        '                        <div class="TFYT-Player-Forward" title="下一首"><i class="fa fa-step-forward"></i></div>\n' +
        '                    </div>\n' +
        '                    <div class="TFYT-Player-Progress" title="点击进度条可进行快退/快进">\n' +
        '                        <div class="TFYT-Player-Progress-Back"></div>\n' +
        '                        <div class="TFYT-Player-Progress-Btn"></div>\n' +
        '                    </div>\n' +
        '                    <div class="TFYT-Player-Lyric" title="点击关闭歌词"><i class="fa fa-toggle-on"></i></div>\n' +
        '                    <div class="TFYT-Player-List" title="播放列表"><i class="fa fa-list-ul"></i></div>\n' +
        '                </div>\n' +
        '            </div>\n' +
        '        </div>\n' +
        '        <div class="TFYT-Player-Switch">\n' +
        '            <div class="TFYT-Player-Switch-Button"><i class="fa fa-chevron-left"></i></div>\n' +
        '        </div>\n' +
        '        <div class="TFYT-Player-Music-List-Container">\n' +
        '            <div class="TFYT-Player-Music-List-Head"><span>天方夜谭音乐播放器</span>-<span>歌单列表</span></div>\n' +
        '            <ol class="TFYT-Player-Music-List" id="TFYT-Player-Music-List1"></ol>\n' +
        '            <ol class="TFYT-Player-Music-List" id="TFYT-Player-Music-List2" style="display: none"></ol>\n' +
        '        </div>\n' +
        '    </div>\n' +
        '    <div class="TFYT-Player-Lyric-Container">\n' +
        '        <div class="TFYT-Player-Lyric-Txt">\n' +
        '            <p>歌词显示在这里</p>\n' +
        '        </div>\n' +
        '    </div>\n' +
        '</div>');

    //加载播放器信息
    var TFYT_Player_Load = (function() {
        var result;
        $.ajax({
            type:'GET',
            url:$.data(TFYT_Cache,'TFYT_URL')+'PlayerList.php',
            dataType:'json',
            data:'id='+$.data(TFYT_Cache,'TFYT_ID')+'&key='+$.data(TFYT_Cache,'TFYT_KEY')+'',
            async:false,
            success:function(data){
                result = data;
            },
            error:function (data) {
                showNotification('加载音乐播放器失败，原因：目标资源站请求错误！');
            }
        });
        return result;
    })();

    //储存播放器信息
    $.data(TFYT_Cache, 'TFYT', TFYT_Player_Load);

    //获取播放器名称
    $('.TFYT-Player-Music-List-Head span:nth-child(1)').html($.data(TFYT_Cache, 'TFYT').info.name);

    //获取要播放的歌单
    $.data(TFYT_Cache, 'TFYT_Song_List',$.data(TFYT_Cache, 'TFYT', TFYT_Player_Load).song_list);

    //获取播放器封面
    $('.TFYT-Player-Cover-img').attr('src',$.data(TFYT_Cache, 'TFYT').song_list[0].img);

    //获取要播放的歌曲
    $.data(TFYT_Cache, 'TFYT_Music_List',$.data(TFYT_Cache, 'TFYT', TFYT_Player_Load).music_list);

    //是否自动播放
    $.data(TFYT_Cache,'AUTO_PLAY',TFYT_Player_Load.info.auto_play);

    //储存播放模式
    $.data(TFYT_Cache,'PLAY_MODE',TFYT_Player_Load.info.play_mode);

    //是否自动播放
    if ($.data(TFYT_Cache,'AUTO_PLAY')=='1'){
        autoplay = true;
    }else{
        autoplay = false;
    }

    //返回歌单列表
    $('.TFYT-Player').on("click",'.TFYT-Player-Return', function(e) {
        $('.TFYT-Player-Music-List-Head span:nth-child(1)').html($.data(TFYT_Cache, 'TFYT').info.name);
        $('.TFYT-Player-Music-List-Head span:nth-child(2)').html('歌单列表');
        $('.TFYT-Player-Music-List-Head').removeClass('TFYT-Player-Return');
        $('#TFYT-Player-Music-List1').slideDown(800);
        $('#TFYT-Player-Music-List2').hide();
    });

    //获取歌单的点击事件
    $("#TFYT-Player-Music-List1.TFYT-Player-Music-List").on("click","li",function(){
        $('#TFYT-Player-Music-List1').hide();
        $('.TFYT-Player-Music-List-Head span:nth-child(1)').html('<i class="fa fa-arrow-circle-left" aria-hidden="true"></i> 点击返回');
        $('.TFYT-Player-Music-List-Head span:nth-child(2)').html('歌曲列表');
        $('.TFYT-Player-Music-List-Head').addClass('TFYT-Player-Return');
        $('#TFYT-Player-Music-List2').slideDown(800);
        TFYT_Load_Music($.data(TFYT_Cache, 'TFYT').song_list[$(this).index()].id);
        $.data(TFYT_Cache, 'TFYT_Song_Index',$(this).index());
        //获取歌单封面
        $.data(TFYT_Cache, 'TFYT_Player_Cover_Load',$.data(TFYT_Cache, 'TFYT').song_list[$(this).index()].img);
    });

    //获取歌曲点击事件
    $("#TFYT-Player-Music-List2.TFYT-Player-Music-List").on("click","li",function(){
        TFYT_Player_Music_Load($(this).index());
    });

    //根据歌单加载音乐列表
    function TFYT_Load_Music(id){
        $('#TFYT-Player-Music-List2').html('<li style="text-align:center;list-style-type:none;"><span class="TFYT-Player-Load"><i class="fa fa-fw fa-refresh fa-spin"></i></span></li>');
        $.ajax({
            type:'GET',
            url:$.data(TFYT_Cache,'TFYT_URL')+'getmusic.php',
            dataType:'json',
            data:'id='+id+'&key='+$.data(TFYT_Cache,'TFYT_KEY')+'',
            success:function(data){
                if (data.length>0){
                    $('#TFYT-Player-Music-List2').html('');
                    for (var i = 0;i<data.length;i++){
                        $('#TFYT-Player-Music-List2').append('<li class="TFYT-Player-Music-List-Lib" TFYT_Music_Id="'+i+'"><span>'+data[i].music_artist+'</span><div>'+data[i].music_name+'</div></li>');
                    }
                    TFYT_Storage_Music_List(data);
                }else{
                    $('#TFYT-Player-Music-List2').html('');
                    showNotification(data.msg);
                }
            },
            error:function (data) {
                showNotification('获取音乐列表失败，原因：目标资源站请求错误！');
            }
        });
    };

    //储存音乐
    var TFYT_Storage_Music_List = function(data){
        $.data(TFYT_Cache, 'TFYT_Music_List', data);
    };

    //播放器开关
    $(".TFYT-Player .TFYT-Player-Switch").on('click', function(){
        var mA = $(".TFYT-Player");
        if ($('.TFYT-Player-Switch .TFYT-Player-Switch-Button').hasClass('TFYT-Player-Switch-Button-No') === false) {
            if (isFirstPlay) {
                setTimeout("showTips('.TFYT-Player .TFYT-Player-Cover-img','点击封面开启(关闭)随机播放', " + function(){setTimeout("showTips('.TFYT-Player .TFYT-Player-Progress .TFYT-Player-Progress-Btn','点击拖动进度按钮快进(快退)')", 1000)} + ");", 500);
                isFirstPlay = !isFirstPlay;
                localStorage.qplayer = 'false';
            }
            mA.css("transform", "translateX(300px)");
            $('.TFYT-Player-Switch .TFYT-Player-Switch-Button').addClass('TFYT-Player-Switch-Button-No');
        } else {
            mA.css("transform", "translateX(0px)");
            $('.TFYT-Player-Switch .TFYT-Player-Switch-Button').removeClass('TFYT-Player-Switch-Button-No')
        }
    });

    //播放器列表
    $('.TFYT-Player .TFYT-Player-List').on('click', function(){
        var pl = $('.TFYT-Player-Music-List');
        if (pl.hasClass('TFYT-Player-Music-List-Open') === false) {
            $('.TFYT-Player .TFYT-Player-Music-List-Container').slideDown(800);
            pl.css({"max-height":"255px","transition":"max-height .5s ease",'overflow-x':'hidden'});
            pl.addClass('TFYT-Player-Music-List-Open');
        } else {
            $('.TFYT-Player .TFYT-Player-Music-List-Container').slideUp(800);
            pl.css({"max-height":"0px","transition":"max-height .5s ease"});
            pl.removeClass('TFYT-Player-Music-List-Open');
        }
    });

    //判断是否显示滚动条
    var totalHeight = 256;
    if (totalHeight > 255) {
        $('.TFYT-Player-Music-List').css("overflow", "auto");
    }

    //悬浮tip
    jQuery(document).ready(function($) {
        var sweetTitles = {
            x: 10,
            y: 20,
            tipElements: "a,span,img,div ",
            noTitle: false,
            init: function() {
                var noTitle = this.noTitle;
                $(this.tipElements).each(function() {
                    $(this).mouseover(function(e) {
                        if (noTitle) {
                            isTitle = true;
                        } else {
                            isTitle = $.trim(this.title) != '';
                        }
                        if (isTitle) {
                            this.myTitle = this.title;
                            this.title = "";
                            var tooltip =
                                "<div class='tooltip'><div class='tipsy-arrow tipsy-arrow-n'></div><div class='tipsy-inner'>" + this.myTitle +
                                "</div></div>";
                            $('body').append(tooltip);
                            $('.tooltip').css({
                                "top": (e.pageY + 20) + "px",
                                "left": (e.pageX - 20) + "px"
                            }).show('fast');
                        }
                    }).mouseout(function() {
                        if (this.myTitle != null) {
                            this.title = this.myTitle;
                            $('.tooltip').remove();
                        }
                    }).mousemove(function(e) {
                        $('.tooltip').css({
                            "top": (e.pageY + 20) + "px",
                            "left": (e.pageX - 20) + "px"
                        });
                    });
                });
            }
        };
        $(function() {
            sweetTitles.init();
        });
    });

    //将歌单加载到列表上
    $('#TFYT-Player-Music-List1').html('');
    for (var i = 0;i<$.data(TFYT_Cache, 'TFYT_Song_List').length;i++){
        $('#TFYT-Player-Music-List1').append('<li class="TFYT-Player-Music-List-Lib" TFYT_Song_Id="'+i+'"><span><i class="fa fa-chevron-right"></i></span><div>'+$.data(TFYT_Cache, 'TFYT').song_list[i].name+'</div></li>');
    }

    //将歌曲加载到列表上
    $('#TFYT-Player-Music-List2').html('');
    for (var i = 0;i<$.data(TFYT_Cache, 'TFYT_Music_List').length;i++){
        $('#TFYT-Player-Music-List2').append('<li class="TFYT-Player-Music-List-Lib" TFYT_Music_Id="'+i+'"><span>'+$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_artist+'</span><div>'+$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_name+'</div></li>');
    }

    //获取歌单封面
    $.data(TFYT_Cache, 'TFYT_Player_Cover_Load',$.data(TFYT_Cache, 'TFYT').song_list[0].img);

    //准备就绪
    var TFYT_Player_Music_Load = function (i) {
        $('.TFYT-Player_Style').remove();
        $('.TFYT-Player-Music-List-Lib').removeClass('TFYT-Player-Music-List-playing');
        $.data(TFYT_Cache, 'TFYT_Music_List_Index',i);  //储存当前播放歌曲的下标
        TFYT_Player_Info_Load(i);   //获取歌曲基本信息
        TFYT_Player_Cover_Load(i);  //获取歌曲封面图片
        TFYT_Player_Mp3_Load(i); //加载歌曲音频
        TFYT_Player_Lyric_Load(i);  //加载歌词
        $('[tfyt_music_id="'+i+'"]').addClass('TFYT-Player-Music-List-playing');
        return;
    };

    //获取歌曲基本信息
    var TFYT_Player_Info_Load = function (i) {
        //获取歌曲名
        $('.TFYT-Player-Song-Name span').text($.data(TFYT_Cache, 'TFYT_Music_List')[i].music_name);
        $('.TFYT-Player-Song-Name').attr('title',$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_name);
        //获取艺术家
        $('.TFYT-Player-Song-Artist span').text($.data(TFYT_Cache, 'TFYT_Music_List')[i].music_artist);
        $('.TFYT-Player-Song-Artist').attr('title',$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_artist);
        //获取专辑
        $('.TFYT-Player-Song-Album span').text($.data(TFYT_Cache, 'TFYT_Music_List')[i].music_album);
        $('.TFYT-Player-Song-Album').attr('title',$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_album);
        //打开通知
        showNotification('正在播放：'+$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_name+' - '+$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_artist);
    };

    //获取歌曲封面图片
    var TFYT_Player_Cover_Load = function (i) {
        //判断是否符合http://符合返回真不符合返回假
        var http = /^http:\/\/.*/i.test($.data(TFYT_Cache, 'TFYT_Music_List')[i].music_pic_id);
        //判断是否符合https://符合返回真不符合返回假
        var https = /^https:\/\/.*/i.test($.data(TFYT_Cache, 'TFYT_Music_List')[i].music_pic_id);
        //如果两个都为假，我们就为客户添加http://
        if (http || https) {
            $('.TFYT-Player-Cover-img').attr('src',$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_pic_id);
            $('<style class="TFYT-Player_Style">.TFYT-Player .TFYT-Player-background:after{background: transparent url('+$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_pic_id+') center center no-repeat}</style>').appendTo('head');
            $('<style class="TFYT-Player_Style">.TFYT-Player .TFYT-Player-Music-List-Container::before{background: transparent url('+$.data(TFYT_Cache, 'TFYT_Music_List')[i].music_pic_id+') center center no-repeat}</style>').appendTo('head');
        }else{
            $.ajax({
                type: 'POST',
                url: music_api,
                data: "types=pic&id=" + $.data(TFYT_Cache, 'TFYT_Music_List')[i].music_pic_id + "&source=" + $.data(TFYT_Cache, 'TFYT_Music_List')[i].music_source,
                dataType : "jsonp",
                success: function(jsonData){
                    if(jsonData.url !== "") {
                        $('.TFYT-Player-Cover-img').attr('src',jsonData.url);
                        $('<style class="TFYT-Player_Style">.TFYT-Player .TFYT-Player-background:after{background: transparent url('+jsonData.url+') center center no-repeat}</style>').appendTo('head');
                        $('<style class="TFYT-Player_Style">.TFYT-Player .TFYT-Player-Music-List-Container::before{background: transparent url('+jsonData.url+') center center no-repeat}</style>').appendTo('head');
                    }else{
                        $('.TFYT-Player-Cover-img').attr('src',$.data(TFYT_Cache, 'TFYT_Player_Cover_Load'));
                        $('<style class="TFYT-Player_Style">.TFYT-Player .TFYT-Player-background:after{background: transparent url('+$.data(TFYT_Cache, 'TFYT_Player_Cover_Load')+') center center no-repeat}</style>').appendTo('head');
                        $('<style class="TFYT-Player_Style">.TFYT-Player .TFYT-Player-Music-List-Container::before{background: transparent url('+$.data(TFYT_Cache, 'TFYT_Player_Cover_Load')+') center center no-repeat}</style>').appendTo('head');
                    }
                },
                error: function(data) {
                    console.log('获取歌曲封面图片失败!原因：'+data);
                    $('.TFYT-Player-Cover-img').attr('src',$.data(TFYT_Cache, 'TFYT_Player_Cover_Load'));
                    $('<style class="TFYT-Player_Style">.TFYT-Player .TFYT-Player-background:after{background: transparent url('+$.data(TFYT_Cache, 'TFYT_Player_Cover_Load')+') center center no-repeat}</style>').appendTo('head');
                    $('<style class="TFYT-Player_Style">.TFYT-Player .TFYT-Player-Music-List-Container::before{background: transparent url('+$.data(TFYT_Cache, 'TFYT_Player_Cover_Load')+') center center no-repeat}</style>').appendTo('head');
                }   // error
            }); //ajax
        }
    };

    //获取歌曲链接
    var TFYT_Player_Mp3_Load = function (i) {
        $.ajax({
            type: 'POST',
            url: music_api,
            data: "types=url&id=" + $.data(TFYT_Cache, 'TFYT_Music_List')[i].music_url_id + "&source=" + $.data(TFYT_Cache, 'TFYT_Music_List')[i].music_source,
            dataType : "jsonp",
            success: function(jsonData){
                if($.data(TFYT_Cache, 'TFYT_Music_List')[i].music_source == "netease") {
                    if(jsonData.url === "") {
                        jsonData.url = 'err';
                    } else {
                        jsonData.url = jsonData.url.replace(/m7c.music./g, "m7.music.");
                        jsonData.url = jsonData.url.replace(/m8c.music./g, "m8.music.");
                    }
                } else if($.data(TFYT_Cache, 'TFYT_Music_List')[i].music_source == "baidu") {    // 解决百度音乐防盗链
                    jsonData.url = jsonData.url.replace(/http:\/\/zhangmenshiting.qianqian.com/g, "https://gss0.bdstatic.com/y0s1hSulBw92lNKgpU_Z2jR7b2w6buu");
                }
                if(jsonData.url === "") {
                    jsonData.url = 'err';
                }else{
                    TFYT_Update_Music_url(jsonData.url);
                }
            },
            error: function(data) {
                showNotification('歌曲链接为空，已停止播放！');
                console.log('获取歌曲链接失败！原因：'+data);
            }
        });
    };

    //更新歌曲链接
    var TFYT_Update_Music_url = function(url){
        $('audio').remove();   //移除之前的audio
        if (url=='err' || typeof(url)==undefined){  //没有音乐就走这里
            $(".TFYT-Player-Control .TFYT-Player-Forward").click();
            return false;
        }else{
            var newaudio = $('<audio>').html('<source src="'+url+'">').appendTo('.TFYT-Player');
            audio = newaudio[0];
            audio.addEventListener('progress', player_progress, false);
            audio.addEventListener('canplay', player_canplay, false);
            audio.addEventListener('ended', player_ended, false);
            audio.addEventListener('timeupdate', playerTime, false);
        }
    };

    //更新歌词等信息...
    var TFYT_Lyric_I=0;
    $(".TFYT-Player-Lyric-Txt p").eq(0).css("color","aqua");
    var playerTime = function(){
        if (audio!==null){
            if (audio.currentTime==audio.duration){
                //下一首
                $(".TFYT-Player-Control .TFYT-Player-Forward").click();
                return false;
            }
            var duration = audio.duration;
            var curTime = audio.currentTime;
            var percentage = curTime/duration * 100;
            $(".TFYT-Player-Progress-Back").css("width",percentage + "%");
            $(".TFYT-Player-Progress-Btn").css("left",parseInt(percentage)-parseInt(3) + "%");
            $('.TFYT-Player-Time time:nth-child(1) span').text(format(audio.currentTime));
            $('.TFYT-Player-Time time:nth-child(2) span').text(format(duration));
            if ($(".TFYT-Player-Lyric-Txt p").eq(TFYT_Lyric_I).attr("lrctime")<=curTime) {
                $(".TFYT-Player-Lyric-Txt p").css("color","#8bc34a");
                $(".TFYT-Player-Lyric-Txt p").eq(TFYT_Lyric_I).css("color","#8bc34a");
                $(".TFYT-Player-Lyric-Txt").css("top",-$(".TFYT-Player-Lyric-Txt p").eq(TFYT_Lyric_I).position().top+20)
                TFYT_Lyric_I=TFYT_Lyric_I+1;
            }
            if (curTime==0) {
                $(".TFYT-Player-Lyric-Txt").css("top","24px");
                $(".TFYT-Player-Lyric-Txt p").eq(0).css("color","#8bc34a");
                TFYT_Lyric_I=0;
            }
        }
    };

    var TFYT_Player_Lyric_Load = function (i) {
        $('.TFYT-Player-Lyric-Txt').html('<li>歌词加载中...</li>');   //加载歌词
        $.ajax({
            type: 'POST',
            url: music_api,
            data: "types=lyric&id=" + $.data(TFYT_Cache, 'TFYT_Music_List')[i].music_lyric_id + "&source=" + $.data(TFYT_Cache, 'TFYT_Music_List')[i].music_source,
            dataType : "jsonp",
            success: function(jsonData){
                if (jsonData.lyric){
                    var lyric = jsonData.lyric;
                    Music_Lyric(lyric);
                }else{
                    $('.TFYT-Player-Lyric-Txt').html('<p>没有歌词！</p>');
                }
            },
            error: function(data) {
                $('.TFYT-Player-Lyric-Txt').html('<p>获取歌词失败！</p>');
            }
        });
    };

    var Music_Lyric = function(lyric){
        $(".TFYT-Player-Lyric-Txt").empty();   //清空上一次的歌词
        //储存歌词
        var CHlrc = lyric;
        var CHlrcs = CHlrc.split("\n");
        var medisArray = new Array();
        for (var i=0;i<CHlrcs.length;i++) {
            var time = CHlrcs[i].substring(CHlrcs[i].indexOf("[") + 1, CHlrcs[i].indexOf("]"));
            medisArray.push({
                time: (time.split(":")[0] * 60 + parseFloat(time.split(":")[1])).toFixed(3),
                CHlrc: CHlrcs[i].substring(CHlrcs[i].indexOf("]") + 1, CHlrcs[i].length),
            });
        }
        $.each(medisArray, function (i, item) {
            if (!isNaN(item.time)){
                var div_list = $("<p lrctime="+item.time+">");
                div_list.html(item.CHlrc);
                $(".TFYT-Player-Lyric-Txt").append(div_list);
            }
        });
        $.data(TFYT_Cache,'Lyric',CHlrc);
    };

    //暂停/播放
    $('.TFYT-Player-Play').on('click', function(){
        if (audio!==null){
            var html = $('.TFYT-Player-Play').html();
            if(html==='<i class="fa fa-pause-circle"></i>'){
                player_pause();
            }else{
                player_play();
            }
        }
    });

    //暂停播放
    var player_ended = function () {
        audio.currentTime = 0;
        player_pause();
    };

    //暂停播放
    var player_pause = function () {
        audio.pause();
        $(".TFYT-Player .TFYT-Player-Cover img").css("animation-play-state","paused");
        $('.TFYT-Player-Play').html('<i class="fa fa-play-circle"></i>');
        $('.TFYT-Player-Play').attr('title','点击播放');
        showNotification('歌词已关闭！');
        $('.TFYT-Player-Lyric-State span').html('歌词已关闭');
        $('.TFYT-Player-Lyric-State').attr('title','歌词已关闭');
        $('.TFYT-Player-Lyric').attr('title','点击开启歌词');
        $('.TFYT-Player-Lyric i').attr('class','fa fa-toggle-off');
        $('.TFYT-Player-Lyric-Container').slideUp(800);
    };

    // 开始播放
    var player_canplay = function(){
        if (autoplay == true) player_play();
    };

    //开始播放
    var player_play = function () {
        audio.play();
        $(".TFYT-Player .TFYT-Player-Cover img").css("animation","9.8s linear 0s normal none infinite rotate");
        $(".TFYT-Player .TFYT-Player-Cover img").css("animation-play-state","running");
        $('.TFYT-Player-Play').html('<i class="fa fa-pause-circle"></i>');
        $('.TFYT-Player-Play').attr('title','点击暂停');
        showNotification('歌词已开启！');
        $('.TFYT-Player-Lyric-State span').html('歌词已开启');
        $('.TFYT-Player-Lyric-State').attr('title','歌词已开启');
        $('.TFYT-Player-Lyric').attr('title','点击关闭歌词');
        $('.TFYT-Player-Lyric i').attr('class','fa fa-toggle-on');
        $('.TFYT-Player-Lyric-Container').slideDown(800);
    };

    //音频进度条调控功能实现
    $(".TFYT-Player-Progress").mousedown(function(ev){
        var posX = ev.clientX;
        var targetLeft = $(this).offset().left;
        var percentage = (posX - targetLeft)/140 * 100;
        audio.currentTime = audio.duration * percentage / 100;
    });

    var player_progress = function () {
        if (audio.buffered.length == 1) {
            // only one range
            if (audio.buffered.start(0) == 0) {
                // The one range starts at the beginning and ends at
                // the end of the video, so the whole thing is loaded
                var buffered = audio.buffered.end(0);
                var percentage = buffered/audio.duration * 100;
                $(".TFYT-Player-Progress-Back").css("width",percentage + "%");
            }
        }
    };

    //初始化播放器
    if ($.data(TFYT_Cache,'PLAY_MODE')=='2'){  //判断是否随机播放
        showNotification('随机播放已开启！');
        $('.TFYT-Player .TFYT-Player-Cover-img').attr('title','点击更改播放模式');
        $.data(TFYT_Cache,'PLAY_MODE',2);
        $('.TFYT-Player .TFYT-Player-Pattern-State').html('<i class="fa fa-random"></i> 随机播放');
        $('.TFYT-Player .TFYT-Player-Pattern-State').attr('title','播放模式：随机播放');
        var index = Math.floor(Math.random()*$.data(TFYT_Cache, 'TFYT_Music_List').length);
        TFYT_Player_Music_Load(index);
    }else{
        showNotification('随机播放已关闭！');
        $('.TFYT-Player .TFYT-Player-Cover-img').attr('title','点击更改播放模式');
        $('.TFYT-Player .TFYT-Player-Pattern-State').attr('title','播放模式：歌曲循环');
        $.data(TFYT_Cache,'PLAY_MODE',1);
        $('.TFYT-Player .TFYT-Player-Pattern-State').html('<i class="fa fa-retweet"></i> 歌曲循环');
        TFYT_Player_Music_Load(0);
    }

    //随机播放开关
    $('.TFYT-Player').on("click",'.TFYT-Player-Cover', function(e) {
        if ($.data(TFYT_Cache,'PLAY_MODE')=='2'){
            showNotification('随机播放已关闭！');
            $('.TFYT-Player .TFYT-Player-Cover-img').attr('title','点击更改播放模式');
            $('.TFYT-Player .TFYT-Player-Pattern-State').attr('title','播放模式：歌曲循环');
            $.data(TFYT_Cache,'PLAY_MODE',1);
            $('.TFYT-Player .TFYT-Player-Pattern-State').html('<i class="fa fa-retweet"></i> 歌曲循环');
        }else{
            showNotification('随机播放已开启！');
            $('.TFYT-Player .TFYT-Player-Cover-img').attr('title','点击更改播放模式');
            $('.TFYT-Player .TFYT-Player-Pattern-State').attr('title','播放模式：随机播放');
            $.data(TFYT_Cache,'PLAY_MODE',2);
            $('.TFYT-Player .TFYT-Player-Pattern-State').html('<i class="fa fa-random"></i> 随机播放');
        }
    });

    //下一首
    $(".TFYT-Player-Control").on("click",".TFYT-Player-Forward", function(e) {
        if ($.data(TFYT_Cache,'PLAY_MODE')==2){
            TFYT_Player_Music_Load(Math.floor(Math.random()*$.data(TFYT_Cache, 'TFYT_Music_List').length));
        }else{
            var index = parseInt($.data(TFYT_Cache, 'TFYT_Music_List_Index'))+parseInt(1);
            if (index>parseInt($('#TFYT-Player-Music-List2 li').length)-parseInt(1)){
                $.data(TFYT_Cache, 'TFYT_Music_List_Index',0);
            }else{
                $.data(TFYT_Cache, 'TFYT_Music_List_Index',index);
            }
            TFYT_Player_Music_Load($.data(TFYT_Cache, 'TFYT_Music_List_Index'));
        }
    });

    //上一首
    $(".TFYT-Player-Control").on("click",".TFYT-Player-Backward", function(e) {
        if ($.data(TFYT_Cache,'PLAY_MODE')==2){
            TFYT_Player_Music_Load(Math.floor(Math.random()*$.data(TFYT_Cache, 'TFYT_Music_List').length));
        }else{
            var index = parseInt($.data(TFYT_Cache, 'TFYT_Music_List_Index'))-parseInt(1);
            if (index<0){
                $.data(TFYT_Cache, 'TFYT_Music_List_Index',parseInt($('#TFYT-Player-Music-List2 li').length)-parseInt(1));
            }else{
                $.data(TFYT_Cache, 'TFYT_Music_List_Index',index);
            }
            TFYT_Player_Music_Load($.data(TFYT_Cache, 'TFYT_Music_List_Index'));
        }
    });

    //歌词开关
    $(".TFYT-Player").on("click",".TFYT-Player-Lyric", function(e) {
        var classs = $('.TFYT-Player-Lyric i').attr('class');
        if (classs=='fa fa-toggle-on'){
            showNotification('歌词已关闭！');
            $('.TFYT-Player-Lyric-State span').html('歌词已关闭');
            $('.TFYT-Player-Lyric-State').attr('title','歌词已关闭');
            $('.TFYT-Player-Lyric').attr('title','点击开启歌词');
            $('.TFYT-Player-Lyric i').attr('class','fa fa-toggle-off');
            $('.TFYT-Player-Lyric-Container').slideUp(800);
        }else{
            showNotification('歌词已开启！');
            $('.TFYT-Player-Lyric-State span').html('歌词已开启');
            $('.TFYT-Player-Lyric-State').attr('title','歌词已开启');
            $('.TFYT-Player-Lyric').attr('title','点击关闭歌词');
            $('.TFYT-Player-Lyric i').attr('class','fa fa-toggle-on');
            $('.TFYT-Player-Lyric-Container').slideDown(800);
        }
    });

};

function format(time)
{
    var time=parseInt(time);
    var m=parseInt(time/60);
    var s=parseInt(time%60);
    m=zero(m);
    s=zero(s);
    function zero(num)
    {
        if(num<10)
        {
            num="0"+num;
        }
        return num;
    }
    return m+":"+s;
}

//打开通知
function showNotification(info) {
    isShowNotification = true;
    //判断通知是否存在，存在就移除
    if ($('.qplayer-notification').length>0) {
        $('.qplayer-notification').remove();
        clearTimeout(autoClearTimer);
        clearTimeout(autoShowTimer);
    }
    $('body').append('<div class="qplayer-notification animation-target"><span class="qplayer-notification-icon">i</span><span class="body" style="box-shadow: rgba(0, 0, 0, 0.0980392) 0px 0px 5px;"><span class="message"></span></span><a class="close" href="#" onclick="closeNotification();return false;">×</a><div style="clear: both"></div>');
    $('.qplayer-notification .message').text(info);
    //用width:auto来自动获取通知栏宽度
    var width = $('.qplayer-notification').css({"opacity":"0", "width":"auto"}).width() + 20;
    $('.qplayer-notification').css({"width":"50px","opacity":"1"});
    autoShowTimer = setTimeout(function(){
        $('.qplayer-notification').css({"width":width,"transition":"all .7s ease"});
        $('.qplayer-notification .close').delay(500).show(0);
    },1500);
    autoClearTimer = setTimeout("if ($('.qplayer-notification').length>0) {closeNotification()}",7000);
}

//关闭通知
function closeNotification() {
    isShowNotification = false;
    $('.qplayer-notification').css({"width":"50px","transition":"all .7s ease"});
    $('.qplayer-notification .close').delay(500).hide(0);
    setTimeout(function(){
        if (!isShowNotification) {
            $('.qplayer-notification').css("opacity","0");
            $('.qplayer-notification-icon').css({"transform":"scale(0)","transition":"transform .5s ease"});
        }
    },1000);
    setTimeout(function(){
        if (!isShowNotification) {
            $('.qplayer-notification').remove();
        }
    },1500);
    clearTimeout(autoClearTimer);
    clearTimeout(autoShowTimer);
}

/*
*div: 要在其上面显示tip的div
*info: tip内容
*func: 不再提示按钮的click绑定函数
*/
function showTips(div, info, func) {
    var box_height = 100;
    $('body').append('<div class="qplayer_tips"><span class="tips_arrow"></span><span class="info" style="display:none">' + info + '</span><button class="tips_button" onclick="removeTips()">不再提示</button></div>');
    $('.qplayer_tips').css({"top":$(div).offset().top-box_height-30-15, "left": $(div).offset().left-28});
    $('.qplayer_tips').css({"height":box_height,"transition":"all .5s ease-in-out"});
    $('.qplayer_tips .info').delay(500).fadeIn();
    $('.tips_arrow').css({"border-width":"15px","transition":"all .5s ease-in-out"});
    $('.tips_button').css({"height":"30px","transition":"all .5s ease-in-out"});
    if (func != undefined) {
        $('.tips_button').click(func);
    }
}

//关闭
function removeTips() {
    $('.qplayer_tips .info').fadeOut();
    $('.qplayer_tips').css({"height":"0","transition":"all .5s ease-in-out"});
    $('.tips_arrow').css({"border-width":"0","transition":"all .5s ease-in-out"});
    $('.tips_button').css({"opacity":"0","transition":"all .2s ease-in-out"});
    setTimeout(function(){$('.qplayer_tips').remove()}, 500);
}