﻿// ==PREPROCESSOR==
// @name "Biography Text && Picture. www.last.fm"
// @author "kgena_ua - mod zeremy for multilanguage "
// @author "arranged Junya Renno"
// @version "2020/09/30"
// @import "%fb2k_component_path%docs\Flags.txt"
// @import "%fb2k_component_path%docs\Helpers.txt"
// @feature "v1.4"
// @feature "watch-metadb"
// ==/PREPROCESSOR==

//------------------------ プロパティ ------------------------
var wait_sec = window.GetProperty("General: wait time(sec)", 5);
var limit = window.GetProperty("General: download limit", 5);
var abc = window.GetProperty("General: language number", 5);
var select_p_a = window.GetProperty("General: pictures/albums", 0);
var isSave_picture =  window.GetProperty("General: save artist image", false);
var artist_folder_path = window.GetProperty("General: save folder path", fb.ProfilePath + "tmp_Biography\\download\\artists\\");
var selection_mode = window.GetProperty("General: selection mode", 0);

var nocover = window.GetProperty("Visual: nocover image", false);
var nocover_path = window.GetProperty("Visual: nocover path", ".\\nocover\\nocover.png");
var search_artist = window.GetProperty("General: search artist(artist=0,album artist=1)", 1);

var info_picture ={
    position_h: window.GetProperty("Visual: image position h (left,center,right)", "center"),
    position_v: window.GetProperty("Visual: image position v (top,center,bottom)", "center"),
    margin: window.GetProperty("Visual: margin-picture", 10),
}

var info_text = {
    artist_font_color: str2rgb(window.GetProperty("Visual: color - artist name", "RGB(220,220,220)")),
    artist_font_background_color: str2rgb(window.GetProperty("Visual: color - background", "RGB(31,41,48)")),
	artist_font_name: window.GetProperty("Visual: font - artist", "MS ゴシック"),
	artist_font_size: window.GetProperty("Visual: font-size - artist", 14),
	artist_font_style: 1,

    bio_font_color: str2rgb(window.GetProperty("Visual: color - text", "RGB(255,255,230)")),
    bio_font_background_color: str2rgb(window.GetProperty("Visual: color - text background", "RGB(50,50,50)")),
	bio_font_name: window.GetProperty("Visual: font - biography", "MS ゴシック"),
	bio_font_size: window.GetProperty("Visual: font-size - biography", 12),
	bio_font_style: 0,
	transparent: window.GetProperty("Visual: color - transparent", 190),
	margin: window.GetProperty("Visual: margin-text", 10),
	
	show: window.GetProperty("Visual: show text", true),
	lines_space: window.GetProperty("Visual: space between the lines", 1.4),
	x: window.GetProperty("Visual: info_text_x", 0),
	y: window.GetProperty("Visual: info_text_y", window.Height / 2),
	scrollbar: window.GetProperty("Visual: show scrollbar", false),
	delta_x: null,
	delta_y: null,
	rows: 0,
	row_height: 0,
	text_array: [],
	visable_rows: 0,
	visable_height: 0,
	artist: artist_select(search_artist,selection_mode),
	old_artist: "",
}
info_text.artist_font = get_font_obj(info_text.artist_font_name, info_text.artist_font_size, info_text.artist_font_style);
info_text.bio_font = get_font_obj(info_text.bio_font_name, info_text.bio_font_size, info_text.bio_font_style);

//------------------------ 初期設定 ------------------------
var ww, wh;

// ActiveX関連

var doc = new ActiveXObject("htmlfile");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var WshShell = new ActiveXObject("WScript.Shell");
var script_path = fb.ProfilePath + "tmp_Biography\\download\\";
var vbs = "cscript //nologo \"" + script_path + "download.vbs\"";
var tmp_b_path = fb.ProfilePath + "tmp_Biography\\";
if (!fso.FolderExists(tmp_b_path)) {
	fso.CreateFolder(tmp_b_path)
};
if (!fso.FolderExists(tmp_b_path + "\\download\\")) {
	fso.CreateFolder(tmp_b_path + "\\download\\")
};
if (!fso.FolderExists(tmp_b_path + "\\download\\artists\\")) {
	fso.CreateFolder(tmp_b_path + "\\download\\artists\\")
};
if (!fso.FileExists(tmp_b_path + "\\download\\" + "download.vbs")) {
	create_download_file(fso,tmp_b_path + "\\download\\" + "download.vbs")
};

// 画像読み込み関係
var g_img = null;
var files = [], selected = 0;
var pic_scroll = false;

// スクロールその他
var sb_down = false;
var sb_scroll = false;
var scrollbar_k;
var posy = 0;
var b_x = 0, b_y = 0;
var text = "";
var s_text = 0;
var mouse_down = false;
var text_scroll = false;

var abc_lang = new Array("", "ru/", "es/", "fr/", "it/", "ja/", "pl/", "pt/", "de/", "sv/", "tr/", "zh/");
var if_not_found = new Array("Nothing found", "Ничего не найдено", "Nothing found", "Nothing found", "Nothing found", "見つかりませんでした", "Nothing found", "Nothing found", "Nothing found", "Nothing found", "Nothing found", "Nothing found");   // var if_not_found = new Array(_("Nothing found"), _("Nothing found"));
var select_p_a_old;
var p_a = new Array("images", "albums");
var handle;


//最初に呼び出す
on_size();
on_item_focus_change();


//-----------  コールバック  ----------------------------------

function on_paint(gr) {
	gr.SetSmoothingMode(2);
    if (!window.IsTransparent){
        gr.FillSolidRect(0, 0, ww, wh,  info_text.bio_font_background_color);
    }
	
	if (select_p_a == 1){
		handle = fb.GetNowPlaying();
	}
	g_img = gdi.Image(files[selected]);
    
	if (!g_img && nocover) {
		try {
			g_img = gdi.Image(nocover_path);
		} catch (e) {};
	}
	//画像表示
	if (g_img){
		var pp = picture_position(g_img,info_picture);
		gr.DrawImage(g_img, pp[0], pp[1], g_img.Width * pp[2], g_img.Height * pp[2], 0, 0, g_img.Width, g_img.Height);
	}
	
	//テキスト表示
	if (info_text.show){
		var artist_x = info_text.x + info_text.margin;
		var artist_y = info_text.y + info_text.margin;
		
		gr.FillSolidRect(info_text.x, info_text.y, ww - info_text.x, wh - info_text.y, RGBA(getRed(info_text.bio_font_background_color), getGreen(info_text.bio_font_background_color), getBlue(info_text.bio_font_background_color), info_text.transparent));
		//アーティスト名描画
		gr.DrawString(info_text.artist, info_text.artist_font, RGB(0, 0, 0), artist_x + 1, artist_y + 2, ww - artist_x - info_text.margin, wh);
		gr.DrawString(info_text.artist, info_text.artist_font, info_text.artist_font_color, artist_x, artist_y, ww - artist_x - info_text.margin, wh);
		//本文描画
		for (var i = 0; i < info_text.visable_rows; i++) {
			gr.SetTextRenderingHint(1);
			gr.DrawString(info_text.text_array[i + s_text], info_text.bio_font, info_text.bio_font_color, b_x, b_y + info_text.row_height * i, ww, wh);
		}
		//スクロールバー描画
		info_text.scrollbar && draw_scrollbar(gr);
	}
}

function draw_scrollbar(gr) {
	scrollbar_h = info_text.rows > info_text.visable_rows ? info_text.visable_height * (info_text.visable_rows / info_text.rows) : 0;
	scrollbar_y = s_text > 0 ? s_text * scrollbar_k : 0;
	gr.FillSolidRect(ww - 6, b_y + scrollbar_y, 6, scrollbar_h, info_text.artist_font_color);
}

function on_size() {
	ww = window.Width;
	wh = window.Height;
	info_text.x = window.GetProperty("Visual: info_text_x",0);
	info_text.y = window.GetProperty("Visual: info_text_y",window.Height / 2);
	info_text.x = info_text.x >= ww - 50 && info_text.x >= 0 ? ww - 50 : info_text.x;
	info_text.y = info_text.y >= wh - 50 && info_text.y >= 0 ? wh - 50 : info_text.y;
	get_b_text_array(text);
}

function on_playlist_switch() {
	on_item_focus_change();
}

function on_playback_new_track() {
	on_item_focus_change();
}

function on_playback_dynamic_info_track() {
	on_item_focus_change();
}

function on_playback_stop() {
	on_item_focus_change();
}


function on_item_focus_change() {
	
	switch (selection_mode) {
		case 0:
			handle = fb.IsPlaying ? fb.GetNowPlaying() : fb.GetFocusItem();
			break;
		case 1:
			handle = fb.GetFocusItem();
			break;
	}
	if (handle)
		on_metadb_changed();
}

function on_metadb_changed() {
	info_text.artist = artist_select(search_artist,selection_mode);
    change_items(0);
	window.repaint();
}

function force_download() {
	change_items(1);
}

//------------------------  画像取得  ----------------------- 
function get_pic() {
	var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	var file;
	var artist_plus = space2plus(info_text.artist);
	var url1 = ("https://www.last.fm/" + abc_lang[abc] + "music/" + artist_plus + "/+" + p_a[select_p_a]);
    xmlhttp.open("GET", url1, true);
	xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	xmlhttp.send();
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				
			doc.open();
			var div = doc.createElement("div");
			div.innerHTML = xmlhttp.responsetext;
			var data = div.getElementsByTagName("img");
            var urls = [];
			for (i = 0; i < data.length; i++) {
			data_x = data[i].parentNode.className;
            data_x = data_x.replace(/\n|\s+/g,"");
                if (select_p_a == 0 && data_x == "image-list-item") {              
                    if (data[i].src.indexOf("https://lastfm.freetls.fastly.net/i/u/avatar170s/") == 0) {
                        urls.push(data[i].src.replace("avatar170s/", ""))
                    }
                }
                if (select_p_a == 1 && data[i].parentNode.className == "resource-list--release-list-item-image cover-art") {
                    if (data[i].src.indexOf("https://lastfm.freetls.fastly.net/i/u/300x300/") == 0 && data[i].src.indexOf("c6f59c1e5e7240a4c0d427abd71f3dbb") < 0){
                    	urls.push(data[i].src.replace("300x300/", ""))
                	}
                }
                if (urls.length > limit) {
                    break;
                }
			}
			for (i = 0; i < Math.min(urls.length, limit); i++) {
				if (isSave_picture){
					file = "\"" + artist_folder_path + info_text.re_artist + "\\" + info_text.re_artist + "_" + i + "_" + p_a[select_p_a] + ".jpg" + "\"";
				} else {
					file = "\"" + tmp_b_path + info_text.re_artist + "_" + i + "_" + p_a[select_p_a] + ".jpg" + "\"";
				}
                delay_get(vbs + " " + urls[i] + " " + file,i);

			}
			doc.close();
            info_picture.count = 0; 
			re_display();				
		}
	}
}

function re_display(){
	dis_timer = window.SetTimeout(function () {
        info_picture.count++;
		get_files_from_dir();
        if (files.length < limit && info_picture.count<6) re_display();
		window.repaint();
	}, 1000 * wait_sec);
}

function delay_get(file_path,i){
	dis_timer2 = window.SetTimeout(function () {
        WshShell.Run(file_path, false);
	}, 3000 * i + 100);
}

//実際の動作
function change_items(force){	
    //window.GetBackgroundImage()
    if (!handle)
		return;
    //パスに使うための文字変換           
	info_text.re_artist = replace_word(info_text.artist);
	//検索に使うアーティスト名は変換前のものを使う
	if (info_text.artist != info_text.old_artist || select_p_a != select_p_a_old || force == 1) {
		CollectGarbage();
		g_img = null;
		files = [];
		if ((!isSave_picture) || force == 1){
			del_files_from_dir();
		}
		selected = 0;
		s_text = 0;
		text = "";
		//テキスト
        
        
		var fn1 = write_file_path(isSave_picture,info_text.re_artist,true);
 		var fn2 = write_file_path(isSave_picture,info_text.re_artist,false);
      
        if (fso.FileExists(fn1)){
            read_bio_file(fn1);	
        } else if (fso.FileExists(fn2)){
            read_bio_file(fn2);
        } else {            
			get_b_text();
 		}
		get_b_text_array(text);
		//画像
		get_files_from_dir();
 		if (files.length == 0){
			get_pic();
		}
		selected = 0;
		
		info_text.old_artist = info_text.artist;
		select_p_a_old = select_p_a;
	}
}

//ローカルの画像ファイルを数える
function get_files_from_dir() {
	files = [];
	var s_path;
	if (isSave_picture){
		if (!fso.FolderExists(artist_folder_path + info_text.re_artist)){
			fso.CreateFolder(artist_folder_path + info_text.re_artist);
		}
		s_path =  artist_folder_path + info_text.re_artist +"\\";
	} else {
		s_path = tmp_b_path;
	}
	var e = new Enumerator(fso.GetFolder(s_path).Files);
	while (e.atEnd() == false) {
		var name = e.item().Name;
		areg = new RegExp('.?_' + p_a[select_p_a] + '\.(bmp|jpg|png)$', 'i')
        if (name.match(areg)) {
			files.push(s_path + name);
		}
		e.moveNext();
	}
}

//ローカルファイルを削除
function del_files_from_dir() {
	var s_path;
	if (isSave_picture){
		if (!fso.FolderExists(artist_folder_path + info_text.re_artist))
			return;
		else 
			s_path =  artist_folder_path + info_text.re_artist +"\\";
	} else
		s_path = tmp_b_path;
	var e = new Enumerator(fso.GetFolder(s_path).Files);
	while (!e.atEnd()) {
		var name = e.item().Name;
		try {
            if (/_bio\.txt/.test(name)){}
            else {fso.deleteFile(s_path + name);}
		} catch (e) {};
		e.moveNext();
	}
}

//------------------------ テキスト取得 ------------------------ 
function get_b_text() {
	var xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
    var artist_plus = space2plus(info_text.artist);
	var url2 = ("https://www.last.fm/" + abc_lang[abc] + "music/" + artist_plus + "/+wiki");
    xmlhttp2.open("GET", url2, true);
	xmlhttp2.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2010 00:00:00 GMT");
	xmlhttp2.send();
	xmlhttp2.onreadystatechange = function () {
		if (xmlhttp2.readyState == 4  && xmlhttp2.status == 200) {		
			doc.open();

			var div = doc.createElement("div");
			div.innerHTML = xmlhttp2.responsetext;
			var data = div.getElementsByTagName("div");
			for (i = 0; i < data.length; i++) {
				if (data[i].className == "wiki-content") {
					text = strip_tags(data[i].innerHTML);
					break;
				}
			}
		doc.close();
		}
		if (text == "")
			text = if_not_found[abc];
		else {
			write_bio_file(write_file_path(isSave_picture,info_text.re_artist,false),text);
			}
		get_b_text_array(text);
		window.repaint();
	}
}

//テキストを表示用に整形
function get_b_text_array(text) {
	var string_width;
	var strings_array = [];
	info_text.text_array = [];
	temp_bmp = gdi.CreateImage(1, 1);
	temp_gr = temp_bmp.GetGraphics();
	b_x = info_text.x + info_text.margin;
	b_y = info_text.y + temp_gr.CalcTextHeight("text", info_text.artist_font) + info_text.margin * 2;
	info_text.row_height = Math.floor(temp_gr.CalcTextHeight("text", info_text.bio_font) * info_text.lines_space);
	string_width = Math.max(ww - b_x - 20, 0);
	if (text)
		strings_array = temp_gr.EstimateLineWrap(text, info_text.bio_font, string_width).toArray();
        
	for (var i = 0; i < strings_array.length; i += 2) {
		info_text.text_array.push(strings_array[i].replace(/^\s+|\s+$/g, ""));
	}
	info_text.rows = info_text.text_array.length;
	info_text.visable_rows = Math.round((wh - b_y - 10) / info_text.row_height);
	info_text.visable_height = Math.round(wh - b_y - 10);
	temp_bmp.ReleaseGraphics(temp_gr);
	temp_bmp.Dispose();
	temp_gr = null;
	temp_bmp = null;
	if (info_text.visable_rows + s_text > info_text.rows && s_text > 0) {
		s_text = info_text.rows - info_text.visable_rows;
	};
	scrollbar_k = info_text.visable_height / info_text.rows;
	window.Repaint();
}

function write_file_path(isSave_picture,artist,fix){
	var path;
    var f_char = fix ? "_" : "";
	if (isSave_picture){
        path = artist_folder_path + artist + "\\" + f_char + "bio.txt";
    } else {
        path = tmp_b_path + "bio.txt";
    }	
	return path;
}


//タグ処理
function strip_tags(t) {
	doc.open();
	var div = doc.createElement("div");
	div.innerHTML = t.replace(/<[Pp][^>]*>/g, "").replace(/<\/[Pp]>/g, "<br>").replace(/\n/g, "<br>");
	var text = div.innerText;
	doc.close();
	return text;
}

//多言語対応
function _(s) {
	switch (abc) {
		case 1:
			if (typeof(ru) != 'undefined' && ru[s]) { return ru[s]; }
			return s;
			break;
		case 5:
			if (typeof(ja) != 'undefined' && ja[s]) { return ja[s]; }
			return s;
			break;
		default:
			return s;
	}
}

//メニュー
function on_mouse_rbtn_up(x, y) {
	var _menu = window.CreatePopupMenu();
	var _firstgroup = window.CreatePopupMenu();
	_firstgroup.AppendTo(   _menu, MF_ENABLED, "Language / 言語");
	_firstgroup.AppendMenuItem(MF_ENABLED, 101, "EN - English");
	_firstgroup.AppendMenuItem(MF_ENABLED, 102, "RU - Русский");
	_firstgroup.AppendMenuItem(MF_ENABLED, 106, "JA - 日本語");
	_menu.CheckMenuRadioItem(101, 112, abc + 101);
	_menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
	_menu.AppendMenuItem(MF_ENABLED, 3, _("Prefer now playing"));
	_menu.AppendMenuItem(MF_ENABLED, 4, _("Follow selected track"));
	_menu.CheckMenuRadioItem(3, 4, selection_mode + 3);
	_menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
	_menu.AppendMenuItem(MF_ENABLED, 5, _("Artist pictures"));
	_menu.AppendMenuItem(MF_ENABLED, 6, _("Albums pictures"));
	_menu.CheckMenuRadioItem(5, 6, select_p_a + 5);
	_menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
	var is_artist = info_text.artist ? MF_ENABLED : MF_GRAYED;
	_menu.AppendMenuItem(is_artist, 7, _("Last.fm Artist"));
    _menu.AppendMenuItem(is_artist, 11, _("Wikipedia Artist"));
	_menu.AppendMenuItem(is_artist, 8, _("Force Image Download"));
    var is_save = isSave_picture ? MF_ENABLED : MF_GRAYED;
	_menu.AppendMenuItem(is_save, 9, _("Make Biography Text"));
 //   _menu.CheckMenuItem(9, is_fix);
	if (("Reload" in window)) {
		_menu.AppendMenuItem(MF_SEPARATOR, 0, 0);
		_menu.AppendMenuItem(MF_ENABLED, 10, _("Reload"));
	}
	_menu.AppendMenuItem(MF_ENABLED, 20, _("Properties"));
	_menu.AppendMenuItem(MF_ENABLED, 30, _("Configure..."));
	ret = _menu.TrackPopupMenu(x, y);
	switch (ret) {
		case 101:
			abc = 0;
			window.SetProperty("General: Language number", abc);
			s_text = 0;
			text = "";
            get_b_text();
			break;
		case 102:
			abc = 1;
			window.SetProperty("General: Language number", abc);
			s_text = 0;
			text = "";
            get_b_text();
			break;
		case 106:
			abc = 5;
			window.SetProperty("General: Language number", abc);
			s_text = 0;
			text = "";
            get_b_text();
			break;
		case 3:
			selection_mode = 0;
			window.SetProperty("General: selection mode", selection_mode);
			on_item_focus_change();
			break;
		case 4:
			selection_mode = 1;
			window.SetProperty("General: selection mode", selection_mode);
			on_item_focus_change();
			break;
		case 5:
			select_p_a = 0;
			window.SetProperty("General: pictures/albums", select_p_a);
			on_metadb_changed();
			break;
		case 6:
			select_p_a = 1;
			window.SetProperty("General: pictures/albums", select_p_a);
			on_metadb_changed();
			break;
		case 7:
            var lm_artist = prompt("Please input ARTIST", "Last.fm Search", info_text.artist);
            if (lm_artist){
                lm_artist = encodeURIComponent(lm_artist);
                lm_artist = lm_artist.replace(/%20/ig,"+");
			    WshShell.run("http://www.last.fm/" + abc_lang[abc] + "music/" + lm_artist);
            }
			break;
		case 8:
			force_download();
			break;
		case 9:
			if (isSave_picture == true)
                write_bio_file(write_file_path(isSave_picture,info_text.re_artist,true),text);
            window.Reload();
            break;
		case 10:
			window.Reload();
			break;
        case 11:
            var lm_artist = prompt("Please input ARTIST", "Wikipedia Search", info_text.artist);
            if (lm_artist){
                lm_artist = encodeURIComponent(lm_artist);
                lm_artist = lm_artist.replace(/%20/ig,"_");
                var country = "";
                if (abc == 0) country = "en"
                else
                    country = abc_lang[abc].slice(0, -1);
			    WshShell.run("https://" + country+".wikipedia.org/wiki/" + lm_artist);
            }
			break;
		case 20:
			window.ShowProperties();
			break;
		case 30:
			window.ShowConfigure();
			break;
	}
	_menu.Dispose();
	return true;
}

//別ウィンドウ（入力用）
function prompt(text, title, defaultText) {
    var sc = new ActiveXObject("ScriptControl");
    var code = 'Function fn(text, title, defaultText)\n'
    + 'fn = InputBox(text, title, defaultText)\n'
    + 'End Function'
    sc.Language = "VBScript";
    sc.AddCode(code);
    return sc.Run("fn", text, title, defaultText);
}

//マウス操作系
function on_mouse_move(x, y) {
	window.SetCursor(32649);
	text_scroll = x >= info_text.x && x < ww - 20 && y >= info_text.y ? true : false;
	sb_scroll = x > ww - 20 && y >= info_text.y ? true : false;
	pic_scroll = !text_scroll && !sb_scroll ? true : false;
	if (mouse_down && info_text.show) {
		info_text.x = x - info_text.delta_x;
		info_text.y = y - info_text.delta_y;
		info_text.x = info_text.x <= 0 ? 0 : info_text.x >= ww - 50 ? ww - 50 : info_text.x;
		info_text.y = info_text.y <= 0 ? 0 : info_text.y >= wh - 50 ? wh - 50 : info_text.y;
		get_b_text_array(text);
	}
	if (sb_down && info_text.scrollbar) {
		posy = y + info_text.delta_y;
		s_text = y + info_text.delta_y >= 0 ? y + info_text.delta_y <= (info_text.rows - info_text.visable_rows) * scrollbar_k ? Math.round(posy / scrollbar_k) : info_text.rows - info_text.visable_rows : 0;
		window.Repaint();
	}
}

var delay = false;

function fdelay() {
	var delay_timer = window.SetTimeout(function () {
		delay = false;
		window.ClearTimeout(delay_timer);
	}, 200);
}

function on_mouse_wheel(delta) {
	if (!delay && pic_scroll) {
//	if (pic_scroll){
		delay = true;
		fdelay();
		get_files_from_dir();
		if (delta < 0) {
			selected = selected <= 0 ? files.length - 1 : selected = selected - 1
		};
		if (delta > 0) {
			selected = selected >= files.length - 1 ? 0 : selected = selected + 1
		};
	}
	if (text_scroll) {
		if (info_text.rows > info_text.visable_rows) {
			if (delta < 0) {
				s_text = info_text.rows - s_text <= info_text.visable_rows ? info_text.rows - info_text.visable_rows : s_text += 1
			}
			if (delta > 0) {
				s_text = s_text <= 0 ? 0 : s_text -= 1
			}
		}
	}
	window.Repaint();
}

function on_mouse_lbtn_down(x, y) {
	if (text_scroll) {
		mouse_down = true;
		info_text.delta_x = x - info_text.x;
		info_text.delta_y = y - info_text.y;
	}
	if (sb_scroll) {
		sb_down = true;
		posy = s_text * scrollbar_k;
		info_text.delta_y = posy - y;
	}
}

function on_mouse_lbtn_up(x, y) {
	window.SetProperty("Visual: info_text_x", info_text.x);
	window.SetProperty("Visual: info_text_y", info_text.y);
	mouse_down = false;
	sb_down = false;
}

function on_mouse_lbtn_dblclk(x, y) {
	info_text.show = !info_text.show;
	window.Repaint();
}

function on_mouse_leave() {
	window.SetCursor(32512);
	window.Repaint();
}

//  -----------------------------------------------------------------------
function space2plus(word){
	var p_word = encodeURIComponent(word);
    p_word = p_word.replace(/%20/ig,"+");
	return p_word;
}

function read_fix_bio_file(){
    var fn1 = write_file_path(isSave_picture,info_text.re_artist,true);
    if (isSave_picture && fso.FileExists(fn1)){
        read_bio_file(fn1);	
    }
}

function get_font_obj(name,size,style){
	size = size < 10 ? 10 : 16 < size ? 16 : size ;
	return gdi.Font(name,size,style);
}

function str2rgb(str) {
    if (!str) {
        return RGB(0,0,0);
    }
	var c = str.match(/(\d+)/g);
    if (c.length < 3){
        fb.trace("Error: rgb?")
        return
    }else if (c.length == 3){
        return RGB( parseInt(c[0], 10)>255 ? 255 : parseInt(c[0], 10),
                    parseInt(c[1], 10)>255 ? 255 : parseInt(c[1], 10),
                    parseInt(c[2], 10)>255 ? 255 : parseInt(c[2], 10))
    } else if (c.length == 4){
         return RGBA(   parseInt(c[0], 10)>255 ? 255 : parseInt(c[0], 10),
                        parseInt(c[1], 10)>255 ? 255 : parseInt(c[1], 10),
                        parseInt(c[2], 10)>255 ? 255 : parseInt(c[2], 10),
                        parseInt(c[3], 10)>255 ? 255 : parseInt(c[3], 10))
    }
}

function Eval(field,handle) {
	if (!handle)
		return;
	else
		return fb.Titleformat("[" + field + "]").EvalWithMetadb(handle) ? fb.TitleFormat("[" + field + "]").EvalWithMetadb(handle) : fb.TitleFormat("[" + field + "]").Eval(true);
}

function replace_word(path){
	path = path.replace(/\*/g,"＊");
	path = path.replace(/\?/g,"？");
	path = path.replace(/\!/g,"！");
	path = path.replace(/\//g,"／");
	path = path.replace(/\:/g,"：");
	path = path.replace(/\</g,"＜");
	path = path.replace(/\>/g,"＞");
	path = path.replace(/\~/g,"～");
	path = path.replace(/\./g,"．");
	path = path.replace(/\"/g,"”");	
	path = path.replace(/\'/g,"’");
	return path;
}

function picture_position(g_img,info_picture){
	var pos_x,pos_y;
	var scale_w = (ww - info_picture.margin * 2) / g_img.Width;
	var scale_h = (wh - info_picture.margin * 2) / g_img.Height;
	var scale = Math.min(scale_w, scale_h);
	switch (info_picture.position_h) {
		case "left":
			pos_x = info_picture.margin;
			break;
		case "center":
			if (scale_w > scale_h){
				pos_x = (ww - (g_img.Width * scale))/2;
			} else 
				pos_x = info_picture.margin;
			break;
		case "right":
			pos_x = ww - g_img.Width * scale - info_picture.margin;
			break;
		default:
			pos_x = info_picture.margin;
	}
	switch (info_picture.position_v) {
		case "top":
			pos_y = info_picture.margin;
			break;
		case "center":
			if (scale_w < scale_h){
				pos_y = (wh - (g_img.Height * scale))/2;
			} else 
				pos_y = info_picture.margin;
			break;
		case "bottom":
			pos_y = wh - g_img.Height * scale - info_picture.margin;
			break;
		default:
			pos_y = info_picture.margin;
	}
	return [pos_x,pos_y,scale];
}

//テキスト保存
function write_bio_file(file_path,text){
	if (!file_path)
		return;
    stream = new ActiveXObject("ADODB.Stream");
	stream.type = 2;
	stream.charset = "utf-8";
	stream.open();
    stream.WriteText(text);
	stream.saveToFile(file_path, 2);
	stream.close();
	stream = null;
}

//テキスト読み込み
function read_bio_file(file_path){
    if (!file_path)
		return;
    stream = new ActiveXObject("ADODB.Stream");
	stream.type = 2;
	stream.charset = "utf-8";
	stream.open();
    stream.loadFromFile(file_path);
    text = stream.readText(-1);
	stream.close();
	stream = null;
}

//download.vbs自動作成
function create_download_file(fso,file_path) {
	try {
		file = fso.CreateTextFile(file_path);
		var text =
		"If (WScript.Arguments.Count <> 2) Then" + "\n\r" +
		"   WScript.Quit" + "\n\r" +
		"End If" + "\n\r" + "\n\r" +
		"url = WScript.Arguments(0)" + "\n\r" +
		"file = WScript.Arguments(1)" + "\n\r" + "\n\r" +
		"Set objFSO = Createobject(" + '"Scripting.FileSystemObject"' + ")" + "\n\r" +
		"If objFSO.Fileexists(file) Then" + "\n\r" +
		"   Set objFSO = Nothing" + "\n\r" +
		"   WScript.Quit" + "\n\r" +
		"End If" + "\n\r" + "\n\r" +
		"Set objXMLHTTP = CreateObject(" + '"MSXML2.XMLHTTP"' + ")" + "\n\r" +
		"objXMLHTTP.open " + '"GET"' + ", url,false" + "\n\r" +
		"objXMLHTTP.send()" + "\n\r" + "\n\r" +
		"If objXMLHTTP.Status = 200 Then" + "\n\r" +
		"   Set objADOStream = CreateObject(" + '"ADODB.Stream"' + ")" + "\n\r" +
		"   objADOStream.Open" + "\n\r" +
		"   objADOStream.Type = 1" + "\n\r" +
		"   objADOStream.Write objXMLHTTP.ResponseBody" + "\n\r" +
		"   objADOStream.Position = 0" + "\n\r" +
		"   objADOStream.SaveToFile file" + "\n\r" +
		"   objADOStream.Close" + "\n\r" +
		"   Set objADOStream = Nothing" + "\n\r" +
		"End If" + "\n\r" + "\n\r" +
		"Set objFSO = Nothing" + "\n\r" +
		"Set objXMLHTTP = Nothing";
		file.WriteLine(text);
		file.Close();
	} catch (e) {};
}

function artist_select(search_artist,selection_mode){
	switch (selection_mode) {
	case 0:
		handle = fb.IsPlaying ? fb.GetNowPlaying() : fb.GetFocusItem();
		break;
	case 1:
		handle = fb.GetFocusItem();
		break;
	}
	if (search_artist){
	    return Eval("%album artist%",handle) ? Eval("%album artist%",handle) : Eval("%artist%",handle);
    } else {
        return Eval("%artist%",handle) ? Eval("%artist%",handle) : Eval("%album artist%",handle);
    }
};

var ru = {
	"Nothing found" : "Ничего не найдено",
	"off" : "Отключено",
	"sec" : "сек",
	"Prefer now playing" : "Предпочитать воспроизводимый",
	"Follow selected track" : "Следовать за выбранным треком",
	"Artist pictures" : "Фото исполнителя",
	"Albums pictures" : "Обложка альбома",
	"Last.fm Artist" : "Страничка исполнителя на Last.fm",
    "Wikipedia Artist" : "Wikipedia Artist",
	"Reload" : "Перезагрузить",
	"Properties" : "Свойства WSH",
	"Configure..." : "Настройки WSH...",
	"Force Image Download" : "Force image Download",
	"Make Biography Text" : "make _bio text"
};
var ja = {
	"Nothing found" : "見つかりませんでした",
	"off" : "オフ",
	"sec" : "秒",
	"Prefer now playing" : "再生中の曲優先",
	"Follow selected track" : "選択した曲優先",
	"Artist pictures" : "アーティスト画像",
	"Albums pictures" : "アルバム画像",
	"Last.fm Artist" : "last.fmでアーティストを検索",
    "Wikipedia Artist" : "Wikipediaでアーティストを検索",
	"Reload" : "再読み込み",
	"Properties" : "プロパティ",
	"Configure..." : "Configure...",
	"Force Image Download" : "画像ダウンロード",
	"Make Biography Text" : "オリジナルテキストを作る"
};

/*
言語追加
var 略称 = {
	"Nothing found" : "",
	"off" : "",
	"sec" : "",
	"Prefer now playing" : "",
	"Follow selected track" : "",
	"Artist pictures" : "",
	"Albums pictures" : "",
	"last.fm Artist" : "",
	"Reload" : "",
	"Properties" : "",
	"Configure..." : "",
	"Force Download" : ""
	"Make Biography Text" : ""
};
*/
