﻿pl = {
	name: 'dplugin_Lyricwikia',
	label: prop.Panel.Lang == 'ja' ? '歌詞検索: LyricWikia' : 'Download Lyrics: LyricWikia',
	author: 'tomato111,Junya Renno',
	onStartUp: function () { // 最初に一度だけ呼び出される関数
	},
	onCommand: function (isAutoSearch) { // プラグインのメニューをクリックすると呼び出される関数
		if (!isAutoSearch && utils.IsKeyPressed(VK_CONTROL)) {
			plugins['splugin_AutoSearch'].setAutoSearchPluginName(this.name);
			return;
		}
		
		if (!fb.IsPlaying) {
			StatusBar.showText(prop.Panel.Lang == 'ja' ? '再生していません。' : 'Not Playing');
			return;
		}
		
		var debug_html = false; // for debug
		var depth = 0;
		var label = this.label.replace(/^.+?: /, '');
		var NotAlphaNumericRE = /[^a-z0-9]/g;
			// title, artist for search
		var title = fb.TitleFormat('%title%').Eval();
		var artist = fb.TitleFormat('%artist%').Eval();
		if (!isAutoSearch) {
			title = prompt('Please input TITLE', label, title);
			if (!title) return;
			artist = prompt('Please input ARTIST', label, artist);
			if (!artist) return;
		}
		StatusBar.showText((prop.Panel.Lang == 'ja' ? '検索中......' : 'Searching......') + label);
		getHTML(null, 'GET', createQuery(artist,title), ASYNC, depth, onLoaded);

		//------------------------------------

		function createQuery(artist,title) {
			artist = artist.replace(/[\s|\/]+/g,"_");
			artist = encodeURIComponent(artist).replaceEach("'", '%27', '\\(', '%28', '\\)', '%29', '%20', '+', 'g');
			title = title.replace(/[\s|\/]+/g,"_");
			title = encodeURIComponent(title).replaceEach("'", '%27', '\\(', '%28', '\\)', '%29', '%20', '+', 'g');
			return "http://lyrics.wikia.com/wiki/" + artist + ":" + title;
		}
		
		function onLoaded(request, depth, file) {
			StatusBar.showText((prop.Panel.Lang == 'ja' ? '検索中......' : 'Searching......') + label);
			debug_html && fb.trace('\nOpen#' + depth + ': ' + file + '\n');
			var res = request.responseText;
			debug_html && fb.trace(res);
			var resArray = res.split(getLineFeedCode(res));
			var Page = new AnalyzePage(resArray, depth);
			if (Page.lyrics) {
				var text = onLoaded.info + Page.lyrics;
				debug_html && fb.trace('\n' + text + '\n===End debug=============');
				if (isAutoSearch) {
					plugins['splugin_AutoSearch'].results.push({ name: label, lyric: text });
				}
				else {
					main(text);
					StatusBar.showText(prop.Panel.Lang == 'ja' ? '検索終了。歌詞を取得しました。' : 'Search completed.');
					var AutoSaveTo = window.GetProperty('Plugin.Search.AutoSaveTo');

					if (/^Tag$/i.test(AutoSaveTo))
						saveToTag(getFieldName());
					else if (/^File$/i.test(AutoSaveTo))
						saveToFile(parse_path + (filetype === 'lrc' ? '.lrc' : '.txt'));
				}
			} else {
				if (isAutoSearch) {
					plugins['splugin_AutoSearch'].results.push({ name: label, lyric: null });
					return;
				}
				StatusBar.hide();
				var intButton = ws.Popup(prop.Panel.Lang == 'ja' ? 'ページが見つかりませんでした。\nブラウザで開きますか？' : 'Page not found.\nOpen the URL in browser?', 0, 'Confirm', 36);
				if (intButton === 6)
					FuncCommand('"' + file + '"');
			}
		}
		
		function AnalyzePage(resArray, depth) {
			var isLyric;
			var StartLyricRE = /<div class='lyricbox'>/ig;
			var LineBreakRE = /<br\s?\/>/ig;
			var EndLyricRE = /<!--/i;
			var IgnoreRE = /<i>|<\/i>/ig;
			var BreakLyricRE = /<div class='lyricsbreak'><\/div>/ig;
			var LineFeedCode = prop.Save.LineFeedCode;
			
			onLoaded.info = title + LineFeedCode + LineFeedCode + LineFeedCode;
			this.lyrics = '';
			for (var i = 0; i < resArray.length; i++){
				if (StartLyricRE.test(resArray[i])) {
					this.lyrics = resArray[i].replace(StartLyricRE,'');
					break;
				}
			}
			this.lyrics = this.lyrics
				.decNumRefToString()
				.replace(LineBreakRE, LineFeedCode)
				.replace(EndLyricRE, '')
				.replace(BreakLyricRE, '')
				.replaceEach('&quot;', '"', '&amp;', '&', 'ig')
				.trim();
		}
	}
};
