/* ===================================================
 * jqlyric.js v0.1
 * shawnk@qq.com

 * 使用方法
 * var $container=$('#lyriccontainer'); //用于显示歌词的容器对象，样式自己定义
 * $container.jqlyric({
 *      lyric:'\
            [ti:存在] \
            [ar:汪峰] \
            [al:存在] \
            [by:Love] \
            [00:00.00]汪峰 - 存在 \
            [00:00.68]多少人走着却困在原地 \
            [00:07.93]多少人活着却如同死去',   // 歌词字符串，标准lrc文件格式
 *      speed:1000,                  // 歌词滚动间隔 (毫秒)
 *      getPosition:function(){      // 获取当前播放位置的函数(返回秒数), 请定义外部函数，不指定本参数则默认从调用插件开始自动播放
 *          return position;
 *      }
 * });

 * ===================================================
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

(function($) {
	var gtime = 0;
	var lyric_listener;
	$.fn.jqlyric = function(options) {
		var opts = $.extend({},
		$.fn.jqlyric.defaults, options);

		return this.each(function() {
			var o = $.meta ? $.extend({},
			opts, $this.data()) : opts;
			var $this = $(this);

			var arrLyric = new Array(); //放存汉字的歌词
			var arrTime = new Array(); //存放时间
			var currentLine = 0; //当前活动的歌词行号
			// 开始解析歌词
			//将歌词解析成数组
			var arrly = o.lyric.split('\n'); 
			for (var i = 0; i < arrly.length; i++) {
				var str = arrly[i];
				str = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

				if (str.indexOf('ti:') > -1 || str.indexOf('ar:') > -1 || str.indexOf('al:') > -1 || str.indexOf('by:') > -1) {
					// 歌曲特征字段
					var tmp = str.substring(str.indexOf(':') + 1);
					var text = tmp;
					//tag=tag.replace(/([ti|ar|al|by])/g,'');
					//arrLyric.push(tag+text);
					//arrTime.push(toSeconds('00:00:00'));   //
				} else {
					var text = arrly[i].substring(arrly[i].indexOf("]") + 1);
					//if(text==''){text='&nbsp;';}
					arrLyric.push(text); //放歌词
					arrTime.push(toSeconds(str)); //放时间    
				}
			}

			// 所有歌词按时间顺序排列
			for (var k = 0; k < arrTime.length; k++) {
				for (var j = 0; j < arrTime.length - k; j++) {
					if (arrTime[j] > arrTime[j + 1]) {
						temp = arrTime[j];
						arrTime[j] = arrTime[j + 1];
						arrTime[j + 1] = temp;

						temp = arrLyric[j];
						arrLyric[j] = arrLyric[j + 1];
						arrLyric[j + 1] = temp;
					}
				}
			}
			// 所有歌词封装成歌词对象
			var arrLyricObj = new Array();
			for (var k = 0; k < arrTime.length; k++) {
				var lrcContent = arrLyric[k];
				var len = lrcContent.replace(/(^s*)|(s*$)/g, "").length; 
				if (!lrcContent || len == 0) {
					continue;
				}
				var timeStart = arrTime[k];
				var timeEnd = k < arrTime.length - 1 ? arrTime[k + 1] - 0.01 : 99999999999999;
				if (timeEnd < 0) {
					continue;
				}

				var lrc = {
					timeStart: timeStart,
					timeEnd: timeEnd,
					lrcContent: lrcContent
				};
				arrLyricObj.push(lrc);
			}
			// 显示歌词
			var displayLine = function(lineID,num){
				var lc = arrLyricObj[num].lrcContent.split("<br/>");
				$(lineID+" span:eq(0)").text(lc[0]);
				if (lc.length > 1) {
					$(lineID+" span:eq(1)").text(lc[1]);
				}
				if (lc.length > 2) {
					$(lineID+" span:eq(2)").text(lc[2]);
				}
				$(lineID).attr("currentLine", num);
			};
			
			clearTimeout(lyric_listener);
			var timeFun = function() { // 定时检查当前播放进度，作出滚动动作
				var pos = o.getPosition();
				for (var k = 0; k < arrLyricObj.length; k++) {
					if (pos >= arrLyricObj[k].timeStart && pos <= arrLyricObj[k].timeEnd) {
						if ($("#line-current").attr("currentLine") != k) {
							if (k > 0) {
								displayLine("#line-last",k-1);
							}
							if (k < arrTime.length - 1) {
								displayLine("#line-next",k+1);
							}

							displayLine("#line-current",k);

							break;
						}
					}
				}
				lyric_listener = setTimeout(timeFun, o.speed);
			};
			lyric_listener = setTimeout(timeFun, o.speed);
		});
	};

	$.fn.jqlyric.defaults = {
		lyric: '[00:00.00]未找到歌词',
		// 歌词字符串 (lrc格式)
		speed: 500,
		// 歌词进度一首歌间隔(毫秒)
		getPosition: function() { // 获取播放器当前播放位置
			gtime += 0.5;
			return gtime;
		}
	}

	function toSeconds(t) { //把形如：01：25的时间转化成秒；
		var m = t.substring(0, t.indexOf(":"));
		var s = t.substring(t.indexOf(":") + 1);
		s = parseInt(s.replace(/\b(0+)/gi, ""));
		if (isNaN(s)) s = 0;
		var totalt = parseInt(m) * 60 + s;
		//alert(parseInt(s.replace(/\b(0+)/gi,"")));
		if (isNaN(totalt)) return 0;
		return totalt;
	}

})(jQuery);

$(function() {
	var audio = document.getElementById("audio");
	if (!audio) {
		return;
	}
	var fun_getPosition = function() {
		return audio.currentTime;
	}
	audio.onerror = audio.onabort = audio.onstalled = function(m) {
		layer.msg('播放器发生错误：'+m.type,{
		  type: 1,
		  title: false,
		  shade:0,
		  offset:'b',
		  time:8000
		});
	};
	var url = audio.currentSrc;
	var urlArr = url.split('?');
	var k = urlArr[0],
	appU = k.split('/');
	var srcFileExt = appU[appU.length - 1].split('.')[1];
	url = url.replace("." + srcFileExt, ".lrc");
	var url = "https://djt-res.fzcl.org.cn/getJSON.php?callback=?&url=" + (url);
	var $container = $('#lyriccontainer');
	var noSleep = new NoSleep();
	var enableNoSleep = false;
	var isFullScreen = false;
	var btn_lyricFullscreen = document.getElementById("lyricFullscreen");
	//  监听全屏事件触发
	var fullscreenchange = function() {
		isFullScreen = !!(
        document.fullscreen ||
        document.mozFullScreen ||
        document.webkitIsFullScreen ||
        document.webkitFullScreen ||
        document.msFullScreen
      );
		if (isFullScreen) {
			if(!enableNoSleep){noSleep.enable();}
			$(btn_lyricFullscreen).html('退出全屏');
			enableNoSleep = true;
		} else {
			if(enableNoSleep){noSleep.disable();}
			$(btn_lyricFullscreen).html('全屏播放');
			enableNoSleep = false;
		}
		$("#lyricSleep").prop("checked",enableNoSleep);
	}; 
	if (btn_lyricFullscreen) {
		btn_lyricFullscreen.addEventListener('click',
		function(event) {
			var element = $container[0];
			audio.play();
			// 判断浏览器前缀
			if (document.fullscreenEnabled) {
				if($(btn_lyricFullscreen).html()=='全屏播放'){
					if (element.requestFullscreen) {
						element.requestFullscreen();
					} else if (element.mozRequestFullScreen) {
						element.mozRequestFullScreen();
					} else if (element.webkitRequestFullscreen) {
						element.webkitRequestFullscreen();
					} else if (element.msRequestFullscreen) {
						element.msRequestFullscreen();
					}
				}else{
					document.exitFullscreen();
				}
			}else{
				if($(btn_lyricFullscreen).html()=='全屏播放'){
					var i=layer.open({
					  type: 1,
					  title: false,
					  content: $container
					});
					layer.full(i);
				}else{
					
				}
			}
		});
	}
	
	['fullscreenchange','webkitfullscreenchange','mozfullscreenchange'].forEach((item,index) => {
          $container[0].addEventListener(item, () => fullscreenchange());
    });

	$.getJSON(url,
	function(data) {
		var lrcContent = data.data; 
		if (!lrcContent || lrcContent == "") {
			return;
		}
		//用于显示歌词的容器对象，样式自己定义
		$container.jqlyric({
			lyric: lrcContent,
			// 歌词字符串，标准lrc文件格式
			getPosition: fun_getPosition
		});
	});

	var btn_lyricBigger = document.getElementById("lyricBigger");
	//调节字体大小
	var adjustFontSize = function (sizeOffset){
		var size='',num=0;
		if(isFullScreen){
			var styleStr=($('#lyriccontainer').attr("style")+"");
			var styleArr=$.map(styleStr.split(";"),function(node){
				var returnNode=node;
				if(node.indexOf("--full-font-size")>-1){
					num = $.trim(node.split(":")[1]);
					var unit = "vmin";
					num = parseFloat(num.substring(0,num.indexOf(unit)));
					num += sizeOffset;
					size = num + unit;
					returnNode="--full-font-size:"+size;
				}
				return returnNode;
			});
			$('#lyriccontainer').attr("style",styleArr.join(";"));
		}else{
		    var styleStr=($('#lyriccontainer').attr("style")+"");
			var styleArr=$.map(styleStr.split(";"),function(node){
				var returnNode=node;
				if(node.indexOf("--default-font-size")>-1){
					num = $.trim(node.split(":")[1]);
					var unit = "rem";
					num = parseFloat(num.substring(0,num.indexOf(unit)));
					num += sizeOffset;
					size = num + unit;
					returnNode="--default-font-size:"+size;
				}
				return returnNode;
			});
			$('#lyriccontainer').attr("style",styleArr.join(";"));
		}
	};
	
	if (btn_lyricBigger) {
		btn_lyricBigger.addEventListener('click',
		function() {
			adjustFontSize(1);
		},
		false);
	}
	
	var btn_lyricSmaller = document.getElementById("lyricSmaller");
	if (btn_lyricSmaller) {
		btn_lyricSmaller.addEventListener('click',
		function() {
			adjustFontSize(-1);
		},
		false);
	}
	var chk_lyricSleep = document.getElementById("lyricSleep");
	if (chk_lyricSleep) {
		chk_lyricSleep.addEventListener('change',
		function(event) {
			let isCheck = event.srcElement.checked;
			if (isCheck) {
				if(!enableNoSleep){noSleep.enable();}
				enableNoSleep = true;
			} else {
				if(enableNoSleep){noSleep.disable();}
				enableNoSleep = false;
			}
		});
	}
	
	var btn_lyricCache = document.getElementById("lyricCache");
	if (btn_lyricCache) {
		btn_lyricCache.addEventListener('click',
		function() {
			audio.preload="auto";
		},
		false);
	}
});