/* ================================================================= */
/* music_score.js                                                    */
/* ================================================================= */

//=====================================================================
//	バージョン情報
//=====================================================================
var msceditor_version = "1.007";		//20240930 メトロノーム記号の基準音符の変更機能実装、強弱記号のcrescendoとdiminuendoの始点・終点の可視化
//var msceditor_version = "1.006";		//20240929 連桁内の休符対応、Undo・Redoの使用データ量削減、強弱記号の下段への配置、連続スラーの設定時バグ修正、スタッカートとスラーの同時配置のバグ修正、異常スクロール対応
//var msceditor_version = "1.005";		//20240928 ５連符対応、装飾音符の実装、複旋律の実装、不完全小節（弱起）対応、曲途中での音部記号・調号・拍子記号・速度記号の変更機能実装
//var msceditor_version = "1.004";		//20240913 演奏時の音色選択機能を実装
//var msceditor_version = "1.003";		//20240909 操作説明（ヘルプボタン）実装
//var msceditor_version = "1.002";		//20240901 各段の小節数を可変化、小節番号表示、調号のイメージ化、ブレス記号の追加、曲名・作者名対応
//var msceditor_version = "1.001";		//20240820 公開開始
//=====================================================================

//=====================================================================	B2[K:clef=bass]B2B2B2|[Q:"Largo"1/4=90][K:F]Z|[M:3/4]Z|Z|
//
//																		[V][K:clef=bass][K:F][M:3/4][Q:"Adagio"]
//
//																		[V: 1 K:clef=bass][V][K:F][M:3/4][Q:"Largo"] Z|Z|[M:2/4]Z|[K:clef=treble]Z|
//																		[V: 2][V][M:3/4] Z|Z|[M:2/4]Z|Z|
//																		[V][K:clef=bass][K:F][M:3/4][Q:"Largo"]|[K:clef=treble][K:F][M:2/4][Q:"Adagio"]Z|B2[K:clef=bass][Q:"Largo"]E,2|[K:clef=treble]Z|Z|
//
//	定数
//=====================================================================		[K:clef=treble][K:F][M:3/4][Q:"Largo"1/4=90]	
var cMaxLines = 30;
var cMaxMeasures = 8;
var cMultiArticulation = true;

var allPitches = [
	'C,,,,', 'D,,,,', 'E,,,,', 'F,,,,', 'G,,,,', 'A,,,,', 'B,,,,',
	'C,,,', 'D,,,', 'E,,,', 'F,,,', 'G,,,', 'A,,,', 'B,,,',
	'C,,', 'D,,', 'E,,', 'F,,', 'G,,', 'A,,', 'B,,',
	'C,', 'D,', 'E,', 'F,', 'G,', 'A,', 'B,',
	'C', 'D', 'E', 'F', 'G', 'A', 'B',
	'c', 'd', 'e', 'f', 'g', 'a', 'b',
	"c'", "d'", "e'", "f'", "g'", "a'", "b'",
	"c''", "d''", "e''", "f''", "g''", "a''", "b''",
	"c'''", "d'''", "e'''", "f'''", "g'''", "a'''", "b'''",
	"c''''", "d''''", "e''''", "f''''", "g''''", "a''''", "b''''"
];

const ArticulationArr = [
	"staccato",
	"wedge",
	"accent",
	"upbow",
	"downbow",
	"tenuto",
	"fermata",
	"lowermordent",
	"uppermordent",
	"trill",
	"roll",
	"turn",
];

const DynamicsArr = [
	"crescendo(",
	"crescendo)",
	"diminuendo(",
	"diminuendo)",
	"ffff",
	"fff",
	"ff",
	"f",
	"mf",
	"mp",
	"p",
	"pp",
	"ppp",
	"pppp",
	"fp",
	"fz",
	"sf",
	"sfp",
	"sfz",
	"rf",
	"rfz",
];

const RepeatSignsArr1 = [
	"D.C.",
	"fine",
	"D.S.",
	"segno",
	"coda",
];

const RepeatSignsArr2 = [
	"[1",
	"[2",
	"[3",
	"[1,2",
	"[1,3",
	"[2,3",
	"]",
];

//=====================================================================
//	変数
//=====================================================================
var callbackFunc = null;

var nowAbcPlaying = false;

var abcTitle = [];							//タイトル
abcTitle[0] = "";
abcTitle[1] = "";
var abcAuthor = [];							//作者
abcAuthor[0] = "";
abcAuthor[1] = "";
abcAuthor[2] = "";
var dispTitleAndAythor = false;				//タイトルと作者の表示

var MeasuresCount = [];						//各段の小節数

var selectClefSymbol;						//音部記号のイメージselectのオブジェクト
var selectTimingSymbol;						//拍子記号のイメージselectのオブジェクト
var selectBarLineLeft;						//小節線のイメージselectのオブジェクト
var selectKeySignature;						//調号のイメージselectのオブジェクト
var selectClefAndKeySignature;				//音部記号・調号設定のイメージselectのオブジェクト
var currentClefSymbol = "treble";			//現在の音部記号（ト音記号treble、ヘ音記号bass）
var currentTimeSignatureSymbol = "C";		//現在の拍子記号( Cや4/4 .....)
var currentKeySignature = "C";				//現在の調号（＃や♭）
var currentTempoMarkings = "";				//現在の速度記号
var currentTempoMarkings2 = 0;				//現在のメトロノーム記号
var currentTempoMarkings2Base = "1/4";		//現在のメトロノーム記号の基準音符
var currentRowsCount = 4;					//現在の行数
var currentLyricNumber = 0;					//現在の歌詞番数

var countByBar = 8;							//１小節内の八分音符の数
var countByBarArr = [];						//小節内の八分音符の数の配列 countByBarArr[line][Measure]
for (let i = 0; i < cMaxLines; i++) {
	countByBarArr[i] = [];	
	for (let j = 0; j < cMaxMeasures+1; j++) {
		countByBarArr[i][j] = 0;	
	}
}

var disabledSelClefSymbol = false;			//音部記号イメージプルダウンの無効化
var disabledSelKeySignature = false;		//調号イメージプルダウンの無効化
var disabledSelClefAndKeySignature = false;	//音部記号・調号設定イメージプルダウンの無効化
var disabledSelTimeSignatureSymbol = false;	//拍子記号イメージプルダウンの無効化
var disabledSelBarLine = true;				//仕切り線イメージプルダウンの無効化

var selBarLineEvent = true;					//仕切り線変更イベントのON/OFF

//-----------

var bodyId;							//abcjsの表示域DIVのエレメントid
var editorId;						//edelitaのTEXTAREAのエレメントid

var stopRender = false;				//レンダリングの停止

var abcEditor = null;				//abcEditor

var currentAbcString;				//現在表示中のabcString
var currentVisualArray;				//現在表示中の楽譜データ配列（音符を要素とする配列）

var currentLineNo = -1;				//選択中の行番号（０～）
var currentMeasureNo = -1;			//選択中の小節番号（０～）
var currentVoice = -1;				//選択中のvoice番号（ 0 | 1 | 2 | 3 ）
var currentVoiceDan = -1;			//選択中の段番号（ 0 | 1 ）

var selectVisualData;				//選択中の音符のVisualArrayデータ
var selectVisualDataIndex;			//選択中の音符index（選択中のVisualArrayデータのcurrentVisualArrayに対するindex）

var selectNoteStartIndex = -1;		//選択範囲の先頭index
var selectNoteEndIndex = -1;		//選択範囲の末尾index（終了の次を指している）

var selectNoteStr = "";				//選択範囲のabc文字列

var selectNoteOrRest = "";			//選択範囲の種類（'note' | 'rest' | 'bar'）

var selectPitches = [];				//選択範囲の音階配列
var selectPitchesStr = "";			//選択範囲の音階配列文字列
var selectDuration = 0;				//選択範囲の音長（八分音符単位）
var selectDecoration = [];			//選択範囲の装飾配列
var selectBarType = "";				//選択範囲の区切り線種（ 'bar_thin' | 'bar_thin_thin' | 'bar_thin_thick' | 'bar_left_repeat' | 'bar_right_repeat' | 'bar_dbl_repeat' ）
var selectStartEnding = "";			//選択範囲の繰り返し（「1,「2...）

var selectBarStartIndex = -1;		//選択範囲の小節の先頭index
var selectBarEndIndex = -1;			//選択範囲の小節の末尾index（終了の次を指している）
var selectBarStr = "";				//選択範囲の小節のabc文字列

var selectBarBeforeLen = 0;			//選択範囲の小節の先頭から、選択範囲までの音長（八分音符単位）選択範囲は含まない
var selectBarAfterLen = 0;			//選択範囲から、選択範囲の小節の末尾までの音長（八分音符単位）選択範囲は含まない

var MSC_ParaQuestion = "";			//問題文
var MSC_ParaMenuConfig = "";		//メニュー設定文字列（16進数表記）

var paramContainerId;
var paramMSCMode = "";
var paramMSCData = "";

var currentFileName = "";

var stopChange = 0;

//---------------------------------------------
var v_haveCounterpointByLine = 0;		// 0=ない、1=あり
var v_haveCounterpointByMeasure = 0;	// 0=ない、1=あり
var v_isTrebleLine = true;				// true=ト音記号の段、false=ヘ音記号段
var v_isUpperLine = true;				// true=上段、false=下段
var v_isMainVoice = true;				// true=主旋律、false=副旋律


//##########################################################################
//##########################################################################
//	フォーム処理
//		初期化処理			initMscEditor();
//		サイズ変更処置		MSC_resize();
//		挿入ボタンの押下	clkMSC_Insert();
//		再編集				setSource(data);
//##########################################################################
function getNowAbcPlaying() {
	return nowAbcPlaying;
}

//=====================================================================
//	初期化処理（フォーム読み込み時）
//=====================================================================
function initMscEditor(containerId, callback=null, buttonCaption="挿入", lang="auto", mode="", data="") {

	paramContainerId = containerId;
	paramMSCMode = mode;
	paramMSCData = data;

	//コンテナに、エディタのHTMLをセット
	document.getElementById(containerId).innerHTML = editorHtml;
	document.getElementById("divWaitAnime").style.width = document.body.clientWidth + "px";

	//装飾音符
	var html = "";
	for (let i = 0; i < 31; i++) {
		for (let j = 0; j < 4; j++) {
			//臨時記号
			var y = i * 6.9 + 10;
			var x = j * 16 + 76;
			html += '<img class="noteArtImg2" id="noteArtImg2_' + i + '_' + j + '" src="./imgMSC/none10x20.png" style="top: ' + y + 'px; left: ' + x + 'px;">';
			//音符
			var y = i * 6.9 + 10;
			var x = j * 16 + 78;
			if (j == 0) {
				html += '<input type="checkbox" class="noteArtChk2" id="noteArtChk2_' + i + '_' + j + '" style="top: ' + y + 'px; left: ' + x + 'px;" onclick="clkChkNoteArt2(this, ' + i + ', ' + j + ')" ondblclick="dclkChkNoteArt2(this, ' + i + ', ' + j + ')">';
			} else {
				html += '<input type="checkbox" class="noteArtChk2" id="noteArtChk2_' + i + '_' + j + '" style="top: ' + y + 'px; left: ' + x + 'px; visibility: hidden;" onclick="clkChkNoteArt2(this, ' + i + ', ' + j + ')" ondblclick="dclkChkNoteArt2(this, ' + i + ', ' + j + ')">';
			}
		}
	}
	document.getElementById("spanNoteArt").innerHTML = html;


	editorId = "abc-editor";
	bodyId = "abcjs-body";

	//言語設定
	//lang = "auto";
	//lang = "en";
	//lang = "ko";
	MSC_initLang(lang, containerId);

	currentFileName = MAC_convLang("新規楽曲.msd");

	var html = "";
	for (let i = 1; i <= cMaxLines; i++) {
		if (i == 4) {
			html += "<option value='" + i + "' selected>" + MAC_convLang_1("%1段", i) + "</option>\n";
		} else {
			html += "<option value='" + i + "'>" + MAC_convLang_1("%1段", i) + "</option>\n";
		}
		MeasuresCount[i] = 4;
	}
	document.getElementById("selRowsCount").innerHTML = html;

	//callback関数の取得
	if (callback == null) {
		//document.getElementById("insertButton").style.display = "none";
		document.getElementById("divInsert").style.display = "none";
	} else {
		document.getElementById("insertButton").innerHTML = buttonCaption;
		callbackFunc = callback;
	}
	
	//バージョンセット
	document.getElementById('divVersion').innerHTML = "ver. " + msceditor_version;

	//メニュー 音部記号
	const divClefSymbol = document.getElementById('divClefSymbol');
	selectClefSymbol = new MSC_ImageSelector(divClefSymbol);
		//音部記号の変更
		selectClefSymbol.setOnChange( function() {
			chgClefSymbol(selectClefSymbol.value);
		});

	//メニュー 調号
	const divKeySignature = document.getElementById('divKeySignature');
	selectKeySignature = new MSC_ImageSelector(divKeySignature);
		//音部記号の変更
		selectKeySignature.setOnChange( function() {
			chgKeySignature(selectKeySignature.value);
		});

	//メニュー 音部記号・調号設定
	const divClefAndKeySignature = document.getElementById('divClefAndKeySignature');
	selectClefAndKeySignature = new MSC_ImageSelector(divClefAndKeySignature);
		//音部記号の変更
		selectClefAndKeySignature.setOnChange( function() {
			chgClefAndKeySignature(selectClefAndKeySignature.value);
		});

	//メニュー 拍子記号
	const divTimingSymbol = document.getElementById('divTimeSignatureSymbol');
	selectTimingSymbol = new MSC_ImageSelector(divTimingSymbol);
		//拍子記号の変更
		selectTimingSymbol.setOnChange( function() {
			chgTimeSignatureSymbol(selectTimingSymbol.value);
		});

	//メニュー 小節線 左端
	const divBarLineLeft = document.getElementById('divBarLineLeft');
	selectBarLineLeft = new MSC_ImageSelector(divBarLineLeft);
		//小節線 左端の変更
		selectBarLineLeft.setOnChange( function() {
			chgBar(selectBarLineLeft.value);
		});

	//メニュー 小節線の無効設定
	setDisabledSelBarLine(true);

	//音符・休符、装飾ボタン等の無効設定
	setDisabledNoteRestButton("disabled")

	//----------------------------------------------
	//abc-editor（textarea）のリサイズ処理
	//----------------------------------------------
	//ResizeObserverのインスタンスの生成
	const resizeObserver = new ResizeObserver((elements) => {
		MSC_resize();
	});
	//監視対象となる要素
	const target = document.getElementById("abc-editor");
	// 監視を開始する構文
	resizeObserver.observe(target);


	//----------------------------------------------
	//パラメータ取得（パラメータにデータがついている場合、そのデータを読み込む）
	//----------------------------------------------
	let queryString = window.location.search;
	queryString = decodeURIComponent(queryString.substr(1));
	queryString =  queryString.replace(/\\n/g, "\n");		// 改行を元に戻す

	//----------------------------------------------
	//楽譜の初期化
	//----------------------------------------------
	if (paramMSCMode.substr(0, 10) == "wbtbuilder") {
		if (paramMSCData == "") {
			initScore();
		} else {
			setSource(paramMSCData);
		}
		if (paramMSCMode == "wbtbuilderKadaiToi") {
		   	document.getElementById("spanEditorTitleFileName").innerHTML = "［問題登録］";
			document.getElementById("spanMSC_BtnCancel").style.display = "";
			document.getElementById("spanMSC_BtnMenuConfig").style.display = "inline-block";

		} else if (paramMSCMode == "wbtbuilderKadaiKai") {
		   	document.getElementById("spanEditorTitleFileName").innerHTML = "［正解登録］";
			document.getElementById("spanMSC_BtnCancel").style.display = "";
			document.getElementById("spanMSC_BtnMenuConfig").style.display = "inline-block";

		} else if (paramMSCMode == "wbtbuilderKaitou") {
		   	document.getElementById("spanEditorTitleFileName").innerHTML = "［解答入力］";
			document.getElementById("spanMSC_BtnCancel").style.display = "";
			document.getElementById("spanMSC_BtnMenuConfig").style.display = "none";

		} else if (paramMSCMode == "wbtbuilderTensaku") {
		   	document.getElementById("spanEditorTitleFileName").innerHTML = "［添削入力］";
			document.getElementById("spanMSC_BtnCancel").style.display = "";
			document.getElementById("spanMSC_BtnMenuConfig").style.display = "none";
		}

		document.getElementById("chkInsertTitle").checked = true;
		document.getElementById("labelInsertTitle").style.display = "none";
		
	} else {
		if (queryString == "" || location.href.indexOf("/office/") != -1) {
			initScore();
		} else {
			setSource(queryString);
		}
	   	document.getElementById("spanEditorTitleFileName").innerHTML = currentFileName;
	}

	//----------------------------------------------
	//エディタ書換イベントリスナー
	//----------------------------------------------
    document.getElementById("abc-editor").addEventListener("input", function() {
        currentAbcString = document.getElementById("abc-editor").value;
        renderScore(currentAbcString, "abcjs-body", "abc-editor");
    });


	//----------------------------------------------
	//Waitプログレスの消去と楽譜の表示
	//----------------------------------------------
	setTimeout( function() {
		//Waitプログレスの消去
		document.getElementById("divWaitAnime").innerHTML = "";
		//楽譜の表示
		if (document.getElementById("reEditButton")) {
			document.getElementById("reEditButton").style.display = "block";
		}
		document.getElementById("divEditor").style.display = "block";
		
		MSC_resize();
		MSC_resize();	//縮小時は、２度MSC_resize()しないと、コンテナの高さが正しく設定されない
		
	}, 2000);
}


//=====================================================================
//	フォームのサイズ変更イベント
//=====================================================================
//スロットリング（Throttling）処理
function throttle(func, limit) {
	let lastFunc;
	let lastRan;
	return function(...args) {
		if (!lastRan) {
			func(...args);
			lastRan = Date.now();
		} else {
			clearTimeout(lastFunc);
			lastFunc = setTimeout(function() {
				if ((Date.now() - lastRan) >= limit) {
					func(...args);
					lastRan = Date.now();
				}
			}, limit - (Date.now() - lastRan));
		}
	};
}
//---------------------------------------------------------------------
window.onresize = throttle(function() {
	//エディタのサイズ・ズーム値設定
	MSC_resize();
	MSC_resize();
}, 200); // 200ミリ秒に1回のみ実行

//=====================================================================
//	サイズ変更処理（エディタのサイズとズーム値設定）
//=====================================================================
function MSC_resize() {

	if (!document.getElementById(paramContainerId)) return;
	
	//------------------------------------------------------
	//	wbtbuilderから呼ばれた場合
	//------------------------------------------------------
	if (paramMSCMode.substr(0, 10) == "wbtbuilder") {
		var wid = document.getElementById(paramContainerId).offsetWidth;
		var hit = document.getElementById(paramContainerId).offsetHeight;
		
		let elem = document.getElementById("abc-editor");

		if (elem.style.display == "none") {
			document.getElementById("abcjs-container").style.maxHeight = (hit - 270) + "px";
			let btm = document.getElementById("divAbcJs").offsetTop + document.getElementById("divAbcJs").offsetHeight;
			document.getElementById("divEditor").style.height = (btm + 40) + "px";
		} else {
			document.getElementById("abcjs-container").style.maxHeight = (hit - 270 - elem.offsetHeight) + "px";
			let btm = document.getElementById("divAbcJs").offsetTop + document.getElementById("divAbcJs").offsetHeight;
			document.getElementById("divEditor").style.height = (btm + 40) + "px";
		}

		return;
	}
	
	//------------------------------------------------------
	//	独立で使用の場合
	//------------------------------------------------------
	var wid = document.body.clientWidth;
	var hit = document.documentElement.clientHeight;
	
	if (wid < 625) {
		var scale = wid / 808;
		var scale2 = wid / 625;

	} else if (wid < 808) {
		var scale = wid / 808;
		var scale2 = 1.0;

	} else {
		var scale = 1.0;
		var scale2 = 1.0;
	}

	let containerTop = document.getElementById(paramContainerId).offsetTop;

	let elem = document.getElementById("abc-editor");

//	hit = hit / scale;

	if (elem.style.display == "none") {
		document.getElementById("abcjs-container").style.maxHeight = (hit - containerTop)/ scale - (270/scale)*scale2 + "px";
	} else {
		document.getElementById("abcjs-container").style.maxHeight = (hit - containerTop - elem.offsetHeight)/ scale - (270/scale)*scale2 + "px";
	}

	let btm = document.getElementById("divAbcJs").offsetTop + document.getElementById("divAbcJs").offsetHeight;
	document.getElementById("divEditor").style.height = (btm + 40) + "px";


	if (wid < 625) {
		document.getElementById("divEditor").style.transform = "scale(" + scale + ")";
		document.getElementById("divEditor").style.transformOrigin = "left top";

		document.getElementById("divEditorMenu").style.transform = "scale(" + scale2/scale + ")";
		document.getElementById("divEditorMenu").style.transformOrigin = "left top";
/*
		document.getElementById("divChord").style.transform = "scale(" + scale2 + ")";
		document.getElementById("divChord").style.transformOrigin = "left top";
		document.getElementById("divChord").style.left = (285 * scale2) + "px";
		document.getElementById("divChord").style.top = (75 * scale2) + "px";
*/
		document.getElementById("abc-editor").style.fontSize = (12 / scale) + "px";
		document.getElementById("abc-editor").style.lineHeight = (16 / scale) + "px";

		document.getElementById("divAbcJs").style.transform = "scale(1.0)";
		document.getElementById("divAbcJs").style.transformOrigin = "left top";
		document.getElementById("divAbcJs").style.top = (document.getElementById("divEditorMenu").offsetHeight * (1.0 - 1.0/(scale2/scale)) + 16) +"px";

	} else if (wid < 808) {
		document.getElementById("divEditor").style.transform = "scale(" + scale + ")";
		document.getElementById("divEditor").style.transformOrigin = "left top";

		document.getElementById("divEditorMenu").style.transform = "scale(" + 1.0/scale + ")";
		document.getElementById("divEditorMenu").style.transformOrigin = "left top";
/*
		document.getElementById("divChord").style.transform = "scale(1.0)";
		document.getElementById("divChord").style.transformOrigin = "left top";
		document.getElementById("divChord").style.left = "285px";
		document.getElementById("divChord").style.top = (75 - (28- 28 * scale)) + "px";
*/
		document.getElementById("abc-editor").style.fontSize = (12 / scale) + "px";
		document.getElementById("abc-editor").style.lineHeight = (16 / scale) + "px";

		document.getElementById("divAbcJs").style.transform = "scale(1.0)";
		document.getElementById("divAbcJs").style.transformOrigin = "left top";
		document.getElementById("divAbcJs").style.top = (document.getElementById("divEditorMenu").offsetHeight * (1.0/scale - 1.0) + 4) +"px";
	
	} else {
		document.getElementById("divEditor").style.transform = "scale(" + scale + ")";
		document.getElementById("divEditor").style.transformOrigin = "left top";

		document.getElementById("divEditorMenu").style.transform = "scale(" + scale + ")";
		document.getElementById("divEditorMenu").style.transformOrigin = "left top";
/*
		document.getElementById("divChord").style.transform = "scale(1.0)";
		document.getElementById("divChord").style.transformOrigin = "left top";
		document.getElementById("divChord").style.left = "285px";
		document.getElementById("divChord").style.top = "75px";
*/
		document.getElementById("abc-editor").style.fontSize = "12px";
		document.getElementById("abc-editor").style.lineHeight = "16px";

		document.getElementById("divAbcJs").style.transform = "scale(1.0)";
		document.getElementById("divAbcJs").style.transformOrigin = "left top";
		document.getElementById("divAbcJs").style.top = "4px";
	}
}

//=====================================================================
//	メニュー設定ボタンの押下
//=====================================================================
var handleWinMscMenuConfig = null;
function clkMSC_MenuConfig() {
	let url = "./MSC/menuConfig.html";
	handleWinMscMenuConfig = window.open(url, "winMscMenuConfig", "width=800,height=860,menubar=0,toolbar=0,location=0,status=0");
}

//=====================================================================
//	メニュー設定コールバック
//=====================================================================
function callback_MSC_MenuConfig(configStr, question) {
	
	MSC_ParaMenuConfig = configStr;
	MSC_ParaQuestion = question;
	
	let lines = currentAbcString.split("\n");
	for (let i = lines.length-1; i >= 0; i--) {
		if (lines[i].substr(0, 10) == "% CFG1.0_:") {
			lines.splice(i, 1);
		}
		if (lines[i].substr(0, 11) == "% Question:") {
			lines.splice(i, 1);
		}
	}
	
	//メニュー設定データ
	lines.splice(1, 0, "% CFG1.0_:" + MSC_ParaMenuConfig);  // 1番目の位置に「メニュー設定データ」を挿入。第2引数は削除する要素数（今回は0）
	
	//問題文
	let brQuestion = MSC_ParaQuestion.replace(/\n/g, "<br>");		// 改行をエスケープ
	lines.splice(2, 0, "% Question:" + brQuestion);  			// 2番目の位置に「問題文（改行をエスケープ）」を挿入。第2引数は削除する要素数（今回は0）

	currentAbcString = lines.join("\n");
	document.getElementById("abc-editor").value = currentAbcString;

	//問題文の設定
	if (MSC_ParaQuestion != "") {
		document.getElementById("divQuestion").innerHTML = MSC_ParaQuestion;
		document.getElementById("divQuestion").style.display = "block";
	} else {
		document.getElementById("divQuestion").style.display = "none";
	}

	//メニュー表示の設定
	if (paramMSCMode != "wbtbuilderKadaiToi" && paramMSCMode.substr(0, 10) == "wbtbuilder") {
		setMenuSetting(MSC_ParaMenuConfig);
	} else {
		setMenuSetting("");
	}
}

//=====================================================================
//	キャンセルボタンの押下
//=====================================================================
function clkMSC_Cancel() {
	try {
		handleWinMscMenuConfig.close();
	} catch(e) {
	}
	//---------------------------------------------------
    //PNGイメージ（pngData）とabcソースをcallback
	//---------------------------------------------------
	callbackFunc("", "");
}

//=====================================================================
//	挿入ボタンの押下
//=====================================================================
function clkMSC_Insert() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//abcデータを退避
	var backAbcString = currentAbcString;
	
	//---------------------------------------------------
	//タイトルと著者を有効化し、再描画
	//---------------------------------------------------
	if (chkInsertTitle.checked == true) {
	    let lines = currentAbcString.split("\n");
	    for (i = 0; i < lines.length; i++) {
	    	//タイトル
	    	if (lines[i].substr(0, 4) == "% T:") {
	    		if (lines[i].substr(2).trim() != "T:") {
		    		lines[i] = lines[i].substr(2).trim();
		    	}
	    	}
	    	//作者
	    	if (lines[i].substr(0, 4) == "% C:") {
	    		if (lines[i].substr(2).trim() != "C:") {
	     			lines[i] = lines[i].substr(2).trim();
	     		}
	    	}
	    }
		currentAbcString = lines.join("\n");

	//---------------------------------------------------
	//タイトルと著者を無効化し、再描画
	//---------------------------------------------------
	} else if (chkInsertTitle.checked == false && dispTitleAndAythor == true) {
	    let lines = currentAbcString.split("\n");
	    for (i = 0; i < lines.length; i++) {
	    	//タイトル
	    	if (lines[i].substr(0, 2) == "T:") {
	    		lines[i] = "% " + lines[i];
	    	}
	    	//作者
	    	if (lines[i].substr(0, 2) == "% C:") {
	     		lines[i] = "% " + lines[i];
	    	}
	    }
		currentAbcString = lines.join("\n");
	}
	document.getElementById("abc-editor").value = currentAbcString;
	var retAbcString = currentAbcString;
    
	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
    stopUndoRedo = true;
    
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//
	MSC_resize();
	//非選択状態にする
	abcjsBodyMouseDown(true);


	(async () => {
	    try {
	        var pngData = await getPngImage(); // PNGイメージのデータを取得
			
			//abcデータを戻す
			currentAbcString = backAbcString;
			document.getElementById("abc-editor").value = currentAbcString;
	        
			//-----------------------------------------------------------
			//	エディタと楽譜の表示更新
			//-----------------------------------------------------------
			//エディタにセット
			document.getElementById("abc-editor").value = currentAbcString;
			//レンダリング
			renderScore(currentAbcString);
			//
			MSC_resize();
	        //非選択状態にする
	        abcjsBodyMouseDown(true);

	        stopUndoRedo = false;
			
			try {
				handleWinMscMenuConfig.close();
			} catch(e) {
			}

			//---------------------------------------------------
	        //PNGイメージ（pngData）とabcソースをcallback
			//---------------------------------------------------
			callbackFunc(retAbcString, pngData);

	    } catch (error) {
	        console.error("Error generating PNG image:", error);
	        stopUndoRedo = false;
	    }
	})();
}

//=====================================================================
//	再編集
//=====================================================================
function setSource(data) {

	stopChange++;
	
	//-----------------------------------------------------------
	//メニュー１行目のselectの設定
	//-----------------------------------------------------------
	document.getElementById("selTempoMarkings").value = "";
	document.getElementById("txtTempoMarkings2").value = "";

	let lineCount = 1;
	let sCountStart = false;
	let sCount = 0;
	let wCount = 0;
	
	stopRender = true;

	var lines = data.split("\n");
	
	//----------------------------------------------------
	//メニューの有効・無効設定、問題文の読み込み
	//----------------------------------------------------
	MSC_ParaMenuConfig = "";
	MSC_ParaQuestion = "";
	for (let i = lines.length-1; i >= 0; i--) {
		if (lines[i].substr(0, 10) == "% CFG1.0_:") {
			MSC_ParaMenuConfig = lines[i].substr(10);
		}
		
		if (lines[i].substr(0, 11) == "% Question:") {
			MSC_ParaQuestion = lines[i].substr(11);
			MSC_ParaQuestion = MSC_ParaQuestion.replace(/<br>/g, "\n");
		}
	}
	if (MSC_ParaQuestion != "") {
		document.getElementById("divQuestion").innerHTML = MSC_ParaQuestion;
		document.getElementById("divQuestion").style.display = "block";
	} else {
		document.getElementById("divQuestion").style.display = "none";
	}

	if (paramMSCMode != "wbtbuilderKadaiToi" && paramMSCMode.substr(0, 10) == "wbtbuilder") {
		setMenuSetting(MSC_ParaMenuConfig);
	} else {
		setMenuSetting("");
	}
	
	//----------------------------------------------------
	//データ互換性
	//----------------------------------------------------
    //曲名を２行にする（複数行対応のための互換性維持）
    var cnt = 0;
    var lin = 2;
    for (i = 0; i < lines.length; i++) {
    	if (lines[i].substr(0, 2) == "T:" || lines[i].substr(0, 4) == "% T:") {
    		cnt++;
    		lin = i;
    	}
    }
    for (i = cnt; i < 2; i++) {
		lines.splice(lin+i, 0, "% T: ");
    }

    //作者を３行にする（作者の複数行対応のための互換性維持）
    var cnt = 0;
    var lin = 4;
    for (i = 0; i < lines.length; i++) {
    	if (lines[i].substr(0, 2) == "C:" || lines[i].substr(0, 4) == "% C:") {
    		cnt++;
    		lin = i;
    	}
    }
    for (i = cnt; i < 3; i++) {
		lines.splice(lin+i, 0, "% C: ");
    }

    //%%barnumbers の追加
	var cnt = 0;
    var lin = 1;
    for (i = 0; i < lines.length; i++) {
    	if (lines[i].substr(0, 14) == "%%barnumbers 1") {
    		cnt = 1;
    	}
    }
    if (cnt == 0) {
		lines.splice(lin, 0, "%%barnumbers 1");
    }
    
    //%%staffsep 80px の追加
	var cnt = 0;
    var lin = 2;
    for (i = 0; i < lines.length; i++) {
    	if (lines[i].substr(0, 10) == "%%staffsep") {
    		cnt = 1;
    	}
    }
    if (cnt == 0) {
		lines.splice(lin, 0, "%%staffsep 80px");
    }

	//----------------------------------------------------

	for (let i = 0; i < lines.length; i++) {
		//音部記号
		if (lines[i].substr(0, 8) == "% HEADER") {
			let tmp = lines[i].substr(8).trim();
			if (tmp == "treble only") {
				currentClefSymbol = "treble";
				selectClefSymbol.setValue("treble");
				lineCount = 1;
			} else if (tmp == "bass only") {
				currentClefSymbol = "bass";
				selectClefSymbol.setValue("bass");
				lineCount = 1;
			} else if (tmp == "treble+treble") {
				currentClefSymbol = "treble_treble";
				selectClefSymbol.setValue("treble_treble");
				lineCount = 2;
			} else if (tmp == "treble+bass") {
				currentClefSymbol = "treble_bass";
				selectClefSymbol.setValue("treble_bass");
				lineCount = 2;
			}
		}

		//調号
		if (lines[i].substr(0, 2) == "K:") {
			let tmp = lines[i].substr(2).trim();
			currentKeySignature = tmp;
			selectKeySignature.setValue(tmp);
		}

		//拍子記号
		if (lines[i].substr(0, 2) == "M:") {
			let tmp = lines[i].substr(2).trim();
			if (tmp == "C" || tmp == "C|" || tmp == "2/2" || tmp == "4/4") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 8;
				selectTimingSymbol.setValue(tmp + ",8");
			} else if (tmp == "3/2" || tmp == "6/4" || tmp == "12/8") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 12;
				selectTimingSymbol.setValue(tmp + ",12");
			} else if (tmp == "2/4") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 4;
				selectTimingSymbol.setValue(tmp + ",4");
			} else if (tmp == "3/4" || tmp == "6/8") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 6;
				selectTimingSymbol.setValue(tmp + ",6");
			} else if (tmp == "3/8") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 3;
				selectTimingSymbol.setValue(tmp + ",3");
			} else if (tmp == "9/8") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 9;
				selectTimingSymbol.setValue(tmp + ",9");
			} else if (tmp == "5/4") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 10;
				selectTimingSymbol.setValue(tmp + ",10");
			} else if (tmp == "5/8") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 5;
				selectTimingSymbol.setValue(tmp + ",5");
			} else if (tmp == "7/8") {
				currentTimeSignatureSymbol = tmp;
				countByBar = 7;
				selectTimingSymbol.setValue(tmp + ",7");
			}
		}

		//速度記号
		if (lines[i].substr(0, 2) == "Q:") {
			let tmp = lines[i].substr(2).trim();
			let tmps = (tmp + " 1/4=").split(" ");
			currentTempoMarkings = tmps[0].trim().replace(/\"/g, "");	//"
			let tmp2 = tmps[1].trim();
			let tmps2 = tmp2.split("=");

			currentTempoMarkings2Base = tmps2[0];
			currentTempoMarkings2 = (tmps2[1].trim() == "0") ? "" : tmps2[1].trim();

			if (currentTempoMarkings2Base == "3/4") {
				document.getElementById("imgTempoMarkings2").src = "./imgMSC/note2dEqSel_22.png";
			} else if (currentTempoMarkings2Base == "1/2") {
				document.getElementById("imgTempoMarkings2").src = "./imgMSC/note2EqSel_22.png";
			} else if (currentTempoMarkings2Base == "3/8") {
				document.getElementById("imgTempoMarkings2").src = "./imgMSC/note4dEqSel_22.png";
			} else if (currentTempoMarkings2Base == "1/4") {
				document.getElementById("imgTempoMarkings2").src = "./imgMSC/note4EqSel_22.png";
			} else if (currentTempoMarkings2Base == "1/8") {
				document.getElementById("imgTempoMarkings2").src = "./imgMSC/note8EqSel_22.png";
			}

			document.getElementById("selTempoMarkings").value = currentTempoMarkings;
			document.getElementById("txtTempoMarkings2").value = currentTempoMarkings2;
		}

		//行数カウント
		if (lines[i].substr(0, 2) == "K:") {
			sCountStart = true;
			continue;
		}
		if (sCountStart == true && lines[i].substr(0, 1) != "%" && lines[i].substr(0, 2) != "w:") sCount++;

		//歌詞行数カウント
		if (sCountStart == true && lines[i].substr(0, 2) == "w:") wCount++;
	}
	
	//行数
	document.getElementById("selRowsCount").value = sCount / lineCount;
	currentRowsCount = sCount / lineCount;
	
	//歌詞番数
	document.getElementById("selLyric").value = wCount / currentRowsCount / lineCount;
	currentLyricNumber = wCount / currentRowsCount / lineCount;

	//-----------------------------------------------------------
	//	タイトルと作者を取得
	//-----------------------------------------------------------
    var titleCount = 0;
    abcTitle[0] = "";
    abcTitle[1] = "";
    var authorCount = 0;
	abcAuthor[0] = "";
	abcAuthor[1] = "";
	abcAuthor[2] = "";
	dispTitleAndAythor = false;

    //曲名、作者を表示する場合
    for (i = 0; i < lines.length; i++) {
    	if (lines[i].substr(0, 2) == "T:" || lines[i].substr(0, 2) == "C:") {
    		dispTitleAndAythor = true;
    	}
	}

    for (i = 0; i < lines.length; i++) {
    	//タイトル
    	if (lines[i].substr(0, 4) == "% T:") {
    		if (titleCount < 2) {
	    		abcTitle[titleCount] = lines[i].substr(4).trim();
    		
	    		if (dispTitleAndAythor == true && abcTitle[titleCount] != "") {
	    			lines[i] = abcTitle[titleCount];
	    		}
	    		
	    		titleCount++;
	    	}
    	} else if (lines[i].substr(0, 2) == "T:") {
    		if (titleCount < 2) {
	    		abcTitle[titleCount] = lines[i].substr(2).trim();
	    		
	    		if (dispTitleAndAythor == false || abcTitle[titleCount] == "") {
	    			lines[i] = "% " + abcTitle[titleCount];
	    		}
	    		
	    		titleCount++;
	    	}
    	}
    	//作者
    	if (lines[i].substr(0, 4) == "% C:") {
    		if (authorCount < 3) {
	    		abcAuthor[authorCount] = lines[i].substr(4).trim();

				if (dispTitleAndAythor == true && abcAuthor[authorCount] != "") {
					lines[i] = abcAuthor[authorCount];
				}

	    		authorCount++;
	    	}
    	} else if (lines[i].substr(0, 2) == "C:") {
    		if (authorCount < 3) {
	    		abcAuthor[authorCount] = lines[i].substr(2).trim();

				if (dispTitleAndAythor == false || abcAuthor[authorCount] == "") {
					lines[i] = "% " + abcAuthor[authorCount];
				}

	    		authorCount++;
	    	}
    	}
    }

    if (abcTitle[0] == "") {
	    currentFileName = MAC_convLang("再編集楽曲.msd");
	} else {
	    currentFileName = abcTitle[0] + '.msd';
	}

	//-----------------------------------------------------------
	//	互換性（音部記号）
	//-----------------------------------------------------------
	if (currentClefSymbol == "treble_treble" || currentClefSymbol == "treble_bass") {
		for (let i = 0; i < lines.length; i++) {
			if (lines[i].substr(0, 6) == "[V: 1]") {
				lines[i] = "[V: 1 K:clef=treble]" + lines[i].substr(6);
			} else if (lines[i].substr(0, 6) == "[V: 2]") {
				if (currentClefSymbol == "treble_treble") {
					lines[i] = "[V: 2 K:clef=treble]" + lines[i].substr(6);
				} else {
					lines[i] = "[V: 2 K:clef=bass]" + lines[i].substr(6);
				}
			}
		}
	}

    data = lines.join("\n");
    
	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	stopScrollAdjust = true;
	
	stopRender = false;

    stopUndoRedo = true;
	//abcStringデータをセット
	currentAbcString = data;
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//
	MSC_resize();
    //非選択状態にする
    abcjsBodyMouseDown(true);

    stopUndoRedo = false;
    
    clearUndo();
	prevAbcString = currentAbcString;

	//-------------------------------------------------------
	//各段の小節数（MeasuresCount[]を取得）
	//-------------------------------------------------------
	setTimeout( function() {
		var tmpMeasuresCount = [];
		for (let i = 0; i < cMaxLines; i++) {
			tmpMeasuresCount[i] = 0;
			MeasuresCount[i] = 4;
		}
		for (let i = 0; i < currentVisualArray.length; i++) {
			if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
				if (currentVisualArray[i].absEl.counters) {
					//voice == 0 の小節番号の最大値から取得（複旋律対応での修正は不要）
					if (currentVisualArray[i].absEl.counters.voice == 0) {
						let line = currentVisualArray[i].absEl.counters.line;
						let measure = currentVisualArray[i].absEl.counters.measure + 1;
						if (measure > tmpMeasuresCount[line]) tmpMeasuresCount[line] = measure;
					}
				}
			}
		}
		for (let i = 0; i < cMaxLines; i++) {
			if (tmpMeasuresCount[i] > 0) {
				MeasuresCount[i] = tmpMeasuresCount[i]
			}
		}

		stopChange--;
		
		stopScrollAdjust = false;
	}, 0);
}


//##########################################################################
//##########################################################################
//	abcString データ処理
//		abcヘッダを生成								makeAbcHeader();
//		abc初期楽曲データを生成						makeAbcInitScore();
//		楽譜の初期化（初期表示時、音部記号変更時）	initScore();
//		楽譜の更新（ヘッダのみの書換え）			updateHeader();
//##########################################################################

//=====================================================================
//	abcヘッダを生成
//=====================================================================
function makeAbcHeader() {
	let header = "";
	
	//コメント行
	if (currentClefSymbol == "treble") {
		header += "% HEADER treble only\n";
	} else if (currentClefSymbol == "bass") {
		header += "% HEADER bass only\n";
	} else if (currentClefSymbol == "treble_treble") {
		header += "% HEADER treble+treble\n";
	} else if (currentClefSymbol == "treble_bass") {
		header += "% HEADER treble+bass\n";
	}

	//小節番号表示
	header += "%%barnumbers 1\n";
	
	//段間隔
	header += "%%staffsep 80px\n";

	//曲目行（１行に固定）
	header += "X: 1\n";

	//タイトル（コメント行とする）
	if (abcTitle[0] == "") {
		header += "% T: \n";
	} else if (dispTitleAndAythor == false) {
		header += "% T: " + abcTitle[0] + "\n";
	} else {
		header += "T: " + abcTitle[0] + "\n";
	}
	if (abcTitle[1] == "") {
		header += "% T: \n";
	} else if (dispTitleAndAythor == false) {
		header += "% T: " + abcTitle[1] + "\n";
	} else {
		header += "T: " + abcTitle[1] + "\n";
	}

	//作者（コメント行とする）
	if (abcAuthor[0] == "") {
		header += "% C: \n";
	} else if (dispTitleAndAythor == false) {
		header += "% V: " + abcAuthor[0] + "\n";
	} else {
		header += "C: " + abcAuthor[0] + "\n";
	}
	if (abcAuthor[1] == "") {
		header += "% C: \n";
	} else if (dispTitleAndAythor == false) {
		header += "% V: " + abcAuthor[1] + "\n";
	} else {
		header += "C: " + abcAuthor[1] + "\n";
	}
	if (abcAuthor[2] == "") {
		header += "% C: \n";
	} else if (dispTitleAndAythor == false) {
		header += "% V: " + abcAuthor[2] + "\n";
	} else {
		header += "C: " + abcAuthor[2] + "\n";
	}

	//拍子記号行
	header += "M: " + currentTimeSignatureSymbol + "\n";

	//八分音符基準
	header += "L: 1/8\n";

	//テンポ行
	if (currentTempoMarkings != "" && currentTempoMarkings2 != 0) {
		header += 'Q: "' + currentTempoMarkings + '" ' + currentTempoMarkings2Base + '=' + currentTempoMarkings2 + '\n';
	} else if (currentTempoMarkings != "") {
		header += 'Q: "' + currentTempoMarkings + '"\n';
	} else if (currentTempoMarkings2 != 0) {
		header += 'Q: ' + currentTempoMarkings2Base + '=' + currentTempoMarkings2 + '\n';
	}

	//２段の場合
	if (currentClefSymbol == "treble_treble") {
		header += "%%score [1 2]\n";
		header += "V: 1 clef=treble\n"
		header += "V: 2 clef=treble\n"
	} else if (currentClefSymbol == "treble_bass") {
		header += "%%score [1 2]\n";
		header += "V: 1 clef=treble\n"
//		header += "V: 2 clef=bass octave=-2\n"
		header += "V: 2 clef=bass\n"
	}

	//調号行（Kフィールドはヘッダの最終行でなければならない）
	if (currentClefSymbol == "bass") {
		header += "K: " + currentKeySignature + " bass\n";
	} else {
		header += "K: " + currentKeySignature + "\n";
	}

	//コメント行
	header += "% end of HEADER\n"

	return header;
}

//=====================================================================
//	abc初期楽曲データを生成
//=====================================================================@@||
function makeAbcInitScore() {
	let score = "";

	for (let i = 0; i < cMaxLines; i++) {
		MeasuresCount[i] = 4;
	}

	for (let row = 0; row < currentRowsCount; row++) {
		//----------------------------------------
		//１段の場合
		//----------------------------------------
		if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
			score += "Z|Z|Z|Z|";
			//最終行
			if (row == currentRowsCount-1) score += "]";
			score += "\n";
			
			//歌詞がある場合
			for (let i = 0; i < currentLyricNumber; i++) {
				score += "w:  | | | \n";
				/*
				//最終番（１・２番なら、２番（ピリオド））
				if (i == currentLyricNumber-1) {
					score += ".\n";
				//最終番以外（１・２番なら、１番（カンマ））
				} else {
					score += ",\n";
				}
				*/
			}

		//----------------------------------------
		//２段の場合
		//----------------------------------------
		} else {
			//コメント行（〇行目、上段）
			score += "% " + (row+1) + "行目、上段\n";

			//楽曲データ（上段）
			score += "[V: 1 K:clef=treble] Z|Z|Z|Z|";
			//最終行
			if (row == currentRowsCount-1) score += "]";
			score += "\n";

			//歌詞がある場合
			for (let i = 0; i < currentLyricNumber; i++) {
				score += "w:  | | | \n";
				/*
				//最終番（１・２番なら、２番（ピリオド））
				if (i == currentLyricNumber-1) {
					score += ".\n";
				//最終番以外（１・２番なら、１番（カンマ））
				} else {
					score += ",\n";
				}
				*/
			}

			//コメント行（〇行目、下段）
			score += "% " + (row+1) + "行目、下段\n";

			//楽曲データ（下段）
			if (currentClefSymbol == "treble_treble") {
				score += "[V: 2 K:clef=treble] Z|Z|Z|Z|";
			} else {
				score += "[V: 2 K:clef=bass] Z|Z|Z|Z|";
			}
			//最終行
			if (row == currentRowsCount-1) score += "]";
			score += "\n";

			//歌詞がある場合
			for (let i = 0; i < currentLyricNumber; i++) {
				score += "w:  | | | \n";
				/*
				//最終番（１・２番なら、２番（ピリオド））
				if (i == currentLyricNumber-1) {
					score += ".\n";
				//最終番以外（１・２番なら、１番（カンマ））
				} else {
					score += ",\n";
				}
				*/
			}
		}
	}
	
	//コメント行
	score += "% end of SCORE";

	return score;
}

//=====================================================================
//	楽譜の初期化（初期表示時、音部記号変更時）
//=====================================================================
function initScore() {
	//楽譜の初期データ
	let abcString = makeAbcHeader() + makeAbcInitScore();
	//楽譜のレンダリング
	renderScore(abcString, "abcjs-body", "abc-editor");
	//表示をbodyサイズに合わせる
    MSC_resize();

	prevAbcString = abcString;
	clearUndo();
}

//=====================================================================
//	楽譜の更新（ヘッダのみの書換え）
//=====================================================================
function updateHeader() {
	//楽譜のscore部分の切出し
	let abcString = document.getElementById("abc-editor").value;
	let lines = abcString.split("\n");
	let score = "";
	let flag = false;
	for (let i = 0; i < lines.length; i++) {
		if (flag == true && lines[i].indexOf("end of HEADER") == -1) {
			score += lines[i];
			if (i < lines.length-1) score += "\n";
		}
		if (lines[i].substr(0, 3) == "K: ") flag = true;
	}
	//楽譜データ
	abcString = makeAbcHeader() + score
 	//楽譜のレンダリング
	renderScore(abcString, "abcjs-body", "abc-editor");
	MSC_resize();
}


//##########################################################################
//##########################################################################
//	メニュー処理（上段）
//		音部記号の変更				chgClefSymbol(val);
//		拍子記号の変更				chgTimeSignatureSymbol(val);
//		調号の変更					chgKeySignature(val);
//		速度記号の変更				chgTempoMarkings(val);
//		メトロノーム記号の変更		chgTempoMarkings2(val);
//		楽譜行数の変更				chgRowsCount(val);
//		歌詞番数の変更				chgLyric(val);
//		楽譜エリアでのキーダウン	containerKeydown(event);
//		歌詞文字の変更				inputLyricText(no, elem);
//##########################################################################

//=====================================================================
//	音部記号の変更時
//=====================================================================
function chgClefSymbol(val) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//変更がない場合は戻る（「いいえ」選択時は、ここに来る）
	if (val == currentClefSymbol) return;

	//確認メッセージ
	document.getElementById("spanMessageYesNo").innerHTML = "音部記号を変更すると、現在の楽譜は失われます。よいですか？";
	document.getElementById("dialogMessageYesNo").showModal();

	//「はい」の場合
	document.getElementById("btnMessageYesNoYes").onclick = function() {
		currentClefSymbol = val;
		//行数の初期化（４行）
		document.getElementById("selRowsCount").value = 4;
		currentRowsCount = 4;
		document.getElementById("dialogMessageYesNo").close();
		//楽譜の初期化
		initScore();
	}

	//「いいえ」の場合
	document.getElementById("btnMessageYesNoNo").onclick = function() {
		selectClefSymbol.setValue(currentClefSymbol);
		document.getElementById("dialogMessageYesNo").close();
	}
}

//=====================================================================
//	調号の変更時
//=====================================================================
function chgKeySignature(val) {
	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	currentKeySignature = val;
	//ヘッダの更新
	updateHeader();
}

//=====================================================================
//	音部記号・調号設定の変更時
//=====================================================================
function chgClefAndKeySignature(val) {

	if (stopChange != 0) return;

	//選択小節線や音符・休符直後の設定を取得
	//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
	let res = getAfterSettings();
	if (res[1] == 0) return;

	//音部記号・調号
	let str = val;
	var match = str.match(/\[K:clef=[^\]]+\]/);		//(/\[V: [12] K:clef=[^\]]+\]/);
	if (match) {
		var strClef = match[0];
	} else {
		var strClef = "";
	}
	var cleanedStr = str.replace(/\[K:clef=[^\]]+\]/g, "");  // [K:clef=...] を除去
	var matches = cleanedStr.match(/\[K:[^\]]+\]/g);  // 残りの [K:...] を取得
	if (matches) {
		var strkeySignature = matches[0];
	} else {
		var strkeySignature = "";
	}
	
	//拍子記号
	let strTempo = "";
	if (res[4] != "none") {
		str += "[M:" + res[4] + "]";
		strTempo = "[V][M:" + res[4] + "]";
	}
	
	//速度記号
	let strSp = "";

	if (res[5] != "none" && res[6] != "none") {
		let tempoBase = res[6].split("=")[0];
		let tempoValue = res[6].split("=")[1];
		strSp += '[Q:"' + res[5] + '"' + tempoBase + '=' + tempoValue + ']';
	
	} else if (res[5] != "none") {
		strSp += '[Q:"' + res[5] + '"]';
	
	} else if (res[6] != "none") {
		let tempoBase = res[6].split("=")[0];
		let tempoValue = res[6].split("=")[1];
		strSp += '[Q:' + tempoBase + '=' + tempoValue + ']';
	}
	
	//currentAbcStringへセット
	//１段の場合
	if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
		if (res[8] == "btmBar") {
			currentAbcString = currentAbcString.substring(0, res[0]) + str + "[V]" + str + strSp + currentAbcString.substring(res[1]);
		} else {
			currentAbcString = currentAbcString.substring(0, res[0]) + str + strSp + currentAbcString.substring(res[1]);
		}

	//２段の場合
	} else {
		if (res[8] == "btmBar") {

			if (res[9] == true) {		//danUp	上段==true
				var idx = currentAbcString.indexOf("[V: 1", res[1]);
			} else {
				var idx = currentAbcString.indexOf("[V: 2", res[1]);
			}
			//次lineの先頭
			let strNextLine = "";
			if (res[9] == true) {		//danUp	上段==true
				//strNextLine += "[V: 1 K:clef=treble]" + str.replace(val, "") + strSp;		//K:clef=xxxx の再構築で設定するので、仮にtrebleとする
				strNextLine += "[V: 1 K:clef=treble]" + strkeySignature + strTempo + strSp;		//K:clef=xxxx の再構築で設定するので、仮にtrebleとする
			} else {
				//strNextLine += "[V: 2 K:clef=treble]" + str.replace(val, "") + strSp;		//K:clef=xxxx の再構築で設定するので、仮にtrebleとする
				strNextLine += "[V: 2 K:clef=treble]" + strTempo + strSp;		//K:clef=xxxx の再構築で設定するので、仮にtrebleとする
			}
			currentAbcString = currentAbcString.substring(0, res[0]) + strNextLine + currentAbcString.substring(res[1]);

			//自lineの末尾
			let st = selectNoteEndIndex;
			let ed = currentAbcString.indexOf("\n", st);
			//currentAbcString = currentAbcString.substring(0, st) + str + strSp + currentAbcString.substring(ed);
			currentAbcString = currentAbcString.substring(0, st) + strClef + strTempo.replace("[V]", "") + currentAbcString.substring(ed);
			
		} else {
			currentAbcString = currentAbcString.substring(0, res[0]) + str + strSp + currentAbcString.substring(res[1]);
		}
	}

	//-------------------------------------------------
	//K:clef=xxxx の再構築		//@@@@@@@@@@@@@@@@@
	//-------------------------------------------------
	rebuildeClef();
	
	document.getElementById("abc-editor").value = currentAbcString;
	
 	//楽譜のレンダリング
	renderScore(currentAbcString);
	MSC_resize();

    //非選択状態にする
    //abcjsBodyMouseDown(true);

    //小節線を選択状態にする
	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
	abcEditor.updateSelection();
}

//=====================================================================
//	K:clef=xxxx の再構築		//@@@@@@@@@@@@@@@@@
//=====================================================================
function rebuildeClef() {
	if (currentClefSymbol == "treble_treble") {
		var clef1 = "treble";
		var clef2 = "treble";
	} else {
		var clef1 = "treble";
		var clef2 = "bass";
	}
	let lines = currentAbcString.split("\n");
	for (let i = 0; i < lines.length; i++) {
		
		if (lines[i].substr(0, 5) == "[V: 1") {
			if (lines[i].substr(0, 20) == "[V: 1 K:clef=treble]" && clef1 == "bass") {
				lines[i] = "[V: 1 K:clef=b00000]" + lines[i].substr(20);
			} else if (lines[i].substr(0, 18) == "[V: 1 K:clef=bass]" && clef1 == "treble") {
				lines[i] = "[V: 1 K:clef=t000]" + lines[i].substr(18);
			}
			let idx = 0;
			while (true) {
				idx = lines[i].indexOf("[K:clef=", idx);
				if (idx == -1) {
					break;
				}
				if (lines[i].substr(idx+8, 6) == "treble") {
					clef1 = "treble";
				} else {
					clef1 = "bass";
				}
				idx += 8;
			}
		}

		if (lines[i].substr(0, 5) == "[V: 2") {
			if (lines[i].substr(0, 20) == "[V: 2 K:clef=treble]" && clef2 == "bass") {
				lines[i] = "[V: 2 K:clef=b00000]" + lines[i].substr(20);
			} else if (lines[i].substr(0, 18) == "[V: 2 K:clef=bass]" && clef2 == "treble") {
				lines[i] = "[V: 2 K:clef=t000]" + lines[i].substr(18);
			}
			let idx = 0;
			while (true) {
				idx = lines[i].indexOf("[K:clef=", idx);
				if (idx == -1) {
					break;
				}
				if (lines[i].substr(idx+8, 6) == "treble") {
					clef2 = "treble";
				} else {
					clef2 = "bass";
				}
				idx += 8;
			}
		}
	}
	currentAbcString = lines.join("\n");
	currentAbcString = currentAbcString.replace(/t000/g, "treble");
	currentAbcString = currentAbcString.replace(/b00000/g, "bass");
}

//=====================================================================
//	拍子記号の変更時@@@
//=====================================================================
function chgTimeSignatureSymbol(val) {

	if (stopChange != 0) return;

	//--------------------------------------------------------------
	//	音符等の選択がないので、全体変更
	//--------------------------------------------------------------
	if (selectNoteOrRest == "") {

		document.getElementById("divOptionNoteAndRest").style.display = "none";
		document.getElementById("divOptionArticulation").style.display = "none";
		document.getElementById("divTempoMarkings2").style.display = "none";
		tmpSymbolIdx1 = -1;
		tmpSymbolIdx2 = -1;

		//変更がない場合は戻る（「いいえ」選択時は、ここに来る）
		if (val.split(",")[0] == currentTimeSignatureSymbol) return;
/*
		//拍子記号は変わるが、１小節内のdurationは変わらない
		if (val.split(",")[1] == countByBar) {
			currentTimeSignatureSymbol = val.split(",")[0];
			countByBar = val.split(",")[1];
			//楽譜の初期化
			initScore();
			return;
		}
*/
		//確認メッセージ
		//document.getElementById("spanMessageYesNo").innerHTML = "この拍子記号へ変更すると、現在の楽譜は失われます。よいですか？";
		document.getElementById("spanMessageYesNo").innerHTML = "拍子記号へ変更すると、現在の楽譜は失われます。よいですか？";
		document.getElementById("dialogMessageYesNo").showModal();

		//「はい」の場合
		document.getElementById("btnMessageYesNoYes").onclick = function() {
			currentTimeSignatureSymbol = val.split(",")[0];
			countByBar = val.split(",")[1];
			//行数の初期化（４行）
			document.getElementById("selRowsCount").value = 4;
			currentRowsCount = 4;
			document.getElementById("dialogMessageYesNo").close();
			//楽譜の初期化
			initScore();
		}

		//「いいえ」の場合
		document.getElementById("btnMessageYesNoNo").onclick = function() {
			selectTimingSymbol.setValue(currentTimeSignatureSymbol + "," + countByBar);
			document.getElementById("dialogMessageYesNo").close();
		}

	//--------------------------------------------------------------
	//	拍子記号	音符等の選択があるので、曲途中での変更
	//--------------------------------------------------------------
	} else {
		
		document.getElementById("divOptionNoteAndRest").style.display = "none";
		document.getElementById("divOptionArticulation").style.display = "none";
		document.getElementById("divTempoMarkings2").style.display = "none";
		tmpSymbolIdx1 = -1;
		tmpSymbolIdx2 = -1;

		//拍子記号変更時は、各小節内のdurationが変わるので、以降の小節をクリアする必要がある。
		//確認メッセージ
		document.getElementById("spanMessageYesNo").innerHTML = "拍子記号へ変更すると、この位置以降の楽譜は失われます。よいですか？";
		document.getElementById("dialogMessageYesNo").showModal();
		
		//「はい」の場合
		document.getElementById("btnMessageYesNoYes").onclick = function() {
			document.getElementById("dialogMessageYesNo").close();

			//----------------------------------------------------
			//１段の場合
			//----------------------------------------------------
			if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
				
				//選択小節線や音符・休符直後の設定を取得
				//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
				let res = getAfterSettings();
				if (res[1] == 0) return;

				let str = "";
				//音部記号・調号
				if (res[7] != "none")
				 	str += res[7];
				
				//拍子記号
				if (val != "0,0") {
					var strT = "[M:" + val.split(",")[0] + "]";
					str += "[M:" + val.split(",")[0] + "]";
				} else {
					var strT = "";
				}
				
				//速度記号
				let strSp = "";
				if (res[5] != "none" && res[6] != "none") {
					let tempoBase = res[6].split("=")[0];
					let tempoValue = res[6].split("=")[1];
					strSp += '[Q:"' + res[5] + '"' + tempoBase + '=' + tempoValue + ']';
				
				} else if (res[5] != "none") {
					strSp += '[Q:"' + res[5] + '"]';
				
				} else if (res[6] != "none") {
					let tempoBase = res[6].split("=")[0];
					let tempoValue = res[6].split("=")[1];
					strSp += '[Q:' + tempoBase + '=' + tempoValue + ']';
				}
				
				//最終位置から現在位置までのすべての小節内を"Z"とする
				let noteCnt = 0;
				for (let i = currentVisualArray.length-1; i >= selectVisualDataIndex+1; i--) {
					if (currentVisualArray[i].absEl.type == "bar") {
						noteCnt = 0;
					} else if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
						let st = currentVisualArray[i].absEl.abcelem.startChar;
						let ed = currentVisualArray[i].absEl.abcelem.endChar;
						//Zに置き換える
						if (noteCnt == 0) {
							currentAbcString = currentAbcString.substring(0, st) + "Z" + currentAbcString.substring(ed);
						//削除
						} else {
							currentAbcString = currentAbcString.substring(0, st) + currentAbcString.substring(ed);
						}
						noteCnt++;
					}
				}
				if (res[8] == "btmBar") {
					currentAbcString = currentAbcString.substring(0, res[0]) + str + "[V]" + str + strSp + currentAbcString.substring(res[1]);
				} else {
					currentAbcString = currentAbcString.substring(0, res[0]) + str + strSp + currentAbcString.substring(res[1]);
				}
			
			//----------------------------------------------------
			//２段の場合
			//----------------------------------------------------
			} else {
				//選択小節線や音符・休符直後の設定を取得
				//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
				let res = getAfterSettings();
				if (res[1] == 0) return;

				//---------------------------------------------------------------------
				//下段への設定（lineとx座標が同一の小節線の直後に挿入、挿入文字列は、再構築する必要がある）
				//---------------------------------------------------------------------
				//選択中の小節線のx座標
				let xPos = currentVisualArray[selectVisualDataIndex].absEl.x;
				var idx = -1;
				//同一x座標の小節線の検索
				for (let i = selectVisualDataIndex+1; i < currentVisualArray.length; i++) {
					if (currentVisualArray[i].absEl.counters) {
						if (currentVisualArray[i].absEl.counters.line != currentLineNo) break;
					}
					if (currentVisualArray[i].absEl.type == "bar" && currentVisualArray[i].absEl.x == xPos) {
						idx = i;
						break;
					}
				}

				if (idx != -1) {


					//以降の全小節をクリア（"Z"とする）
					//２段の場合（currentVisualArray[idx].absEl.abcelem.startChar以降で、小節線で囲まれた部分の音符と休符を、"Z"とする）
					let noteCnt = 0;
					for (let i = currentVisualArray.length-1; i >= idx; i--) {
						if (currentVisualArray[i].absEl.type == "bar") {
							noteCnt = 0;
						} else if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
							let st = currentVisualArray[i].absEl.abcelem.startChar;
							let ed = currentVisualArray[i].absEl.abcelem.endChar;
							//Zに置き換える
							if (noteCnt == 0) {
								currentAbcString = currentAbcString.substring(0, st) + "Z" + currentAbcString.substring(ed);
							//削除
							} else {
								currentAbcString = currentAbcString.substring(0, st) + currentAbcString.substring(ed);
							}
							noteCnt++;
						}
					}

					document.getElementById("abc-editor").value = currentAbcString;
					
				 	//楽譜のレンダリング
				    stopUndoRedo = true;
					renderScore(currentAbcString);
				    stopUndoRedo = false;


					let bak_selectVisualDataIndex = selectVisualDataIndex;
					let bak_selectNoteEndIndex = selectNoteEndIndex;
				
					selectVisualDataIndex = idx;
					selectNoteEndIndex = currentVisualArray[idx].absEl.abcelem.endChar;
					
					//選択小節線や音符・休符直後の設定を取得
					//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
					var res2 = getAfterSettings();	
					
					selectVisualDataIndex = bak_selectVisualDataIndex;
					selectNoteEndIndex = bak_selectNoteEndIndex;

					//------------------------------------------------
					//自段・上段（選択小節線）の設定文字列
					var st1u = currentVisualArray[selectVisualDataIndex].absEl.abcelem.endChar;
					if (res[8] == "btmBar") {
						var ed1u = currentAbcString.indexOf("\n", st1u);
					} else {
						var ed1u = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
					}
					//※　st1u,ed1uは、自段・上段（選択小節線）の設定文字列（ex. [K:clef=bass][M:3/4][Q:...]）

					//------------------------------------------------
					//自段・下段の、同一小節線の設定文字列
					let st1d = currentVisualArray[idx].absEl.abcelem.endChar;
					if (res[8] == "btmBar") {
						var ed1d = currentAbcString.indexOf("\n", st1d);
					} else {
						var ed1d = currentVisualArray[idx+1].absEl.abcelem.startChar;
					}
					//※　st1d,ed1dは、自段の下段の、同一小節線の設定文字列（ex. [K:clef=bass][M:3/4][Q:...]）
					
					//------------------------------------------------
					var st2u = res2[0];
					var ed2u = res2[1];
					//※　res2[0],res2[1]は、次段の上段先頭の設定文字列（ex. [V: 1 K:clef=bass][K:D][V][M:3/4][Q:...]）
					
					//------------------------------------------------
					var st2d = currentAbcString.indexOf("[V: 2", ed2u);
					var ed2d = st2d;
					for (let i = idx; i < currentVisualArray.length; i++) {
						if (currentVisualArray[i].absEl.abcelem.startChar > st2d) {
							ed2d = currentVisualArray[i].absEl.abcelem.startChar;
							break;
						}
					}
					//※　st2d,ed2dは、次段の下段先頭の設定文字列（ex. [V: 1 K:clef=bass][K:D][V][M:3/4][Q:...]）
					
		
		//console.log("1u", st1u, ed1u, currentAbcString.substring(st1u, ed1u));
		//console.log("1d", st1d, ed1d, currentAbcString.substring(st1d, ed1d));
		//console.log("2u", st2u, ed2u, currentAbcString.substring(st2u, ed2u));
		//console.log("2d", st2d, ed2d, currentAbcString.substring(st2d, ed2d));
					
					
					//音部記号
					var match = currentAbcString.substring(st1u, ed1u).match(/\[K:clef=[^\]]+\]/);		//(/\[V: [12] K:clef=[^\]]+\]/);
					if (match) {
						var strClefU = match[0];
					} else {
						var strClefU = "";
					}
					var match = currentAbcString.substring(st1d, ed1d).match(/\[K:clef=[^\]]+\]/);		//(/\[V: [12] K:clef=[^\]]+\]/);
					if (match) {
						var strClefD = match[0];
					} else {
						var strClefD = "";
					}

					//調号
					var cleanedStr = currentAbcString.substring(st2u, ed2u).replace(/\[K:clef=[^\]]+\]/g, "");  // [K:clef=...] を除去
					var matches = cleanedStr.match(/\[K:[^\]]+\]/g);  // 残りの [K:...] を取得
					if (matches) {
						var strKeySignature = matches[0];
					} else {
						var strKeySignature = "";
					}

					//拍子記号
					if (val != "0,0") {
						var strTempo = "[M:" + val.split(",")[0] + "]";
					} else {
						var strTempo = "";
					}

					//速度記号
					var match = currentAbcString.substring(st2u, ed2u).match(/\[Q:[^\]]+\]/);  // [Q: と ] で囲まれた部分を取得
					if (match) {
						var strSpeed = match[0];
					} else {
						var strSpeed = "";
					}
					
					//------------------------------------------------
					//	次段の設定（btmBarの場合のみ。行頭）
					//------------------------------------------------
					if (res[8] == "btmBar") {
						//次段の下段の先頭に、[V][M:x/x]を追加・削除
						var str = "[V]" + strTempo;
						var tmpSt = currentAbcString.indexOf("]", st2d) + 1;
						currentAbcString = currentAbcString.substring(0, tmpSt) + str + currentAbcString.substring(ed2d);
						
						//次段の上段の先頭に、[V][M:x/x]を追加・削除
						var str = strKeySignature + "[V]" + strTempo + strSpeed;
						var tmpSt = currentAbcString.indexOf("]", st2u) + 1;
						currentAbcString = currentAbcString.substring(0, tmpSt) + str + currentAbcString.substring(ed2u);
					}

					//------------------------------------------------
					//	自段・下段の設定（末尾or行中）
					//------------------------------------------------
					//btmBar
					if (res[8] == "btmBar") {
						//自段の下段の末尾に、[M:x/x]を追加・削除。以降の全小節を初期化
						var str = strClefD + strTempo;
						currentAbcString = currentAbcString.substring(0, st1d) + str + currentAbcString.substring(ed1d);
					//midBar
					} else {
						//自段の下段の同一小節線に、[M:x/x]を追加・削除。以降の全小節を初期化
						var str = strClefD + strTempo;
						currentAbcString = currentAbcString.substring(0, st1d) + str + currentAbcString.substring(ed1d);
					}
					
					//------------------------------------------------
					//	自段・上段の設定（末尾or行中）
					//------------------------------------------------
					//以降の自段上段の全小節を初期化
					first_nIdx = currentAbcString.indexOf("\n", ed1u);
					if (first_nIdx != -1) {
						let noteCnt = 0;
						for (let i = currentVisualArray.length-1; i >= selectVisualDataIndex; i--) {
							if (currentVisualArray[i].absEl.abcelem.endChar > first_nIdx) continue;
							
							if (currentVisualArray[i].absEl.type == "bar") {
								noteCnt = 0;
							} else if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
								let st = currentVisualArray[i].absEl.abcelem.startChar;
								let ed = currentVisualArray[i].absEl.abcelem.endChar;
								//Zに置き換える
								if (noteCnt == 0) {
									currentAbcString = currentAbcString.substring(0, st) + "Z" + currentAbcString.substring(ed);
								//削除
								} else {
									currentAbcString = currentAbcString.substring(0, st) + currentAbcString.substring(ed);
								}
								noteCnt++;
							}
						}
					}

					//btmBar
					if (res[8] == "btmBar") {
						//自段の上段の末尾に、[M:x/x]を追加・削除。以降の自段上段の全小節を初期化
						var str = strClefU + strTempo;
						currentAbcString = currentAbcString.substring(0, st1u) + str + currentAbcString.substring(ed1u);
					
					//midBar
					} else {
					
						//自段の上段の同一小節線に、[M:x/x]を追加・削除。以降の時段上段の全小節を初期化
						var str = strClefU + strTempo + strSpeed;
						currentAbcString = currentAbcString.substring(0, st1u) + str + currentAbcString.substring(ed1u);
					}
				}
			}
			
			document.getElementById("abc-editor").value = currentAbcString;
			
		 	//楽譜のレンダリング
			renderScore(currentAbcString);
			MSC_resize();
		    //非選択状態にする
		    //abcjsBodyMouseDown(true);

		    //小節線を選択状態にする
			document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
			abcEditor.updateSelection();
		}

		//「いいえ」の場合
		document.getElementById("btnMessageYesNoNo").onclick = function() {
		    //非選択状態にする
		    abcjsBodyMouseDown(true);
			document.getElementById("dialogMessageYesNo").close();
		}
	}
}


//=====================================================================
//	曲名・作者ボタンのクリック
//=====================================================================
function clkBtnTitle() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	document.getElementById("divForTitleInput").style.display = "";
	document.getElementById("divForPrint").style.display = "none";
	document.getElementById("chkTitleDisp").checked = dispTitleAndAythor;
	document.getElementById("btnPrintOK").innerHTML = "OK";

	//---------------------------------------------------
	//タイトルと著者のセット
	//---------------------------------------------------
	var text = "";
	if (abcTitle[0] != "") {
		text += abcTitle[0];
		if (abcTitle[1] != "") {
			text += "\n";
			text += abcTitle[1];
		}
	}
	document.getElementById("txtTitle").value = text;

	var text = "";
	if (abcAuthor[0] != "") {
		text += abcAuthor[0];
		if (abcAuthor[1] != "") {
			text += "\n";
			text += abcAuthor[1];
			if (abcAuthor[2] != "") {
				text += "\n";
				text += abcAuthor[2];
			}
		}
	}
	document.getElementById("txtAuthor").value = text;

	//---------------------------------------------------
	//ダイアログの表示
	//---------------------------------------------------
	document.getElementById("dialogTitleAndAuthor").showModal();

	//---------------------------------------------------
	//キャンセルボタン
	//---------------------------------------------------
	document.getElementById("btnPrintCancel").onclick = function() {
		document.getElementById("dialogTitleAndAuthor").close();
	}

	//---------------------------------------------------
	//OKボタン
	//---------------------------------------------------
	document.getElementById("btnPrintOK").onclick = function() {
		dispTitleAndAythor = document.getElementById("chkTitleDisp").checked;

		var lines = (document.getElementById("txtTitle").value+"\n").split("\n");
		abcTitle[0] = lines[0];
		abcTitle[1] = lines[1];

		var lines = (document.getElementById("txtAuthor").value+"\n\n").split("\n");
		abcAuthor[0] = lines[0];
		abcAuthor[1] = lines[1];
		abcAuthor[2] = lines[2];

		document.getElementById("dialogTitleAndAuthor").close();
		
		//---------------------------------------------------
		//タイトルと著者の保存
		//---------------------------------------------------
    	var cntT = 0;
    	var cntA = 0;
        var lines = currentAbcString.split("\n");
        for (i = 0; i < lines.length; i++) {
        	//タイトル
        	if (lines[i].substr(0, 4) == "% T:" || lines[i].substr(0, 2) == "T:") {
        		if (cntT < 2 && dispTitleAndAythor == true && abcTitle[cntT] != "") {
        			lines[i] = "T: " + abcTitle[cntT];
        		} else {
        			lines[i] = "% T: " + abcTitle[cntT];
        		}
        		cntT++;
        	}
        	//作者
        	if (lines[i].substr(0, 4) == "% C:" || lines[i].substr(0, 2) == "C:") {
        		if (cntA < 3 && dispTitleAndAythor == true && abcAuthor[cntA] != "") {
	         		lines[i] = "C: " + abcAuthor[cntA];
	         	} else {
	         		lines[i] = "% C: " + abcAuthor[cntA];
	         	}
        		cntA++;
        	}
        }
		currentAbcString = lines.join("\n");
		document.getElementById("abc-editor").value = currentAbcString;
		
	 	//楽譜のレンダリング
		renderScore(currentAbcString);
		MSC_resize();
        //非選択状態にする
        abcjsBodyMouseDown(true);
	}
}

//=====================================================================
//	textareaの入力行数制限（曲名と作者）
//=====================================================================
function textareaMaxLines(elem, maxLine) {
	let lines = elem.value.split("\n");
	let text = "";
	for (let i = 0; i < lines.length; i++) {
		if (i < maxLine) {
			if (i > 0) text += "\n";
			text += lines[i];
		}
	}
	elem.value = text;
}

//=====================================================================
//	速度記号の変更時@@@
//=====================================================================
function chgTempoMarkings(val) {
	//--------------------------------------------------------------
	//	音符等の選択がないので、全体変更
	//--------------------------------------------------------------
	if (selectNoteOrRest == "") {

		document.getElementById("divOptionNoteAndRest").style.display = "none";
		document.getElementById("divOptionArticulation").style.display = "none";
		document.getElementById("divTempoMarkings2").style.display = "none";
		tmpSymbolIdx1 = -1;
		tmpSymbolIdx2 = -1;

		currentTempoMarkings = val;

/*
		if (val != "") {
			var sp = "";
			switch (val) {
				case "Largo":
					sp = 46; break;
				case "Lento":
					sp = 52; break;
				case "Adagio":
					sp = 56; break;
				case "Andante":
					sp = 72; break;
				case "Moderato":
					sp = 96; break;
				case "Allegretto":
					sp = 108; break;
				case "Allegro":
					sp = 132; break;
				case "Vivace":
					sp = 160; break;
				case "Presto":
					sp = 184; break;
			}
			document.getElementById("txtTempoMarkings2").value = sp;
			currentTempoMarkings2 = sp;
		}
*/
		//ヘッダの更新
		updateHeader();

	//--------------------------------------------------------------
	//	速度記号　音符等の変更があるので、曲途中での変更
	//--------------------------------------------------------------
	} else {

		//currentAbcStringへセット
		//--------------------------------------------------
		//１段の場合
		//--------------------------------------------------
		if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {

			//選択小節線や音符・休符直後の設定を取得
			//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
			let res = getAfterSettings();
			if (res[1] == 0) return;

			let str = "";
			//音部記号・調号
			if (res[7] != "none")
			 	str += res[7];
			
			//拍子記号
			let strT = "";
			if (res[4] != "none") {
				strT = "[M:" + res[4] + "]";
				str += "[M:" + res[4] + "]";
			}
			
			//速度記号
			let strSp = ""
			if (val != "" && res[6] != "none") {
				let tempoBase = res[6].split("=")[0];
				let tempoValue = res[6].split("=")[1];
				strSp += '[Q:"' + val + '"' + tempoBase + '=' + tempoValue + ']';
			
			} else if (val != "") {
				strSp += '[Q:"' + val + '"]';
			
			} else if (res[6] != "none") {
				let tempoBase = res[6].split("=")[0];
				let tempoValue = res[6].split("=")[1];
				strSp += '[Q:' + tempoBase + '=' + tempoValue + ']';
			}
			let oldSp = ""
			if (res[5] != "none" && res[6] != "none") {
				let tempoBase = res[6].split("=")[0];
				let tempoValue = res[6].split("=")[1];
				oldSp += '[Q:"' + res[5] + '"' + tempoBase + '=' + tempoValue + ']';

			} else if (res[5] != "none") {
				oldSp += '[Q:"' + res[5] + '"]';
			
			} else if (res[6] != "none") {
				let tempoBase = res[6].split("=")[0];
				let tempoValue = res[6].split("=")[1];
				oldSp += '[Q:' + tempoBase + '=' + tempoValue + ']';
			}

			if (res[8] == "btmBar") {
				currentAbcString = currentAbcString.substring(0, res[0]) + str + "[V]" + str + strSp + currentAbcString.substring(res[1]);
			} else {
				currentAbcString = currentAbcString.substring(0, res[0]) + str + strSp + currentAbcString.substring(res[1]);
			}

		//--------------------------------------------------
		//２段の場合
		//--------------------------------------------------
		} else {
		
			//選択小節線や音符・休符直後の設定を取得
			//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
			let res = getAfterSettings();
			if (res[1] == 0) return;

			//---------------------------------------------------------------------
			//下段への設定（lineとx座標が同一の小節線の直後に挿入、挿入文字列は、再構築する必要がある）
			//---------------------------------------------------------------------
			//選択中の小節線のx座標
			let xPos = currentVisualArray[selectVisualDataIndex].absEl.x;
			var idx = -1;
			//同一x座標の小節線の検索
			for (let i = selectVisualDataIndex+1; i < currentVisualArray.length; i++) {
				if (currentVisualArray[i].absEl.counters) {
					if (currentVisualArray[i].absEl.counters.line != currentLineNo) break;
				}
				if (currentVisualArray[i].absEl.type == "bar" && currentVisualArray[i].absEl.x == xPos) {
					idx = i;
					break;
				}
			}
			
			if (idx != -1) {

				let str = "";
				//音部記号・調号
				if (res[7] != "none")
				 	str += res[7];
				
				//拍子記号
				let strT = "";
				if (res[4] != "none") {
					strT = "[M:" + res[4] + "]";
					str += "[M:" + res[4] + "]";
				}
				
				//速度記号
				let strSp = ""
				if (val != "" && res[6] != "none") {
					let tempoBase = res[6].split("=")[0];
					let tempoValue = res[6].split("=")[1];
					strSp += '[Q:"' + val + '"' + tempoBase + '=' + tempoValue + ']';
				
				} else if (val != "") {
					strSp += '[Q:"' + val + '"]';
				
				} else if (res[6] != "none") {
					let tempoBase = res[6].split("=")[0];
					let tempoValue = res[6].split("=")[1];
					strSp += '[Q:' + tempoBase + '=' + tempoValue + ']';
				}
				let oldSp = ""
				if (res[5] != "none" && res[6] != "none") {
					let tempoBase = res[6].split("=")[0];
					let tempoValue = res[6].split("=")[1];
					oldSp += '[Q:"' + res[5] + '"' + tempoBase + '=' + tempoValue + ']';
				
				} else if (res[5] != "none") {
					oldSp += '[Q:"' + res[5] + '"]';
				
				} else if (res[6] != "none") {
					let tempoBase = res[6].split("=")[0];
					let tempoValue = res[6].split("=")[1];
					oldSp += '[Q:' + tempoBase + '=' + tempoValue + ']';
				}
				
				//==============================
				let bak_selectVisualDataIndex = selectVisualDataIndex;
				let bak_selectNoteEndIndex = selectNoteEndIndex;
				
				selectVisualDataIndex = idx;
				selectNoteEndIndex = currentVisualArray[idx].absEl.abcelem.endChar;
				
				//選択小節線や音符・休符直後の設定を取得
				//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
				var res2 = getAfterSettings();	
				
				selectVisualDataIndex = bak_selectVisualDataIndex;
				selectNoteEndIndex = bak_selectNoteEndIndex;

				//------------------------------------------------
				//自段・上段（選択小節線）の設定文字列
				var st1u = currentVisualArray[selectVisualDataIndex].absEl.abcelem.endChar;
				if (res[8] == "btmBar") {
					var ed1u = currentAbcString.indexOf("\n", st1u);
				} else {
					var ed1u = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
				}
				//※　st1u,ed1uは、自段・上段（選択小節線）の設定文字列（ex. [K:clef=bass][M:3/4][Q:...]）

				//------------------------------------------------
				//自段・下段の、同一小節線の設定文字列
				let st1d = currentVisualArray[idx].absEl.abcelem.endChar;
				if (res[8] == "btmBar") {
					var ed1d = currentAbcString.indexOf("\n", st1d);
				} else {
					var ed1d = currentVisualArray[idx+1].absEl.abcelem.startChar;
				}
				//※　st1d,ed1dは、自段の下段の、同一小節線の設定文字列（ex. [K:clef=bass][M:3/4][Q:...]）

				//------------------------------------------------
				var st2u = res2[0];
				var ed2u = res2[1];
				//※　res2[0],res2[1]は、次段の上段先頭の設定文字列（ex. [V: 1 K:clef=bass][K:D][V][M:3/4][Q:...]）
				
				//------------------------------------------------
				var st2d = currentAbcString.indexOf("[V: 2", ed2u);
				var ed2d = st2d;
				for (let i = idx; i < currentVisualArray.length; i++) {
					if (currentVisualArray[i].absEl.abcelem.startChar > st2d) {
						ed2d = currentVisualArray[i].absEl.abcelem.startChar;
						break;
					}
				}
				//※　st2d,ed2dは、次段の下段先頭の設定文字列（ex. [V: 1 K:clef=bass][K:D][V][M:3/4][Q:...]）

				//自段の変更
				if (res[8] != "btmBar") {
					//自段下段
					var newStr = currentAbcString.substring(st1d, ed1d);
					if (oldSp == "") {
						newStr = newStr + strSp;
					} else {
						newStr = newStr.replace(oldSp, strSp);
					}
					currentAbcString = currentAbcString.substring(0, st1d) + newStr + currentAbcString.substring(ed1d);
					
					//自段上段
					var newStr = currentAbcString.substring(st1u, ed1u);
					if (oldSp == "") {
						newStr = newStr + strSp;
					} else {
						newStr = newStr.replace(oldSp, strSp);
					}
					
					currentAbcString = currentAbcString.substring(0, st1u) + newStr + currentAbcString.substring(ed1u);
				
				//次段の変更
				} else {
					//次段下段
					var newStr = currentAbcString.substring(st2d, ed2d);
					if (oldSp == "") {
						newStr = newStr + strSp;
					} else {
						newStr = newStr.replace(oldSp, strSp);
					}
					currentAbcString = currentAbcString.substring(0, st2d) + newStr + currentAbcString.substring(ed2d);
					
					//次段上段
					var newStr = currentAbcString.substring(st2u, ed2u);
					if (oldSp == "") {
						newStr = newStr + strSp;
					} else {
						newStr = newStr.replace(oldSp, strSp);
					}
					
					currentAbcString = currentAbcString.substring(0, st2u) + newStr + currentAbcString.substring(ed2u);
				}
				
			}
		}

		document.getElementById("abc-editor").value = currentAbcString;
		
	 	//楽譜のレンダリング
		renderScore(currentAbcString);
		MSC_resize();
	    //非選択状態にする
	    //abcjsBodyMouseDown(true);

	    //小節線を選択状態にする
		document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		abcEditor.updateSelection();
	}
}


function replaceFromIndex(str, searchValue, replaceValue, startIndex) {
    // 開始位置より前の部分を取得
    const before = str.slice(0, startIndex);
    // 開始位置以降の部分に対して置換を適用
    const after = str.slice(startIndex).replace(searchValue, replaceValue);
    // 2つの部分を結合して返す
    return before + after;
}

//=====================================================================
//	メトロノーム記号の基準音符の選択クリック
//=====================================================================
function clkBtnTempoMarkings2() {
	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	elem = document.getElementById("divTempoMarkings2");
	if (elem.style.display == "block") {
		elem.style.display = "none";
	} else {
		elem.style.left = "446px";
		elem.style.top = "33px";
		elem.style.display = "block";
		
		let elems = document.getElementsByClassName("tempo2");
		for (let i = 0; i < elems.length; i++) {
			elems[i].disabled = false;
		}
	}
}

//=====================================================================
//	メトロノーム記号の基準音符のクリック
//		val		2d | 2 | 4d | 4 | 8
//=====================================================================
function clkChangeTempoMarkings2(val) {

	document.getElementById("imgTempoMarkings2").src = "./imgMSC/note" + val + "EqSel_22.png";

	//--------------------------------------------------------------
	//	音符等の選択がないので、全体変更
	//--------------------------------------------------------------
	if (selectNoteOrRest == "") {
		if (val == "2d") {
			currentTempoMarkings2Base = "3/4";
		} else if (val == "2") {
			currentTempoMarkings2Base = "1/2";
		} else if (val == "4d") {
			currentTempoMarkings2Base = "3/8";
		} else if (val == "4") {
			currentTempoMarkings2Base = "1/4";
		} else if (val == "8") {
			currentTempoMarkings2Base = "1/8";
		}
		
		document.getElementById("divTempoMarkings2").style.display = "none";

		//ヘッダの更新
		updateHeader();
	
	//--------------------------------------------------------------
	//	メトロノーム記号の基準音符	音符等の選択があるので、曲途中での変更
	//--------------------------------------------------------------
	} else {
		chgTempoMarkings2(document.getElementById("txttxtTempoMarkings2").value);
	}
}

//=====================================================================
//	メトロノーム記号の変更時@@@
//=====================================================================
function chgTempoMarkings2(val) {
	//--------------------------------------------------------------
	//	音符等の選択がないので、全体変更
	//--------------------------------------------------------------
	if (selectNoteOrRest == "") {

		document.getElementById("divOptionNoteAndRest").style.display = "none";
		document.getElementById("divOptionArticulation").style.display = "none";
		document.getElementById("divTempoMarkings2").style.display = "none";
		tmpSymbolIdx1 = -1;
		tmpSymbolIdx2 = -1;

		if (val == 1) {
			document.getElementById("txtTempoMarkings2").value = 30;
			currentTempoMarkings2 = 30;
		} else if (val < 30) {
			document.getElementById("txtTempoMarkings2").value = "";
			currentTempoMarkings2 = 0;
		} else {
			currentTempoMarkings2 = val;
		}
		//ヘッダの更新
		updateHeader();

	//--------------------------------------------------------------
	//	メトロノーム記号	音符等の選択があるので、曲途中での変更
	//--------------------------------------------------------------
	} else {

		if (val == 1) {
			val = 30;
			document.getElementById("txtTempoMarkings2").value = val;
		} else if (val < 30) {
			val = "";
			document.getElementById("txtTempoMarkings2").value = "";
		}


		//currentAbcStringへセット
		//------------------------------------------------------
		//１段の場合
		//------------------------------------------------------
		if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
			//選択小節線や音符・休符直後の設定を取得
			//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
			let res = getAfterSettings();
			if (res[1] == 0) return;

			let str = "";
			//音部記号・調号
			if (res[7] != "none")
			 	str += res[7];
			
			//拍子記号
			let strT = "";
			if (res[4] != "none") {
				strT = "[M:" + res[4] + "]";
				str += "[M:" + res[4] + "]";
			}
			
			let strSp = "";
			//速度記号
			if (res[5] != "none" && val != "" && val != "0") {
				let tempoBase = "1/4";
				if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel2d_22.png") != -1) {
					tempoBase = "3/4";
				} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel2_22.png") != -1) {
					tempoBase = "1/2";
				} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel4d_22.png") != -1) {
					tempoBase = "3/8";
				} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel4_22.png") != -1) {
					tempoBase = "1/4";
				} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel8_22.png") != -1) {
					tempoBase = "1/8";
				}
				
				strSp += '[Q:"' + res[5] + '"' + tempoBase + '=' + val + ']';
			
			} else if (res[5] != "none") {
				strSp += '[Q:"' + res[5] + '"]';
			
			} else if (val != "" && val != "0") {
				let tempoBase = "1/4";
				if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel2d_22.png") != -1) {
					tempoBase = "3/4";
				} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel2_22.png") != -1) {
					tempoBase = "1/2";
				} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel4d_22.png") != -1) {
					tempoBase = "3/8";
				} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel4_22.png") != -1) {
					tempoBase = "1/4";
				} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel8_22.png") != -1) {
					tempoBase = "1/8";
				}

				strSp += '[Q:' + tempoBase + '=' + val + ']';
			}
			let oldSp = ""
			if (res[5] != "none" && res[6] != "none") {
				let tempoBase = res[6].split("=")[0];
				let tempoValue = res[6].split("=")[1];
				oldSp += '[Q:"' + res[5] + '"' + tempoBase + '=' + tempoValue + ']';
			
			} else if (res[5] != "none") {
				oldSp += '[Q:"' + res[5] + '"]';
			
			} else if (res[6] != "none") {
				let tempoBase = res[6].split("=")[0];
				let tempoValue = res[6].split("=")[1];
				oldSp += '[Q:' + tempoBase + '=' + tempoValue + ']';
			}

			if (res[8] == "btmBar") {
				currentAbcString = currentAbcString.substring(0, res[0]) + str + "[V]" + str + strSp + currentAbcString.substring(res[1]);
			} else {
				currentAbcString = currentAbcString.substring(0, res[0]) + str + strSp + currentAbcString.substring(res[1]);
			}

		//------------------------------------------------------
		//２段の場合
		//------------------------------------------------------
		} else {
			//選択小節線や音符・休符直後の設定を取得
			//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
			let res = getAfterSettings();
			if (res[1] == 0) return;

			//---------------------------------------------------------------------
			//下段への設定（lineとx座標が同一の小節線の直後に挿入、挿入文字列は、再構築する必要がある）
			//---------------------------------------------------------------------
			//選択中の小節線のx座標
			let xPos = currentVisualArray[selectVisualDataIndex].absEl.x;
			var idx = -1;
			//同一x座標の小節線の検索
			for (let i = selectVisualDataIndex+1; i < currentVisualArray.length; i++) {
				if (currentVisualArray[i].absEl.counters) {
					if (currentVisualArray[i].absEl.counters.line != currentLineNo) break;
				}
				if (currentVisualArray[i].absEl.type == "bar" && currentVisualArray[i].absEl.x == xPos) {
					idx = i;
					break;
				}
			}

			if (idx != -1) {

				let str = "";
				//音部記号・調号
				if (res[7] != "none")
				 	str += res[7];
				
				//拍子記号
				let strT = "";
				if (res[4] != "none") {
					strT = "[M:" + res[4] + "]";
					str += "[M:" + res[4] + "]";
				}
				
				//速度記号
				let strSp = ""
				if (res[5] != "none" && val != "" && val != "0") {
					let tempoBase = "1/4";
					if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel2d_22.png") != -1) {
						tempoBase = "3/4";
					} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel2_22.png") != -1) {
						tempoBase = "1/2";
					} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel4d_22.png") != -1) {
						tempoBase = "3/8";
					} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel4_22.png") != -1) {
						tempoBase = "1/4";
					} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel8_22.png") != -1) {
						tempoBase = "1/8";
					}

					strSp += '[Q:"' + res[5] + '"' + tempoBase + '=' + val + ']';
				
				} else if (res[5] != "none") {
					strSp += '[Q:"' + res[5] + '"]';
				
				} else if (val != "" && val != "0") {
					let tempoBase = "1/4";
					if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel2d_22.png") != -1) {
						tempoBase = "3/4";
					} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel2_22.png") != -1) {
						tempoBase = "1/2";
					} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel4d_22.png") != -1) {
						tempoBase = "3/8";
					} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel4_22.png") != -1) {
						tempoBase = "1/4";
					} else if ((document.getElementById("imgTempoMarkings2").src).indexOf("noteEqSel8_22.png") != -1) {
						tempoBase = "1/8";
					}

					strSp += '[Q:' + tempoBase + '=' + val + ']';
				}
				let oldSp = ""
				if (res[5] != "none" && res[6] != "none") {
					let tempoBase = res[6].split("=")[0];
					let tempoValue = res[6].split("=")[1];
					oldSp += '[Q:"' + res[5] + '"' + tempoBase + '=' + tempoValue + ']';
				
				} else if (res[5] != "none") {
					oldSp += '[Q:"' + res[5] + '"]';
				
				} else if (res[6] != "none") {
					let tempoBase = res[6].split("=")[0];
					let tempoValue = res[6].split("=")[1];
					oldSp += '[Q:' + tempoBase + '=' + tempoValue + ']';
				}
				
				
				//==============================
				let bak_selectVisualDataIndex = selectVisualDataIndex;
				let bak_selectNoteEndIndex = selectNoteEndIndex;
				
				selectVisualDataIndex = idx;
				selectNoteEndIndex = currentVisualArray[idx].absEl.abcelem.endChar;
				
				//選択小節線や音符・休符直後の設定を取得
				//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
				var res2 = getAfterSettings();	
				
				selectVisualDataIndex = bak_selectVisualDataIndex;
				selectNoteEndIndex = bak_selectNoteEndIndex;

				//------------------------------------------------
				//自段・上段（選択小節線）の設定文字列
				var st1u = currentVisualArray[selectVisualDataIndex].absEl.abcelem.endChar;
				if (res[8] == "btmBar") {
					var ed1u = currentAbcString.indexOf("\n", st1u);
				} else {
					var ed1u = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
				}
				//※　st1u,ed1uは、自段・上段（選択小節線）の設定文字列（ex. [K:clef=bass][M:3/4][Q:...]）

				//------------------------------------------------
				//自段・下段の、同一小節線の設定文字列
				let st1d = currentVisualArray[idx].absEl.abcelem.endChar;
				if (res[8] == "btmBar") {
					var ed1d = currentAbcString.indexOf("\n", st1d);
				} else {
					var ed1d = currentVisualArray[idx+1].absEl.abcelem.startChar;
				}
				//※　st1d,ed1dは、自段の下段の、同一小節線の設定文字列（ex. [K:clef=bass][M:3/4][Q:...]）

				//------------------------------------------------
				var st2u = res2[0];
				var ed2u = res2[1];
				//※　res2[0],res2[1]は、次段の上段先頭の設定文字列（ex. [V: 1 K:clef=bass][K:D][V][M:3/4][Q:...]）
				
				//------------------------------------------------
				var st2d = currentAbcString.indexOf("[V: 2", ed2u);
				var ed2d = st2d;
				for (let i = idx; i < currentVisualArray.length; i++) {
					if (currentVisualArray[i].absEl.abcelem.startChar > st2d) {
						ed2d = currentVisualArray[i].absEl.abcelem.startChar;
						break;
					}
				}
				//※　st2d,ed2dは、次段の下段先頭の設定文字列（ex. [V: 1 K:clef=bass][K:D][V][M:3/4][Q:...]）

				//自段の変更
				if (res[8] != "btmBar") {
					//自段下段
					var newStr = currentAbcString.substring(st1d, ed1d);
					if (oldSp == "") {
						newStr = newStr + strSp;
					} else {
						newStr = newStr.replace(oldSp, strSp);
					}
					currentAbcString = currentAbcString.substring(0, st1d) + newStr + currentAbcString.substring(ed1d);
					
					//自段上段
					var newStr = currentAbcString.substring(st1u, ed1u);
					if (oldSp == "") {
						newStr = newStr + strSp;
					} else {
						newStr = newStr.replace(oldSp, strSp);
					}
					
					currentAbcString = currentAbcString.substring(0, st1u) + newStr + currentAbcString.substring(ed1u);
				
				//次段の変更
				} else {
					//次段下段
					var newStr = currentAbcString.substring(st2d, ed2d);
					if (oldSp == "") {
						newStr = newStr + strSp;
					} else {
						newStr = newStr.replace(oldSp, strSp);
					}
					currentAbcString = currentAbcString.substring(0, st2d) + newStr + currentAbcString.substring(ed2d);
					
					//次段上段
					var newStr = currentAbcString.substring(st2u, ed2u);
					if (oldSp == "") {
						newStr = newStr + strSp;
					} else {
						newStr = newStr.replace(oldSp, strSp);
					}
					
					currentAbcString = currentAbcString.substring(0, st2u) + newStr + currentAbcString.substring(ed2u);
				}
			}
		}
		
		document.getElementById("abc-editor").value = currentAbcString;
		
	 	//楽譜のレンダリング
		renderScore(currentAbcString);
		MSC_resize();
	    //非選択状態にする
	    //abcjsBodyMouseDown(true);
	    
	    //小節線を選択状態にする
		document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		abcEditor.updateSelection();
	}
}

//=====================================================================
//	楽譜段数の変更時
//=====================================================================
function chgRowsCount(val) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//段数が減る場合
	if (val < parseInt(currentRowsCount)) {
		//確認メッセージ
		document.getElementById("spanMessageYesNo").innerHTML = "段数を減らすと、減らした行の楽譜データは消去されます。よいですか？";
		document.getElementById("dialogMessageYesNo").showModal();

		//「はい」の場合
		document.getElementById("btnMessageYesNoYes").onclick = function() {
			document.getElementById("dialogMessageYesNo").close();
			
			//楽譜データの楽譜行数の減じた部分を削除
			let lines = document.getElementById("abc-editor").value.split("\n");
			let delCount = parseInt(currentRowsCount) - val;
			if (currentClefSymbol != "treble" && currentClefSymbol != "bass") {
				delCount = delCount * 2;
			}
			for (let i = lines.length-1; i > 0; i--) {
				if (lines[i] == "") continue;
				if (lines[i].substr(0, 14) == "% end of SCORE") continue;
				if (lines[i].substr(0, 3) == "K: ") break;
				
				if (lines[i].substr(0, 3) != "w: " && lines[i].substr(0, 1) != "%") delCount--;
				lines.splice(i, 1);
				if (delCount == 0) {
					if (currentClefSymbol != "treble" && currentClefSymbol != "bass") {
						lines.splice(i-1, 1);
					}
					break;
				}
			}
			
			//最終行の最終小節のbarを、|] にする
			let idx = -1;
			for (let i = lines.length-1; i > 0; i--) {
				if (lines[i] == "") continue;
				if (lines[i].substr(0, 1) == "%") continue;
				if (lines[i].substr(0, 3) == "K: ") break;
				
				if (lines[i].substr(0, 3) != "w: ") {
					idx = i;
					break;
				}
			}
			if (idx != -1 && lines[idx].substr(-1) == "|") {
				lines[idx] += "]";
				if (currentClefSymbol != "treble" && currentClefSymbol != "bass") {
					lines[idx-currentLyricNumber-2] += "]";
				}
			}
			
			currentAbcString = lines.join("\n");
			document.getElementById("abc-editor").value = currentAbcString;

			currentRowsCount = val;

		 	//楽譜のレンダリング
			renderScore(currentAbcString);
			MSC_resize();
		}

		//「いいえ」の場合
		document.getElementById("btnMessageYesNoNo").onclick = function() {
			document.getElementById("selRowsCount").value = parseInt(currentRowsCount);
			document.getElementById("dialogMessageYesNo").close();
		}

	//段数が増える場合
	} else {
		
		//楽譜データの楽譜行数の増した部分を追加
		let lines = document.getElementById("abc-editor").value.split("\n");
		
		//行追加前の最終行の最終小節のbarを、|] から | にする
		let idx = -1;
		for (let i = lines.length-1; i > 0; i--) {
			if (lines[i] == "") continue;
			if (lines[i].substr(0, 1) == "%") continue;
			if (lines[i].substr(0, 3) == "K: ") break;
			
			if (lines[i].substr(0, 3) != "w: ") {
				idx = i;
				break;
			}
		}
		if (idx != -1 && lines[idx].substr(-2) == "|]") {
			lines[idx] = lines[idx].substr(0, lines[idx].length-1);
			
			if (currentClefSymbol != "treble" && currentClefSymbol != "bass") {
				lines[idx-currentLyricNumber-2] = lines[idx-currentLyricNumber-2].substr(0, lines[idx-currentLyricNumber-2].length-1);
			}
		}
		
		//行追加
		let addCount = val - parseInt(currentRowsCount);
		for (let i = 0; i < addCount; i++) {

			MeasuresCount[parseInt(currentRowsCount) + i] = 4;

			//---------------------------------------------------
			//１段（行追加）
			//---------------------------------------------------
			if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
				if (i < addCount-1) {
					lines.splice(lines.length-1, 0, 'Z|Z|Z|Z|');
				} else {
					lines.splice(lines.length-1, 0, 'Z|Z|Z|Z|]');
				}
				for (j = 0; j < currentLyricNumber; j++) {
					lines.splice(lines.length-1, 0, 'w:  | | | ');
				}
			
			//---------------------------------------------------
			//２段（行追加）
			//---------------------------------------------------
			} else {
				lines.splice(lines.length-1, 0, '% ' + (parseInt(currentRowsCount)+i+1) + '行目、上段');
				if (i < addCount-1) {
					lines.splice(lines.length-1, 0, '[V: 1 K:clef=treble] Z|Z|Z|Z|');		//@@@@@@@@@@@@@@@@@
				} else {
					lines.splice(lines.length-1, 0, '[V: 1 K:clef=treble] Z|Z|Z|Z|]');		//@@@@@@@@@@@@@@@@@
				}
				for (j = 0; j < currentLyricNumber; j++) {
					lines.splice(lines.length-1, 0, 'w:  | | | ');
				}
				
				lines.splice(lines.length-1, 0, '% ' + (parseInt(currentRowsCount)+i+1) + '行目、下段');
				if (i < addCount-1) {
					lines.splice(lines.length-1, 0, '[V: 2 K:clef=treble] Z|Z|Z|Z|');		//@@@@@@@@@@@@@@@@@
				} else {
					lines.splice(lines.length-1, 0, '[V: 2 K:clef=treble] Z|Z|Z|Z|]');		//@@@@@@@@@@@@@@@@@
				}
				for (j = 0; j < currentLyricNumber; j++) {
					lines.splice(lines.length-1, 0, 'w:  | | | ');
				}
			}
		}

		currentAbcString = lines.join("\n");
		
		rebuildeClef();
		
		document.getElementById("abc-editor").value = currentAbcString;

		currentRowsCount = val;

	 	//楽譜のレンダリング
		renderScore();
		MSC_resize();
	}
}

//=====================================================================
//	小節数ボタン
//=====================================================================
function clkMeasuresCount() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	let html = "";
	html += "<tr>\n";
	html += "<th style='width: 70px;'>" + MAC_convLang("段番号") + "</th>\n";
	html += "<th>" + MAC_convLang("小節数") + "</th>\n";
	html += "</tr>\n";

	for (let i = 1; i <= currentRowsCount; i++) {
		html += "<tr>\n";
	
		html += "<td style=' text-align: center;'>" + MAC_convLang_3("第 %1 段", i) + "</td>\n";
		html += "<td style=' text-align: center;'>\n";
	
		html += "<select id='selMeasuresCount_" + i + "' style='width: 70px; height: 22px;'>\n";
		
		for (let j = 1; j <= cMaxMeasures; j++) {
			if (j == MeasuresCount[i-1]) {
				html += "<option value='" + j + "' selected>" + MAC_convLang_1("%1小節", j) + "</option>\n";
			} else {
				html += "<option value='" + j + "'>" + MAC_convLang_1("%1小節", j) + "</option>\n";
			}
		}
		
		html += "</select>\n";
	
		html += "</td>\n";
		html += "</tr>\n";
	}
	
	let table = document.getElementById("tableMeasuresCount");
	table.innerHTML = html;

	document.getElementById("divMeasuresCount").showModal();

	//「キャンセル」の場合
	document.getElementById("btnMeasuresCountCancel").onclick = function() {
		document.getElementById("divMeasuresCount").close();
	}

	//「OK」の場合
	document.getElementById("btnMeasuresCountOK").onclick = function() {
		
		let lines = currentAbcString.split("\n");
		let lineNo = 0;
		for (let i = 0; i < lines.length; i++) {
			if (lines[i].substr(0, 3) == "K: ") {
				lineNo = i+1;
				break;
			}
		}
		
		for (let i = 1; i <= currentRowsCount; i++) {
			let oldMeasuresCount = MeasuresCount[i-1];
			let newMeasuresCount = document.getElementById("selMeasuresCount_" + i).value;
			
			MeasuresCount[i-1] = newMeasuresCount;
			
			//-----------------------------------------------
			//1段の場合
			//-----------------------------------------------
			if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
				while (true) {
					//楽譜行？
					if (lines[lineNo].substr(0, 1) != "%" && lines[lineNo].substr(0, 2) != "w:") {
						//減った分の小節を削除
						if (newMeasuresCount < oldMeasuresCount) {
							let tmp = "";
							if (lines[lineNo].substr(-2) == "|]") {
								tmp = "]";
							}
							var cnt = 0;
							for (let i = lines[lineNo].length - 1; i >= 0; i--) {
								if (lines[lineNo][i] === '|') {
									cnt++;
									// n個目の'|'を見つけたら、それ以降の部分を切り捨てる
									if (cnt == oldMeasuresCount-newMeasuresCount+1) {
										lines[lineNo] = lines[lineNo].substring(0, i+1) + tmp;
										break;
									}
								}
							}
							lineNo++;
							//歌詞の削除
							for(let j = 0; j < currentLyricNumber; j++) {
								var cnt = 0;
								for (let i = lines[lineNo].length - 1; i >= 0; i--) {
									if (lines[lineNo][i] === '|') {
										cnt++;
										// n個目の'|'を見つけたら、それ以降の部分を切り捨てる
										if (cnt == oldMeasuresCount-newMeasuresCount) {
											lines[lineNo] = lines[lineNo].substring(0, i);
											break;
										}
									}
								}
								lineNo++;
							}
							break;
							
						//増えた分の小節を追加
						} else if (newMeasuresCount > oldMeasuresCount) {
							var tmp = "";
							for(let k = 0; k < newMeasuresCount-oldMeasuresCount; k++) {
								tmp += "|Z";
							}
							
							let idx = lines[lineNo].lastIndexOf("|");
							lines[lineNo] = lines[lineNo].substring(0, idx) + tmp + lines[lineNo].substring(idx);
							
							//if (lines[lineNo].substr(-2) == "|]") {
							//	lines[lineNo] = lines[lineNo].substr(0, lines[lineNo].length-1) + tmp + "]";
							//} else {
							//	lines[lineNo] += tmp;
							//}
							
							lineNo++;
							//歌詞の追加
							for(let j = 0; j < currentLyricNumber; j++) {
								var tmp = "";
								for(let k = 0; k < newMeasuresCount-oldMeasuresCount; k++) {
									tmp += "| ";
								}
								lines[lineNo] += tmp;
								lineNo++;
							}
							break;
						//小節数の変更なし
						} else {
							lineNo++;
							break;
						}
					}
					lineNo++;
				}
			
			//-----------------------------------------------
			//2段の場合
			//-----------------------------------------------
			} else {
				while (true) {
					if (lines[lineNo].substr(0, 5) == "[V: 1") {		//@@@@@@@@@@@@@@@@@
						//減った分の小節を削除
						if (newMeasuresCount < oldMeasuresCount) {
							let tmp = "";
							if (lines[lineNo].substr(-2) == "|]") {
								tmp = "]";
							}
							
							var cnt = 0;
							for (let i = lines[lineNo].length - 1; i >= 0; i--) {
								if (lines[lineNo][i] === '|') {
									cnt++;
									// n個目の'|'を見つけたら、それ以降の部分を切り捨てる
									if (cnt == oldMeasuresCount-newMeasuresCount+1) {
										lines[lineNo] = lines[lineNo].substring(0, i+1) + tmp;
										break;
									}
								}
							}
							lineNo++;
							//歌詞の削除
							for(let j = 0; j < currentLyricNumber; j++) {
								var cnt = 0;
								for (let i = lines[lineNo].length - 1; i >= 0; i--) {
									if (lines[lineNo][i] === '|') {
										cnt++;
										// n個目の'|'を見つけたら、それ以降の部分を切り捨てる
										if (cnt == oldMeasuresCount-newMeasuresCount) {
											lines[lineNo] = lines[lineNo].substring(0, i);
											break;
										}
									}
								}
								lineNo++;
							}
							break;

						//増えた分の小節を追加
						} else if (newMeasuresCount > oldMeasuresCount) {
							var tmp = "";
							for(let k = 0; k < newMeasuresCount-oldMeasuresCount; k++) {
								tmp += "|Z";
							}
							
							let idx = lines[lineNo].lastIndexOf("|");
							lines[lineNo] = lines[lineNo].substring(0, idx) + tmp + lines[lineNo].substring(idx);

							//if (lines[lineNo].substr(-2) == "|]") {
							//	lines[lineNo] = lines[lineNo].substr(0, lines[lineNo].length-1) + tmp + "]";
							//} else {
							//	lines[lineNo] += tmp;
							//}
							
							lineNo++;
							//歌詞の追加
							for(let j = 0; j < currentLyricNumber; j++) {
								var tmp = "";
								for(let k = 0; k < newMeasuresCount-oldMeasuresCount; k++) {
									tmp += "| ";
								}
								lines[lineNo] += tmp;
								lineNo++;
							}
							break;
						//小節数の変更なし
						} else {
							lineNo++;
							break;
						}
					}
					lineNo++;
				}
				while (true) {
					if (lines[lineNo].substr(0, 5) == "[V: 2") {		//@@@@@@@@@@@@@@@@@

						//減った分の小節を削除
						if (newMeasuresCount < oldMeasuresCount) {
							let tmp = "";
							if (lines[lineNo].substr(-2) == "|]") {
								tmp = "]";
							}
							
							var cnt = 0;
							for (let i = lines[lineNo].length - 1; i >= 0; i--) {
								if (lines[lineNo][i] === '|') {
									cnt++;
									// n個目の'|'を見つけたら、それ以降の部分を切り捨てる
									if (cnt == oldMeasuresCount-newMeasuresCount+1) {
										lines[lineNo] = lines[lineNo].substring(0, i+1) + tmp;
										break;
									}
								}
							}
							lineNo++;
							//歌詞の削除
							for(let j = 0; j < currentLyricNumber; j++) {
								var cnt = 0;
								for (let i = lines[lineNo].length - 1; i >= 0; i--) {
									if (lines[lineNo][i] === '|') {
										cnt++;
										// n個目の'|'を見つけたら、それ以降の部分を切り捨てる
										if (cnt == oldMeasuresCount-newMeasuresCount) {
											lines[lineNo] = lines[lineNo].substring(0, i);
											break;
										}
									}
								}
								lineNo++;
							}
							break;

						//増えた分の小節を追加
						} else if (newMeasuresCount > oldMeasuresCount) {
							var tmp = "";
							for(let k = 0; k < newMeasuresCount-oldMeasuresCount; k++) {
								tmp += "|Z";
							}

							let idx = lines[lineNo].lastIndexOf("|");
							lines[lineNo] = lines[lineNo].substring(0, idx) + tmp + lines[lineNo].substring(idx);

							//if (lines[lineNo].substr(-2) == "|]") {
							//	lines[lineNo] = lines[lineNo].substr(0, lines[lineNo].length-1) + tmp + "]";
							//} else {
							//	lines[lineNo] += tmp;
							//}
							
							lineNo++;
							//歌詞の追加
							for(let j = 0; j < currentLyricNumber; j++) {
								var tmp = "";
								for(let k = 0; k < newMeasuresCount-oldMeasuresCount; k++) {
									tmp += "| ";
								}
								lines[lineNo] += tmp;
								lineNo++;
							}
							break;
						//小節数の変更なし
						} else {
							lineNo++;
							break;
						}
					}
					lineNo++;
				}
			}
		}
		
		currentAbcString = lines.join("\n");
		document.getElementById("abc-editor").value = currentAbcString;

	 	//楽譜のレンダリング
		renderScore();
		MSC_resize();

		document.getElementById("divMeasuresCount").close();
	}
}

//=====================================================================
//	歌詞番数の変更時
//=====================================================================
function chgLyric(val) {
	//-----------------------------------------------------
	//	歌詞入力テキストボックスの有効・無効
	//-----------------------------------------------------
	function disableTxtLyric() {
		document.getElementById("txtLyric_1").value = "";
		document.getElementById("txtLyric_2").value = "";
		document.getElementById("txtLyric_3").value = "";
		document.getElementById("txtLyric_1").disabled = true;
		document.getElementById("txtLyric_2").disabled = true;
		document.getElementById("txtLyric_3").disabled = true;
	}
	//-----------------------------------------------------

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//番数が減る場合
	if (val < currentLyricNumber) {
		//確認メッセージ
		document.getElementById("spanMessageYesNo").innerHTML = "歌詞番数を減らすと、減らした部分の歌詞データは消去されます。よいですか？";
		document.getElementById("dialogMessageYesNo").showModal();

		//「はい」の場合
		document.getElementById("btnMessageYesNoYes").onclick = function() {
			currentLyricNumber = val;
			document.getElementById("dialogMessageYesNo").close();
			
			//楽譜データの番数の減じた部分を削除
			let lines = document.getElementById("abc-editor").value.split("\n");
			let countW;
			for (let i = 0; i < lines.length; i++) {
				if (lines[i].substr(0, 3) == "w: ") {
					countW++;
					if (countW > currentLyricNumber) {
						lines[i] = "% delele line %";
					}
				} else {
					countW = 0;
				}
			}
			for (let i = lines.length-1; i >= 0; i--) {
				if (lines[i] == "% delele line %") {
					lines.splice(i, 1);
				}
			}
			
			currentAbcString = lines.join("\n");
			document.getElementById("abc-editor").value = currentAbcString;

			//歌詞入力テクストボックスの有効・無効
			disableTxtLyric();
			
		 	//楽譜のレンダリング
			renderScore(currentAbcString);
			MSC_resize();
		}

		//「いいえ」の場合
		document.getElementById("btnMessageYesNoNo").onclick = function() {
			document.getElementById("selLyric").value = currentLyricNumber;
			document.getElementById("dialogMessageYesNo").close();
		}

	} else {
		//楽譜データの番数の増した部分を追加
		let lines = document.getElementById("abc-editor").value.split("\n");
		
		if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
			var lineIdx = currentRowsCount-1;
			var rowDecCnt = 1;
		} else {
			var lineIdx = currentRowsCount*2-1;
			var rowDecCnt = 2;
		}
		
		var rowIndex = currentRowsCount-1;
		var cnt = 0;;

		for (let i = lines.length-1; i >= 0; i--) {
			if (lines[i] == "") continue;
			if (lines[i].substr(0, 1) == "%") continue;
			if (lines[i].substr(0, 3) == "K: ") break;
			
			if (lines[i].substr(0, 3) != "w: ") {
				
				//追加する歌詞の行（lineNo）データの生成（音符情報から生成）
				let lineLyric = [];
				lineLyric[0] = [];
				lineLyric[1] = [];
				lineLyric[2] = [];
				for (col = 0; col < MeasuresCount[rowIndex]; col++) {
					let lyricStr = getDefaultLyricData(lineIdx, col);
					
					lineLyric[0].push(lyricStr[0]);
					lineLyric[1].push(lyricStr[1]);
					lineLyric[2].push(lyricStr[2]);
				}
				
				for (let j = 0; j < val - currentLyricNumber; j++) {
					let idx = parseInt(currentLyricNumber) + j;
					lines.splice(i + idx + 1, 0, 'w: ' + lineLyric[idx].join("|"));
				}
				
				cnt ++;
				if (cnt == rowDecCnt) {
					rowIndex--;
					cnt = 0;
				}
				
				lineIdx--;
			}
		}

		currentLyricNumber = val;

		currentAbcString = lines.join("\n");
		document.getElementById("abc-editor").value = currentAbcString;

		//歌詞入力テクストボックスの有効・無効
		disableTxtLyric();
		
	 	//楽譜のレンダリング
		renderScore(currentAbcString);
		MSC_resize();
	}
}

//=====================================================================
//	楽譜エリアでのキーダウン（歌詞入力とみなして、歌詞の１番の入力へフォーカス）
//=====================================================================
function containerKeydown(event) {
	//↑38
	//↓40
	//上下移動キーは、音程変更
	if (event.keyCode == 9) {
		document.getElementById("txtLyric_1").focus();
		event.stopPropagation();
        event.preventDefault();

	} else if (event.keyCode != 38 && event.keyCode != 40) {
		document.getElementById("txtLyric_1").focus();
	}
}

//=====================================================================
//	歌詞入力テキストボックスでのキーダウン（最終番の場合は、選択noteを１つ進め、歌詞の１番の入力へフォーカス）
//=====================================================================
function keydownLyric(no) {
	//Tabの場合
	if (event.keyCode == 9) {
		//最終番の場合
		if (no == currentLyricNumber) {
			//選択noteを１つ進める
			
			let idx = selectVisualDataIndex;
			
			for (let i = selectVisualDataIndex+1; i < currentVisualArray.length; i++) {
				if (currentVisualArray[i].absEl.type == "note") {
					idx = i;
					break;
				}
			}
			
			if (idx != selectVisualDataIndex) {
				
				selectNoteStartIndex = currentVisualArray[idx].absEl.abcelem.startChar;
				selectNoteEndIndex = currentVisualArray[idx].absEl.abcelem.endChar;
				
				document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
				abcEditor.updateSelection();

				getDataFromRange(selectNoteStartIndex, selectNoteEndIndex);
				
				//新しい選択音符の歌詞を入力エリアにセット
				for (let i = 0; i < currentLyricNumber; i++) {
					if (currentVisualArray[idx].absEl.abcelem.lyric) {
						document.getElementById("txtLyric_" + (i+1)).value = currentVisualArray[idx].absEl.abcelem.lyric[i].syllable;
					} else {
						document.getElementById("txtLyric_" + (i+1)).value = "";
					}
				}

				//歌詞の１番の入力へフォーカス
				document.getElementById("txtLyric_1").focus();
			}
			event.stopPropagation();
	        event.preventDefault();
		}
	}
}

//=====================================================================
//	歌詞文字の変更
//		no	0 | 1 | 2
//=====================================================================
function inputLyricText(no, elem) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//選択が音符以外
	if (selectNoteOrRest != "note") {
		elem.value = "";
		return
	}

	//入力文字の空白等を除去
	let val = elem.value;
	val = val.replace(/ /g, "");
	val = val.replace(/%/g, "");
	val = val.replace(/-/g, "");
	val = val.replace(/_/g, "");
	val = val.replace(/\|/g, "");
	elem.value = val;
	if (val == "") val = "_";
	

	//この小節の何音目（noteCount）かを取得
	var idx = selectVisualDataIndex;
	let noteCount = 0;
	while (true) {
		if (idx < 0) break;
		
		if (currentVisualArray[idx].absEl.type == "bar") break;
		if (currentVisualArray[idx].absEl.abcelem.abselem.counters.measure != currentMeasureNo) break;
		if (currentVisualArray[idx].absEl.type == "note") noteCount++;
		idx--;
	}

	//選択位置（selectNoteEndIndex）から、歌詞番目（no）の"w: "の後の、この小節目（currentMeasureNo）の、この音目（noteCount:1～）の歌詞を val に差し替える
	abcString = currentAbcString;
	let noCnt = 0;
	let measureCnt = 0;
	let noteCnt = 0;
	let st;
	let ed;
	let breakFlag = false;
	var idx = selectNoteEndIndex;
	while (true) {
		//w: 行
		if (abcString.substr(idx, 3) == "w: ") {
			//no 番目の w: 行
			if (noCnt == no) {

				//currentMeasureNo 小節の先頭index（st）
				while (true) {
					if ((measureCnt == 0 && abcString[idx] == " " && abcString[idx+1] != " ") || (abcString[idx-1] == "|" && abcString[idx] == " " && abcString[idx+1] != " ")) {
						if (measureCnt == currentMeasureNo) {

							while (true) {
								if (abcString[idx] == " " && abcString[idx+1] != " ") {
									//noteCount:1～音目の先頭
									if (noteCnt == noteCount-1) {
										st = idx+1;

										///noteCount:1～音目の終端
										while (true) {
											if (abcString[idx] != " " && abcString[idx+1] == " ") {
												ed = idx;
												breakFlag = true;
												break;
											}
											idx++;
											if (idx >= abcString.length) break;
										}
										if (breakFlag == true) break;
									}
									noteCnt++;
								}
								idx++;
								if (idx >= abcString.length) break;
							}
							if (breakFlag == true) break;

						}
						measureCnt++;
					}
					idx++;
					if (idx >= abcString.length) break;
				}
				if (breakFlag == true) break;

			}
			noCnt++;
		}
		idx++;
		if (idx >= abcString.length) break;
	}

	let str = abcString.substring(0, st) + val + abcString.substring(ed+1);
	
	currentAbcString = str;
	document.getElementById("abc-editor").value = currentAbcString;

 	//楽譜のレンダリング
	renderScore();
	MSC_resize();

	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
	abcEditor.updateSelection();
}


//##########################################################################
//##########################################################################
//	メニュー処理（中段）
//		小節線の変更								chgBar(val);
//		音階のアップ・ダウンボタン押下				clkNoteUpDown(step);
//		音符ボタン押下								clkNote(len);
//		休符ボタン押下								clkRest(len);
//		シャープ、フラット、ナチュラルボタン押下	clkSharpFlat(kind);
//		タイ・スラー設定ボタン押下					clkTaiSlur(job);
//		アーティキュレーションボタン押下			clkArticulation(kind);
//		追加のアーティキュレーションボタン押下		clkOptionArticulation();
//		和音設定ボタン押下							clkChord();
//		和音解除ボタン押下							clkChordRemove();
//		８分音符、16分音符の分離・結合				clkNoteSeparateJoin(job);
//		３連符の設定、解除							clkTriplets(job);
//		
//		
//##########################################################################

//=====================================================================
//	小節線の変更時
//=====================================================================
function chgBar(val) {

	if (selBarLineEvent == false) {
		selBarLineEvent = true;
		return;
	}

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//小節線の選択時
	if (selectNoteOrRest == "bar") {
		//２段楽譜の場合
		if (currentClefSymbol != "treble" && currentClefSymbol != "bass") {
			//voice==0での何番目の小節線か？
			var cntBar0 = 0;
			for (let i = 0; i < currentVisualArray.length; i++) {
				if (currentVisualArray[i].absEl.type == "bar") {
					//上段をカウント
					if (isUpperLineByArrIndex(i) == true) {
						cntBar0++;
						if (currentVisualArray[i].absEl.abcelem.startChar == selectNoteStartIndex) {
							break;
						}
					}
				}
			}

			//voice==1でのその番目（cntBar0）の小節線のstartCharとendCharを取得
			var st = -1;
			var ed = -1;
			var cntBar1 = 0;
			for (let i = 0; i < currentVisualArray.length; i++) {
				if (currentVisualArray[i].absEl.type == "bar") {
					//下段をカウント
					if (isUpperLineByArrIndex(i) == false) {
						cntBar1++;
						if (cntBar1 == cntBar0) {
							st = currentVisualArray[i].absEl.abcelem.startChar;
							ed = currentVisualArray[i].absEl.abcelem.endChar
							break;
						}
					}
				}
			}
			
			if (st != -1 && ed != -1) {
				currentAbcString = currentAbcString.substring(0, st) + val + currentAbcString.substring(ed);
			}
		}	//２段の場合

		currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + val + currentAbcString.substring(selectNoteEndIndex);

		document.getElementById("abc-editor").value = currentAbcString;
		
		selectNoteEndIndex = selectNoteStartIndex + val.length;
		selectNoteStr = currentAbcString.substring(selectNoteStartIndex, selectNoteEndIndex);

	 	//楽譜のレンダリング
		renderScore();

		if (val == "") {
			abcjsBodyMouseDown(true);
		} else {
			document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
			abcEditor.updateSelection();
		}

	//左端の小節での選択時
	} else {
		let st = selectBarStartIndex;
		
		if (currentClefSymbol != "treble" && currentClefSymbol != "bass") {
			//２段目の行頭（[V: 2]）を検索
			let st2 = st;
			while (true) {
				if (currentAbcString.substr(st2, 3) == "[V:") {		//@@@@@@@@@@@@@@@@@
					break;
				}
				st2++;
			}

			//２段目の先頭小節線の位置を取得
			while (true) {
				if (currentAbcString.substr(st2, 1) == "]") {
				st2++;
					break;
				}
				st2++;
			}

			//小節線の終点の取得
			let ed2;
			//現在、小節線はない
			if (currentAbcString.substr(st2, 1) != "|" && currentAbcString.substr(st2, 1) != ":") {
				ed2 = st2;
			} else if (currentAbcString.substr(st2, 3) != ":|:") {
				ed2 = st2 + 3;
			} else {
				ed2 = st2 + 2;
			}

			currentAbcString = currentAbcString.substring(0, st2) + val + currentAbcString.substring(ed2);


			//１段目の先頭小節線の位置を取得
			let off = 0;
			while (true) {
				if (currentAbcString.substr(st+off, 1) == "]") {
					off++;
					break;
				}
				if (off >= 8) {
					off = 0;
					break;
				}
				off++;
			}
			st += off;
		}
		let ed;
		
		//現在、小節線はない
		if (currentAbcString.substr(st, 1) != "|" && currentAbcString.substr(st, 1) != ":") {
			ed = st;
		} else if (currentAbcString.substr(st, 3) != ":|:") {
			ed = st + 3;
		} else {
			ed = st + 2;
		}

		currentAbcString = currentAbcString.substring(0, st) + val + currentAbcString.substring(ed);

		document.getElementById("abc-editor").value = currentAbcString;
		
		selectNoteStartIndex = st;
		selectNoteEndIndex = selectNoteStartIndex + val.length;
		selectNoteStr = currentAbcString.substring(selectNoteStartIndex, selectNoteEndIndex);
		selectNoteOrRest = "bar";

	 	//楽譜のレンダリング
		renderScore();
		
		if (val == "") {
			abcjsBodyMouseDown(true);
		} else {
			document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
			abcEditor.updateSelection();
		}
	}
}

//=====================================================================
//	音階のアップ・ダウンボタン押下時
//=====================================================================
function clkNoteUpDown(step) {

	let lastSpace = false;

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	var originalText = currentAbcString.substring(selectNoteStartIndex, selectNoteEndIndex);

	if (originalText.substr(-1) == " ") {
		lastSpace = true;
	}
	
	var arr = tokenize(originalText);

	// arr now contains elements that are either a chord, a decoration, a note name, or anything else. It can be put back to its original string with .join("").
	for (var i = 0; i < arr.length; i++) {
		arr[i] = moveNote(arr[i], -step);
	}
	var newText = arr.join("");
	
	if (lastSpace == true) {
		newText += " ";
	}
	
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + newText + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + newText.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		//（変更はないので、不要）setDisabledNoteRestButton("auto")
	}, 0);
}

//=====================================================================
//	音符ボタン押下時
//		更新位置より右を削除しても、countByBarを超える場合は、処理しない
//=====================================================================
function clkNote(len) {

	var tmpDisp = document.getElementById("divOptionNoteAndRest").style.display;
	
	document.getElementById("divOptionArticulation").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//if (selectBarBeforeLen + len <= countByBar && (selectNoteOrRest == "note" || selectNoteOrRest == "rest")) {
	if (selectBarBeforeLen + len <= countByBarArr[currentLineNo][currentMeasureNo] && (selectNoteOrRest == "note" || selectNoteOrRest == "rest")) {

		//初期音階（五線譜の真ん中の音階）
		if (currentClefSymbol == "bass" || (currentClefSymbol == "treble_bass" && isTrebleLine() == false)) {
			delaultScale = "D,";
		} else {
			delaultScale = "B";
		}

		//選択中の音長＝挿入音長（指定長の音符と差換え）
		if (selectDuration == len) {
			//休符→音符で、同じ長さなので、「休符を同長の音符（音階はdelaultScale）」に差し替え
			if (selectNoteOrRest == "rest") {
				if (getCurrentTripletsNumber() == 1) {
					var newStr = "(3" + cnveRestToNoteForSame(selectNoteStr, selectPitchesStr, selectDuration, delaultScale, len);
				} else if (getCurrentQuintupletNumber() == 1) {
					var newStr = "(5" + cnveRestToNoteForSame(selectNoteStr, selectPitchesStr, selectDuration, delaultScale, len);
				} else {
					var newStr = cnveRestToNoteForSame(selectNoteStr, selectPitchesStr, selectDuration, delaultScale, len);
				}
				replaceAbcStr(newStr, selectNoteStartIndex, selectNoteEndIndex);
			
			//音符→音符で同じ長さなので、「変更なし」
			} else {
				return;
			}
		
		//選択中の音長＞挿入音長（指定長の音符＋差分休符と差換え）
		} else if (selectDuration > len) {
			//休符→音符で、挿入音長が短いので、「指定長の音符（音階はdelaultScale）＋差分の休符」に差し替え
			if (selectNoteOrRest == "rest") {
				let newStr = cnveRestToNoteForShort(selectNoteStr, selectPitchesStr, selectDuration, delaultScale, len);
				replaceAbcStr(newStr, selectNoteStartIndex, selectNoteEndIndex);
			
			//音符→音符で、挿入音長が短いので、「指定長の音符（元の音階）＋差分の音符（元の音階）」に差し替え
			} else {
				//現在の音長（selectDuration）を、len と （selectDuration-len） の分解する
				let newStr = cnveNoteToNoteForShort(selectNoteStr, selectPitchesStr, selectDuration, delaultScale, len);
				replaceAbcStr(newStr, selectNoteStartIndex, selectNoteEndIndex);
			}
		
		//選択中の音長＜挿入音長（指定長音符＋差分長分を右隣から削除）
		} else {
			//挿入長より長くなるまで、選択範囲終端を伸ばし、合計長sumLenと仮選択終端を求める
			let sumLen = selectDuration;
			let idx = selectVisualDataIndex + 1;		//選択中の音符index（選択中のVisualArrayデータのcurrentVisualArrayに対するindex）

			var tmpSelectNoteEndIndex = selectNoteEndIndex;

			while (true) {
				if (currentVisualArray[idx].absEl.abcelem.duration) {
					sumLen += currentVisualArray[idx].absEl.abcelem.duration*8;
					
					//選択中の音長＜挿入音長
					if (sumLen >= len) {
						tmpSelectNoteEndIndex = currentVisualArray[idx].absEl.abcelem.endChar;
						break;
					}
				}
				idx++;
			}

			//「指定長の音符（音階はdelaultScale）＋ 合計長に対する差分の休符」に差し替え
			if (selectNoteOrRest == "rest") {
				let newStr = cnveRestToNoteForLong(selectNoteStr, selectPitchesStr, sumLen, delaultScale, len);
				replaceAbcStr(newStr, selectNoteStartIndex, tmpSelectNoteEndIndex);
			
			//「指定長の音符（元の音階）＋ 合計長に対する差分の音符（元の音階）」に差し替え
			} else {
				let newStr = cnveNoteToNoteForLong(selectNoteStr, selectPitchesStr, sumLen, delaultScale, len);
				replaceAbcStr(newStr, selectNoteStartIndex, tmpSelectNoteEndIndex);
			}

			selectNoteEndIndex = tmpSelectNoteEndIndex;
		}
		
		//楽譜のレンダリング
		currentAbcString = document.getElementById("abc-editor").value;
		renderScore(currentAbcString);

		//barの場合は進めない
		if (currentVisualArray[selectVisualDataIndex + 1].absEl.type == "bar") {
			var st = currentVisualArray[selectVisualDataIndex].absEl.abcelem.startChar;
			var ed = currentVisualArray[selectVisualDataIndex].absEl.abcelem.endChar;
		} else {
			var st = currentVisualArray[selectVisualDataIndex + 1].absEl.abcelem.startChar;
			var ed = currentVisualArray[selectVisualDataIndex + 1].absEl.abcelem.endChar;
		}
		
		//選択解除
		abcjsBodyMouseDown(true);
		
		setTimeout( function() {
			//エディタのスクロール位置の保存
			let scrollTop = document.getElementById(editorId).scrollTop;
	    	//エディタにフォーカス
	    	document.getElementById(editorId).focus();
	    	//エディタの選択領域（range）をセット
	    	document.getElementById(editorId).setSelectionRange(st, ed);
			//楽譜上の該当箇所を選択表示（赤色表示）
			abcEditor.updateSelection();
			
			getDataFromRange(st, ed);
			setDisabledNoteRestButton("auto");
			
			//エディタのスクロール位置を戻す
			document.getElementById(editorId).scrollTop = scrollTop;
			//ボタン類の有効・無効設定
			//（変更はないので、不要）setDisabledNoteRestButton("auto")
			
			document.getElementById("divOptionNoteAndRest").style.display = tmpDisp;
		}, 0);
	}
}

//=====================================================================
//	休符ボタン押下時
//=====================================================================
function clkRest(len) {

	var tmpDisp = document.getElementById("divOptionNoteAndRest").style.display;
	
	document.getElementById("divOptionArticulation").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//if ((selectBarBeforeLen + len <= countByBar && (selectNoteOrRest == "note" || selectNoteOrRest == "rest")) || (len == 8)) {
	if ((selectBarBeforeLen + len <= countByBarArr[currentLineNo][currentMeasureNo] && (selectNoteOrRest == "note" || selectNoteOrRest == "rest")) || (len == 8)) {

		//全休符の場合
		if (len == 8) {
			//var newStr = "z" + countByBar + " ";
			var newStr = "z" + countByBarArr[currentLineNo][currentMeasureNo] + " ";
			replaceAbcStr(newStr, selectBarStartIndex, selectBarEndIndex);

		//選択中の音長＝挿入音長（指定長の休符と差換え）
		} else if (selectDuration == len) {
			//休符→休符で、同じ長さなので、「変更なし」
			if (selectNoteOrRest == "rest") {
				return;
			
			//音符→休符で同じ長さなので、「音符を同長の休符」に差し替え
			} else {
				if (getCurrentTripletsNumber() == 1) {
					var newStr = "(3" + cnveNoteToRestForSame(selectNoteStr, selectPitchesStr, selectDuration, len);
				} else if (getCurrentQuintupletNumber() == 1) {
					var newStr = "(5" + cnveNoteToRestForSame(selectNoteStr, selectPitchesStr, selectDuration, len);
				} else {
					var newStr = cnveNoteToRestForSame(selectNoteStr, selectPitchesStr, selectDuration, len);
				}
				replaceAbcStr(newStr, selectNoteStartIndex, selectNoteEndIndex);
			}
		
		//選択中の音長＞挿入音長（指定長音符＋差分休符と差換え）
		} else if (selectDuration > len) {
			//休符→休符で、挿入音長が短いので、「指定長の休符＋差分の休符」に差し替え
			if (selectNoteOrRest == "rest") {
				//現在の音長（selectDuration）を、len と （selectDuration-len） の分解する
				let newStr = cnveRestToRestForShort(selectNoteStr, selectPitchesStr, selectDuration, len);
				replaceAbcStr(newStr, selectNoteStartIndex, selectNoteEndIndex);
			
			//音符→休符で、挿入音長が短いので、「指定長の休符＋差分の音符（元の音階）」に差し替え
			} else {
				let newStr = cnveNoteToRestForShort(selectNoteStr, selectPitchesStr, selectDuration, len);
				replaceAbcStr(newStr, selectNoteStartIndex, selectNoteEndIndex);
			}
		
		//選択中の音長＜挿入音長（指定長音符＋差分長分を右隣から削除）
		} else {
			//挿入長より長くなるまで、選択範囲終端を伸ばし、合計長sumLenと仮選択終端を求める
			let sumLen = selectDuration;
			let idx = selectVisualDataIndex + 1;		//選択中の音符index（選択中のVisualArrayデータのcurrentVisualArrayに対するindex）

			var tmpSelectNoteEndIndex = selectNoteEndIndex;

			while (true) {
				if (currentVisualArray[idx].absEl.abcelem.duration) {
					sumLen += currentVisualArray[idx].absEl.abcelem.duration*8;		//選択中の音長＜挿入音長（指定長音符＋差分長分を右隣から削除）
					if (sumLen >= len) {
						tmpSelectNoteEndIndex = currentVisualArray[idx].absEl.abcelem.endChar;
						break;
					}
				}
				idx++;
			}

			//「指定長の休符＋ 合計長に対する差分の休符」に差し替え
			if (selectNoteOrRest == "rest") {
				let newStr = cnveRestToRestForLong(selectNoteStr, selectPitchesStr, sumLen, len);
				replaceAbcStr(newStr, selectNoteStartIndex, tmpSelectNoteEndIndex);
			
			//「指定長の休符＋ 合計長に対する差分の休符」に差し替え
			} else {
				let newStr = cnveNoteToRestForLong(selectNoteStr, selectPitchesStr, sumLen, len);
				replaceAbcStr(newStr, selectNoteStartIndex, tmpSelectNoteEndIndex);
			}

			selectNoteEndIndex = tmpSelectNoteEndIndex;

		}
		
		//楽譜のレンダリング
		currentAbcString = document.getElementById("abc-editor").value;
		renderScore(currentAbcString);

		//barの場合は進めない
		if (currentVisualArray[selectVisualDataIndex + 1].absEl.type == "bar") {
			var st = currentVisualArray[selectVisualDataIndex].absEl.abcelem.startChar;
			var ed = currentVisualArray[selectVisualDataIndex].absEl.abcelem.endChar;
		} else {
			var st = currentVisualArray[selectVisualDataIndex + 1].absEl.abcelem.startChar;
			var ed = currentVisualArray[selectVisualDataIndex + 1].absEl.abcelem.endChar;
		}

		//選択解除
		abcjsBodyMouseDown(true);

		setTimeout( function() {
			//エディタのスクロール位置の保存
			let scrollTop = document.getElementById(editorId).scrollTop;
	    	//エディタにフォーカス
	    	document.getElementById(editorId).focus();
	    	//エディタの選択領域（range）をセット
	    	document.getElementById(editorId).setSelectionRange(st, ed);
			//楽譜上の該当箇所を選択表示（赤色表示）
			abcEditor.updateSelection();
			
			getDataFromRange(st, ed);
			setDisabledNoteRestButton("auto");
			
			//エディタのスクロール位置を戻す
			document.getElementById(editorId).scrollTop = scrollTop;
			//ボタン類の有効・無効設定
			//（変更はないので、不要）setDisabledNoteRestButton("auto")
			
			document.getElementById("divOptionNoteAndRest").style.display = tmpDisp;
		}, 0);
	}
}

//=====================================================================
//	追加の音符・休符ボタン押下時
//=====================================================================
function clkOptionNoteAndRest() {

	document.getElementById("divOptionArticulation").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	elem = document.getElementById("divOptionNoteAndRest");

	if (elem.style.display == "block") {
		elem.style.display = "none";
	} else {
		elem.style.left = "280px";
		elem.style.top = "134px";
		elem.style.display = "block";
	}
}


//=====================================================================
//	音符・休符の削除（不完全小節化）	@@@
//=====================================================================
function clkNoteDel() {

	let str = currentAbcString.substring(0, selectNoteStartIndex) + currentAbcString.substring(selectNoteEndIndex);
	currentAbcString = str;

	//楽譜のレンダリング
	document.getElementById("abc-editor").value = currentAbcString;
	renderScore(currentAbcString);

	//選択解除
	abcjsBodyMouseDown(true);
}


//=====================================================================
//	完全小節に戻す	@@@
//=====================================================================
function clkNoteOrg() {

	let str = currentAbcString.substring(0, selectBarStartIndex) + "Z" + currentAbcString.substring(selectBarEndIndex);
	currentAbcString = str;

	//楽譜のレンダリング
	document.getElementById("abc-editor").value = currentAbcString;
	renderScore(currentAbcString);

	//選択解除
	abcjsBodyMouseDown(true);
}

//=====================================================================
//	複旋律	追加の音符・休符 / 追加した音符・休符の削除		@@@
//		job : set | remove
//=====================================================================
function clkNoteAdd(job) {
	//追加の場合（現在の小節の末尾に"&Z"を追加）
	if (job == "set") {
		currentAbcString = currentAbcString.substring(0, selectBarEndIndex) + "&Z" + currentAbcString.substring(selectBarEndIndex);

	//削除の場合（現在の小節の、"&"以降を削除し、末尾の空白を除去）
	} else {
		let str = currentAbcString.substring(selectBarStartIndex, selectBarEndIndex);
		let pos = str.indexOf("&");
		if (pos == -1) return

		str = str.substring(0, pos);
		currentAbcString = currentAbcString.substring(0, selectBarStartIndex) + str + currentAbcString.substring(selectBarEndIndex);
	}

	//楽譜のレンダリング
	document.getElementById("abc-editor").value = currentAbcString;
	renderScore(currentAbcString);

	//選択解除
	abcjsBodyMouseDown(true);
}


//=====================================================================
//	シャープ、フラット、ナチュラルボタン押下時
//=====================================================================
function clkSharpFlat(kind) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	let str = selectNoteStr;
	let mark = "";

	//現在の、シャープ、フラット、ナチュラル を削除（正規表現で ^ _ = の後に a-g または A-G が続く場合に一致するパターン）
	//const pattern = /[\^_=](?=[abcdefgABCDEFG])/g;
	const pattern = /(\^\^|\^|__|_|=)(?=[abcdefgABCDEFG])/g;		//ダブルフラット、ダブルシャープ対応
	// パターンに一致する部分を削除
	str =  str.replace(pattern, '');

	if (kind == "sharp") {
		if ((document.getElementById("imgSharpFlatSharp").src).indexOf("sharpDbl22.png") != -1) {
			mark = "^^";
		} else {
			mark = "^";
		}
	} else if (kind == "flat") {
		if ((document.getElementById("imgSharpFlatFlat").src).indexOf("flatDbl22.png") != -1) {
			mark = "__";
		} else {
			mark = "_";
		}
	} else if (kind == "natural") {
		mark = "=";
	}
	
	// 正規表現で a-g または A-G の前に _ を挿入
	if (mark != "") {
		const pattern = /(?=[abcdefgABCDEFG])/g;
		str = str.replace(pattern, mark);
	}
	
	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + str + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + str.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
	}, 0);
}

//=====================================================================
//	タイ・スラー設定ボタン押下時
//=====================================================================
function clkTaiSlur(job) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	if (selectVisualDataIndex == -1) return;
	
	let forceChange = false;

	//-----------------
	let taiSt = false;
	let taiEd = false;
	let slurSt = false;
	let slurEd = false;

	let st = selectNoteStartIndex;
	let ed = selectNoteEndIndex;

	//タイの開始チェック
	if (currentAbcString[selectNoteEndIndex-1] == "-") {			//末尾が"-"
		taiSt = true;
	} else if (currentAbcString[selectNoteEndIndex] == "-") {		//末尾の次が"-"
		taiSt = true;
		ed = selectNoteEndIndex+1;
	}
	//タイの終了チェック
	if (currentAbcString[selectNoteStartIndex] == "-") {			//先頭が"-"
		taiEd = true;
	} else if (currentAbcString[selectNoteStartIndex-1] == "-") {	//先頭の前が"-"
		taiEd = true;
		st = selectNoteStartIndex-1;
	} else if (currentAbcString[selectNoteStartIndex-1] == ")" &&
			   currentAbcString[selectNoteStartIndex-2] == "-") {	//先頭の前が"("で、２つ前が"-"
		taiEd = true;
		st = selectNoteStartIndex-2;
	}

	//スラーの開始チェック
	if (currentAbcString[selectNoteStartIndex] == "(") {			//先頭が"("
		slurSt = true;
	} else if (currentAbcString[selectNoteStartIndex-1] == "(") {	//先頭の前が"("
		slurSt = true;
		st = selectNoteStartIndex-1;
	}
	//スラーの終了チェック
	if (currentAbcString[selectNoteEndIndex-1] == ")") {			//末尾が")"
		slurEd = true;
	}

	let newStr = currentAbcString.substring(st, ed);

	//-----------------
	//次の音符のindexを取得
	let nextNoteIdx = -1;
	var idx = selectVisualDataIndex + 1;
	while (true) {
		if (idx > currentVisualArray.length-1) break;
		if (currentVisualArray[idx].absEl.abcelem.pitches) {
			nextNoteIdx = idx;
			break;
		}
		idx++;
	}

	//-----------------
	//タイ・スラーの開始を設定
	if (job == "st") {
		if (nextNoteIdx == -1) return;

		//既にスラーの開始設定がある場合は、タイの開始を追加設定
		if (slurSt == true && cfgBtnTaiSlurTaiDisabled == false) {
			newStr = newStr + "-";

		//既にタイの開始設定がある場合は、スラーの開始に変更
		} else if (taiSt == true && cfgBtnTaiSlurSlurDisabled == false) {
			newStr = "(" + newStr.substr(0, newStr.length-1);

		//タイ開始もスラー開始も設定がない場合は、タイ開始を設定
		} else {
			if (cfgBtnTaiSlurTaiDisabled == false) {
				newStr = newStr + "-";
			} else if (cfgBtnTaiSlurSlurDisabled == false) {
				newStr = "(" + newStr;
			}
		}

	//-------------------------------------------------------------
	//スラーの終了を設定
	} else if (job == "ed") {
		//スラーの終了を設定
		if (newStr.substr(-1) == " ") {
			newStr = newStr.substr(0, newStr.length-1) + ") ";
		} else {
			newStr = newStr + ")";
		}

	//-------------------------------------------------------------
	//タイ・スラーの開始を解除
	} else if (job == "stdel") {
		//まず、タイの開始がある場合は、タイの開始を削除
		if (taiSt == true) {
			newStr = newStr.substr(0, newStr.length-1);
		
		//次に、スラーの開始がある場合は、スラーの開始を削除
		} else if (slurSt == true) {
			newStr = newStr.substr(1);
		}

	//-------------------------------------------------------------
	//タイ・スラーの終了を解除
	} else if (job == "eddel") {

		//まず、タイの終了がある場合は、直前のタイの開始を削除
		if (taiEd == true) {
			newStr = newStr.substr(1);

		//スラーの終了がある場合は、スラーの終了を削除
		} else if (slurEd == true) {
			//newStr = newStr.replace(")", "");
			if (newStr.substr(-1) == " ") {
				newStr = newStr.substr(0, newStr.length-2) + " ";
			} else {
				newStr = newStr.substr(0, newStr.length-1);
			}
		}
	}

	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, st) + newStr + currentAbcString.substring(ed);
	

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	MSC_resize();
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + newStr.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
	}, 0);
}

//=====================================================================
//	ブレスボタン押下時
//=====================================================================
function clkBreath(kind) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//設定を一旦削除
	let str = selectNoteStr.replace('"　　　V"', '').replace('"V"', '');
	
	//設定を追加
	if (kind == "breath") {
		if (selectNoteOrRest == "bar") {
			strBreath = '"V"';
		} else {
			strBreath = '"　　　V"';
		}
	
		str = strBreath + str;
	}
	
	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + str + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	MSC_resize();
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + str.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
	}, 0);
}

//=====================================================================
//	アーティキュレーションボタン押下時
//=====================================================================
function clkArticulation(kind) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//現在の設定を取得
	let orgDecorationStr = "";
	for (let i = 0; i < selectDecoration.length; i++) {
		if (selectDecoration[i] == "staccato") {
			orgDecorationStr += ".";
		} else {
			orgDecorationStr += "!" + selectDecoration[i] + "!";
		}
	}

	//新規の設定を取得
	let newDecorationStr = "";
	if (kind != "none") {
		//複数配置可
		if (cMultiArticulation == true) {
			if (orgDecorationStr.indexOf(kind) == -1) {
				if (kind == ".") {
					newDecorationStr = kind + orgDecorationStr;
				} else {
					newDecorationStr = "!" + kind + "!" + orgDecorationStr;
				}
			} else {
				newDecorationStr = orgDecorationStr;
			}
		
		//複数配置不可
		} else {
			if (kind == ".") {
				newDecorationStr += kind;
			} else {
				newDecorationStr += "!" + kind + "!";
			}
		}
	}
/*
	for (let i = 0; i < selectDecoration.length; i++) {
		if (ArticulationArr.indexOf(selectDecoration[i]) == -1) {
			newDecorationStr += "!" + selectDecoration[i] + "!";
		}
	}
*/
	//現在の設定と新規の設定を入れ替える
	if (orgDecorationStr == "") {
		if (selectNoteStr[0] == "(") {
			var newstr = "(" + newDecorationStr + selectNoteStr.substr(1);
		} else {
			var newstr = newDecorationStr + selectNoteStr;
		}
	} else {
		var newstr = selectNoteStr.replace(orgDecorationStr, newDecorationStr);
	}
	
	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + newstr + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	MSC_resize();
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + newstr.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
	}, 0);
}

//=====================================================================
//	追加のアーティキュレーションボタン押下時
//=====================================================================
function clkOptionArticulation() {
	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";

	elem = document.getElementById("divOptionArticulation");
	if (elem.style.display == "block") {
		elem.style.display = "none";
	} else {
		elem.style.left = "453px";
		elem.style.top = "134px";
		elem.style.display = "block";
	}
}

//=====================================================================
//	和音設定ボタン押下時
//=====================================================================
var chordTimerId;
var	chordSelectedId = -1;

var chordPitchesTreble = [
													"c''",
	"b'",	"a'",	"g'",   "f'",   "e'",   "d'",   "c'",
	"b",    "a",    "g",    "f",    "e",    "d",    "c",
	"B",    "A",    "G",    "F",    "E",    "D",    "C",
	"B,",   "A,",   "G,",   "F,",   "E,",	"D,",	"C,",
	"B,,",	"A,,",
];

var chordPitchesBass = [
									"e",	"d",	"c",
	"B",    "A",    "G",    "F",    "E",    "D",    "C",
	"B,",   "A,",   "G,",   "F,",   "E,",   "D,",   "C,",
	"B,,",  "A,,",  "G,,",  "F,,",  "E,,",  "D,,",  "C,,",
	"B,,,", "A,,,", "G,,,",	"F,,,",	"E,,,",	"D,,,",	"C,,,",
];

var chordPitches = [];

var chordOrgPitchesStr;

function clkChord() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;
	
	setDisabledNoteRestButton("disabled");

	document.getElementById("divBackCover").style.display = "block";
	document.getElementById("divBackCover2").style.display = "block";
	document.getElementById("divChord").style.left = "321px";
	document.getElementById("divChord").style.top = "4px";
	document.getElementById("divChord").style.display = "block";

	//背景の設定（treble or bass）
	if (v_isTrebleLine == true) {
		chordPitches = chordPitchesTreble;
		document.getElementById("divChordBody").style.backgroundImage = 'url("./imgMSC/chord_treble2.png")';
	} else {
		chordPitches = chordPitchesBass;
		document.getElementById("divChordBody").style.backgroundImage = 'url("./imgMSC/chord_bass2.png")';
	}

	//音符のチェック解除 と シャープ、フラット、ナチュラルの消去
	for (let i = 0; i < 31; i++) {
		document.getElementById("chordChk_" + i).checked = false;
		document.getElementById("chordImg_" + i).src = "./imgMSC/none10x20.png";
	}

	//選択中の音符の設定（音符のチェック状態と臨時記号イメージsrc）
	chordOrgPitchesStr = "";
	for (let i = 0; i < selectPitches.length; i++) {
		let pitch = selectPitches[i].name;
		chordOrgPitchesStr += pitch;
		//シャープ、フラット、ナチュラル
		let acc = "none";
		if (pitch.indexOf("^") != -1) {
			acc = "sharp";
			pitch = pitch.substr(1);
		} if (pitch.indexOf("_") != -1) {
			acc = "flat";
			pitch = pitch.substr(1);
		} if (pitch.indexOf("=") != -1) {
			acc = "natural";
			pitch = pitch.substr(1);
		}
		let idx = chordPitches.indexOf(pitch);
		document.getElementById("chordChk_" + idx).checked = true;
		document.getElementById("chordImg_" + idx).src = "./imgMSC/" + acc + "10x20.png";
	}
	if (selectPitches.length > 1) {
		chordOrgPitchesStr = "[" + chordOrgPitchesStr + "]";
	}

	//ダイアログ内のコントロールの有効・無効評価用タイマー
	chordTimerId = setInterval( function() {

		let elems = document.getElementsByClassName("chordChk");

		//OKボタンの有効、無効化
		var flag = true;
		for (let i = 0; i < elems.length; i++) {
			if (elems[i].checked == true) {
				flag = false;
				break;
			}
		}
		document.getElementById("btnChordOK").disabled = flag;
		
		//フォーカスのある音符がチェックの場合、上部メニューボタンを有効化
		var flag = true;
		var flagRemove = true;
		for (let i = 0; i < elems.length; i++) {
			if (elems[i] == document.activeElement && elems[i].checked == true) {
				flag = false;
				if (elems[i].checked == true) flagRemove = false;
				break;
			}
		}
		document.getElementById("btnDlgChordSharp").disabled = flag;
		document.getElementById("btnDlgChordFlat").disabled = flag;
		document.getElementById("btnDlgChordNatural").disabled = flag;
		document.getElementById("btnDlgChordRemove").disabled = flagRemove;
	}, 100);
}

//---------------------------------------------------------------
//	和音音符のクリック
//---------------------------------------------------------------
function clkChkChord(elem, id) {
	event.preventDefault();			// シングルクリックでのデフォルトのチェック動作を防止
	elem.focus();					// フォーカスを移動

	chordSelectedId = id;
}

//---------------------------------------------------------------
//	和音音符のダブルクリック
//---------------------------------------------------------------
function dclkChkChord(elem, id) {
	event.preventDefault();			// ダブルクリックでのデフォルトのチェック動作を防止
	elem.checked = !elem.checked;	// チェック状態を切り替え

	chordSelectedId = id;

	if (elem.checked == false) {
		document.getElementById("chordImg_" + chordSelectedId).src = "./imgMSC/none10x20.png";
	}
}

//---------------------------------------------------------------
//	和音設定ダイアログの「シャープ・フラット・ナチュラル・解除」ボタン押下時
//---------------------------------------------------------------
function clkChordSharpFlat(kind) {
	let id = chordSelectedId;

	if (kind == "remove") {
		document.getElementById("chordImg_" + id).src = "./imgMSC/none10x20.png";
	} else if (kind == "sharp") {
		document.getElementById("chordImg_" + id).src = "./imgMSC/sharp10x20.png";
	} else if (kind == "flat") {
		document.getElementById("chordImg_" + id).src = "./imgMSC/flat10x20.png";
	} else if (kind == "natural") {
		document.getElementById("chordImg_" + id).src = "./imgMSC/natural10x20.png";
	}
	
	setTimeout( function() {
		chordSelectedId = id;
		document.getElementById("chordChk_" + chordSelectedId).focus();
	}, 0);
}

//---------------------------------------------------------------
//	和音設定ダイアログの「キャンセル」ボタン押下時
//---------------------------------------------------------------
function clkChordCancel() {
	clearInterval(chordTimerId);
	document.getElementById("divBackCover").style.display = "none";
	document.getElementById("divBackCover2").style.display = "none";
	document.getElementById("divChord").style.display = "none";
	setDisabledNoteRestButton("auto");
}

//---------------------------------------------------------------
//	和音設定ダイアログの「OK」ボタン押下時
//---------------------------------------------------------------
function clkChordOK() {
	clearInterval(chordTimerId);
	document.getElementById("divBackCover").style.display = "none";
	document.getElementById("divBackCover2").style.display = "none";
	document.getElementById("divChord").style.display = "none";
	setDisabledNoteRestButton("auto");

	let newPitchesStr = "";
	let cnt = 0;
	for (let i = 30; i >= 0; i--) {
		if (document.getElementById("chordChk_" + i).checked == true) {
			let acc = ""
			if (document.getElementById("chordImg_" + i).src.indexOf("sharp10x20.png") != -1) {
				acc = "^";
			} else if (document.getElementById("chordImg_" + i).src.indexOf("flat10x20.png") != -1) {
				acc = "_";
			} else if (document.getElementById("chordImg_" + i).src.indexOf("natural10x20.png") != -1) {
				acc = "=";
			}
			newPitchesStr += (acc + chordPitches[i]);
			cnt++
		}
	}
	
	if (cnt > 1) {
		newPitchesStr = "[" + newPitchesStr + "]";
	}

	let str = selectNoteStr.replace(chordOrgPitchesStr, newPitchesStr);

	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + str + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + str.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
	}, 0);
}

//=====================================================================
//	和音解除ボタン押下時（未使用）
//=====================================================================
function clkChordRemove() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//確認メッセージ
	document.getElementById("spanMessageYesNo").innerHTML = "１音のみを残し、和音を削除します。よいですか？";
	document.getElementById("dialogMessageYesNo").showModal();

	//「はい」の場合
	document.getElementById("btnMessageYesNoYes").onclick = function() {
		document.getElementById("dialogMessageYesNo").close();

		//現在の和音文字列の取得
		let orgPitchesStr = "";
		for (let i = 0; i < selectPitches.length; i++) {
			let pitch = selectPitches[i].name;
			orgPitchesStr += pitch;
		}
		if (selectPitches.length > 1) {
			orgPitchesStr = "[" + orgPitchesStr + "]";
		}
		
		//削除後の音符文字列（selectPitchesの最初の音階を採用）
		let newPitchesStr = selectPitches[0].name;
		let str = selectNoteStr.replace(orgPitchesStr, newPitchesStr);

		//挿入後の、currentAbcString を取得
		currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + str + currentAbcString.substring(selectNoteEndIndex);

		//-----------------------------------------------------------
		//	エディタと楽譜の表示更新
		//-----------------------------------------------------------
		//エディタにセット
		document.getElementById("abc-editor").value = currentAbcString;
		//レンダリング
		renderScore(currentAbcString);
		//各種データの取得
		getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + str.length);
		//エディタの選択領域変更
		setTimeout( function() {
			//エディタのスクロール位置の保存
			let scrollTop = document.getElementById(editorId).scrollTop;
	    	//エディタにフォーカス
	    	document.getElementById(editorId).focus();
	    	//エディタの選択領域（range）をセット
	    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
			//楽譜上の該当箇所を選択表示（赤色表示）
			abcEditor.updateSelection();
			//エディタのスクロール位置を戻す
			document.getElementById(editorId).scrollTop = scrollTop;
			//ボタン類の有効・無効設定
			setDisabledNoteRestButton("auto")
		}, 0);
	}

	//「いいえ」の場合
	document.getElementById("btnMessageYesNoNo").onclick = function() {
		document.getElementById("dialogMessageYesNo").close();
	}
}


//=====================================================================
//	装飾音符の設定ボタン押下時
//=====================================================================
var noteArtTimerId;
var	noteArtSelectedId_1 = -1;
var	noteArtSelectedId_2 = -1;

var noteArtPitchesTreble = [
													"c''",
	"b'",	"a'",	"g'",   "f'",   "e'",   "d'",   "c'",
	"b",    "a",    "g",    "f",    "e",    "d",    "c",
	"B",    "A",    "G",    "F",    "E",    "D",    "C",
	"B,",   "A,",   "G,",   "F,",   "E,",	"D,",	"C,",
	"B,,",	"A,,",
];

var noteArtPitchesBass = [
									"e",	"d",	"c",
	"B",    "A",    "G",    "F",    "E",    "D",    "C",
	"B,",   "A,",   "G,",   "F,",   "E,",   "D,",   "C,",
	"B,,",  "A,,",  "G,,",  "F,,",  "E,,",  "D,,",  "C,,",
	"B,,,", "A,,,", "G,,,",	"F,,,",	"E,,,",	"D,,,",	"C,,,",
];

var noteArtPitches = [];

var noteArtOrgPitchesStr;

var noteArtDuration = [];			//2 | 1 | 0.5
var noteArtAccidental = [];			//sharp | flat | natural
var noteArtAcciaccatura = false;	//slash

function clkNoteArt() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;
	
	setDisabledNoteRestButton("disabled");

	document.getElementById("divBackCover").style.display = "block";
	document.getElementById("divBackCover2").style.display = "block";
	document.getElementById("divNoteArt").style.left = "265px";
	document.getElementById("divNoteArt").style.top = "4px";
	document.getElementById("divNoteArt").style.display = "block";

	//背景の設定（treble or bass）
	if (v_isTrebleLine == true) {
		noteArtPitches = noteArtPitchesTreble;
		document.getElementById("divNoteArtBody").style.backgroundImage = 'url("./imgMSC/noteArt_treble2.png")';
	} else {
		noteArtPitches = noteArtPitchesBass;
		document.getElementById("divNoteArtBody").style.backgroundImage = 'url("./imgMSC/noteArt_bass2.png")';
	}

	//音符のチェック解除 と シャープ、フラット、ナチュラル等の消去
	for (let i = 0; i < 31; i++) {
		//元音符
		document.getElementById("noteArtChk_" + i).checked = false;
		document.getElementById("noteArtImg_" + i).src = "./imgMSC/none10x20.png";

		//装飾音符
		for (let j = 0; j < 4; j++) {
			document.getElementById("noteArtChk2_" + i + "_" + j).checked = false;
			document.getElementById("noteArtImg2_" + i + "_" + j).src = "./imgMSC/none10x20.png";
			noteArtDuration[j] = 0;
			noteArtAccidental[j] = "";			//sharp | flat | natural
			
		
			if (j > 0) {
				document.getElementById("noteArtChk2_" + i + "_" + j).style.visibility = "hidden";
			}
		}
	}
	noteArtAcciaccatura = false;	//slash
	document.getElementById("imgNoteArtPrview").src = "./imgMSC/noteArt_0-0-0-0.png";
	document.getElementById("imgNoteArtPrviewSlash").src = "./imgMSC/noteArt_0-0-0-0.png";


	//元音符の選択中の音符の設定（音符のチェック状態と臨時記号イメージsrc）
	noteArtOrgPitchesStr = "";
	for (let i = 0; i < selectPitches.length; i++) {
		let pitch = selectPitches[i].name;
		noteArtOrgPitchesStr += pitch;
		//シャープ、フラット、ナチュラル
		let acc = "none";
		if (pitch.indexOf("^") != -1) {
			acc = "sharp";
			pitch = pitch.substr(1);
		} if (pitch.indexOf("_") != -1) {
			acc = "flat";
			pitch = pitch.substr(1);
		} if (pitch.indexOf("=") != -1) {
			acc = "natural";
			pitch = pitch.substr(1);
		}
		let idx = noteArtPitches.indexOf(pitch);
		document.getElementById("noteArtChk_" + idx).checked = true;
		document.getElementById("noteArtImg_" + idx).src = "./imgMSC/" + acc + "10x20.png";
	}
	if (selectPitches.length > 1) {
		noteArtOrgPitchesStr = "{" + noteArtOrgPitchesStr + "}";
	}

	//現在の装飾音符

	//装飾音符の選択中の音符の設定（音符のチェック状態と臨時記号イメージsrc）
	if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.gracenotes) {
		
		let gracenotes = currentVisualArray[selectVisualDataIndex].absEl.abcelem.gracenotes;
		
		//装飾音符あり
		if (gracenotes.length == 4) {
			var ed = 4;
		} else {
			var ed = gracenotes.length + 1;
		}
		//音符の表示
		for (let j = 0; j < ed; j++) {
			for (let i = 0; i < 31; i++) {
				document.getElementById("noteArtChk2_" + i + "_" + j).style.visibility = "visible";
			}
		}
		//音符にチェック
		noteArtAcciaccatura = false;
		for (let j = 0; j < gracenotes.length; j++) {
			let name = gracenotes[gracenotes.length - 1 - j].name;
			name = name.replace("^", "");
			name = name.replace("=", "");
			name = name.replace("_", "");
			noteArtDuration[j] = gracenotes[j].duration*8;
			noteArtAccidental[j] = "";
			if (gracenotes[gracenotes.length - 1 - j].accidental) {
				noteArtAccidental[j] = gracenotes[gracenotes.length - 1 - j].accidental;
			}
			if (gracenotes[gracenotes.length - 1 - j].acciaccatura) {
				acciaccatura = gracenotes[gracenotes.length - 1 - j].acciaccatura;
			}
			
			let idx = noteArtPitches.indexOf(name);
			
			//音符選択
			document.getElementById("noteArtChk2_" + idx + "_" + j).checked = true;
			
			//臨時記号
			if (noteArtAccidental[j] == "sharp") {
				var acc = "sharp";
			} else if (noteArtAccidental[j] == "flat") {
				var acc = "flat";
			} else if (noteArtAccidental[j] == "natural") {
				var acc = "natural";
			} else {
				var acc = "none";
			}
			document.getElementById("noteArtImg2_" + idx + "_" + j).src = "./imgMSC/" + acc + "10x20.png";
			
			//音符種別（Duration）プレビュー
			dispNoteArtPreView();
			
		}
	}

	//ダイアログ内のコントロールの有効・無効評価用タイマー
	noteArtTimerId = setInterval( function() {
		
		//-----------------------------------------
		//音符種ボタンと臨時記号ボタンの有効・無効
		//-----------------------------------------
		let elem = document.getElementById("noteArtChk2_" + noteArtSelectedId_1 + "_" + noteArtSelectedId_2);
		//選択中の装飾音符にチェックがある場合
		if (document.activeElement ==  elem) {
			if (elem.checked == true) {
				//音符種
				document.getElementById("btnNoteArtNote1").disabled = false;
				if (noteArtSelectedId_2 == 0 && noteArtDuration[1] == 0 && noteArtDuration[2] ==0 && noteArtDuration[3] == 0) {
					document.getElementById("btnNoteArtNote0_5").disabled = true;
					document.getElementById("btnNoteArtNote0_25").disabled = true;
				} else {
					document.getElementById("btnNoteArtNote0_5").disabled = false;
					document.getElementById("btnNoteArtNote0_25").disabled = false;
				}
				//臨時記号
				document.getElementById("btnDlgNoteArtSharp").disabled = false;
				document.getElementById("btnDlgNoteArtFlat").disabled = false;
				document.getElementById("btnDlgNoteArtNatural").disabled = false;
				//臨時記号の設定あり
				if (noteArtAccidental[noteArtSelectedId_2] != "") {
					document.getElementById("btnDlgNoteArtRemove").disabled = false;
				} else {
					document.getElementById("btnDlgNoteArtRemove").disabled = true;
				}
			} else {
				//音符種
				document.getElementById("btnNoteArtNote1").disabled = true;
				document.getElementById("btnNoteArtNote0_5").disabled = true;
				document.getElementById("btnNoteArtNote0_25").disabled = true;
				//臨時記号
				document.getElementById("btnDlgNoteArtSharp").disabled = true;
				document.getElementById("btnDlgNoteArtFlat").disabled = true;
				document.getElementById("btnDlgNoteArtNatural").disabled = true;
				document.getElementById("btnDlgNoteArtRemove").disabled = true;
				
				noteArtSelectedId_1 = -1;
				noteArtSelectedId_2 = -1;
			}
		} else {
			//音符種
			document.getElementById("btnNoteArtNote1").disabled = true;
			document.getElementById("btnNoteArtNote0_5").disabled = true;
			document.getElementById("btnNoteArtNote0_25").disabled = true;
			//臨時記号
			document.getElementById("btnDlgNoteArtSharp").disabled = true;
			document.getElementById("btnDlgNoteArtFlat").disabled = true;
			document.getElementById("btnDlgNoteArtNatural").disabled = true;
			document.getElementById("btnDlgNoteArtRemove").disabled = true;
			
			noteArtSelectedId_1 = -1;
			noteArtSelectedId_2 = -1;
		}

		//-----------------------------------------
		//スラッシュの設定の有効・無効
		//-----------------------------------------
		if (noteArtAcciaccatura == true) {
			document.getElementById("btnNoteArtNoteSlash").disabled = true;
			document.getElementById("btnNoteArtNoteSlashDel").disabled = false;
		} else {
			document.getElementById("btnNoteArtNoteSlash").disabled = false;
			document.getElementById("btnNoteArtNoteSlashDel").disabled = true;
		}
	}, 100);
}

//---------------------------------------------------------------
//	装飾音符プレビューの表示
//---------------------------------------------------------------
function dispNoteArtPreView() {
	
	let fn = "./imgMSC/noteArt_";
	for (let j = 0; j < 4; j++) {
		if (j > 0) fn += "-";
		
		if (noteArtDuration[j] == 2) {
			fn += "8";
		} else if (noteArtDuration[j] == 1) {
			fn += "16";
		} else if (noteArtDuration[j] == 0.5) {
			fn += "32";
		} else {
			fn += "0";
		}
	}
	fn += ".png";
	document.getElementById("imgNoteArtPrview").src = fn;

	if (noteArtAcciaccatura == true) {
		document.getElementById("imgNoteArtPrviewSlash").src = "./imgMSC/noteArt_slash.png";
	} else {
		document.getElementById("imgNoteArtPrviewSlash").src = "./imgMSC/noteArt_0-0-0-0.png";
	}
}

//---------------------------------------------------------------
//	装飾音符の音符のクリック（何もしない）
//---------------------------------------------------------------
function clkChkNoteArt(elem, id) {
	event.preventDefault();			// シングルクリックでのデフォルトのチェック動作を防止
}

//---------------------------------------------------------------
//	装飾音符のクリック
//---------------------------------------------------------------
function clkChkNoteArt2(elem, id, id2) {
	event.preventDefault();			// シングルクリックでのデフォルトのチェック動作を防止
	elem.focus();					// フォーカスを移動

	noteArtSelectedId_1 = id;
	noteArtSelectedId_2 = id2;
}

//---------------------------------------------------------------
//	装飾音符のダブルクリック
//---------------------------------------------------------------
function dclkChkNoteArt2(elem, id, id2) {
	event.preventDefault();			// ダブルクリックでのデフォルトのチェック動作を防止

	let tmp = !elem.checked;

	for (let i = 0; i < 31; i++) {
		document.getElementById("noteArtChk2_" + i + "_" + id2).checked = false;
		document.getElementById("noteArtImg2_" + i + "_" + id2).src = "./imgMSC/none10x20.png";
		noteArtDuration[id2] = 0;
		noteArtAccidental[id2] = "";
	}

	elem.checked = tmp;		// チェック状態を切り替え

	if (elem.checked) {
		for (let i = 0; i < 31; i++) {
			noteArtDuration[id2] = 1;
			noteArtAccidental[id2] = "";

			if (id2 < 3) {
				if (noteArtDuration[id2+1] == 0) {
					document.getElementById("noteArtChk2_" + i + "_" + (id2+1)).style.visibility = "visible";
					noteArtDuration[id2+1] = 0;
					noteArtAccidental[id2+1] = "";
				}
			}
		}
	} else {
		for (let j = id2+1; j < 4; j++) {
			for (let i = 0; i < 31; i++) {
				document.getElementById("noteArtChk2_" + i + "_" + j).checked = false;
				document.getElementById("noteArtChk2_" + i + "_" + j).style.visibility = "hidden";
				document.getElementById("noteArtImg2_" + i + "_" + j).src = "./imgMSC/none10x20.png";
			}
			
			noteArtDuration[j] = 0;
			noteArtAccidental[j] = "";
		}
	}

	noteArtSelectedId_1 = id;
	noteArtSelectedId_2 = id2;
	
	dispNoteArtPreView();
}


//---------------------------------------------------------------
//	装飾音符設定ダイアログの「音調、スラッシュ」ボタン押下時
//		kind : 1=８分音符、0.5=16分音符、0.25=32分音符、0=スラッシュ、-1=スラッシュ解除
//---------------------------------------------------------------
function clkNoteArtNote(kind) {
	event.preventDefault();			// クリックによるフォーカス移動を防止

	//スラッシュの設定
	if (kind == 0) {
		noteArtAcciaccatura = true;
	
	//スラッシュの解除
	} else if (kind == -1) {
		noteArtAcciaccatura = false;
	
	//音符種の場合
	} else if (noteArtSelectedId_2 != -1) {
		if (noteArtSelectedId_2 == 0 && noteArtDuration[1] == 0 && noteArtDuration[2] ==0 && noteArtDuration[3] == 0) {
			noteArtDuration[noteArtSelectedId_2] = 1;
		} else {
			noteArtDuration[noteArtSelectedId_2] = kind*2;
		}
	}
	
	dispNoteArtPreView();
}

//---------------------------------------------------------------
//	装飾音符設定ダイアログの「シャープ・フラット・ナチュラル・解除」ボタン押下時
//		kind = sharp | flat | natural | remove
//---------------------------------------------------------------
function clkNoteArtSharpFlat(kind) {
	event.preventDefault();			// クリックによるフォーカス移動を防止

	if (noteArtSelectedId_1 != -1 && noteArtSelectedId_2 != -1) {
		if (kind == "sharp") {
			var acc = "sharp";
		} else if (kind == "flat") {
			var acc = "flat";
		} else if (kind == "natural") {
			var acc = "natural";
		} else if (kind == "remove") {
			var acc = "none";
		}
		
		document.getElementById("noteArtImg2_" + noteArtSelectedId_1 + "_" + noteArtSelectedId_2).src = "./imgMSC/" + acc + "10x20.png";
	}
}

//---------------------------------------------------------------
//	装飾音符設定ダイアログの「キャンセル」ボタン押下時
//---------------------------------------------------------------
function clkNoteArtCancel() {
	clearInterval(noteArtTimerId);
	document.getElementById("divBackCover").style.display = "none";
	document.getElementById("divBackCover2").style.display = "none";
	document.getElementById("divNoteArt").style.display = "none";
	setDisabledNoteRestButton("auto");
}

//---------------------------------------------------------------
//	装飾音符設定ダイアログの「OK」ボタン押下時
//---------------------------------------------------------------
function clkNoteArtOK() {
	clearInterval(noteArtTimerId);
	document.getElementById("divBackCover").style.display = "none";
	document.getElementById("divBackCover2").style.display = "none";
	document.getElementById("divNoteArt").style.display = "none";
	setDisabledNoteRestButton("auto");
	
	let newPitchesStr = "";

	//装飾音符なしの場合
	if (noteArtDuration[0] == 0 && noteArtDuration[1] == 0 && noteArtDuration[2] == 0 && noteArtDuration[3] == 0) {
		//

	//１音の場合
	} else if (noteArtDuration[0] != 0 && noteArtDuration[1] == 0 && noteArtDuration[2] == 0 && noteArtDuration[3] == 0) {
		let pitche = "";
		if (noteArtAcciaccatura == true) {
			pitche += "/";
		}
		for (let i = 0; i < 31; i++) {
			if (document.getElementById("noteArtChk2_" + i + "_0").checked == true) {
				if (noteArtAccidental[0] == "sharp") {
					pitche += "^";
				} else if (noteArtAccidental[0] == "flat") {
					pitche += "_";
				} else if (noteArtAccidental[0] == "natural") {
					pitche += "=";
				}
				pitche += noteArtPitches[i];
				break;
			}
		
		}
		if (pitche != "") {
			newPitchesStr = "{" + pitche + "}";
		}

	//２音以上の場合
	} else {
		let pitche = "";
		if (noteArtAcciaccatura == true) {
			pitche += "/";
		}
		for (let j = 0; j < 4; j++) {
			if (noteArtDuration[j] != 0) {
				for (let i = 0; i < 31; i++) {
					if (document.getElementById("noteArtChk2_" + i + "_" + j).checked == true) {
						if (noteArtAccidental[0] == "sharp") {
							pitche += "^";
						} else if (noteArtAccidental[0] == "flat") {
							pitche += "_";
						} else if (noteArtAccidental[0] == "natural") {
							pitche += "=";
						}
						pitche += noteArtPitches[i];
						
						if (noteArtDuration[j] == 2) {
							pitche += "2";
						} else if (noteArtDuration[j] == 1) {
							//
						} else if (noteArtDuration[j] == 0.5) {
							pitche += "/2";
						}
						break;
					}
				
				}
			}
		}
		if (pitche != "") {
			newPitchesStr = "{" + pitche + "}";
		}
	}

	//現在の装飾音符を削除（{}で囲まれた部分を削除）
	let str = selectNoteStr.replace(/\{.*?\}/g, "");
	str = str.replace(noteArtOrgPitchesStr, newPitchesStr + noteArtOrgPitchesStr);

	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + str + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + str.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
	}, 0);
}


//=====================================================================
//	８分音符、16分音符の分離・結合
//=====================================================================
function clkNoteSeparateJoin(job) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	if (job == "separate") {
		//選択abcStringの末尾に" "を付加
		var str = selectNoteStr + " ";
	} else {
		//選択abcStringの末尾の" "を除去
		var str = selectNoteStr.trimEnd();
	}

	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + str + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + str.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
	}, 0);
}

//=====================================================================
//	３連符の設定、解除
//=====================================================================
function clkTriplets(job) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//-------------------------------------------------------------
	//	設定
	//-------------------------------------------------------------
	if (job == "set") {
		let tmp = selectPitchesStr + decimalToFraction(selectDuration / 2);

		var selLen = (" (3" + tmp).length;
		tmp = " (3" + tmp + tmp + tmp + " ";

		var str = selectNoteStr.replace(selectPitchesStr + decimalToFraction(selectDuration), tmp);

	//-------------------------------------------------------------
	//	解除
	//-------------------------------------------------------------
	} else {
		//0=３連符音符ではない、1-3=n番目の音符（1は先頭、3は右端）
		let no = getCurrentTripletsNumber();		
		
		if (no > 0) {
			let pos = -1;
			//３連符の最初の音符
			if (no == 1) {
				pos = selectVisualDataIndex;
			//３連符の２番目の音符
			} else if (no == 2) {
				pos = selectVisualDataIndex-1;
			//３連符の３番目の音符
			} else if (no == 3) {
				pos = selectVisualDataIndex-2;
			}

			if (pos == -1) return;
			
			let st1 = currentVisualArray[pos].absEl.abcelem.startChar;
			let ed1 = currentVisualArray[pos].absEl.abcelem.endChar;
			let ed3 = currentVisualArray[pos+2].absEl.abcelem.endChar;

			//currentVisualArray[pos]の、音符の "(3" を削除、長さを２倍にする
			var str = currentAbcString.substring(st1, ed1);
			//"(3" を削除
			str = str.replace("(3", "");
			//長さを２倍にする
			let tmp = selectPitchesStr + decimalToFraction(selectDuration * 2);
			str = str.replace(selectPitchesStr + decimalToFraction(selectDuration), tmp);
			//currentVisualArray[pos+1]とcurrentVisualArray[pos+2] の音符を削除
			selectNoteStartIndex = st1;
			selectNoteEndIndex = ed3;
		}
	}
	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + str + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//この小節の歌詞文字列を生成（指定行・小節の歌詞文字列生成とabcStringへの反映）
	setLyricStrByBar();
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + selLen);  //str.length);

//if (job != "set") return;

	//エディタの選択領域変更
	setTimeout( function() {
		stopChange++;
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
		stopChange--;

	}, 0);
}

//=====================================================================
//	５連符の設定、解除
//=====================================================================
function clkQuintuplet(job) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//-------------------------------------------------------------
	//	設定
	//-------------------------------------------------------------
	if (job == "set") {
		let tmp = selectPitchesStr + decimalToFraction(selectDuration / 4);

		var selLen = (" (5:4" + tmp).length;
		tmp = " (5:4" + tmp + tmp + tmp + tmp + tmp + " ";

		var str = selectNoteStr.replace(selectPitchesStr + decimalToFraction(selectDuration), tmp);

	//-------------------------------------------------------------
	//	解除
	//-------------------------------------------------------------
	} else {
		//0=５連符音符ではない、1-5=n番目の音符（1は先頭、5は右端）
		let no = getCurrentQuintupletNumber();		
		
		if (no > 0) {
			let pos = -1;
			//５連符の最初の音符
			if (no == 1) {
				pos = selectVisualDataIndex;
			//５連符の２番目の音符
			} else if (no == 2) {
				pos = selectVisualDataIndex-1;
			//５連符の３番目の音符
			} else if (no == 3) {
				pos = selectVisualDataIndex-2;
			//５連符の４番目の音符
			} else if (no == 4) {
				pos = selectVisualDataIndex-3;
			//５連符の５番目の音符
			} else if (no == 5) {
				pos = selectVisualDataIndex-4;
			}

			if (pos == -1) return;
			
			let st1 = currentVisualArray[pos].absEl.abcelem.startChar;
			let ed1 = currentVisualArray[pos].absEl.abcelem.endChar;
			let ed5 = currentVisualArray[pos+4].absEl.abcelem.endChar;

			//currentVisualArray[pos]の、音符の "(5" を削除、長さを４倍にする
			var str = currentAbcString.substring(st1, ed1);
			//"(5" を削除
			str = str.replace("(5:4", "");
			//長さを４倍にする
			let tmp = selectPitchesStr + decimalToFraction(selectDuration * 4);
			str = str.replace(selectPitchesStr + decimalToFraction(selectDuration), tmp);
			//currentVisualArray[pos+1]とcurrentVisualArray[pos+2] の音符を削除
			selectNoteStartIndex = st1;
			selectNoteEndIndex = ed5;
		}
	}
	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + str + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//この小節の歌詞文字列を生成（指定行・小節の歌詞文字列生成とabcStringへの反映）
	setLyricStrByBar();
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + selLen);  //str.length);

//if (job != "set") return;

	//エディタの選択領域変更
	setTimeout( function() {
		stopChange++;
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
		stopChange--;

	}, 0);
}

//##########################################################################
//##########################################################################
//	メニュー処理（下段）
//		強弱記号の変更						chgDynamics(elem);
//		反復記号の変更						chgRepeatSigns(elem);
//		Undo Redo
//			Undo Redo ボタンの有効・無効化		updateUndoRedoButtons();
//			clear UNDO							clearUndo();
//			push UNDO							pushUndo();
//			pop UNDO							popUndo();
//			pop REDO							popRedo();
//		undoボタン押下						undoButton();
//		redoボタン押下						redoButton();
//		newボタン押下						newButton();
//		openボタン押下						openButton();
//		saveボタン押下						saveButton();
//		楽譜のPNGイメージの取得
//			楽譜をPNGイメージとして取得			getPngImage();
//		printボタン押下						printButton();
//		playボタン押下						playButton();
//		playerの閉じるボタン				clkClosePlayer();
//		演奏用
//			プレーヤーの初期化					loadSound();
//		abcエディタチェックボックス			clkAbcEditor(elem);
//##########################################################################

//=====================================================================
//	強弱記号の変更
//=====================================================================
//------------------------------------------------------
//	selectの表示用フォントの動的変更
//------------------------------------------------------
function setFontDynamics(elem, value) {
	if (value == "none") {
		elem.style.fontFamily = "Arial, sans-serif";
	} else {
		elem.style.fontFamily = "BravuraText";
	}
}
//------------------------------------------------------
var tmpSymbolIdx1 = -1;
var tmpSymbolIdx2 = -1;
function chgDynamics(elem) {
	//------------------------------------------
	//	arrIdxに、強弱記号（＜＞）を設定
	//------------------------------------------
	function setSymbol(arrIdx, val) {
		let selectDecoration0 = currentVisualArray[arrIdx].absEl.abcelem.decoration;
		if (!selectDecoration0) {
			selectDecoration0 = [];
		}

		//現在の設定を取得
		let orgDecorationStr0 = "";
		for (let i = 0; i < selectDecoration0.length; i++) {
			if (selectDecoration0[i] == "staccato") {
				orgDecorationStr0 += ".";
			} else {
				orgDecorationStr0 += "!" + selectDecoration0[i] + "!";
			}
		}
		//新規の設定を取得
		let newDecorationStr0 = "";
		for (let i = 0; i < selectDecoration0.length; i++) {
			if (DynamicsArr.indexOf(selectDecoration0[i]) == -1) {
				newDecorationStr0 += "!" + selectDecoration0[i] + "!";
			}
		}

		let st = currentVisualArray[arrIdx].absEl.abcelem.startChar;
		let ed = currentVisualArray[arrIdx].absEl.abcelem.endChar;

		//設定の場合
		if (val != "" && val != "none") {
			newDecorationStr0 += "!" + val + "!";
		
		//削除の場合
		} else {
			//＜＞の始点の削除の場合は、直後の終点を削除（仮設定の場合は、仮設定フラグをfalseに）
			if (orgDecorationStr0.indexOf("crescendo(") != -1 && newDecorationStr0.indexOf("crescendo(") == -1) {
				let pos = currentAbcString.indexOf("crescendo)", ed);
				if (pos != -1) {
					currentAbcString = currentAbcString.slice(0, pos) + "R" + currentAbcString.slice(pos + 1);;
				}
			} else if (orgDecorationStr0.indexOf("diminuendo(") != -1 && newDecorationStr0.indexOf("diminuendo(") == -1) {
				let pos = currentAbcString.indexOf("diminuendo)", ed);
				if (pos != -1) {
					currentAbcString = currentAbcString.slice(0, pos) + "R" + currentAbcString.slice(pos + 1);;
				}
				
			//＜＞の終点の削除の場合は、直前の始点も削除（仮設定の場合は、仮設定フラグをfalseに）
			} else if (orgDecorationStr0.indexOf("crescendo)") != -1 && newDecorationStr0.indexOf("crescendo)") == -1) {
				let pos = currentAbcString.lastIndexOf("crescendo(", st);
				if (pos != -1) {
					currentAbcString = currentAbcString.slice(0, pos) + "R" + currentAbcString.slice(pos + 1);;
				}
			} else if (orgDecorationStr0.indexOf("diminuendo)") != -1 && newDecorationStr0.indexOf("diminuendo)") == -1) {
				let pos = currentAbcString.lastIndexOf("diminuendo(", st);
				if (pos != -1) {
					currentAbcString = currentAbcString.slice(0, pos) + "R" + currentAbcString.slice(pos + 1);;
				}
			}
		}

		//現在の設定と新規の設定を入れ替える
		if (orgDecorationStr0 == "") {
			var newStr = newDecorationStr0 + currentAbcString.substring(st, ed);
		} else {
			var newStr = currentAbcString.substring(st, ed).replace(orgDecorationStr0, newDecorationStr0);
		}
	
		//挿入後の、currentAbcString を取得
		let strTop = currentAbcString.substring(0, st);
		strTop = strTop.replace("!Rrescendo(!", "");
		strTop = strTop.replace("!Riminuendo(!", "");
		
		let strBtm = currentAbcString.substring(ed);
		strBtm = strBtm.replace("!Rrescendo)!", "");
		strBtm = strBtm.replace("!Riminuendo)!", "");
		
		currentAbcString = strTop + newStr + strBtm;
		
		return newStr;
	}
	//------------------------------------------

	//------------------------------------------
	//	arrIdxの直前の強弱記号（＜＞）を削除
	//------------------------------------------
	function delSymbol(arrIdx, val) {
		let st = currentVisualArray[arrIdx].absEl.abcelem.startChar;
		let ed = currentVisualArray[arrIdx].absEl.abcelem.endChar;
		let newStr = currentAbcString.substring(st, ed);
		if (newStr.indexOf(val) != -1) {
			newStr = newStr.replace(val, "");
			currentAbcString = currentAbcString.substring(0, st) + newStr + currentAbcString.substring(ed);
		}
		return newStr;
	}
	//------------------------------------------


	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";

	//selectの表示用フォントの動的変更
	setFontDynamics(elem, elem.value)

	let kind = elem.value;

	//----------------------------------------
	//下段の設定、現在が上段の場合は、下段にも設定）
	//----------------------------------------
	if (currentClefSymbol != "treble" && currentClefSymbol != "bass" && isUpperLine() == true) {
		//---------------------------------------------------------------------
		//下段への設定（lineとx座標が同一の音符・休符のindex取得）
		//---------------------------------------------------------------------
		//選択中の小節線のx座標
		let xPos = currentVisualArray[selectVisualDataIndex].absEl.x;
		var idx = -1;
		//同一x座標の小節線の検索
		for (let i = selectVisualDataIndex+1; i < currentVisualArray.length; i++) {
			if (currentVisualArray[i].absEl.counters) {
				if (currentVisualArray[i].absEl.counters.line != currentLineNo) break;
			}
			if ((currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") && currentVisualArray[i].absEl.x == xPos) {
				idx = i;
				break;
			}
		}
		
		//----------------------------------------------------------
		//＜、＞の始点設定の場合は、
		//	下段に同一Ｘ座標の音符・休符がある場合は、
		//		①下段の次の音符・休符に終了記号（!crescendo)!、!diminuendo)!）を設定し、
		//		②下段の選択音符・休符に開始記号（!crescendo(!、!diminuendo(!）を設定する
		//----------------------------------------------------------
		if (kind == "crescendo(" || kind == "diminuendo(") {
			if (tmpSymbolIdx2 == -1) {
				//下段に同一Ｘ座標の音符・休符がある場合
				if (idx != -1) {
					setSymbol(idx+1, kind.replace("(", ")"));		//①
					setSymbol(idx  , kind);							//②
					tmpSymbolIdx2 = idx;
				//下段に同一Ｘ座標の音符・休符がない場合（何もしない）
				} else {
					//hasStartSymbol2 = false;
				}
			}
		
		//----------------------------------------------------------
		//＜、＞の終点設定の場合で、下段に仮開始記号がある（hasStartSymbol2 == true）場合は、
		//	下段に同一Ｘ座標の音符・休符がある場合は、
		//		①選択位置idxに　　終了記号（!crescendo)!、!diminuendo)!）を設定し、
		//		②tmpSymbolIdx2+1の終了記号（!crescendo)!、!diminuendo)!）を削除
		//	下段に同一Ｘ座標の音符・休符がない場合は、
		//		④tmpSymbolIdx2+1の終了記号（!crescendo)!、!diminuendo)!）を削除し、
		//		⑤tmpSymbolIdx2  の開始記号（!crescendo(!、!diminuendo(!）を削除する。
		//----------------------------------------------------------
		} else if (kind == "crescendo)" || kind == "diminuendo)") {
			if (tmpSymbolIdx2 != -1) {
				//下段に同一Ｘ座標の音符・休符がある場合
				if (idx != -1) {
					setSymbol(idx, kind);								//①
					if (idx != tmpSymbolIdx2+1) {
						delSymbol(tmpSymbolIdx2+1, "!" + kind + "!");	//②
					}
					tmpSymbolIdx2 = -1;

				//下段に同一Ｘ座標の音符・休符がない場合
				} else {
					delSymbol(tmpSymbolIdx2+1, "!" + kind + "!");					//④
					delSymbol(tmpSymbolIdx2, "!" + kind.replace(")", "(") + "!");	//⑤
					tmpSymbolIdx2 = -1;
				}
			}
		
		//----------------------------------------------------------
		//＜、＞以外の場合は、
		//	下段に同一Ｘ座標の音符・休符がある場合、下段にも強弱記号を設定
		//----------------------------------------------------------
		} else {
			//---------------------------------------------------------------------
			//同一X座標の下段の音符・休符のindex（ここに、強弱記号を入れる）
			//---------------------------------------------------------------------
			if (idx != -1) {
				//console.log("下段の設定（＜、＞以外の場合は、現在が上段の場合は、下段にも設定）");
				if (kind != "" && kind != "none") {
					setSymbol(idx, kind);
				}
			}
		}
	}
	
	//--------------------------------------------------------
	//	選択中の音符・休符への設定
	//--------------------------------------------------------
	var idx = selectVisualDataIndex;

	//----------------------------------------------------------
	//＜、＞の始点設定の場合は、
	//	①次の音符・休符に終了記号（!crescendo)!、!diminuendo)!）を設定し、
	//	②選択音符・休符に開始記号（!crescendo(!、!diminuendo(!）を設定する
	//----------------------------------------------------------
	if (kind == "crescendo(" || kind == "diminuendo(") {
		if (tmpSymbolIdx1 == -1) {
			setSymbol(idx+1, kind.replace("(", ")"));		//①
			var newstr = setSymbol(idx, kind);				//②
			tmpSymbolIdx1 = idx;
		}
	
	//----------------------------------------------------------
	//＜、＞の終点設定の場合で、仮開始記号がある（hasStartSymbol1 == true）場合は、
	//	①選択位置idxに　  終了記号（!crescendo)!、!diminuendo)!）を設定し、
	//	②tmpSymbolIdx1+1の終了記号（!crescendo)!、!diminuendo)!）を削除
	//----------------------------------------------------------
	} else if (kind == "crescendo)" || kind == "diminuendo)") {
		if (tmpSymbolIdx1 != -1) {
			var newstr = setSymbol(idx, kind);						//①
			if (idx != tmpSymbolIdx1+1) {
				delSymbol(tmpSymbolIdx1+1, "!" + kind + "!");		//②
			}
			tmpSymbolIdx1 = -1;
		}
	
	//----------------------------------------------------------
	//＜、＞以外の場合は、
	//	下段に同一Ｘ座標の音符・休符がある場合、下段にも強弱記号を設定
	//----------------------------------------------------------
	} else {
		//console.log("下段の設定（＜、＞以外の場合は、現在が上段の場合は、下段にも設定）");
		var newstr = setSymbol(idx, kind);
		
		tmpSymbolIdx1 = -1;
		tmpSymbolIdx2 = -1;
	}
	
	if (!newstr) return;

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + newstr.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")
		
		elem.value = kind;
		setFontDynamics(elem, elem.value);
	}, 0);
}

//=====================================================================
//	反復記号の変更
//=====================================================================
//------------------------------------------------------
//	selectの表示用フォントの動的変更
//------------------------------------------------------
function setFontRepeatSigns(elem, value) {
	if (value == "none") {
		elem.style.top = "4px";
		elem.style.fontFamily = "Arial, sans-serif";
		elem.style.fontWeight = "400";
		elem.style.fontStyle = "normal";
		elem.style.fontSize = "13px";
	} else if (value == "D.C." || value == "fine" || value == "D.S.") {
		elem.style.top = "4px";
		elem.style.fontFamily = "'Crimson Text', serif";
		elem.style.fontWeight = "700";
		elem.style.fontStyle = "italic";
		elem.style.fontSize = "15px";
	} else if (value == "segno") {
		elem.style.top = "4px";
		elem.style.fontFamily = "BravuraText";
		elem.style.fontWeight = "400";
		elem.style.fontStyle = "normal";
		elem.style.fontSize = "18px";
	} else if (value == "coda") {
		elem.style.top = "4px";
		elem.style.fontFamily = "BravuraText";
		elem.style.fontWeight = "400";
		elem.style.fontStyle = "normal";
		elem.style.fontSize = "16px";
	} else if (value.substr(0, 1) == "[" || value == "]") {
		elem.style.top = "4px";
		elem.style.fontFamily = "Arial, sans-serif";
		elem.style.fontWeight = "400";
		elem.style.fontStyle = "normal";
		elem.style.fontSize = "13px";
	}
}
//------------------------------------------------------
function chgRepeatSigns(elem) {

	//--------------------------------------------
	//指定された位置（st）からn番目の|とn+1番目の|の間の文字列を取得
	//--------------------------------------------
	function getSubstringBetweenPipes(str, st, n) {
	    // stの位置からの部分文字列を取得
	    let subStr = str.slice(st);

	    // n番目の'|'の位置を取得
	    let startIdx = -1;
	    let endIdx = -1;
	    let count = 0;
	    
	    for (let i = 0; i < subStr.length; i++) {
	        if (subStr[i] === '|') {
	            if (count === n) {
	                startIdx = i + 1;  // n番目の'|'の次の位置
	            } else if (count === n + 1) {
	                endIdx = i;  // n+1番目の'|'の位置
	                break;
	            }
	            count++;
	        }
	    }
	    
	    // n番目の'|'が見つからないか、n+1番目の'|'が見つからなかった場合の処理
	    if (startIdx === -1 || endIdx === -1) {
	        return { start: -1, end: -1 };  // 条件に合う部分が見つからなかった場合
	    }

	    // 指定範囲の文字列を返す
	    return { start: startIdx+st, end: endIdx+st };
	}
	//--------------------------------------------

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//selectの表示用フォントの動的変更
	setFontRepeatSigns(elem, elem.value);
	
	let kind = elem.value;



	//２段の場合、選択とは、別の段の反復記号をを削除（２段目では繰り返し設定はできない）
	if (currentClefSymbol != "treble" && currentClefSymbol != "bass") {

		//現在の行番号と段と小節番号
		if (currentVisualArray[selectVisualDataIndex-1].absEl.type != "bar") {
			var line0 = currentVisualArray[selectVisualDataIndex-1].absEl.counters.line;
			var voice0 = currentVisualArray[selectVisualDataIndex-1].absEl.counters.voice;
			var measure0 = currentVisualArray[selectVisualDataIndex-1].absEl.counters.measure;
		} else {
			var line0 = currentVisualArray[selectVisualDataIndex+1].absEl.counters.line;
			var voice0 = currentVisualArray[selectVisualDataIndex+1].absEl.counters.voice;
			var measure0 = currentVisualArray[selectVisualDataIndex+1].absEl.counters.measure;
		}

		var st = -1;
		var ed = -1;

		//現在の行番号と小節番号と同一のvoice==1の小節の先頭と終端を取得
		for (let i = selectVisualDataIndex; i < currentVisualArray.length; i++) {
			
			if (currentVisualArray[i].absEl.type == "bar") {
			
				//行番号と段と小節番号
				var tmpEd = currentVisualArray[i].absEl.abcelem.endChar;

				if (currentVisualArray[i-1].absEl.type != "bar") {
					var line1 = currentVisualArray[i-1].absEl.counters.line;
					var voice1 = currentVisualArray[i-1].absEl.counters.voice;
					var measure1 = currentVisualArray[i-1].absEl.counters.measure;
				} else {
					var line1 = currentVisualArray[i+1].absEl.counters.line;
					var voice1 = currentVisualArray[i+1].absEl.counters.voice;
					var measure1 = currentVisualArray[i+1].absEl.counters.measure;
				}
				
				//複旋律には小節線（bar）はないので、voice1 != 0でよい
				if (line0 == line1 && measure0 == measure1 && voice1 != 0) {
					st = currentVisualArray[i].absEl.abcelem.startChar;
					ed = currentVisualArray[i].absEl.abcelem.endChar;
					break;
				}
			}
		}
		
		//反復記号を削除
		let orgStr = currentAbcString.substring(st, ed);
		for (i = 0; i < RepeatSignsArr1.length; i++) {
			orgStr = orgStr.replace("!" + RepeatSignsArr1[i] + "!", "");
		}
		for (i = RepeatSignsArr2.length-1; i >= 0; i--) {
			orgStr = orgStr.replace(RepeatSignsArr2[i], "");
		}

		//新たな反復記号を付加
		let newstr;
		if (elem.value == "none") {
			newstr = orgStr;
		} else if (RepeatSignsArr1.indexOf(elem.value) != -1) {
			newstr = "!" + elem.value + "!" + orgStr;
		} else {
			newstr = orgStr + elem.value;
		}

		//挿入後の、currentAbcString を取得
		currentAbcString = currentAbcString.substring(0, st) + newstr + currentAbcString.substring(ed);
	}


	//現在の反復記号を削除
	let orgStr = selectNoteStr;
	for (i = 0; i < RepeatSignsArr1.length; i++) {
		orgStr = orgStr.replace("!" + RepeatSignsArr1[i] + "!", "");
	}
	for (i = RepeatSignsArr2.length-1; i >= 0; i--) {
		orgStr = orgStr.replace(RepeatSignsArr2[i], "");
	}
	
	
	//新たな反復記号を付加
	let newstr;
	if (elem.value == "none") {
		newstr = orgStr;
	} else if (RepeatSignsArr1.indexOf(elem.value) != -1) {
		newstr = "!" + elem.value + "!" + orgStr;
	} else {
		newstr = orgStr + elem.value;
	}

	//挿入後の、currentAbcString を取得
	currentAbcString = currentAbcString.substring(0, selectNoteStartIndex) + newstr + currentAbcString.substring(selectNoteEndIndex);

	//-----------------------------------------------------------
	//	エディタと楽譜の表示更新
	//-----------------------------------------------------------
	//エディタにセット
	document.getElementById("abc-editor").value = currentAbcString;
	//レンダリング
	renderScore(currentAbcString);
	//各種データの取得
	getDataFromRange(selectNoteStartIndex, selectNoteStartIndex + newstr.length);
	//エディタの選択領域変更
	setTimeout( function() {
		//エディタのスクロール位置の保存
		let scrollTop = document.getElementById(editorId).scrollTop;
    	//エディタにフォーカス
    	document.getElementById(editorId).focus();
    	//エディタの選択領域（range）をセット
    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
		//楽譜上の該当箇所を選択表示（赤色表示）
		abcEditor.updateSelection();
		//エディタのスクロール位置を戻す
		document.getElementById(editorId).scrollTop = scrollTop;
		//ボタン類の有効・無効設定
		setDisabledNoteRestButton("auto")

		elem.value = kind;
		setFontRepeatSigns(elem, elem.value);
	}, 0);
}

//=====================================================================
//	Undo Redo
//=====================================================================
let undoStack = [];
let redoStack = [];
let prevAbcString = "";
let stopUndoRedo = false;

//------------------------------------------------------------------
//	2つの文字列を先頭から比較し、
//	最初の相違箇所を見つけるとともに、それまでの一致する文字列を取得
//------------------------------------------------------------------
function findFirstDifferenceAndCommonString(str1, str2) {
	const minLength = Math.min(str1.length, str2.length);
	let index = 0;

	// 先頭から順に比較し、相違点を探す
	while (index < minLength && str1[index] === str2[index]) {
		index++;
	}

	// 相違点が見つかったインデックスとそれまでの一致文字列を返す
	const commonString = str1.slice(0, index);
	return {
		firstDifferenceIndex: (index < minLength || str1.length !== str2.length) ? index : -1,
		commonString: commonString
	};
}

//------------------------------------------------------------------
//	2つの文字列を末尾から比較し、
//	最初の相違箇所を見つけるとともに、一致する末尾部分の文字列を取得
//------------------------------------------------------------------
function findLastDifferenceAndCommonString(str1, str2) {
	const len1 = str1.length;
	const len2 = str2.length;
	const minLength = Math.min(len1, len2);
	let index = 0;

	// 末尾から順に比較し、相違点を探す
	while (index < minLength && str1[len1 - 1 - index] === str2[len2 - 1 - index]) {
		index++;
	}

	// 一致する末尾部分を取得
	const commonString = str1.slice(len1 - index);

	return {
		lastDifferenceIndex: (index < minLength || len1 !== len2) ? Math.max(len1, len2) - 1 - index : -1,
		commonString: commonString
	};
}

//------------------------------------------------------------------
//	変更箇所の取得
//		return [ st, ed, olsStr, newStr	]:
//			st : newStrの変更箇所の先頭index
//			ed : newStrの変更箇所の末尾index（末尾の次に文字のindex）
//			oldStr : 変更箇所の変更前の文字列
//			newStr : 変更箇所の変更後の文字列
//------------------------------------------------------------------
function getStringChangeIndexAndString(str1, str2) {

	let dataTop = findFirstDifferenceAndCommonString(str1, str2);
	
	let str3 = str1.substring(dataTop.firstDifferenceIndex);
	let str4 = str2.substring(dataTop.firstDifferenceIndex);
	
//	console.log("str3", str3);
//	console.log("str4", str4);
	
	let dataBtm = findLastDifferenceAndCommonString(str3, str4);

	return {
		st: dataTop.firstDifferenceIndex,
		ed: str2.length - dataBtm.commonString.length,
		oldStr: str1.substring(dataTop.firstDifferenceIndex, str1.length - dataBtm.commonString.length),
		//newStr: str2.substring(dataTop.firstDifferenceIndex, str2.length - dataBtm.commonString.length),
	};
}

//------------------------------------------------------------------
//	Undo Redo ボタンの有効・無効化
//------------------------------------------------------------------
function updateUndoRedoButtons() {
	document.getElementById("btnUndo").disabled = undoStack.length === 0;
	document.getElementById("btnRedo").disabled = redoStack.length === 0;
}
//------------------------------------------------------------------
//	clear UNDO
//------------------------------------------------------------------
function clearUndo() {
	undoStack = [];
	redoStack = [];
	
	prevAbcString = currentAbcString;

	// ボタンの有効/無効を更新
	updateUndoRedoButtons();
}
//------------------------------------------------------------------
//	push UNDO
//------------------------------------------------------------------
function pushUndo() {

	if (stopUndoRedo == true) {
		return;
	}

	if (currentAbcString != prevAbcString && prevAbcString != "") {

		//差分を取得
		let diff = getStringChangeIndexAndString(prevAbcString, currentAbcString);

	// デバッグ用ログ
//	console.log("Push Undo: ");
//	console.log("prevAbcString: ", prevAbcString);
//	console.log("currentAbcString: ", currentAbcString);
//	console.log("diff: ", diff);
//	console.log("diffStr: ", currentAbcString.substring(diff.st, diff.ed));

		//差分をUndoスタックに保存
		undoStack.push(diff);

		//新しい操作の時、Redoスタックをリセット
		redoStack = [];             

		// ボタンの有効/無効を更新
		updateUndoRedoButtons();
	}

	prevAbcString = currentAbcString;
}
//------------------------------------------------------------------
//	pop UNDO
//------------------------------------------------------------------
function popUndo() {

	if (undoStack.length === 0) return "";

	let diff = undoStack.pop();

	let newStr = currentAbcString.substring(0, diff.st) + diff.oldStr + currentAbcString.substring(diff.ed);

	//Redo用の差分を取得
	let diff2 = getStringChangeIndexAndString(currentAbcString, newStr);

	//差分をRedoスタックに保存
	redoStack.push(diff2);

	//ボタンの有効/無効を更新
	updateUndoRedoButtons();

	// prevAbcString を更新
	prevAbcString = newStr;

	return newStr;
}
//------------------------------------------------------------------
//	pop REDO
//------------------------------------------------------------------
function popRedo() {

	if (redoStack.length === 0) return "";

	let diff = redoStack.pop();

	let newStr = currentAbcString.substring(0, diff.st) + diff.oldStr + currentAbcString.substring(diff.ed);

	//Undo用の差分を取得
	let diff2 = getStringChangeIndexAndString(currentAbcString, newStr);

	//差分をUndoスタックに保存
	undoStack.push(diff2);

	//ボタンの有効/無効を更新
	updateUndoRedoButtons();

	// prevAbcString を更新
	prevAbcString = newStr;

	return newStr;
}

//=====================================================================
//	undoボタン押下時
//=====================================================================
function undoButton() {

	//document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	let data = popUndo();
	
	if (data != "") {
        currentAbcString = data;
        
        stopUndoRedo = true;
		//-----------------------------------------------------------
		//	エディタと楽譜の表示更新
		//-----------------------------------------------------------
		//エディタにセット
		document.getElementById("abc-editor").value = currentAbcString;
		//レンダリング
		renderScore(currentAbcString);
		//
		MSC_resize();
        //非選択状態にする
        abcjsBodyMouseDown(true);

        stopUndoRedo = false;
	}
}

//=====================================================================
//	redoボタン押下時
//=====================================================================
function redoButton() {

	//document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	let data = popRedo();
	
	if (data != "") {
        currentAbcString = data;
        
        stopUndoRedo = true;
		//-----------------------------------------------------------
		//	エディタと楽譜の表示更新
		//-----------------------------------------------------------
		//エディタにセット
		document.getElementById("abc-editor").value = currentAbcString;
		//レンダリング
		renderScore(currentAbcString);
		//
		MSC_resize();
        //非選択状態にする
        abcjsBodyMouseDown(true);

        stopUndoRedo = false;
	}
}

//=====================================================================
//	newボタン押下時
//=====================================================================
function newButton() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//確認メッセージ
	document.getElementById("spanMessageYesNo").innerHTML = MAC_convLang("楽譜データを初期化します。よいですか？");
	document.getElementById("dialogMessageYesNo").showModal();

	//「はい」の場合
	document.getElementById("btnMessageYesNoYes").onclick = function() {

		stopChange++;

		document.getElementById("dialogMessageYesNo").close();
		
		stopRender = true;

		//音部記号
		currentClefSymbol = "treble";
		selectClefSymbol.setValue("treble");
		
		//拍子記号
		currentTimeSymbol = "C";
		countByBar = 8;
		selectTimingSymbol.setValue("C,8");
		
		//調号
		currentKeySignature = "C";
		selectKeySignature.setValue("C");

		//速度記号
		currentTempoMarkings = "";
		currentTempoMarkings2 = 0;
		currentTempoMarkings2Base = "1/4";
		document.getElementById("imgTempoMarkings2").src = "./imgMSC/note4EqSel_22.png"
		document.getElementById("selTempoMarkings").value = ""
		document.getElementById("txtTempoMarkings2").value = "";

		//段数
		currentRowsCount = 4;
		document.getElementById("selRowsCount").value = 4;

		//小節数
		for (let i = 0; i < cMaxLines; i++) {
			MeasuresCount[i] = 4;
		}

		//歌詞番数
		currentLyricNumber = 0;
		document.getElementById("selLyric").value = 0;
		document.getElementById("txtLyric_1").value = "";
		document.getElementById("txtLyric_2").value = "";
		document.getElementById("txtLyric_3").value = "";

		//タイトル・作者の表示
		dispTitleAndAythor = false;

		//タイトル
   		abcTitle[0] = "";
   		abcTitle[1] = "";

		//作者
   		abcAuthor[0] = "";
   		abcAuthor[1] = "";
   		abcAuthor[2] = "";
   		
   		//ファイル名
		currentFileName = MAC_convLang("新規楽曲.msd");
   		if (paramMSCMode.substr(0, 10) != "wbtbuilder") {
		   	document.getElementById("spanEditorTitleFileName").innerHTML = currentFileName;
		}
		
		//楽譜の初期化
   		stopScrollAdjust = true;

   		stopUndoRedo = true;
		stopRender = false;
		initScore();
		MSC_resize();
   		stopUndoRedo = false;

		clearUndo();
		prevAbcString = currentAbcString;
		
		stopChange--;
		
		setTimeout( function() {
			stopScrollAdjust = false;
		}, 0);
	}

	//「いいえ」の場合
	document.getElementById("btnMessageYesNoNo").onclick = function() {
		document.getElementById("dialogMessageYesNo").close();
	}
}

//=====================================================================
//	openボタン押下時
//=====================================================================
function openButton() {
	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	document.getElementById("fileOpenDialog").click();
}
//------------------------------------------------------------------
//	データファイルを開く
//------------------------------------------------------------------
function openAbcData(event) {

    const file = event.target.files[0]; // 選択されたファイルを取得

    if (file) {

    	currentFileName = file.name;
    	if (paramMSCMode.substr(0, 10) != "wbtbuilder") {
	    	document.getElementById("spanEditorTitleFileName").innerHTML = currentFileName;
	    }

        const reader = new FileReader();

        // ファイルが読み込まれたときの処理
        reader.onload = function(e) {

			stopChange++;

            var content = e.target.result; // ファイルの内容
            
            stopRender = true;
            
			var lines = content.split("\n");

			//----------------------------------------------------
			//メニューの有効・無効設定、問題文の読み込み
			//----------------------------------------------------
			MSC_ParaMenuConfig = "";
			MSC_ParaQuestion = "";
			for (let i = lines.length-1; i >= 0; i--) {
				if (lines[i].substr(0, 11) == "% CFG1.0_:1") {
					MSC_ParaMenuConfig = lines[i].substr(10);
				}
				
				if (lines[i].substr(0, 11) == "% Question:") {
					MSC_ParaQuestion = lines[i].substr(11);
					MSC_ParaQuestion = MSC_ParaQuestion.replace(/<br>/g, "\n");
				}
			}
			if (MSC_ParaQuestion != "") {
				document.getElementById("divQuestion").innerHTML = MSC_ParaQuestion;
				document.getElementById("divQuestion").style.display = "block";
			} else {
				document.getElementById("divQuestion").style.display = "none";
			}

			if (paramMSCMode != "wbtbuilderKadaiToi" && paramMSCMode.substr(0, 10) == "wbtbuilder") {
				setMenuSetting(MSC_ParaMenuConfig);
			} else {
				setMenuSetting("");
			}

			//----------------------------------------------------
			//データ互換性
			//----------------------------------------------------
		    //曲名を２行にする（複数行対応のための互換性維持）
		    var cnt = 0;
		    var lin = 2;
		    for (i = 0; i < lines.length; i++) {
		    	if (lines[i].substr(0, 2) == "T:" || lines[i].substr(0, 4) == "% T:") {
		    		cnt++;
		    		lin = i;
		    	}
		    }
		    for (i = cnt; i < 2; i++) {
				lines.splice(lin+i, 0, "% T: ");
		    }

		    //作者を３行にする（作者の複数行対応のための互換性維持）
		    var cnt = 0;
		    var lin = 4;
		    for (i = 0; i < lines.length; i++) {
		    	if (lines[i].substr(0, 2) == "C:" || lines[i].substr(0, 4) == "% C:") {
		    		cnt++;
		    		lin = i;
		    	}
		    }
		    for (i = cnt; i < 3; i++) {
				lines.splice(lin+i, 0, "% C: ");
		    }
		    
		    //%%barnumbers の追加
		    var cnt = 0;
		    var lin = 1;
		    for (i = 0; i < lines.length; i++) {
		    	if (lines[i].substr(0, 14) == "%%barnumbers 1") {
		    		cnt = 1;
		    	}
		    }
		    if (cnt == 0) {
				lines.splice(lin, 0, "%%barnumbers 1");
		    }

		    //%%staffsep 80px の追加
			var cnt = 0;
		    var lin = 2;
		    for (i = 0; i < lines.length; i++) {
		    	if (lines[i].substr(0, 10) == "%%staffsep") {
		    		cnt = 1;
		    	}
		    }
		    if (cnt == 0) {
				lines.splice(lin, 0, "%%staffsep 80px");
		    }
		    
		    content = lines.join("\n");
		    
			//----------------------------------------------------

			//-----------------------------------------------------------
			//メニュー１行目のselectの設定
			//-----------------------------------------------------------
			document.getElementById("selTempoMarkings").value = "";
			document.getElementById("txtTempoMarkings2").value = "";

			var lines = content.split("\n");
			let lineCount = 1;
			let sCountStart = false;
			let sCount = 0;
			let wCount = 0;

			for (let i = 0; i < lines.length; i++) {

				//音部記号
				if (lines[i].substr(0, 8) == "% HEADER") {
					let tmp = lines[i].substr(8).trim();
					if (tmp == "treble only") {
						currentClefSymbol = "treble";
						selectClefSymbol.setValue("treble");
						lineCount = 1;
					} else if (tmp == "bass only") {
						currentClefSymbol = "bass";
						selectClefSymbol.setValue("bass");
						lineCount = 1;
					} else if (tmp == "treble+treble") {
						currentClefSymbol = "treble_treble";
						selectClefSymbol.setValue("treble_treble");
						lineCount = 2;
					} else if (tmp == "treble+bass") {
						currentClefSymbol = "treble_bass";
						selectClefSymbol.setValue("treble_bass");
						lineCount = 2;
					}
				}

				//調号
				if (lines[i].substr(0, 2) == "K:") {
					let tmp = lines[i].substr(2).trim();
					currentKeySignature = tmp;
					selectKeySignature.setValue(tmp);
				}

				//拍子記号
				if (lines[i].substr(0, 2) == "M:") {
					let tmp = lines[i].substr(2).trim();
					if (tmp == "C" || tmp == "C|" || tmp == "2/2" || tmp == "4/4") {
						currentTimeSymbol = tmp;
						countByBar = 8;
						selectTimingSymbol.setValue(tmp + ",8");
					} else if (tmp == "3/2" || tmp == "6/4" || tmp == "12/8") {
						currentTimeSignatureSymbol = tmp;
						countByBar = 12;
						selectTimingSymbol.setValue(tmp + ",12");
					} else if (tmp == "2/4") {
						currentTimeSignatureSymbol = tmp;
						countByBar = 4;
						selectTimingSymbol.setValue(tmp + ",4");
					} else if (tmp == "3/4" || tmp == "6/8") {
						currentTimeSignatureSymbol = tmp;
						countByBar = 6;
						selectTimingSymbol.setValue(tmp + ",6");
					} else if (tmp == "3/8") {
						currentTimeSignatureSymbol = tmp;
						countByBar = 3;
						selectTimingSymbol.setValue(tmp + ",3");
					} else if (tmp == "9/8") {
						currentTimeSignatureSymbol = tmp;
						countByBar = 9;
						selectTimingSymbol.setValue(tmp + ",9");
					} else if (tmp == "5/4") {
						currentTimeSignatureSymbol = tmp;
						countByBar = 10;
						selectTimingSymbol.setValue(tmp + ",10");
					} else if (tmp == "5/8") {
						currentTimeSignatureSymbol = tmp;
						countByBar = 5;
						selectTimingSymbol.setValue(tmp + ",5");
					} else if (tmp == "7/8") {
						currentTimeSignatureSymbol = tmp;
						countByBar = 7;
						selectTimingSymbol.setValue(tmp + ",7");
					}
				}

				//速度記号
				if (lines[i].substr(0, 2) == "Q:") {
					let tmp = lines[i].substr(2).trim();
					let tmps = (tmp + " 1/4=").split(" ");
					currentTempoMarkings = tmps[0].trim().replace(/\"/g, "");	//"
					let tmp2 = tmps[1].trim();
					let tmps2 = tmp2.split("=");

					currentTempoMarkings2Base = tmps2[0];
					currentTempoMarkings2 = (tmps2[1].trim() == "0") ? "" : tmps2[1].trim();
					
					if (currentTempoMarkings2Base == "3/4") {
						document.getElementById("imgTempoMarkings2").src = "./imgMSC/note2dEqSel_22.png";
					} else if (currentTempoMarkings2Base == "1/2") {
						document.getElementById("imgTempoMarkings2").src = "./imgMSC/note2EqSel_22.png";
					} else if (currentTempoMarkings2Base == "3/8") {
						document.getElementById("imgTempoMarkings2").src = "./imgMSC/note4dEqSel_22.png";
					} else if (currentTempoMarkings2Base == "1/4") {
						document.getElementById("imgTempoMarkings2").src = "./imgMSC/note4EqSel_22.png";
					} else if (currentTempoMarkings2Base == "1/8") {
						document.getElementById("imgTempoMarkings2").src = "./imgMSC/note8EqSel_22.png";
					}

					document.getElementById("selTempoMarkings").value = currentTempoMarkings;
					document.getElementById("txtTempoMarkings2").value = currentTempoMarkings2;
				}

				//行数カウント
				if (lines[i].substr(0, 2) == "K:") {
					sCountStart = true;
					continue;
				}
				if (sCountStart == true && lines[i].substr(0, 1) != "%" && lines[i].substr(0, 2) != "w:") sCount++;

				//歌詞行数カウント
				if (sCountStart == true && lines[i].substr(0, 2) == "w:") wCount++;
			}
			
			//行数
			currentRowsCount = sCount / lineCount;
			document.getElementById("selRowsCount").value = sCount / lineCount;
			
			//歌詞番数
			currentLyricNumber = wCount / currentRowsCount / lineCount;
			document.getElementById("selLyric").value = wCount / currentRowsCount / lineCount;

			//-----------------------------------------------------------
			//	タイトルと作者を取得
			//-----------------------------------------------------------
			var lines = content.split("\n");
		    var titleCount = 0;
		    abcTitle[0] = "";
		    abcTitle[1] = "";
		    var authorCount = 0;
			abcAuthor[0] = "";
			abcAuthor[1] = "";
			abcAuthor[2] = "";
			dispTitleAndAythor = false;

		    //曲名、作者を表示する場合（dispTitleAndAythor = true）
		    for (i = 0; i < lines.length; i++) {
		    	if (lines[i].substr(0, 2) == "T:" || lines[i].substr(0, 2) == "C:") {
		    		dispTitleAndAythor = true;
		    	}
			}

		    for (i = 0; i < lines.length; i++) {
		    	//タイトル
		    	if (lines[i].substr(0, 4) == "% T:") {
		    		if (titleCount < 2) {
			    		abcTitle[titleCount] = lines[i].substr(4).trim();
		    		
			    		if (dispTitleAndAythor == true && abcTitle[titleCount] != "") {
			    			lines[i] = abcTitle[titleCount];
			    		}
			    		
			    		titleCount++;
			    	}
		    	} else if (lines[i].substr(0, 2) == "T:") {
		    		if (titleCount < 2) {
			    		abcTitle[titleCount] = lines[i].substr(2).trim();
			    		
			    		if (dispTitleAndAythor == false || abcTitle[titleCount] == "") {
			    			lines[i] = "% " + abcTitle[titleCount];
			    		}
			    		
			    		titleCount++;
			    	}
		    	}
		    	//作者
		    	if (lines[i].substr(0, 4) == "% C:") {
		    		if (authorCount < 3) {
			    		abcAuthor[authorCount] = lines[i].substr(4).trim();

						if (dispTitleAndAythor == true && abcAuthor[authorCount] != "") {
							lines[i] = abcAuthor[authorCount];
						}

			    		authorCount++;
			    	}
		    	} else if (lines[i].substr(0, 2) == "C:") {
		    		if (authorCount < 3) {
			    		abcAuthor[authorCount] = lines[i].substr(2).trim();

						if (dispTitleAndAythor == false || abcAuthor[authorCount] == "") {
							lines[i] = "% " + abcAuthor[authorCount];
						}

			    		authorCount++;
			    	}
		    	}
		    }

			//-----------------------------------------------------------
			//	互換性（音部記号）
			//-----------------------------------------------------------
			if (currentClefSymbol == "treble_treble" || currentClefSymbol == "treble_bass") {
				for (let i = 0; i < lines.length; i++) {
					if (lines[i].substr(0, 6) == "[V: 1]") {
						lines[i] = "[V: 1 K:clef=treble]" + lines[i].substr(6);
					} else if (lines[i].substr(0, 6) == "[V: 2]") {
						if (currentClefSymbol == "treble_treble") {
							lines[i] = "[V: 2 K:clef=treble]" + lines[i].substr(6);
						} else {
							lines[i] = "[V: 2 K:clef=bass]" + lines[i].substr(6);
						}
					}
				}
			}

		    content = lines.join("\n");

			//-----------------------------------------------------------
			//	エディタと楽譜の表示更新
			//-----------------------------------------------------------
			stopScrollAdjust = true;
			
            stopRender = false;

    		stopUndoRedo = true;
			// ファイル内容をセット
            currentAbcString = content;
            
			//エディタにセット
			document.getElementById("abc-editor").value = currentAbcString;
			//レンダリング
			renderScore(currentAbcString);
			//
			MSC_resize();
            //非選択状態にする
            abcjsBodyMouseDown(true);
            //Undo、Redoのクリア
			stopUndoRedo = false;
            clearUndo();
 			prevAbcString = currentAbcString;
            
       		document.getElementById("abcjs-container").scrollTop = 0;
       		document.getElementById(editorId).scrollTop = 0;
       		
			
			//-------------------------------------------------------
			//各段の小節数（MeasuresCount[]を取得）
			//-------------------------------------------------------
			setTimeout( function() {
				var tmpMeasuresCount = [];
				for (let i = 0; i < cMaxLines; i++) {
					tmpMeasuresCount[i] = 0;
					MeasuresCount[i] = 4;
				}
				for (let i = 0; i < currentVisualArray.length; i++) {
					if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
						if (currentVisualArray[i].absEl.counters) {
							if (currentVisualArray[i].absEl.counters.voice == 0) {
								let line = currentVisualArray[i].absEl.counters.line;
								let measure = currentVisualArray[i].absEl.counters.measure + 1;
								if (measure > tmpMeasuresCount[line]) tmpMeasuresCount[line] = measure;
							}
						}
					}
				}
				for (let i = 0; i < cMaxLines; i++) {
					if (tmpMeasuresCount[i] > 0) {
						MeasuresCount[i] = tmpMeasuresCount[i]
					}
				}

				stopChange--;
	       		stopScrollAdjust = false;
			}, 0);
			
      	};

        reader.onerror = function(e) {
            console.error("ファイルの読み込み中にエラーが発生しました:", e);
            stopChange--;
        };

        // テキストファイルを読み込む
        reader.readAsText(file);
    }

	//次の読込に備えて
	document.getElementById("fileOpenDialog").value = "";
}

//=====================================================================
//	saveボタン押下時
//=====================================================================
var fileHandle = null;
async function saveButton() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

    //保存データ
    const data = document.getElementById("abc-editor").value;

    //初期ファイル名
    if (currentFileName != "" && currentFileName != MAC_convLang("新規楽曲.msd")) {
	    var fileName = currentFileName;
    } else if (abcTitle[0] == "") {
	    var fileName = MAC_convLang("新規楽曲.msd");
	} else {
	    var fileName = abcTitle[0] + '.msd';
	}
	currentFileName = fileName;
   	if (paramMSCMode.substr(0, 10) != "wbtbuilder") {
	   	document.getElementById("spanEditorTitleFileName").innerHTML = currentFileName;
	}

    // showSaveFilePickerがサポートされているかを確認
    if ('showSaveFilePicker' in window) {
        try {
            // showSaveFilePickerを使用してファイル保存ダイアログを表示
            const options = {
                suggestedName: fileName,
                types: [
                    {
                        description: 'MSC-Editor Data',
                        accept: {
                            'application/x-msd': ['.msd'],
                        },
                    },
                ],
            };
			
			//if (fileHandle == null) {
	            fileHandle = await showSaveFilePicker(options);
	        //}
            const writableStream = await fileHandle.createWritable();
            await writableStream.write(data);
            await writableStream.close();
        } catch (err) {
            console.error('ファイル保存中にエラーが発生しました:', err);
        }
    } else {
        // showSaveFilePickerがサポートされていない場合は<a>を使ったダウンロードにフォールバック
        const blob = new Blob([data], { type: 'text/plain' });
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = fileName;
        a.click();
        URL.revokeObjectURL(a.href);
    }
    
    clearUndo();
}

//=====================================================================
//	楽譜のPNGイメージの取得
//=====================================================================
//-------------------------------------------------------------------
//	楽譜をキャンバスに描画する関数をPromiseでラップ
//-------------------------------------------------------------------
function drawCanvas() {
    return new Promise((resolve, reject) => {
        const elem = document.querySelector("#abcjs-body svg");
        const canvas = document.getElementById("canvasPng");
        const ctx = canvas.getContext("2d");

        const svgString = new XMLSerializer().serializeToString(elem);
        const svgBlob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
        const url = URL.createObjectURL(svgBlob);

        const img = new Image();
        img.onload = function () {
            canvas.width = img.width;
            canvas.height = img.height;
			// キャンバスの背景を白で塗りつぶす
            ctx.fillStyle = "#ffffff";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            // SVG画像をキャンバスに描画
            ctx.drawImage(img, 0, 0);
            URL.revokeObjectURL(url);	// メモリを解放
            resolve();					// 描画が完了したらPromiseを解決
        };
        img.onerror = function(e) {
            reject(e);					// エラーが発生したらPromiseを拒否
        };
        img.src = url;
    });
}
//-------------------------------------------------------------------

//-------------------------------------------------------------------
//	楽譜をPNGイメージとして取得
//-------------------------------------------------------------------
async function getPngImage() {

	//---------------------------------------------------------
	// 元画像の上下左右の空白の高さと幅を取得する関数
	//---------------------------------------------------------
	function findNonEmptyBounds(image) {
	    // 仮のキャンバスを作成して、画像を描画
	    const tempCanvas = document.createElement("canvas");
	    const tempCtx = tempCanvas.getContext("2d");
	    tempCanvas.width = image.width;
	    tempCanvas.height = image.height;

	    // 画像を仮のキャンバスに描画
	    tempCtx.drawImage(image, 0, 0);

	    // イメージデータを取得
	    const imageData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height).data;

	    // 上部の余白を検出
	    let topTrimHeight = 0;
	    for (let y = 0; y < tempCanvas.height; y++) {
	        let hasContent = false;

	        for (let x = 0; x < tempCanvas.width; x++) {
	            const index = (y * tempCanvas.width + x) * 4; // RGBAの4チャンネル
	            const red = imageData[index];
	            const green = imageData[index + 1];
	            const blue = imageData[index + 2];
	            const alpha = imageData[index + 3];

	            if (alpha > 0 && !(red === 255 && green === 255 && blue === 255)) {
	                hasContent = true;
	                break;
	            }
	        }

	        if (hasContent) {
	            topTrimHeight = y;
	            break;
	        }
	    }

	    // 下部の余白を検出
	    let bottomTrimHeight = tempCanvas.height;
	    for (let y = tempCanvas.height - 1; y >= 0; y--) {
	        let hasContent = false;

	        for (let x = 0; x < tempCanvas.width; x++) {
	            const index = (y * tempCanvas.width + x) * 4;
	            const red = imageData[index];
	            const green = imageData[index + 1];
	            const blue = imageData[index + 2];
	            const alpha = imageData[index + 3];

	            if (alpha > 0 && !(red === 255 && green === 255 && blue === 255)) {
	                hasContent = true;
	                break;
	            }
	        }

	        if (hasContent) {
	            bottomTrimHeight = tempCanvas.height - y - 1;
	            break;
	        }
	    }

	    // 左側の余白を検出
	    let leftTrimWidth = 0;
	    for (let x = 0; x < tempCanvas.width; x++) {
	        let hasContent = false;

	        for (let y = 0; y < tempCanvas.height; y++) {
	            const index = (y * tempCanvas.width + x) * 4;
	            const red = imageData[index];
	            const green = imageData[index + 1];
	            const blue = imageData[index + 2];
	            const alpha = imageData[index + 3];

	            if (alpha > 0 && !(red === 255 && green === 255 && blue === 255)) {
	                hasContent = true;
	                break;
	            }
	        }

	        if (hasContent) {
	            leftTrimWidth = x;
	            break;
	        }
	    }

	    // 右側の余白を検出
	    let rightTrimWidth = tempCanvas.width;
	    for (let x = tempCanvas.width - 1; x >= 0; x--) {
	        let hasContent = false;

	        for (let y = 0; y < tempCanvas.height; y++) {
	            const index = (y * tempCanvas.width + x) * 4;
	            const red = imageData[index];
	            const green = imageData[index + 1];
	            const blue = imageData[index + 2];
	            const alpha = imageData[index + 3];

	            if (alpha > 0 && !(red === 255 && green === 255 && blue === 255)) {
	                hasContent = true;
	                break;
	            }
	        }

	        if (hasContent) {
	            rightTrimWidth = tempCanvas.width - x - 1;
	            break;
	        }
	    }

	    return { topTrimHeight, bottomTrimHeight, leftTrimWidth, rightTrimWidth };
	}
	//------------------------------------------------------

	//---------------------------------------------------------
	// 完成した PNG 画像の上下左右の空白を調整する関数
	//---------------------------------------------------------
	function trimAndAddPadding(pngDataUrl, topPaddingHeight, bottomPaddingHeight, leftPaddingWidth, rightPaddingWidth) {
	    return new Promise((resolve) => {
	        const img = new Image();
	        img.onload = function () {
	            // 既存の PNG イメージをロードしたら、新しいキャンバスを作成
	            const trimmedCanvas = document.createElement("canvas");
	            const ctx = trimmedCanvas.getContext("2d");

	            // 元画像のサイズを取得
	            const originalWidth = img.width;
	            const originalHeight = img.height;

	            // 上下左右の余白を検出
	            const { topTrimHeight, bottomTrimHeight, leftTrimWidth, rightTrimWidth } = findNonEmptyBounds(img);

	            console.log("topTrimHeight:", topTrimHeight, "bottomTrimHeight:", bottomTrimHeight);
	            console.log("leftTrimWidth:", leftTrimWidth, "rightTrimWidth:", rightTrimWidth);

	            // 実際の描画部分のサイズを計算（余分な上下左右の空白を除いた部分）
	            const trimmedWidth = originalWidth - leftTrimWidth - rightTrimWidth;
	            const trimmedHeight = originalHeight - topTrimHeight - bottomTrimHeight;

	            // 新しいキャンバスのサイズを設定（指定した上下左右の余白を追加）
	            trimmedCanvas.width = trimmedWidth + leftPaddingWidth + rightPaddingWidth;
	            trimmedCanvas.height = trimmedHeight + topPaddingHeight + bottomPaddingHeight;

	            // キャンバスの背景を白で塗りつぶす
	            ctx.fillStyle = "#ffffff";
	            ctx.fillRect(0, 0, trimmedCanvas.width, trimmedCanvas.height);

	            // 元画像を新しいキャンバスに描画（上部・左部余白分をスキップして描画）
	            ctx.drawImage(
	                img,
	                leftTrimWidth, topTrimHeight,              // 元画像の描画開始位置 (x, y)
	                trimmedWidth, trimmedHeight,               // 描画範囲の幅と高さ
	                leftPaddingWidth, topPaddingHeight,        // 新しいキャンバスでの描画開始位置 (x, y)
	                trimmedWidth, trimmedHeight                // 新しいキャンバスの描画サイズ
	            );

	            // 新しいキャンバスを PNG データ URL として取得
	            const newPngDataUrl = trimmedCanvas.toDataURL("image/png");
	            resolve(newPngDataUrl);
	        };
	        img.src = pngDataUrl;
	    });
	}
	//---------------------------------------------------------

    await drawCanvas();					//キャンバスに描画が完了するのを待つ
    const canvasPng = document.getElementById("canvasPng");
    let resPng = canvasPng.toDataURL("image/png");

	if (paramMSCMode.substr(0, 10) == "wbtbuilder") {
	    // 完成した PNG イメージの余白を指定して調整
    	return trimAndAddPadding(resPng, 30, 16, 16, 16); // 上、下、左、右の余白を設定
    } else {
		return resPng;
    }
}

//=====================================================================
//	printボタン押下時
//=====================================================================
function printButton() {
	//------------------------------------------------------------------------
	//	キャンバスの描画範囲内で、下から上に向かってピクセルが全て白（空白）である行を探す。
	//	空白行を見つけたらその位置を返し、見つからない場合はnullを返す。
	//------------------------------------------------------------------------
	function detectEmptyRow(canvas, startY, endY) {

	    const ctx = canvas.getContext('2d');
	    const width = canvas.width;
	    
	    let y1 = null;  // 上方向に見つけた最初の完全空白行
	    let y2 = null;  // 50%以上描画されている行
	    let y3 = null;  // 最終的に見つけた完全空白行（連続する空白行の最終行）

	    // 1. 通常の区切り位置から上方向に向かって完全な空白行を探す（y1を見つける）
	    for (let y = endY - 1; y >= startY; y--) {
	        let filledPixels = 0;

	        // 横方向のピクセルを確認して空白かどうか判断
	        for (let x = 0; x < width; x++) {
	            const pixel = ctx.getImageData(x, y, 1, 1).data;
	            const [r, g, b, a] = pixel;
	            if (a > 0 && (r < 255 || g < 255 || b < 255)) {
	                filledPixels++;
	            }
	        }

	        // 完全な空白行が見つかれば、y1を設定
	        if (filledPixels === 0 && y1 === null) {
	            y1 = y;
	            //console.log(`完全空白行 y1 が見つかりました: ${y1} 行`);
	        }

	        // 50%以上描画されている行を見つけたら、ループを終了（y2を設定）
	        if (y1 !== null && filledPixels / width > 0.5) {
	            y2 = y;
	            if (y2 < y1-30) {
		            //console.log(`50%以上描画された行 y2 が見つかりました: ${y2} 行`);
		            break;
		        }
	        }
	    }
	    

	    // y1 と y2 が設定されている場合のみ、y2 から下方向に完全空白行を探す
	    if (y1 !== null && y2 !== null) {
	        for (let y = y2 + 1; y <= y1; y++) {
	            let filledPixels = 0;

	            // 横方向のピクセルを確認して空白かどうか判断
	            for (let x = 0; x < width; x++) {
	                const pixel = ctx.getImageData(x, y, 1, 1).data;
	                const [r, g, b, a] = pixel;
	                if (a > 0 && (r < 255 || g < 255 || b < 255)) {
	                    filledPixels++;
	                }
	            }

	            // 完全に空白な行が続く場合、y3を更新
	            if (filledPixels === 0) {
	                y3 = y;
	                //console.log(`完全空白行 y3 が見つかりました: ${y3} 行`);
	            }
	            
	            // 空白行が途切れたら終了
	            if (y3 !== null && filledPixels > 0) {
	                break;
	            }
	        }
	    }

	    // 最終的に見つかった完全空白行（y3）を返す
	    if (y3 !== null) {
	        //console.log(`区切り行として y3 を返します: ${y3} 行`);
	        return y3;
	    }

	    //console.log("区切り行が見つかりませんでした");
	    return null;  // 見つからなかった場合は null を返す
	}
	//------------------------------------------------------------------------

	//------------------------------------------------------------------------
	//	キャンバスのピクセルデータをチェックし、
	//	キャンバスが空（すべてのピクセルが透明または白）かどうかを判断（空白ページの印刷回避）
	//------------------------------------------------------------------------
	function isCanvasEmpty(canvas) {
	    const ctx = canvas.getContext('2d');
	    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
	    const data = imageData.data;

	    // ピクセルデータをチェックして、すべてのピクセルが透明か白であれば true を返す
	    for (let i = 0; i < data.length; i += 4) {
	        const [r, g, b, a] = data.slice(i, i + 4);
	        if (a > 0 && (r < 255 || g < 255 || b < 255)) {
	            // 描画されたピクセルが見つかった場合、空ではない
	            return false;
	        }
	    }
	    // すべてのピクセルが透明または白だった場合、キャンバスは空
	    return true;
	}
	//------------------------------------------------------------------------

	//------------------------------------------------------------------------
	//	通常通り縦方向にA4のサイズごとに分割しつつ、detectEmptyRow関数で空白部分を探す。
	//	空白部分が見つかった場合、分割位置をその空白行の直前まで上方向にずらす。
	//------------------------------------------------------------------------
	function splitImageForPrinting(imgElement) {
	    const canvas = document.createElement('canvas');
	    const ctx = canvas.getContext('2d');
	    
	    // A4サイズの高さ (縦) をピクセルに換算、96DPIの場合
	    const a4Height = 297 * 3.7795275591; // A4 height in pixels at 96dpi
	    const imgWidth = imgElement.naturalWidth; // 元の画像の幅
	    const imgHeight = imgElement.naturalHeight; // 元の画像の高さ
	    
	    // キャンバスに画像の幅を設定
	    canvas.width = imgWidth;
	    
	    let currentHeight = 0;

	    // 新しいウィンドウを開く
	    const win = window.open();
	    win.document.write(`
	        <html>
	        <head>
	            <title>Print Preview</title>
	            <style>
	                @media print {
	                    img { display: block; }
	                }
	            </style>
	        </head>
	        <body>
	    `);
	    
	    // ページ全体を収める配列
	    const images = [];

	    while (currentHeight < imgHeight) {
	        let nextHeight = Math.min(currentHeight + a4Height, imgHeight);

	        // キャンバスの高さを仮に次の分割部分までに設定（描画はまだ行わない）
	        canvas.height = nextHeight - currentHeight;

	        // 仮のキャンバスで空白行を検出して区切り位置を調整
	        ctx.clearRect(0, 0, canvas.width, canvas.height);
	        ctx.drawImage(imgElement, 0, currentHeight, imgWidth, nextHeight - currentHeight, 0, 0, imgWidth, nextHeight - currentHeight);
	        const emptyRow = detectEmptyRow(canvas, 0, canvas.height);

	        // 空白行が見つかった場合、その位置を次の高さに調整
	        if (emptyRow !== null) {
	            nextHeight = currentHeight + emptyRow;  // 空白行の位置に区切りを調整
	            canvas.height = nextHeight - currentHeight;  // 高さを調整
	        }

	        // 調整された高さで本描画を実行
	        ctx.clearRect(0, 0, canvas.width, canvas.height);
	        ctx.drawImage(imgElement, 0, currentHeight, imgWidth, nextHeight - currentHeight, 0, 0, imgWidth, nextHeight - currentHeight);

	        // キャンバスが空白かどうかをチェック
	        if (!isCanvasEmpty(canvas)) {
	            // キャンバスが空でない場合のみ画像として追加
	            const dataUrl = canvas.toDataURL('image/png');
	            images.push(dataUrl); // ページごとの画像を保存
	        }

	        // 次の区切り位置を設定
	        currentHeight = nextHeight;
	    }

	    // すべての画像を新しいウィンドウに追加
	    images.forEach((dataUrl, index) => {
	        // 最後のページだけ page-break-after を適用しない
	        const pageBreakStyle = (index === images.length - 1) ? '' : 'page-break-after: always;';
	        win.document.write(`<img src="${dataUrl}" style="width:100%; display:block; ${pageBreakStyle}" />`);
	    });

	    // すべての画像が表示された後に印刷を実行
	    win.document.write('</body></html>');
	    win.document.close();

	    // 画像がロードされたら印刷を実行し、印刷ダイアログが開いてからウィンドウを少し遅れて閉じる
	    win.onload = function() {
	        win.print();

	        // 少し遅延させてウィンドウを閉じる
	        setTimeout(function() {
	            win.close();
	        }, 50);  // 50ミリ秒の遅延を設定
	    };
	}
	//------------------------------------------------------------------------


	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	document.getElementById("divForTitleInput").style.display = "none";
	document.getElementById("divForPrint").style.display = "";
	document.getElementById("radioPrintKindScore").checked = true;
	document.getElementById("btnPrintOK").innerHTML = MAC_convLang("印刷");

	//---------------------------------------------------
	//タイトルと著者のセット
	//---------------------------------------------------
	var text = "";
	if (abcTitle[0] != "") {
		text += abcTitle[0];
		if (abcTitle[1] != "") {
			text += "\n";
			text += abcTitle[1];
		}
	}
	document.getElementById("txtTitle").value = text;

	var text = "";
	if (abcAuthor[0] != "") {
		text += abcAuthor[0];
		if (abcAuthor[1] != "") {
			text += "\n";
			text += abcAuthor[1];
			if (abcAuthor[2] != "") {
				text += "\n";
				text += abcAuthor[2];
			}
		}
	}
	document.getElementById("txtAuthor").value = text;

	//---------------------------------------------------
	//曲名・作者ダイアログの表示
	//---------------------------------------------------
	document.getElementById("dialogTitleAndAuthor").showModal();

	//---------------------------------------------------
	//キャンセルボタン
	//---------------------------------------------------
	document.getElementById("btnPrintCancel").onclick = function() {
		document.getElementById("dialogTitleAndAuthor").close();
	}

	//---------------------------------------------------
	//OKボタン
	//---------------------------------------------------
	document.getElementById("btnPrintOK").onclick = function() {
		//dispTitleAndAythor = document.getElementById("chkTitleDisp").checked;

		var lines = (document.getElementById("txtTitle").value+"\n").split("\n");
		abcTitle[0] = lines[0];
		abcTitle[1] = lines[1];

		var lines = (document.getElementById("txtAuthor").value+"\n\n").split("\n");
		abcAuthor[0] = lines[0];
		abcAuthor[1] = lines[1];
		abcAuthor[2] = lines[2];

		document.getElementById("dialogTitleAndAuthor").close();
		
		//---------------------------------------------------
		//タイトルと著者の保存
		//---------------------------------------------------
    	var cntT = 0;
    	var cntA = 0;
        var lines = currentAbcString.split("\n");
        for (i = 0; i < lines.length; i++) {
        	//タイトル
        	if (lines[i].substr(0, 4) == "% T:" || lines[i].substr(0, 2) == "T:") {
        		if (cntT < 2 && dispTitleAndAythor == true && abcTitle[cntT] != "") {
        			lines[i] = "T: " + abcTitle[cntT];
        		} else {
        			lines[i] = "% T: " + abcTitle[cntT];
        		}
        		cntT++;
        	}
        	//作者
        	if (lines[i].substr(0, 4) == "% C:" || lines[i].substr(0, 2) == "C:") {
        		if (cntA < 3 && dispTitleAndAythor == true && abcAuthor[cntA] != "") {
	         		lines[i] = "C: " + abcAuthor[cntA];
	         	} else {
	         		lines[i] = "% C: " + abcAuthor[cntA];
	         	}
        		cntA++;
        	}
        }
		currentAbcString = lines.join("\n");
		document.getElementById("abc-editor").value = currentAbcString;
		
	 	//楽譜のレンダリング
        stopUndoRedo = true;
		renderScore(currentAbcString);
		MSC_resize();
        //非選択状態にする
        abcjsBodyMouseDown(true);
        stopUndoRedo = false;
		
		//---------------------------------------------------
		//楽譜イメージの場合
		//---------------------------------------------------
		if (document.getElementById("radioPrintKindScore").checked == true) {
			//---------------------------------------------------
			//abcStringデータの退避
			//---------------------------------------------------
			var backAbcString = currentAbcString;

			//---------------------------------------------------
			//タイトルと著者を有効化（印刷時は、曲名・作者名は必ず表示）し、再描画
			//---------------------------------------------------
	        let lines = currentAbcString.split("\n");
	        for (i = 0; i < lines.length; i++) {
	        	//タイトル
	        	if (lines[i].substr(0, 4) == "% T:") {
	        		if (lines[i].substr(2).trim() != "") {
		        		lines[i] = lines[i].substr(2).trim();
		        	}
	        	}
	        	//作者
	        	if (lines[i].substr(0, 4) == "% C:") {
	        		if (lines[i].substr(2).trim() != "") {
		         		lines[i] = lines[i].substr(2).trim();
		         	}
	        	}
	        }
			currentAbcString = lines.join("\n");
			document.getElementById("abc-editor").value = currentAbcString;
	        
	        stopUndoRedo = true;
			//-----------------------------------------------------------
			//	エディタと楽譜の表示更新
			//-----------------------------------------------------------
			//レンダリング
			renderScore(currentAbcString);
			//
			MSC_resize();
	        //非選択状態にする
	        abcjsBodyMouseDown(true);

	        stopUndoRedo = false;
			
			(async () => {
			    try {
			        var pngData = await getPngImage(); // PNGイメージのデータを取得
			        
					//---------------------------------------------------
					//タイトルと著者を復帰し、再描画
					//---------------------------------------------------
					currentAbcString = backAbcString;
					document.getElementById("abc-editor").value = currentAbcString;
			        
			        stopUndoRedo = true;
					//-----------------------------------------------------------
					//	エディタと楽譜の表示更新
					//-----------------------------------------------------------
					//エディタにセット
					document.getElementById("abc-editor").value = currentAbcString;
					//レンダリング
					renderScore(currentAbcString);
					//
					MSC_resize();
			        //非選択状態にする
			        abcjsBodyMouseDown(true);

			        stopUndoRedo = false;
			        
					//---------------------------------------------------
			        //PNGイメージ（pngData）の印刷処理
					//---------------------------------------------------
/*
					document.getElementById("divImagePrint").style.display = "block";
					// 画像のsrc属性にBase64データを設定
					const img = document.getElementById('imageToPrint');
					
					img.onload = function() {
						// 印刷を実行
						window.print();
						document.getElementById("divImagePrint").style.display = "none";
					}
					
					img.src = pngData;
*/


					document.getElementById("divImagePrint").style.display = "block";
					// 画像のsrc属性にBase64データを設定
					const img = document.getElementById('imageToPrint');
					
					img.onload = function() {
						// 印刷を実行
						splitImageForPrinting(img);
					}
					
					img.src = pngData;









					/*
					// 画像を含む新しいウィンドウを開く
					const win = window.open();
						win.document.write(`
						<html>
							<head>
								<title>Print Image</title>
								<style>
									@media print {
									    body {
									        margin: 0;
									        padding: 0;
									        box-sizing: border-box;
									    }
									    .print-container {
									        width: 210mm; / * A4 width * /
									        height: 297mm; / * A4 height * /
									        overflow: hidden;
									        display: flex;
									        justify-content: center;
									        align-items: center;
									        page-break-after: always;
									    }
									    img {
									        max-width: 100%;
									        max-height: 100%;
									        object-fit: contain;
									    }
									}
								</style>
							</head>
							<body>
								<img src="${pngData}" onload="window.print(); window.close()" />
								<!--
								<img src="${pngData}" />
								-->
							</body>
						</html>
					`);

					win.document.close();
					
					*/

			    } catch (error) {
			        console.error("Error generating PNG image:", error);
			    }
			})();
		
		//---------------------------------------------------
		//ABCソースの場合
		//---------------------------------------------------
		} else {
			//---------------------------------------------------
	        //タイトルと著者 ＋ ABCソース（currentAbcString）の印刷処理
			//---------------------------------------------------
			let abcData = "";
			
			//タイトル
			abcData += ("タイトル：" + abcTitle[0]);
			abcData += "<br><br>";
			
			//著者
			abcData += ("作者：" + abcAuthor[0]);
			abcData += "<br><br>";
			
			//ABCデータ
			let lines = currentAbcString.split("\n");
			let str = lines.join("<br>");
			abcData += str;

			/*
			document.getElementById("divTextPrint").innerHTML = text;

			//印刷実行
			document.getElementById("divTextPrint").style.display = "inline-block";
			window.print();
			document.getElementById("divTextPrint").style.display = "none";
			*/
			

			// テキストを含む新しいウィンドウを開く
			const win = window.open();
				win.document.write(`
				<html>
					<head>
						<title>Print Source</title>
						<script>
						function init() {
							window.print();
							window.close();
						}
						</script>
					</head>
					<body onload="init()">
						<span style="font-size: 9px;">${abcData}</span>
					</body>
				</html>
			`);
			
			win.document.close();
		}
	}
}

//=====================================================================
//	playボタン押下時
//=====================================================================
var backupAbcScore;

function playButton() {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";
	tmpSymbolIdx1 = -1;
	tmpSymbolIdx2 = -1;

	//音符・休符、装飾ボタン等の無効設定
	setDisabledNoteRestButton("disabled");

	//歌詞入力テキストボックスの無効化
	document.getElementById("txtLyric_1").value = "";
	document.getElementById("txtLyric_2").value = "";
	document.getElementById("txtLyric_3").value = "";
	document.getElementById("txtLyric_1").disabled = true;
	document.getElementById("txtLyric_2").disabled = true;
	document.getElementById("txtLyric_3").disabled = true;

	//音部記号イメージプルダウンの無効化
	setDisabledSelClefSymbol(true);
	//調号イメージプルダウンの無効化
	setDisabledSelKeySignature(true);
	//拍子記号イメージプルダウンの無効化
	setDisabledSelTimeSignatureSymbol(true);

	//曲名・作者ボタンの無効化
	document.getElementById("btnTitle").disabled = true;

	//速度記号の無効化
	document.getElementById("selTempoMarkings").disabled = true;
	//メトロノーム基準音符
	document.getElementById("btnTempoMarkings2").disabled = true;
	//メトロノーム記号の無効化
	document.getElementById("txtTempoMarkings2").disabled = true;
	//行数の無効化
	document.getElementById("selRowsCount").disabled = true;
	//小節数の無効化
	document.getElementById("btnMeasuresCount").disabled = true;
	//歌詞の無効化
	document.getElementById("selLyric").disabled = true;
	//不完全小節
	document.getElementById("btnNoteDel").disabled = true;
	document.getElementById("btnNoteOrg").disabled = true;

	//挿入ボタンの無効化
	document.getElementById("insertButton").disabled = true;
	document.getElementById("chkInsertTitle").disabled = true;
	document.getElementById("spanInsert").style.color = "#C0C0C0";

	//楽譜カバーの表示
	document.getElementById("abcjs-body_cover").style.display = "block";

	//小節線イメージプルダウンの無効化
	setDisabledSelBarLine(true);
	//追加のアーティキュレーションを非表示
	document.getElementById("divOptionArticulation").style.display = "none";

	//エディタ非表示
	document.getElementById("abc-editor").style.display = "none";

	//サウンドコントロールの表示
	document.getElementById("divPlayer").style.display = "block";
	
	//サウンド再生の初期化
	if (abcEditor !== null) abcEditor = null;

	loadSound();
	
    nowAbcPlaying = true;
}

//=====================================================================
//	playerの閉じるボタン押下
//=====================================================================
function clkClosePlayer() {
	
	//演奏の停止
	synthControl.pause(); // 演奏を一時停止
	if (midiBuffer) {
		midiBuffer.stop(); // 再生を完全に停止
	}
	
	//音部記号イメージプルダウンの有効化
	setDisabledSelClefSymbol(cfgSelClefSymbolDisabled);
	//調号イメージプルダウンの無効化
	setDisabledSelKeySignature(cfgSelKeySignatureDisabled);
	//拍子記号イメージプルダウンの有効化
	setDisabledSelTimeSignatureSymbol(cfgSelTimeSignatureSymbolDisabled);

	//曲名・作者ボタンの有効化
	document.getElementById("btnTitle").disabled = cfgBtnTitleAndAuthorDisabled;

	//速度記号の有効化
	document.getElementById("selTempoMarkings").disabled = cfgSelTempoMarkingsDisabled;
	//メトロノーム基準音符
	document.getElementById("btnTempoMarkings2").disabled = cfgBtnTempoMarkings2BaseDisabled;
	//メトロノーム記号の有効化
	document.getElementById("txtTempoMarkings2").disabled = cfgTxtTempoMarkings2Disabled;
	//段数の有効化
	document.getElementById("selRowsCount").disabled = cfgSelRowsCountDisabled;
	//小節数の有効化
	document.getElementById("btnMeasuresCount").disabled = cfgBtnMeasuresCountDisabled;
	//歌詞の有効化
	document.getElementById("selLyric").disabled = cfgSelLyricDisabled;
	//不完全小節
	document.getElementById("btnNoteDel").disabled = cfgBtnIncompleteMeasureDisabled;
	document.getElementById("btnNoteOrg").disabled = cfgBtnIncompleteMeasureDisabled;

	//挿入ボタンの有効化
	document.getElementById("insertButton").disabled = false;
	document.getElementById("chkInsertTitle").disabled = false;
	document.getElementById("spanInsert").style.color = "#000000";

	//楽譜カバーの非表示
	document.getElementById("abcjs-body_cover").style.display = "none";

	//エディタ表示（チェック状態に応じて）
	clkAbcEditor(document.getElementById("chkAbcEditor"));

	//サウンドコントロール非表示
	document.getElementById("divPlayer").style.display = "none";

	//レンダリング
	renderScore(currentAbcString);
	MSC_resize();
    //非選択状態にする
    abcjsBodyMouseDown(true);

    nowAbcPlaying = false;
}

//==================================================================
//	演奏用
//==================================================================
var midiNoChangeFlag = false;

function CursorControl() {
	var self = this;

	self.onReady = function() {
		//console.log("onReady");
	};

	self.onStart = function() {
		//console.log("onStart");

		var svg = document.querySelector("#abcjs-body svg");
		var cursor = document.createElementNS("http://www.w3.org/2000/svg", "line");
		cursor.setAttribute("class", "abcjs-cursor");
		cursor.setAttributeNS(null, 'x1', 0);
		cursor.setAttributeNS(null, 'y1', 0);
		cursor.setAttributeNS(null, 'x2', 0);
		cursor.setAttributeNS(null, 'y2', 0);
		svg.appendChild(cursor);
		
		document.getElementById("abcjs-container").scrollTop = 0;

		//----------------------------------------------------
		//音色選択ボタンを無効化（演奏が開始されたので）
		//----------------------------------------------------
		document.getElementById("selMidiNo").disabled = true;
		//----------------------------------------------------
	};

	self.beatSubdivisions = 2;

	self.onBeat = function(beatNumber, totalBeats, totalTime) {
	};

	self.onEvent = function(ev) {
		//console.log("onEvent", ev);

		if (ev.measureStart && ev.left === null)
			return; // this was the second part of a tie across a measure line. Just ignore it.

		var lastSelection = document.querySelectorAll("#abcjs-body svg .highlight");
		for (var k = 0; k < lastSelection.length; k++)
			lastSelection[k].classList.remove("highlight");

		for (var i = 0; i < ev.elements.length; i++ ) {
			var note = ev.elements[i];
			for (var j = 0; j < note.length; j++) {
				note[j].classList.add("highlight");
			}
		}

		var cursor = document.querySelector("#abcjs-body svg .abcjs-cursor");
		if (cursor) {
			cursor.setAttribute("x1", ev.left - 2);
			cursor.setAttribute("x2", ev.left - 2);
			cursor.setAttribute("y1", ev.top);
			cursor.setAttribute("y2", ev.top + ev.height);
			
			let top = ev.top - 80;
			if (top < 0) top = 0;
			document.getElementById("abcjs-container").scrollTop = top;
		}

		//----------------------------------------------------
		//音色選択ボタンを無効化（演奏中なので）
		//----------------------------------------------------
		if (midiNoChangeFlag == false) {
			document.getElementById("selMidiNo").disabled = true;
		}
		midiNoChangeFlag = false;
		//----------------------------------------------------

	};

	self.onFinished = function() {
		//console.log("onFiinish");
	
		var els = document.querySelectorAll("svg .highlight");
		for (var i = 0; i < els.length; i++ ) {
			els[i].classList.remove("highlight");
		}
		var cursor = document.querySelector("#abcjs-body svg .abcjs-cursor");
		if (cursor) {
			cursor.setAttribute("x1", 0);
			cursor.setAttribute("x2", 0);
			cursor.setAttribute("y1", 0);
			cursor.setAttribute("y2", 0);
		
			document.getElementById("abcjs-container").scrollTop = 0;
		}

		//----------------------------------------------------
		//音色選択ボタンを有効化（演奏が終了したので）
		//----------------------------------------------------
		document.getElementById("selMidiNo").disabled = false;
		//----------------------------------------------------
	};
}

var cursorControl = new CursorControl();
var synthControl;
var midiBuffer;

/*
	repeatTitle: "繰り返し",			//Click to toggle play once/repeat.			class="abcjs-midi-loop abcjs-btn"
	restartTitle: "最初から",			//Click to go to beginning.					class="abcjs-midi-reset abcjs-btn"
	playTitle: "演奏 / 一時停止",		//Click to play/pause.						class="abcjs-midi-start abcjs-btn"
	randomTitle: "演奏位置の変更",		//Click to change the playback position.	class="abcjs-midi-progress-background"
*/

function loadSound() {
	if (ABCJS.synth.supportsAudio()) {
		synthControl = new ABCJS.synth.SynthController();
		synthControl.load("#audio", cursorControl, 
			{
				displayLoop: false, 
				displayRestart: true, 
				displayPlay: true, 
				displayProgress: true, 
				displayWarp: false,
			}
		);
	} else {
		document.querySelector("#audio").innerHTML = "<div class='audio-error'>Audio is not supported in this browser.</div>";
	}
	setTune(false);
	
	//オーディオコントロールの title を変更
	//document.getElementsByClassName("abcjs-midi-loop")[0].title = "繰り返し";
	document.getElementsByClassName("abcjs-midi-reset")[0].title = 	"最初から";
	document.getElementsByClassName("abcjs-midi-start")[0].title =	"演奏 / 一時停止";
	document.getElementsByClassName("abcjs-midi-progress-background")[0].title = "演奏位置の変更";

	//----------------------------------------------------
	//音色選択ボタンを有効化
	//----------------------------------------------------
	document.getElementById("selMidiNo").disabled = false;
	//----------------------------------------------------
}

function setTune(userAction) {
	var abcOptions = {
		add_classes: true,

		paddingtop: 50,      // 上の余白を50pxに設定
		paddingbottom: 50,   // 下の余白を50pxに設定
	};

	synthControl.disable(true);

	let abc = document.getElementById("abc-editor").value;
	let abcs = abc.split("\n");
	let midiData = "%%midi program 1 " + (document.getElementById("selMidiNo").value-1);

	if (abc.indexOf("%%midi program") == -1) {
		abcs.splice(3, 0, midiData);
	} else {
		abcs[3] = midiData;
	}
	abc = abcs.join("\n");

	let visualObj = ABCJS.renderAbc("abcjs-body", abc, abcOptions)[0];

	midiBuffer = new ABCJS.synth.CreateSynth();
	midiBuffer.init({
		visualObj: visualObj,

	}).then(function (response) {
		//console.log(response);
		
		//演奏の最初の数秒が途切れる問題に対処（setTimeout 1000ms）
		setTimeout( function() {
		
			if (synthControl) {
				synthControl.setTune(visualObj, userAction).then(function (response) {
					//console.log("Audio successfully loaded.")

					// 曲頭ボタンが押された時のイベントを取得
					//document.querySelector(".abcjs-midi-start").addEventListener("click", function() {
					document.getElementsByClassName("abcjs-midi-reset")[0].addEventListener("click", function() {
						//----------------------------------------------------
						//500ms後に、音色選択ボタンを有効化（pauseボタンが押された結果、pause中となっている可能性があるので）
						//----------------------------------------------------
						document.getElementById("selMidiNo").disabled = false;
						//----------------------------------------------------
					});

					// 一時停止ボタンが押された時のイベントを取得
					//document.querySelector(".abcjs-midi-start").addEventListener("click", function() {
					document.getElementsByClassName("abcjs-midi-start")[0].addEventListener("click", function() {
						//----------------------------------------------------
						//500ms後に、音色選択ボタンを有効化（pauseボタンが押された結果、pause中となっている可能性があるので）
						//----------------------------------------------------
						document.getElementById("selMidiNo").disabled = false;
						//----------------------------------------------------
					});

					// シークボタンが押された時のイベントを取得
					//document.querySelector(".abcjs-midi-start").addEventListener("click", function() {
					document.getElementsByClassName("abcjs-midi-progress-background")[0].addEventListener("click", function() {
						midiNoChangeFlag = true;
						//----------------------------------------------------
						//500ms後に、音色選択ボタンを有効化（pauseボタンが押された結果、pause中となっている可能性があるので）
						//----------------------------------------------------
						document.getElementById("selMidiNo").disabled = false;
						//----------------------------------------------------
					});


				}).catch(function (error) {
					console.warn("Audio problem:", error);
				});
			}
		}, 1000);
	}).catch(function (error) {
		console.warn("Audio problem:", error);
	});

	//------------------------------------------------------------------
	//	一部のシンボルの表示位置や表示状態を調整
	//------------------------------------------------------------------
	adjustSymbolPosition();
}

//=====================================================================
//	MiDi音色の変更
//=====================================================================
function chgMidiNo(elem) {
	midiNoChangeFlag = true;
	setTune(true);
}

//=====================================================================
//	abcエディタチェックボックスのクリック（エディタの表示・非表示切換）
//=====================================================================
function clkAbcEditor(elem) {

	document.getElementById("divOptionNoteAndRest").style.display = "none";
	document.getElementById("divOptionArticulation").style.display = "none";
	document.getElementById("divTempoMarkings2").style.display = "none";

	if (elem.checked == true) {
		document.getElementById("abc-editor").style.display = "block";
	} else {
		document.getElementById("abc-editor").style.display = "none";
	}
	MSC_resize();
}

//##########################################################################
//##########################################################################
//	メニュー内のオブジェクトの有効・無効設定
//		音部記号選択イメージセレクトの有効・無効		setDisabledSelClefSymbol(val);
//		調号選択イメージセレクトの有効・無効			setDisabledSelKeySignature(val);
//		音部記号・調号設定イメージセレクトの有効・無効	setDisabledSelClefAndKeySignature(val);
//		拍子記号選択イメージセレクトの有効・無効		setDisabledSelTimeSignatureSymbol(val);
//		小節線選択イメージセレクトの有効・無効			setDisabledSelBarLine(val);
//		音符・休符、装飾ボタン等の有効・無効			setDisabledNoteRestButton(val="auto");
//##########################################################################

//=====================================================================
//	音部記号選択イメージセレクトの有効・無効設定
//		val 	true無効 | false有効
//=====================================================================
function setDisabledSelClefSymbol(val) {

	if (cfgSelClefSymbolDisabled == true) {
		val = true;
	}
	
	//クリック割り込み禁止
	disabledSelClefSymbol = val;		//独自拡張
	
	let elemDiv = document.getElementById("divClefSymbol");
	let elemsDiv = document.getElementsByClassName("selectDiv32");
	let elemsImg = document.getElementsByClassName("imgClefSymbol");
	
	//無効時
	if (val == true) {
		//背景をグレーに、cursorをdefaultに
		elemDiv.style.backgroundColor = "#F0F0F0";
		elemDiv.style.cursor = "default";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "default";
		}
		//イメージの透過率を0.7に、cursorをdefaultに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 0.4;
			elemsImg[i].style.cursor = "default";
		}

	//有効時
	} else {
		//背景を白に、cursorをpointerに
		elemDiv.style.backgroundColor = "#FFFFFF";
		elemDiv.style.cursor = "pointer";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "pointer";
		}
		//イメージの透過率を1.0に、cursorをpointerに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 1.0;
			elemsImg[i].style.cursor = "pointer";
		}
	}
}

//=====================================================================
//	調号選択イメージセレクトの有効・無効
//		val 	true無効 | false有効
//=====================================================================
function setDisabledSelKeySignature(val) {
	
	if (cfgSelKeySignatureDisabled == true) {
		val = true;
	}

	//クリック割り込み禁止
	disabledSelKeySignature = val;		//独自拡張
	
	let elemDiv = document.getElementById("divKeySignature");
	let elemsDiv = document.getElementsByClassName("selectDiv32");
	let elemsImg = document.getElementsByClassName("imgKeySignature");
	
	//無効時
	if (val == true) {
		//背景をグレーに、cursorをdefaultに
		elemDiv.style.backgroundColor = "#F0F0F0";
		elemDiv.style.cursor = "default";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "default";
		}
		//イメージの透過率を0.7に、cursorをdefaultに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 0.4;
			elemsImg[i].style.cursor = "default";
		}

	//有効時
	} else {
		//背景を白に、cursorをpointerに
		elemDiv.style.backgroundColor = "#FFFFFF";
		elemDiv.style.cursor = "pointer";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "pointer";
		}
		//イメージの透過率を1.0に、cursorをpointerに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 1.0;
			elemsImg[i].style.cursor = "pointer";
		}
	}
}

//=====================================================================
//	音部記号・調号設定イメージセレクトの有効・無効
//		val 	true無効 | false有効
//=====================================================================
function setDisabledSelClefAndKeySignature(val) {
	
	if (cfgSelKeySignatureDisabled == true) {
		val = true;
	}

	//クリック割り込み禁止
	disabledSelClefAndKeySignature = val;		//独自拡張
	
	let elemDiv = document.getElementById("divClefAndKeySignature");
	let elemsDiv = document.getElementsByClassName("selectDiv32");
	let elemsImg = document.getElementsByClassName("imgClefAndKeySignature");
	
	//無効時
	if (val == true) {
		//背景をグレーに、cursorをdefaultに
		elemDiv.style.backgroundColor = "#F0F0F0";
		elemDiv.style.cursor = "default";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "default";
		}
		//イメージの透過率を0.7に、cursorをdefaultに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 0.4;
			elemsImg[i].style.cursor = "default";
		}

	//有効時
	} else {
		//背景を白に、cursorをpointerに
		elemDiv.style.backgroundColor = "#FFFFFF";
		elemDiv.style.cursor = "pointer";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "pointer";
		}
		//イメージの透過率を1.0に、cursorをpointerに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 1.0;
			elemsImg[i].style.cursor = "pointer";
		}
	}
}


//=====================================================================
//	拍子記号選択イメージセレクトの有効・無効設定
//		val 	true無効 | false有効
//=====================================================================
function setDisabledSelTimeSignatureSymbol(val) {
	
	if (cfgSelTimeSignatureSymbolDisabled == true) {
		val = true;
	}

	//クリック割り込み禁止
	disabledSelTimeSignatureSymbol = val;		//独自拡張
	
	let elemDiv = document.getElementById("divTimeSignatureSymbol");
	let elemsDiv = document.getElementsByClassName("selectDiv32");
	let elemsImg = document.getElementsByClassName("imgTimeSignatureSymbol");
	
	//無効時
	if (val == true) {
		//背景をグレーに、cursorをdefaultに
		elemDiv.style.backgroundColor = "#F0F0F0";
		elemDiv.style.cursor = "default";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "default";
		}
		//イメージの透過率を0.7に、cursorをdefaultに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 0.4;
			elemsImg[i].style.cursor = "default";
		}
		
	//有効時
	} else {
		//背景を白に、cursorをpointerに
		elemDiv.style.backgroundColor = "#FFFFFF";
		elemDiv.style.cursor = "pointer";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "pointer";
		}
		//イメージの透過率を1.0に、cursorをpointerに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 1.0;
			elemsImg[i].style.cursor = "pointer";
		}
	}
}

//=====================================================================
//	小節線選択イメージセレクトの有効・無効設定
//		val 	true無効 | false有効
//=====================================================================
function setDisabledSelBarLine(val) {
	
	if (cfgSelBarLineDisabled == true) {
		val = true;
	}

	//クリック割り込み禁止
	disabledSelBarLine = val;		//独自拡張
	
	let elemDiv = document.getElementById("divBarLineLeft");
	let elemsDiv = document.getElementsByClassName("selectDiv32");
	let elemsImg = document.getElementsByClassName("imgBar");
	
	//無効時
	if (val == true) {
		//背景をグレーに、cursorをdefaultに
		elemDiv.style.backgroundColor = "#F0F0F0";
		elemDiv.style.cursor = "default";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "default";
		}
		//イメージの透過率を0.7に、cursorをdefaultに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 0.4;
			elemsImg[i].style.cursor = "default";
		}
		selBarLineEvent = false;
		selectBarLineLeft.setValue("|");
		
	//有効時
	} else {
		//背景を白に、cursorをpointerに
		elemDiv.style.backgroundColor = "#FFFFFF";
		elemDiv.style.cursor = "pointer";
		for (let i = 0; i < elemsDiv.length; i++) {
			elemsDiv[i].style.cursor = "pointer";
		}
		//イメージの透過率を1.0に、cursorをpointerに
		for (let i = 0; i < elemsImg.length; i++) {
			elemsImg[i].style.opacity = 1.0;
			elemsImg[i].style.cursor = "pointer";
		}
	}
}

//=====================================================================
//	音符・休符、装飾ボタン等の有効・無効設定
//		"disabled"強制無効化、、"enabled"強制有効化、"auto"この関数での自動判定
//		有効無効は、この関数内で評価する
//=====================================================================
function setDisabledNoteRestButton(val="auto") {
	//--------------------------------------------------
	//設定している強弱にselectを合わせる
	//--------------------------------------------------
	function setCurrentDynamics() {
		let idx = 0;
		if (selectDecoration) {
			for (let i = 0; i < selectDecoration.length; i++) {
				let tmp = DynamicsArr.indexOf(selectDecoration[i]);
				if (tmp != -1) {
					idx = tmp + 1;
					break;
				}
			}
		}
		document.getElementById("selDynamics").selectedIndex = idx;
		setFontDynamics(document.getElementById("selDynamics"), document.getElementById("selDynamics").value);
		return;
	}
	//--------------------------------------------------

	//--------------------------------------------------
	//設定している繰り返しにselectを合わせる
	//--------------------------------------------------
	function setCurrentRepeatSigns() {
		let idx = 0;
		if (selectDecoration) {
			for (let i = 0; i < selectDecoration.length; i++) {
				let tmp = RepeatSignsArr1.indexOf(selectDecoration[i]);
				if (tmp != -1) {
					idx = tmp + 1;
					break;
				}
			}
		}
		
		if (selectStartEnding) {
			if (idx == 0 && selectStartEnding != "") {
				let tmp = RepeatSignsArr2.indexOf("[" + selectStartEnding);
				if (tmp != -1) {
					idx = tmp + 6;
				}
			}
		}
		
		document.getElementById("selRepeatSigns").selectedIndex = idx;
		setFontRepeatSigns(document.getElementById("selRepeatSigns"), document.getElementById("selRepeatSigns").value);
		return;
	}
	//--------------------------------------------------

	elemsAll = document.getElementsByClassName("btnNoteRest");
	elemsNarowAll = document.getElementsByClassName("btnNoteRestNarrow");
	elemsNoRest = document.getElementsByClassName("noRest");

	//--------------------------------------------------
	//	"disabled"強制無効化
	//--------------------------------------------------
	if (val == "disabled") {
		//--------------------------------------------------
		//ここに来るのは、選択がない状態の場合なので、
		//（曲途中での変更対応のため）音部記号を 有効とする@@@
		
		stopChange++;
		
		setDisabledSelClefSymbol(false);

		//（曲途中での変更対応のため）調号を、基本設定の調合（currentKeySignature）が選択された状態とするする@@@
		document.getElementById("divKeySignature").style.display = "inline-block";
		document.getElementById("divClefAndKeySignature").style.display = "none";

		//（曲途中での変更対応のため）拍子記号を、基本設定の拍子記号（currentTimeSignatureSymbol）が選択された状態とするする@@@
		let tmp = currentTimeSignatureSymbol;
		if (tmp == "C" || tmp == "C|" || tmp == "2/2" || tmp == "4/4") {
			selectTimingSymbol.setValue(tmp + ",8");
		} else if (tmp == "3/2" || tmp == "6/4" || tmp == "12/8") {
			selectTimingSymbol.setValue(tmp + ",12");
		} else if (tmp == "2/4") {
			selectTimingSymbol.setValue(tmp + ",4");
		} else if (tmp == "3/4" || tmp == "6/8") {
			selectTimingSymbol.setValue(tmp + ",6");
		} else if (tmp == "3/8") {
			selectTimingSymbol.setValue(tmp + ",3");
		} else if (tmp == "9/8") {
			selectTimingSymbol.setValue(tmp + ",9");
		} else if (tmp == "5/4") {
			selectTimingSymbol.setValue(tmp + ",10");
		} else if (tmp == "5/8") {
			selectTimingSymbol.setValue(tmp + ",5");
		} else if (tmp == "7/8") {
			selectTimingSymbol.setValue(tmp + ",7");
		}
		document.getElementById("divTimeSignatureSymbolNone").style.display = "none";
		setDisabledSelTimeSignatureSymbol(false);

		//（曲途中での変更対応のため）速度記号を、基本設定の速度記号（currentTempoMarkings、currentTempoMarkings2）が選択された状態とするする@@@
		document.getElementById("selTempoMarkings").disabled = false;
		document.getElementById("txtTempoMarkings2").disabled = false;
		document.getElementById("btnTempoMarkings2").disabled = false;
		document.getElementById("selTempoMarkings").value = currentTempoMarkings;
		document.getElementById("txtTempoMarkings2").value = (currentTempoMarkings2 == "0") ? "" : currentTempoMarkings2;
		if (currentTempoMarkings2Base == "3/4") {
			document.getElementById("imgTempoMarkings2").src = "./imgMSC/note2dEqSel_22.png";
		} else if (currentTempoMarkings2Base == "1/2") {
			document.getElementById("imgTempoMarkings2").src = "./imgMSC/note2EqSel_22.png";
		} else if (currentTempoMarkings2Base == "3/8") {
			document.getElementById("imgTempoMarkings2").src = "./imgMSC/note4dEqSel_22.png";
		} else if (currentTempoMarkings2Base == "1/4") {
			document.getElementById("imgTempoMarkings2").src = "./imgMSC/note4EqSel_22.png";
		} else if (currentTempoMarkings2Base == "1/8") {
			document.getElementById("imgTempoMarkings2").src = "./imgMSC/note8EqSel_22.png";
		}

		stopChange--;


		//--------------------------------------------------

		for (let i = 0; i < elemsAll.length; i++) {
			elemsAll[i].disabled = true;
		}
		for (let i = 0; i < elemsNarowAll.length; i++) {
			elemsNarowAll[i].disabled = true;
		}
		document.getElementById("selDynamics").disabled = true;
		document.getElementById("selRepeatSigns").disabled = true;
		document.getElementById("selDynamics").selectedIndex = 0;
		document.getElementById("selRepeatSigns").selectedIndex = 0;
		setFontDynamics(document.getElementById("selDynamics"), document.getElementById("selDynamics").value);
		setFontRepeatSigns(document.getElementById("selRepeatSigns"), document.getElementById("selRepeatSigns").value);

		//追加のアーティキュレーションを非表示
		document.getElementById("divOptionArticulation").style.display = "none";

		document.getElementById("imgSeparate").src = "./imgMSC/separate22.png";
		document.getElementById("imgJoin").src = "./imgMSC/join22.png";

	//--------------------------------------------------
	//	"enabled"強制有効化（使われていない）
	//--------------------------------------------------
	} else if (val == "enabled") {
		for (let i = 0; i < elemsAll.length; i++) {
			elemsAll[i].disabled = false;
		}
		for (let i = 0; i < elemsNarowAll.length; i++) {
			elemsNarowAll[i].disabled = false;
		}
		document.getElementById("selDynamics").disabled = false;
		document.getElementById("selRepeatSigns").disabled = false;
		setCurrentDynamics();
		setCurrentRepeatSigns();

		//追加のアーティキュレーションを非表示
		document.getElementById("divOptionArticulation").style.display = "none";

	//--------------------------------------------------
	//	"auto"この関数での自動判定
	//--------------------------------------------------
	} else {

		//--------------------------------------------------
		//ここに来るのは、小節線、音符、休符のいずれかが選択状態の場合なので、
		//（曲途中での変更対応のため）音部記号を 無効とする@@@
		stopChange++;
		
		//音部記号を無効とする
		setDisabledSelClefSymbol(true);
		
		//拍子記号のなし選択肢を表示
		document.getElementById("divTimeSignatureSymbolNone").style.display = "";

		//選択小節線や音符・休符直後の設定を取得
		//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"72 | 120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
		let res = getAfterSettings();
		
	//console.log(res);
		
		//---------------------------------------------------------------
		//１段の場合
		//---------------------------------------------------------------
		if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
		
			let elems = document.getElementsByClassName("keySignature");

			//段の終端の小節線（音部記号、調号、拍子記号、速度記号）
			//	次段の先頭が、[V][K:clef=bass][K:F][M:3/4][Q:"Largo"] のような構成
			if (res[8] == "btmBar") {
				//調号を表示
				for (let i = 0; i < elems.length; i++) {
					elems[i].style.display = "";
				}
				//拍子記号
				var useTimeSignatureSymbol = true;
				//速度記号
				var useTempoMarkings = true;
			
			//段の先頭の小節線（音部記号、拍子記号、速度記号）
			//	小節線の直後が、[K:clef=bass][K:F][M:3/4][Q:"Largo"] のような構成
			} else if (res[8] == "topBar") {
				//調号を非表示
				for (let i = 0; i < elems.length; i++) {
					elems[i].style.display = "";
				}
				//拍子記号
				var useTimeSignatureSymbol = true;
				//速度記号
				var useTempoMarkings = true;
			
			//先頭でも最終でもない小節線（音部記号、拍子記号、速度記号）
			//	小節線の直後が、[K:clef=bass][Q:"Largo"] のような構成
			} else if (res[8] == "midBar") {
				//調号を非表示
				for (let i = 0; i < elems.length; i++) {
					elems[i].style.display = "none";
				}
				//拍子記号
				var useTimeSignatureSymbol = true;
				//速度記号
				var useTempoMarkings = true;
			
			//音符・休符（音部記号、速度記号）
			//	音符・休符の直後が、[K:clef=bass][Q:"Largo"] のような構成
			} else {
				//調号を非表示
				for (let i = 0; i < elems.length; i++) {
					elems[i].style.display = "none";
				}
				//拍子記号
				selectTimingSymbol.setValue("0,0");
				setDisabledSelTimeSignatureSymbol(true);
				var useTimeSignatureSymbol = false;
				//速度記号
				var useTempoMarkings = false;
			}
			
			//拍子記号
			if (useTimeSignatureSymbol == true) {
				let tmp = res[4];
				if (tmp == "none") {
					selectTimingSymbol.setValue("0,0");
				} else if (tmp == "C" || tmp == "C|" || tmp == "2/2" || tmp == "4/4") {
					selectTimingSymbol.setValue(tmp + ",8");
				} else if (tmp == "3/2" || tmp == "6/4" || tmp == "12/8") {
					selectTimingSymbol.setValue(tmp + ",12");
				} else if (tmp == "2/4") {
					selectTimingSymbol.setValue(tmp + ",4");
				} else if (tmp == "3/4" || tmp == "6/8") {
					selectTimingSymbol.setValue(tmp + ",6");
				} else if (tmp == "3/8") {
					selectTimingSymbol.setValue(tmp + ",3");
				} else if (tmp == "9/8") {
					selectTimingSymbol.setValue(tmp + ",9");
				} else if (tmp == "5/4") {
					selectTimingSymbol.setValue(tmp + ",10");
				} else if (tmp == "5/8") {
					selectTimingSymbol.setValue(tmp + ",5");
				} else if (tmp == "7/8") {
					selectTimingSymbol.setValue(tmp + ",7");
				}
				setDisabledSelTimeSignatureSymbol(false);
			}

			//音部記号・調号設定とし、値を設定
			document.getElementById("divKeySignature").style.display = "none";
			document.getElementById("divClefAndKeySignature").style.display = "inline-block";
			selectClefAndKeySignature.setValue(res[7]);

			//速度記号
			if (useTempoMarkings == true) {
				document.getElementById("selTempoMarkings").value = res[5];
				document.getElementById("txtTempoMarkings2").value = (res[6] == "0") ? "" : res[6];
				document.getElementById("selTempoMarkings").disabled = false;
				document.getElementById("txtTempoMarkings2").disabled = false;
				document.getElementById("btnTempoMarkings2").disabled = false;
			} else {
				document.getElementById("selTempoMarkings").selectedIndex = -1;
				document.getElementById("txtTempoMarkings2").value = "";
				document.getElementById("selTempoMarkings").disabled = true;
				document.getElementById("txtTempoMarkings2").disabled = true;
				document.getElementById("btnTempoMarkings2").disabled = true;
			}

			//最終行、最終小節の場合
			if (selectVisualDataIndex == currentVisualArray.length-1 && res[8] == "btmBar") {
				setDisabledSelClefAndKeySignature(true);
				setDisabledSelTimeSignatureSymbol(true);
				document.getElementById("selTempoMarkings").selectedIndex = -1;
				document.getElementById("txtTempoMarkings2").value = "";
				document.getElementById("selTempoMarkings").disabled = true;
				document.getElementById("txtTempoMarkings2").disabled = true;
				document.getElementById("btnTempoMarkings2").disabled = true;
			}
		
		//---------------------------------------------------------------
		//２段の場合
		//---------------------------------------------------------------
		} else {
			
			let elems = document.getElementsByClassName("keySignature");

			//---------------------------------------------------------------------
			//下段への設定（lineとx座標が同一の小節線の直後に挿入、挿入文字列は、再構築する必要がある）
			//---------------------------------------------------------------------
			var idx = 0;
			if (selectNoteOrRest == "bar") {
				//選択中の小節線のx座標
				let xPos = currentVisualArray[selectVisualDataIndex].absEl.x;
				idx = -1;
				//同一x座標の小節線の検索
				for (let i = selectVisualDataIndex+1; i < currentVisualArray.length; i++) {
					if (currentVisualArray[i].absEl.counters) {
						if (currentVisualArray[i].absEl.counters.line != currentLineNo) break;
					}
					if (currentVisualArray[i].absEl.type == "bar" && currentVisualArray[i].absEl.x == xPos) {
						idx = i;
						break;
					}
				}
			}

			//段の終端の小節線（音部記号、調号、拍子記号、速度記号）
			//	次段の先頭が、[V][K:clef=bass][K:F][M:3/4][Q:"Largo"] のような構成
			if (res[8] == "btmBar") {
				//調号を表示
				for (let i = 0; i < elems.length; i++) {
					elems[i].style.display = "";
				}
				//拍子記号
				var useTimeSignatureSymbol = true;
				//速度記号
				var useTempoMarkings = true;
			
			
			//段の先頭の小節線（音部記号、拍子記号、速度記号）
			//	小節線の直後が、[K:clef=bass][K:F][M:3/4][Q:"Largo"] のような構成
			} else if (res[8] == "topBar") {
				//調号を非表示
				for (let i = 0; i < elems.length; i++) {
					elems[i].style.display = "none";
				}
				//拍子記号
				var useTimeSignatureSymbol = true;
				//速度記号
				var useTempoMarkings = true;
			
			//先頭でも最終でもない小節線（音部記号、拍子記号、速度記号）
			//	小節線の直後が、[K:clef=bass][Q:"Largo"] のような構成
			} else if (res[8] == "midBar") {
				//調号を非表示
				for (let i = 0; i < elems.length; i++) {
					elems[i].style.display = "none";
				}
				//拍子記号
				var useTimeSignatureSymbol = true;
				//速度記号
				var useTempoMarkings = true;
			
			//音符・休符（音部記号、速度記号）
			//	音符・休符の直後が、[K:clef=bass][Q:"Largo"] のような構成
			} else {
				//調号を非表示
				for (let i = 0; i < elems.length; i++) {
					elems[i].style.display = "none";
				}
				//拍子記号
				selectTimingSymbol.setValue("0,0");
				setDisabledSelTimeSignatureSymbol(true);
				var useTimeSignatureSymbol = false;
				//速度記号
				var useTempoMarkings = false;
			}

			//-------------------------------------------------------
			//音部記号・調号設定 res[8]=topBar|midBar|btmBar / res[9]=danUp(true|false)
			//-------------------------------------------------------
			//（曲途中での変更対応のため）調号を、音部記号・調号設定とし、主旋律の場合のみ有効とし、小節線や音符・休符直後の設定とする@@@
			document.getElementById("divKeySignature").style.display = "none";
			document.getElementById("divClefAndKeySignature").style.display = "inline-block";
			
			selectClefAndKeySignature.setValue("");
			//if (isMainVoice() == true) {
			if (v_isMainVoice == true) {
				selectClefAndKeySignature.setValue(res[7]);		//"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"
				setDisabledSelClefAndKeySignature(false);
			} else {
				selectClefAndKeySignature.setValue("");
				setDisabledSelClefAndKeySignature(true);
			}

			//-------------------------------------------------------
			//拍子設定
			//-------------------------------------------------------
			//（曲途中での変更対応のため）拍子記号を、小節線、voice==0の場合のみ有効とし、小節線直後の拍子設定とする@@@
			if (useTimeSignatureSymbol == true && res[9] == true) {
				document.getElementById("divTimeSignatureSymbolNone").style.display = "";
				let tmp = res[4];				//4:" C | 3/4 | ..."
				if (tmp == "none") {
					selectTimingSymbol.setValue("0,0");
				} else if (tmp == "C" || tmp == "C|" || tmp == "2/2" || tmp == "4/4") {
					selectTimingSymbol.setValue(tmp + ",8");
				} else if (tmp == "3/2" || tmp == "6/4" || tmp == "12/8") {
					selectTimingSymbol.setValue(tmp + ",12");
				} else if (tmp == "2/4") {
					selectTimingSymbol.setValue(tmp + ",4");
				} else if (tmp == "3/4" || tmp == "6/8") {
					selectTimingSymbol.setValue(tmp + ",6");
				} else if (tmp == "3/8") {
					selectTimingSymbol.setValue(tmp + ",3");
				} else if (tmp == "9/8") {
					selectTimingSymbol.setValue(tmp + ",9");
				} else if (tmp == "5/4") {
					selectTimingSymbol.setValue(tmp + ",10");
				} else if (tmp == "5/8") {
					selectTimingSymbol.setValue(tmp + ",5");
				} else if (tmp == "7/8") {
					selectTimingSymbol.setValue(tmp + ",7");
				}
				setDisabledSelTimeSignatureSymbol(false);
			} else {
				document.getElementById("divTimeSignatureSymbolNone").style.display = "";
				selectTimingSymbol.setValue("0,0");
				setDisabledSelTimeSignatureSymbol(true);
			}

			//-------------------------------------------------------
			//速度設定 res[8]=topBar|midBar|btmBar / res[9]=danUp(true|false)
			//-------------------------------------------------------
			//（曲途中での変更対応のため）速度記号を、小節線で、voice==0の場合のみ有効とし、小節線直後の速度設定とする@@@
			if (useTempoMarkings == true && res[9] == true) {
				document.getElementById("selTempoMarkings").value = res[5];
				document.getElementById("txtTempoMarkings2").value = (res[6] == "0") ? "" : res[6];
				document.getElementById("selTempoMarkings").disabled = false;
				document.getElementById("txtTempoMarkings2").disabled = false;
				document.getElementById("btnTempoMarkings2").disabled = false;
			} else {
				document.getElementById("selTempoMarkings").selectedIndex = -1;
				document.getElementById("txtTempoMarkings2").value = "";
				document.getElementById("selTempoMarkings").disabled = true;
				document.getElementById("txtTempoMarkings2").disabled = true;
				document.getElementById("btnTempoMarkings2").disabled = true;
			}
			
			//最終の小節線の場合は、音部記号・調号設定、拍子記号、速度記号を無効とする
			if (res[8] == "btmBar") {
				if (currentVisualArray[selectVisualDataIndex-1].absEl.counters.line == currentRowsCount-1) {
					setDisabledSelClefAndKeySignature(true);
					setDisabledSelTimeSignatureSymbol(true);
					document.getElementById("selTempoMarkings").selectedIndex = -1;
					document.getElementById("txtTempoMarkings2").value = "";
					document.getElementById("selTempoMarkings").disabled = true;
					document.getElementById("txtTempoMarkings2").disabled = true;
					document.getElementById("btnTempoMarkings2").disabled = true;
				
				}
			}
			
			//上段直下に下段の小節線がない場合は、拍子記号、速度記号を無効とする
			if (idx == -1) {
				setDisabledSelTimeSignatureSymbol(true);
				document.getElementById("selTempoMarkings").selectedIndex = -1;
				document.getElementById("txtTempoMarkings2").value = "";
				document.getElementById("selTempoMarkings").disabled = true;
				document.getElementById("txtTempoMarkings2").disabled = true;
				document.getElementById("btnTempoMarkings2").disabled = true;
			}
		}
		stopChange--;

		//--------------------------------------------------

		//小節線では、反復以外、すべて無効
		if (selectNoteOrRest == "bar") {
			for (let i = 0; i < elemsAll.length; i++) {
				elemsAll[i].disabled = true;
			}
			for (let i = 0; i < elemsNarowAll.length; i++) {
				elemsNarowAll[i].disabled = true;
			}
			document.getElementById("selDynamics").disabled = true;
			document.getElementById("selDynamics").selectedIndex = 0;
			setFontDynamics(document.getElementById("selDynamics"), document.getElementById("selDynamics").value);

			if (currentVisualArray[selectVisualDataIndex-1].absEl.type != "bar") {
				var voice = currentVisualArray[selectVisualDataIndex-1].absEl.counters.voice;
			} else {
				var voice = currentVisualArray[selectVisualDataIndex+1].absEl.counters.voice;
			}
			document.getElementById("selRepeatSigns").disabled = (voice != 0);
			setCurrentRepeatSigns();
			
			//ブレスの有効化
			document.getElementById("btnNoBreath").disabled = false;
			document.getElementById("btnBreath").disabled = false;
			
			//追加のアーティキュレーションを非表示
			document.getElementById("divOptionArticulation").style.display = "none";

		//音符と休符
		} else {

			//----------------------------------------------------------
			//反復以外を、一旦全て有効とする
			//----------------------------------------------------------
			for (let i = 0; i < elemsAll.length; i++) {
				elemsAll[i].disabled = false;
			}
			for (let i = 0; i < elemsNarowAll.length; i++) {
				elemsNarowAll[i].disabled = false;
			}
			document.getElementById("selDynamics").disabled = false;
			setCurrentDynamics();
			document.getElementById("selRepeatSigns").disabled = true;
			document.getElementById("selRepeatSigns").selectedIndex = 0;
			setFontRepeatSigns(document.getElementById("selRepeatSigns"), document.getElementById("selRepeatSigns").value);

			//----------------------------------------------------------
			//追加のアーティキュレーションを非表示
			//----------------------------------------------------------
			document.getElementById("divOptionArticulation").style.display = "none";

			//----------------------------------------------------------
			//休符では、無効とするもの
			//----------------------------------------------------------
			if (selectNoteOrRest == "rest") {
				for (let i = 0; i < elemsNoRest.length; i++) {
					elemsNoRest[i].disabled = true;
				}
				for (let i = 0; i < elemsNarowAll.length; i++) {
					elemsNarowAll[i].disabled = true;
				}
				//ブレスの有効化
				if (selectNoteStr.trim() != "Z") {
					document.getElementById("btnNoBreath").disabled = false;
					document.getElementById("btnBreath").disabled = false;
				}
			}
			
			//----------------------------------------------------------
			//選択以降の長さ（selectDuration+selectBarAfterLen）が ボタン音長（elemsAll[i].value）より長い音符・休符を無効に
			//----------------------------------------------------------@@@
			for (let i = 0; i < elemsAll.length; i++) {
				if (selectDuration+selectBarAfterLen < parseFloat(elemsAll[i].value)) {
					elemsAll[i].disabled = true;
				}
			}
			
			//----------------------------------------------------------
			//小節の残り音長（selectDuration+selectBarAfterLen）が、小節長と等しい＝小節先頭　の場合、全休符を有効にして、その長さの給付を無効にする
			//----------------------------------------------------------
			if (selectDuration+selectBarAfterLen == countByBarArr[currentLineNo][currentMeasureNo]) {
				if (document.getElementById("btnRest" + countByBarArr[currentLineNo][currentMeasureNo])) {
					document.getElementById("btnRest" + countByBarArr[currentLineNo][currentMeasureNo]).disabled = true;
				}
				document.getElementById("btnRest8").disabled = false;
			}
			
			//----------------------------------------------------------
			//	追加の音符・休符ボタン
			//----------------------------------------------------------
			document.getElementById("btnOtherNoteAndRest").disabled = false;

			//----------------------------------------------------------
			//シャープ、フラット、ナチュラルの解除ボタンの無効化（選択範囲内の、^_=[abcdefgABCDEFG] の存否
			//----------------------------------------------------------
			// 正規表現で ^ _ = の後に a-g または A-G が続く場合に一致するパターン
			const pattern = /[\^_=][abcdefgABCDEFG]/;
			// パターンに一致するかどうかを確認
			if (pattern.test(selectNoteStr) == true) {
				document.getElementById("btnSharpFlatRemove").disabled = false;
				
				//フラットの場合は、イメージをダブルフラットにする
				const patternFlatDbl = /__(?=[abcdefgABCDEFG])/g;
				const patternFlat = /_(?=[abcdefgABCDEFG])/g;
				if (patternFlatDbl.test(selectNoteStr) == true) {
					document.getElementById("imgSharpFlatFlat").src = "./imgMSC/flat22.png";
				} else if (patternFlat.test(selectNoteStr) == true) {
					document.getElementById("imgSharpFlatFlat").src = "./imgMSC/flatDbl22.png";
				} else {
					document.getElementById("imgSharpFlatFlat").src = "./imgMSC/flat22.png";
				}
				
				//シャープの場合は、イメージをダブルシャープにする
				const patternSharpDbl = /\^\^(?=[abcdefgABCDEFG])/g;
				const patternSharp = /\^(?=[abcdefgABCDEFG])/g;
				if (patternSharpDbl.test(selectNoteStr) == true) {
					document.getElementById("imgSharpFlatSharp").src = "./imgMSC/sharp22.png";
				} else if (patternSharp.test(selectNoteStr) == true) {
					document.getElementById("imgSharpFlatSharp").src = "./imgMSC/sharpDbl22.png";
				} else {
					document.getElementById("imgSharpFlatSharp").src = "./imgMSC/sharp22.png";
				}
				
			} else {
				document.getElementById("btnSharpFlatRemove").disabled = true;
				document.getElementById("imgSharpFlatFlat").src = "./imgMSC/flat22.png";
				document.getElementById("imgSharpFlatSharp").src = "./imgMSC/sharp22.png";
			}

			//----------------------------------------------------------
			//タイ・スラー設定・解除ボタンの無効化
			//----------------------------------------------------------
			if (selectPitches.length > 0) {
				let pitches = selectPitches;

				if (pitches) {
					//開始設定（無効条件：startTie、stratSlurともにある or 和音でstartSlurがある）
					if ((pitches[0].startTie && pitches[0].startSlur) || (pitches.length > 1 && pitches[0].startSlur)) {
						document.getElementById("btnTaiSlurSt").disabled = true;
					}
					//終了設定（endSlurがある）
					if (pitches[pitches.length-1].endSlur) {
						document.getElementById("btnTaiSlurEd").disabled = true;
					}

					//開始解除（startTie,startSlurともにない）
					if (!(pitches[0].startTie || pitches[0].startSlur)) {
						document.getElementById("btnTaiSlurStDel").disabled = true;
					}
					//終了解除（endTie,endSlurともにない）
					if (!(pitches[pitches.length-1].endTie || pitches[pitches.length-1].endSlur)) {
						document.getElementById("btnTaiSlurEdDel").disabled = true;
					}
				}
			}

			//----------------------------------------------------------
			//和音解除ボタンの無効化
			//----------------------------------------------------------
			if (selectPitches.length == 1) {
				//document.getElementById("btnChordRemove").disabled = true;

				//---------------------------------------------------------
				//	装飾音符の設定	@@@
				//---------------------------------------------------------
				//document.getElementById("btnNoteArt").disabled = true;
			}

			//----------------------------------------------------------
			//複旋律関連
			//----------------------------------------------------------
			if (selectNoteStr != "Z") {
				//---------------------------------------------------------
				//	複旋律の追加（音符・休符の選択状態で、現在の小節内に & がない場合、有効）	@@@
				//---------------------------------------------------------
				var tmp = currentAbcString.substring(selectBarStartIndex, selectBarEndIndex);
				document.getElementById("btnNoteAdd").disabled = (tmp.indexOf("&") != -1);
				//---------------------------------------------------------
				//	複旋律の削除（音符・休符の選択状態で、現在の小節内に & がある場合、有効）	@@@
				//---------------------------------------------------------
				document.getElementById("btnNoteAddDel").disabled = (tmp.indexOf("&") == -1);
			} else {
				document.getElementById("btnNoteAdd").disabled = true;
				document.getElementById("btnNoteAddDel").disabled = true;
			}


			//----------------------------------------------------------
			//不完全小節関連
			//----------------------------------------------------------
			//---------------------------------------------------------
			//	音符・休符の削除（不完全小節化）（小節内に選択中の音符・休符以外の音符・休符が存在する場合に有効）	@@@
			//		選択音符・休符のline番号（line）、小節番号（）、音声番号（voice）
			//---------------------------------------------------------
			if (selectBarBeforeLen == 0 && selectBarAfterLen == 0) {
				document.getElementById("btnNoteDel").disabled = true;
			}

			//---------------------------------------------------------
			//	完全小節に戻す（不完全小節＝小節長!=小節内の音符・休符の音長の総和が異なる場合有効）	@@@
			//---------------------------------------------------------
			if (selectBarBeforeLen + selectDuration + selectBarAfterLen == countByBarArr[currentLineNo][currentMeasureNo]) {
				document.getElementById("btnNoteOrg").disabled = true;
			}


			//----------------------------------------------------------
			//８分音符、16分音符の髭の連続の有無ボタンの無効化
			//----------------------------------------------------------
			document.getElementById("imgSeparate").src = "./imgMSC/separate22.png";
			document.getElementById("imgJoin").src = "./imgMSC/join22.png";
			if (selectVisualDataIndex != -1) {
				//８分音符以下で、右隣りが音符
				if (selectNoteOrRest == "note" && selectDuration < 2 && currentVisualArray[selectVisualDataIndex+1].absEl.type == "note") {
					//右隣りが、８分音符、16分音符の場合
					if (currentVisualArray[selectVisualDataIndex+1].absEl.duration < 0.25) {			//??
						//選択abcStringの終端が" "の場合は、分離している（分離ボタンを無効にする）
						if (selectNoteStr.substr(-1) == " ") {
							document.getElementById("btnNoteSeparate").disabled = true;
						//選択abcStringの終端が" "以外の場合は、結合している（結合ボタンを無効にする）
						} else {
							document.getElementById("btnNoteJoin").disabled = true;
						}
					//右隣りが、８分音符、16分音符の場合以外なので、分離・結合の両ボタンを無効にする
					} else {
						document.getElementById("btnNoteSeparate").disabled = true;
						document.getElementById("btnNoteJoin").disabled = true;
					}

				//８分休符以下で、右隣りが音符
				} else if (selectNoteOrRest == "rest" && selectDuration < 2 && currentVisualArray[selectVisualDataIndex+1].absEl.type == "note") {
					//右隣りが、８分音符、16分音符の場合
					if (currentVisualArray[selectVisualDataIndex+1].absEl.duration < 0.25) {			//??
						//選択abcStringの終端が" "の場合は、分離している（分離ボタンを無効にする）
						document.getElementById("imgSeparate").src = "./imgMSC/separateRest22.png";
						document.getElementById("imgJoin").src = "./imgMSC/joinRest22.png";
						if (selectNoteStr.substr(-1) == " ") {
							document.getElementById("btnNoteSeparate").disabled = true;
							document.getElementById("btnNoteJoin").disabled = false;
							
						//選択abcStringの終端が" "以外の場合は、結合している（結合ボタンを無効にする）
						} else {
							document.getElementById("btnNoteSeparate").disabled = false;
							document.getElementById("btnNoteJoin").disabled = true;
						}
					//右隣りが、８分音符、16分音符の場合以外なので、分離・結合の両ボタンを無効にする
					} else {
						document.getElementById("btnNoteSeparate").disabled = true;
						document.getElementById("btnNoteJoin").disabled = true;
					}

				//選択が、音符でない又は、音符でも８分音符、16分音符ではないので、分離・結合の両ボタンを無効にする
				} else {
					document.getElementById("btnNoteSeparate").disabled = true;
					document.getElementById("btnNoteJoin").disabled = true;
				}
			} else {
				document.getElementById("btnNoteSeparate").disabled = true;
				document.getElementById("btnNoteJoin").disabled = true;
			}

			//----------------------------------------------------------
			//３連符の設定、解除ボタンボタンの無効化
			//５連符の設定、解除ボタンボタンの無効化
			//----------------------------------------------------------
			if (selectVisualDataIndex != -1) {

				if (selectNoteStr.trim() == "Z") {
					var durationRatio = countByBarArr[currentLineNo][currentMeasureNo]/8;
				} else {
					var durationRatio = 1.0;
				}

				//３連符である
				if (getCurrentTripletsNumber() != 0) {		//OK	３連符であるか否かの評価
					//音符休符ボタンをすべて無効
					//	（３連符の長さ変更は、処理がややこしいので、当面は、できないこととする）
					for (let i = 0; i < elemsAll.length; i++) {
						if (elemsAll[i].value != "0" && elemsAll[i].value != currentVisualArray[selectVisualDataIndex].absEl.abcelem.duration * 8) {
							elemsAll[i].disabled = true;
						}
					}

					//８分音符、16分音符の接続・分離ボタンを無効に（３連符の３番目の場合は有効にする）
					//	getCurrentTripletsNumber();	//0=３連符音符ではない、1-3=n番目の音符（1は先頭、3は右端）
					if (getCurrentTripletsNumber() < 3) {
						document.getElementById("btnNoteSeparate").disabled = true;
						document.getElementById("btnNoteJoin").disabled = true;
					}
					//３連符設定ボタンを無効に
					document.getElementById("btnSetTriplets").disabled = true;
					document.getElementById("btnSetTriplets2").disabled = true;
					//５連符設定ボタンを無効に
					document.getElementById("btnSetQuintuplet2").disabled = true;
					//５連符解除ボタンを無効に
					document.getElementById("btnDelQuintuplet2").disabled = true;


				//５連符である
				} else if (getCurrentQuintupletNumber() != 0) {		//OK	５連符であるか否かの評価
					//音符休符ボタンをすべて無効
					//	（５連符の長さ変更は、処理がややこしいので、当面は、できないこととする）
					for (let i = 0; i < elemsAll.length; i++) {
						if (elemsAll[i].value != "0" && elemsAll[i].value != currentVisualArray[selectVisualDataIndex].absEl.abcelem.duration * 8) {
							elemsAll[i].disabled = true;
						}
					}

					//８分音符、16分音符の接続・分離ボタンを無効に（３連符の３番目の場合は有効にする）
					//	getCurrentQuintupletNumber();	//0=５連符音符ではない、1-5=n番目の音符（1は先頭、5は右端）
					if (getCurrentQuintupletNumber() < 5) {
						document.getElementById("btnNoteSeparate").disabled = true;
						document.getElementById("btnNoteJoin").disabled = true;
					}
					//５連符設定ボタンを無効に
					document.getElementById("btnSetQuintuplet2").disabled = true;
					//３連符設定ボタンを無効に
					document.getElementById("btnSetTriplets").disabled = true;
					document.getElementById("btnSetTriplets2").disabled = true;
					//３連符解除ボタンを無効に
					document.getElementById("btnDelTriplets").disabled = true;
					document.getElementById("btnDelTriplets2").disabled = true;


				//３連符でも５連符でもない
				} else {
					//３連符解除ボタンを無効に
					document.getElementById("btnDelTriplets").disabled = true;
					document.getElementById("btnDelTriplets2").disabled = true;
					//５連符解除ボタンを無効に
					document.getElementById("btnDelQuintuplet2").disabled = true;
				}

			} else {
				//３連符設定ボタンを無効に
				document.getElementById("btnSetTriplets").disabled = true;
				document.getElementById("btnSetTriplets2").disabled = true;
				//３連符解除ボタンを無効に
				document.getElementById("btnDelTriplets").disabled = true;
				document.getElementById("btnDelTriplets2").disabled = true;
				
				//５連符設定ボタンを無効に
				document.getElementById("btnSetQuintuplet2").disabled = true;
				//５連符解除ボタンを無効に
				document.getElementById("btnDelQuintuplet2").disabled = true;
			}
		}

		//-------------------------------------------------
		//「メニュー設定」で無効のものを無効にする
		//-------------------------------------------------
		//音符
		if (cfgBtnNoteDisabled || cfgBtnNote8Disabled) document.getElementById("btnNote8").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote6Disabled) document.getElementById("btnNote6").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote4Disabled) document.getElementById("btnNote4").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote3Disabled) document.getElementById("btnNote3").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote2Disabled) document.getElementById("btnNote2").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote1_5Disabled) document.getElementById("btnNote1_5").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote1Disabled) document.getElementById("btnNote1").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote1Disabled) document.getElementById("btnNote1o").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote0_75Disabled) document.getElementById("btnNote0_75").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote0_5Disabled) document.getElementById("btnNote0_5").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote0_5Disabled) document.getElementById("btnNote0_5o").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote0_375Disabled) document.getElementById("btnNote0_375").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote0_25Disabled) document.getElementById("btnNote0_25").disabled = true;
		if (cfgBtnNoteDisabled || cfgBtnNote0_125Disabled) document.getElementById("btnNote0_125").disabled = true;

		//休符
		if (cfgBtnRestDisabled || cfgBtnRest8Disabled) document.getElementById("btnRest8").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest6Disabled) document.getElementById("btnRest6").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest4Disabled) document.getElementById("btnRest4").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest3Disabled) document.getElementById("btnRest3").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest2Disabled) document.getElementById("btnRest2").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest1_5Disabled) document.getElementById("btnRest1_5").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest1Disabled) document.getElementById("btnRest1").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest1Disabled) document.getElementById("btnRest1o").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest0_75Disabled) document.getElementById("btnRest0_75").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest0_5Disabled) document.getElementById("btnRest0_5").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest0_5Disabled) document.getElementById("btnRest0_5o").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest0_375Disabled) document.getElementById("btnRest0_375").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest0_25Disabled) document.getElementById("btnRest0_25").disabled = true;
		if (cfgBtnRestDisabled || cfgBtnRest0_125Disabled) document.getElementById("btnRest0_125").disabled = true;

		//オプション音符・休符
		if ((cfgBtnNoteDisabled && cfgBtnRestDisabled) ||
			(cfgBtnNote1Disabled && cfgBtnNote0_75Disabled && cfgBtnNote0_5Disabled && cfgBtnNote0_375Disabled && cfgBtnNote0_25Disabled && cfgBtnNote0_125Disabled &&
			 cfgBtnRest1Disabled && cfgBtnRest0_75Disabled && cfgBtnRest0_5Disabled && cfgBtnRest0_375Disabled && cfgBtnRest0_25Disabled && cfgBtnRest0_125Disabled) ) {
			document.getElementById("btnOtherNoteAndRest").disabled = true;
		}
		
		//臨時記号
		if (cfgBtnSharpFlatDisabled || cfgBtnSharpFlatSharpDisabled) document.getElementById("btnSharpFlatSharp").disabled = true;
		if (cfgBtnSharpFlatDisabled || cfgBtnSharpFlatFlatDisabled) document.getElementById("btnSharpFlatFlat").disabled = true;
		if (cfgBtnSharpFlatDisabled || cfgBtnSharpFlatNaturalDisabled) document.getElementById("btnSharpFlatNatural").disabled = true;
		if (cfgBtnSharpFlatDisabled || (cfgBtnSharpFlatSharpDisabled && cfgBtnSharpFlatFlatDisabled && cfgBtnSharpFlatNaturalDisabled) ) document.getElementById("btnSharpFlatRemove").disabled = true;

		//タイ・スラー
		if (cfgBtnTaiSlurDisabled || (cfgBtnTaiSlurTaiDisabled && cfgBtnTaiSlurSlurDisabled) ) {
			document.getElementById("btnTaiSlurSt").disabled = true;
			document.getElementById("btnTaiSlurEd").disabled = true;
			document.getElementById("btnTaiSlurStDel").disabled = true;
			document.getElementById("btnTaiSlurEdDel").disabled = true;
		} else if (cfgBtnTaiSlurSlurDisabled) {
			document.getElementById("btnTaiSlurEd").disabled = true;
			document.getElementById("btnTaiSlurEdDel").disabled = true;
		}

		//ブレス
		if (cfgBtnBreathDisabled) {
			document.getElementById("btnNoBreath").disabled = true;
			document.getElementById("btnBreath").disabled = true;
		}
		
		//アーティキュレーション
		if (cfgBtnArticulationDisabled || cfgBtnArticulationAccentDisabled) document.getElementById("btnArticulationAccent").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationStaccatoDisabled) document.getElementById("btnArticulationStaccato").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationStaccatissimoDisabled) document.getElementById("btnArticulationStaccatissimo").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationUpbowDisabled) document.getElementById("btnArticulationUpbow").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationDownbowDisabled) document.getElementById("btnArticulationDownbow").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationRollDisabled) document.getElementById("btnArticulationRoll").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationTenutoDisabled) document.getElementById("btnArticulationTenuto").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationLowermordentDisabled) document.getElementById("btnArticulationLowermordent").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationUppermordentDisabled) document.getElementById("btnArticulationUppermordent").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationTrillDisabled) document.getElementById("btnArticulationTrill").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationTurnDisabled) document.getElementById("btnArticulationTurn").disabled = true;
		if (cfgBtnArticulationDisabled || cfgBtnArticulationFermataDisabled) document.getElementById("btnArticulationFermata").disabled = true;
		//アーティキュレーションの削除ボタン
		if ((cfgBtnArticulationDisabled) ||
			(cfgBtnArticulationAccentDisabled && cfgBtnArticulationStaccatoDisabled && cfgBtnArticulationStaccatissimoDisabled && cfgBtnArticulationUpbowDisabled &&
			 cfgBtnArticulationDownbowDisabled && cfgBtnArticulationRollDisabled && cfgBtnArticulationTenutoDisabled && cfgBtnArticulationLowermordentDisabled &&
			 cfgBtnArticulationUppermordentDisabled && cfgBtnArticulationTrillDisabled && cfgBtnArticulationTurnDisabled && cfgBtnArticulationFermataDisabled) ) {
			document.getElementById("btnNoArticulation").disabled = true;
			document.getElementById("btnNoArticulation2").disabled = true;
		}
		//オプションのアーティキュレーションボタン
		if ((cfgBtnArticulationDisabled) ||
			(cfgBtnArticulationStaccatoDisabled && cfgBtnArticulationStaccatissimoDisabled && cfgBtnArticulationUpbowDisabled &&
			 cfgBtnArticulationDownbowDisabled && cfgBtnArticulationRollDisabled && cfgBtnArticulationTenutoDisabled && cfgBtnArticulationLowermordentDisabled &&
			 cfgBtnArticulationUppermordentDisabled && cfgBtnArticulationTrillDisabled && cfgBtnArticulationTurnDisabled && cfgBtnArticulationFermataDisabled) ) {
			document.getElementById("btnOptionArticulation").disabled = true;
		}

		//和音
		if (cfgBtnChordDisabled) {
			document.getElementById("btnChordSet").disabled = true;
		}
		
		//装飾音符
		if (cfgBtnNoteArtDisabled) {
			document.getElementById("btnNoteArt").disabled = true;
		}
		
		//８分音符等の分離・結合
		if (cfgBtnNoteSeparateJoinDisabled) {
			document.getElementById("btnNoteSeparate").disabled = true;
			document.getElementById("btnNoteJoin").disabled = true;
		}
		
		//３連符
		if (cfgBtnTripletsDisabled) {
			document.getElementById("btnSetTriplets").disabled = true;
			document.getElementById("btnSetTriplets2").disabled = true;
			document.getElementById("btnDelTriplets").disabled = true;
			document.getElementById("btnDelTriplets2").disabled = true;
		}
		
		//５連符
		if (cfgBtnQuintupletDisabled) {
			document.getElementById("btnSetQuintuplet2").disabled = true;
			document.getElementById("btnDelQuintuplet2").disabled = true;
		}
		
		//複旋律
		if (cfgBtnNoteAddDisabled) {
			document.getElementById("btnNoteAdd").disabled = true;
			document.getElementById("btnNoteAddDel").disabled = true;
		}

		//不完全小節
		if (cfgBtnIncompleteMeasureDisabled) {
			document.getElementById("btnNoteDel").disabled = true;
			document.getElementById("btnNoteOrg").disabled = true;
		}

		//強弱記号
		if (cfgSelDynamicsDisabled) document.getElementById("selDynamics").disabled = true;
		
		//反復記号
		if (cfgSelRepeatSignsDisabled) document.getElementById("selRepeatSigns").disabled = true;
	}
}


//##########################################################################
//##########################################################################
//	エディタ・楽譜上でのイベント
//		ABCエディタの変更イベント（onblurで呼ばれる）				changeAbcString()
//		楽譜上の「音符・休符」以外の場所のマウスダウン（選択解除）	abcjsBodyMouseDown(force=false);
//		楽譜上の「音符・休符」選択時イベント（ドラッグ処理を含む）	onNoteClick(abcelem, tuneNumber, classes, analysis, drag, mouseEvent);
//		選択範囲（startChar、endChar）から、
//		 各データ（音符、休符、小節線のクリック時に取得するデータ）
//		 を取得														function getDataFromRange(startChar, endChar);
//##########################################################################

//============================================================
//	ABCエディタの変更イベント（onblurで呼ばれる）
//============================================================
function changeAbcString() {
	currentAbcString = document.getElementById("abc-editor").value;
	abcEditor.updateSelection();
	
	pushUndo(currentAbcString);
}

//============================================================
//	楽譜上の「音符・休符」以外の場所のマウスダウンイベント（選択の解除）
//============================================================
var res_getMousePosition = { x: -1, y: -1, clickedOn: -1 };
var tmpDisp = "none";
function abcjsBodyMouseDown(force=false) {

	tmpDisp = document.getElementById("divOptionNoteAndRest").style.display;

	let res = res_getMousePosition;

	if ((res.clickedOn < 0 && selectNoteStartIndex != -1 && selectNoteEndIndex != -1) || force == true) {
		selectNoteStartIndex = -1;		//選択範囲の先頭index
		selectNoteEndIndex = -1;		//選択範囲の末尾index（終了の次を指している）
		selectNoteOrRest = "";

		document.getElementById(editorId).setSelectionRange(0, 0);
		abcEditor.updateSelection();

		//歌詞入力テキストボックスの無効化
		document.getElementById("txtLyric_1").value = "";
		document.getElementById("txtLyric_2").value = "";
		document.getElementById("txtLyric_3").value = "";
		document.getElementById("txtLyric_1").disabled = true;
		document.getElementById("txtLyric_2").disabled = true;
		document.getElementById("txtLyric_3").disabled = true;
		
		//小節線イメージプルダウンの無効化
		setDisabledSelBarLine(true);
		
		//音符・休符、装飾ボタン等の無効設定
		setDisabledNoteRestButton("disabled");
		
		//追加のアーティキュレーションを非表示
		document.getElementById("divOptionArticulation").style.display = "none";
	}
}

//============================================================
//	楽譜上の「音符・休符」選択時イベント、ドラッグ処理を含む
//============================================================
var selectionCallback;
var currentIndex = -1;
var maxIndex = -1;
function onNoteClick(abcelem, tuneNumber, classes, analysis, drag, mouseEvent) {

	//---------------------------------------------------
	//	編集禁止処理
	//		cfgMeasuresEditable[0][0][0] = false;
	//---------------------------------------------------
	if (abcelem.el_type == "note") {
		let line = abcelem.abselem.counters.line;
		let voice = abcelem.abselem.counters.voice;
		let measure = abcelem.abselem.counters.measure;
		
		let voice2 = isUpperLine(line, voice, measure);

		if (cfgMeasuresEditable[line][voice2][measure] == false) {
			setTimeout( function() {
				abcjsBodyMouseDown(true);
			}, 0);
			renderScore(currentAbcString);
			return;
		}
	}

	//----------------------------------------------
	//	選択音符範囲がある場合
	//----------------------------------------------
    if (abcelem.startChar !== undefined && abcelem.endChar !== undefined) {

		if (drag) {
			selectionCallback = drag.setSelection;
			currentIndex = drag.index;
			maxIndex = drag.max;
		}

		var originalText = currentAbcString.substring(abcelem.startChar, abcelem.endChar);

		//--------------------------------------------------
		//ドラッグ処理
		//--------------------------------------------------
		if (abcelem.pitches && drag && drag.step && abcelem.startChar >= 0 && abcelem.endChar >= 0) {
			//追加のアーティキュレーションを非表示
			document.getElementById("divOptionArticulation").style.display = "none";

			let lastSpace = false;
			if (originalText.substr(-1) == " ") {
				lastSpace = true;
			}

			var arr = tokenize(originalText);

			// arr now contains elements that are either a chord, a decoration, a note name, or anything else. It can be put back to its original string with .join("").
			for (var i = 0; i < arr.length; i++) {
				arr[i] = moveNote(arr[i], drag.step);
			}
			var newText = arr.join("");

			if (lastSpace == true) {
				newText += " ";
			}

			selectNoteStartIndex = abcelem.startChar;

			currentAbcString = currentAbcString.substring(0, abcelem.startChar) + newText + currentAbcString.substring(abcelem.endChar);
			selectNoteEndIndex = selectNoteStartIndex + newText.length;

			renderScore(currentAbcString);

			document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
			abcEditor.updateSelection();
			
			getDataFromRange(selectNoteStartIndex, selectNoteEndIndex)
			
			setDisabledNoteRestButton("auto");



		//--------------------------------------------------
		//選択処理
		//--------------------------------------------------
		} else {
			if (abcelem.startChar < 0 || abcelem.endChar < 0) return;
			if (abcelem.el_type != "note" && abcelem.el_type != "rest" && abcelem.el_type != "bar") return;

/*
console.log("abcelem", abcelem);
console.log("tuneNumber", tuneNumber);
console.log("classes", classes);
console.log("analysis", analysis);
console.log("drag", drag);
console.log("mouseEvent", mouseEvent);
*/
//console.log(abcelem);
//console.log("@abcEditor", abcEditor);

console.log(currentVisualArray);


			//エディタ上の選択範囲の設定
	        let abcEditor = document.getElementById("abc-editor");
	        abcEditor.focus();
	        abcEditor.setSelectionRange(abcelem.startChar, abcelem.endChar);

			//選択中のVisualArrayデータの取得
			selectVisualData = abcelem;

			//選択中の音符index（選択中のVisualArrayデータのcurrentVisualArrayに対するindex）を取得
			selectVisualDataIndex = -1;
			for (let i = 0; i < currentVisualArray.length; i++) {
				if (abcelem.startChar == currentVisualArray[i].absEl.abcelem.startChar && abcelem.endChar == currentVisualArray[i].absEl.abcelem.endChar) {
					selectVisualDataIndex = i;
					break;
				}
			}

	        //選択範囲のindex
	        selectNoteStartIndex = abcelem.startChar;
	        selectNoteEndIndex = abcelem.endChar;

	        //選択範囲のabc文字列
	        selectNoteStr = abcEditor.value.substring(selectNoteStartIndex, selectNoteEndIndex);

			if (abcelem.el_type == "bar") {
		        selectBarStartIndex = -1;
		        selectBarEndIndex = -1;
		        selectBarStr = "";
		        selectBarBeforeLen = -1;
		        selectBarAfterLen = -1;

			} else {
		        //小節の先頭index
		        var pos = selectNoteStartIndex;
		        while (true) {
		        	//if (abcEditor.value.substr(pos-20, 3) == "[V: 1 K:clef=treble]") break;		//@@@@@@@@@@@@@@@@@
		        	if (abcEditor.value.substr(pos-1, 1) == "\n") break;
		        	if (abcEditor.value.substr(pos-1, 1) == "]") break;		//2?
		        	if (abcEditor.value.substr(pos-1, 1) == "|") break;
		        	if (abcEditor.value.substr(pos-1, 1) == ":") break;
		        	pos--;
		        }
		        selectBarStartIndex = pos;

		        //小節の末尾index
		        var pos = selectNoteEndIndex-1;
		        while (true) {
		        	if (abcEditor.value.substr(pos+1, 1) == "|") break;
		        	if (abcEditor.value.substr(pos+1, 1) == ":") break;
		        	pos++;
		        }
		        selectBarEndIndex = pos+1;

		        //選択範囲の小節のabc文字列
		        selectBarStr = abcEditor.value.substring(selectBarStartIndex, selectBarEndIndex);

		        //選択範囲の小節内の、選択範囲までの音長（八分音符単位）選択範囲は含まない
		        if (selectNoteStr.trim() == "Z") {
		        	selectBarBeforeLen = 0;
		        	selectBarAfterLen = 0;
		        	
		        } else {
		        	//選択範囲の小節の先頭から、選択範囲までの音長（八分音符単位）選択範囲は含まない
			        selectBarBeforeLen = -1;
			        var cVoice = -1;
			        var iVoice = -1;
			        var cMeasure = -1;
			        var iMeasure = -1;
			        for (let i = currentVisualArray.length-1; i >= 0; i--) {
			        	if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
			        		iMeasure = currentVisualArray[i].absEl.counters.measure;
			        		iVoice = currentVisualArray[i].absEl.counters.voice;
			        	}
			        	if (currentVisualArray[i].absEl.abcelem.startChar == selectNoteStartIndex) {
			        		selectBarBeforeLen = 0;
			        		cMeasure = iMeasure;
			        		cVoice = iVoice;
			        	
			        	} else if (selectBarBeforeLen != -1 && currentVisualArray[i].absEl.type == "bar") {
							break;
						
						} else if (cMeasure != -1 && (cMeasure != iMeasure || cVoice != iVoice)) {
							break;
			        	
			        	} else if (selectBarBeforeLen != -1 && cMeasure == iMeasure && cVoice == iVoice) {
			        		selectBarBeforeLen += currentVisualArray[i].absEl.duration*8;		//OK
			        	}
			        }
			        selectBarBeforeLen = roundToFive(selectBarBeforeLen);
			        
			        
			        //選択範囲の小節の末尾から、選択範囲までの音長（八分音符単位）選択範囲は含まない
			        selectBarAfterLen = -1;
			        var cVoice = -1;
			        var iVoice = -1;
			        var cMeasure = -1;
			        var iMeasure = -1;
			        for (let i = 0; i < currentVisualArray.length-1; i++) {
			        	if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
			        		iMeasure = currentVisualArray[i].absEl.counters.measure;
			        		iVoice = currentVisualArray[i].absEl.counters.voice;
			        	}
			        	if (currentVisualArray[i].absEl.abcelem.startChar == selectNoteStartIndex) {
			        		selectBarAfterLen = 0;
			        		cMeasure = iMeasure;
			        		cVoice = iVoice;
			        	
			        	} else if (selectBarAfterLen != -1 && currentVisualArray[i].absEl.type == "bar") {
							break;
						
						} else if (cMeasure != -1 && (cMeasure != iMeasure || cVoice != iVoice)) {
							break;
			        	
			        	} else if (selectBarAfterLen != -1 && cMeasure == iMeasure && cVoice == iVoice) {
			        		selectBarAfterLen += currentVisualArray[i].absEl.duration*8;		//OK
			        	}
			        }
			        selectBarAfterLen = roundToFive(selectBarAfterLen);
			    }
		    }

	        //選択範囲が音符
	        if (abcelem.pitches) {
	        	selectNoteOrRest = "note";
				//行番号（０～）、小節番号（０～）、段番号（ 0 | 1 ）
				//if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
					currentLineNo = abcelem.abselem.counters.line;
				//} else {
				//	currentLineNo = abcelem.abselem.counters.line * 2 + abcelem.abselem.counters.voice;
				//}
				currentMeasureNo = abcelem.abselem.counters.measure;
				currentVoice = abcelem.abselem.counters.voice;
				//選択範囲の音階
				selectPitches = abcelem.pitches;
				//選択範囲の音階文字列
				selectPitchesStr = "";
				for (let i = 0; i < selectPitches.length; i++) {
					selectPitchesStr += selectPitches[i].name;
				}
				if (selectPitches.length > 1) {
					selectPitchesStr = "[" + selectPitchesStr + "]";
				}
				//選択範囲の音長（八分音符単位）
				selectDuration = abcelem.duration * 8;		//??
				//選択範囲の装飾
				if (abcelem.decoration) {
					selectDecoration = abcelem.decoration;
				} else {
					selectDecoration = [];
				}
				//選択範囲の区切り線種
				selectBarType = "";
				//選択範囲の繰り返し（「1,「2...）
				selectStartEnding = "";

				//小節線イメージプルダウンの有効化（上段(isUpperLine() == true)で、最初の小節(currentMeasureNo == 0)で、直前の改行(\n)までの間に小節線(|)がない場合）
				if (isUpperLine() == true && currentMeasureNo == 0) {
					let st = selectNoteStartIndex;
					let disabled = false;
					while (true) {
						st--;
						if (st == 0) break;
						if (currentAbcString[st] == "\n") break;
						if (currentAbcString[st] == "|") {
							disabled = true;
							break;
						}
					}
					document.getElementById("imgNoBar").style.display = "";
					selBarLineEvent = false;
					//selectBarLineLeft.setValue(tmp);
					selectBarLineLeft.setValue("");
					if (disabled == false) {
						setDisabledSelBarLine(disabled);
					}
				}

				//音符・休符、装飾ボタン等の自動有効設定
				setDisabledNoteRestButton("auto");

			//選択範囲が休符
	        } else if (abcelem.rest) {
	        	selectNoteOrRest = "rest";
				//行番号（０～）、小節番号（０～）、段番号（ 0 | 1 ）
				//if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
					currentLineNo = abcelem.abselem.counters.line;
				//} else {
				//	currentLineNo = abcelem.abselem.counters.line * 2 + abcelem.abselem.counters.voice;
				//}
				currentMeasureNo = abcelem.abselem.counters.measure;
				currentVoice = abcelem.abselem.counters.voice;
				//選択範囲の音階
				selectPitches = [];
				//選択範囲の音階文字列
				selectPitchesStr = "";
				//選択範囲の音長（八分音符単位）
				if (selectNoteStr.trim() == "Z") {
					selectDuration = countByBarArr[currentLineNo][currentMeasureNo];		//??
				} else {
					selectDuration = abcelem.duration * 8;		//??
				}
				//選択範囲の装飾
				if (abcelem.decoration) {
					selectDecoration = abcelem.decoration;
				} else {
					selectDecoration = [];
				}
				//選択範囲の区切り線種
				selectBarType = "";
				//選択範囲の繰り返し（「1,「2...）
				selectStartEnding = "";

				//小節線イメージプルダウンの有効化（上段(isUpperLine() == true)で、最初の小節(currentMeasureNo == 0)で、直前の改行(\n)までの間に小節線(|)がない場合）
				if (isUpperLine() == true && currentMeasureNo == 0) {
					let st = selectNoteStartIndex;
					let disabled = false;
					while (true) {
						st--;
						if (st == 0) break;
						if (currentAbcString[st] == "\n") break;
						if (currentAbcString[st] == "|") {
							disabled = true;
							break;
						}
					}
					document.getElementById("imgNoBar").style.display = "";
					selBarLineEvent = false;
					//selectBarLineLeft.setValue(tmp);
					selectBarLineLeft.setValue("");
					if (disabled == false) {
						setDisabledSelBarLine(disabled);
					}
				}

				//音符・休符、装飾ボタン等の自動有効設定
				setDisabledNoteRestButton("auto")

	        //選択範囲が小節線
	        } else {
	        	selectNoteOrRest = "bar";
				//行番号（０～）、小節番号（０～）、段番号（ 0 | 1 ）
				currentLineNo = analysis.line;
				currentMeasureNo = -1;
				currentVoice = -1;
				//選択範囲の音階
				selectPitches = [];
				//選択範囲の音階文字列
				selectPitchesStr = "";
				//選択範囲の音長
				selectDuration = 0;
				//選択範囲の装飾
				if (abcelem.decoration) {
					selectDecoration = abcelem.decoration;
				} else {
					selectDecoration = [];
				}
				//選択範囲の区切り線種
				selectBarType = abcelem.type;
				//選択範囲の繰り返し（「1,「2...）
				if (abcelem.startEnding) {
					selectStartEnding = abcelem.startEnding;
				} else {
					selectStartEnding = "";
				}

				//小節線イメージプルダウンの無効化
				let offset = 0;
				if (currentClefSymbol != "treble" && currentClefSymbol != "bass") {
					offset = 6;
				}
				if (currentAbcString[abcelem.startChar-1-offset] != "\n") {
					document.getElementById("imgNoBar").style.display = "none";
				} else {
					document.getElementById("imgNoBar").style.display = "";
				}
				selBarLineEvent = false;
				//selectBarLineLeft.setValue(selectNoteStr);
				selectBarLineLeft.setValue(getBarType());

				if (currentVisualArray[selectVisualDataIndex-1].absEl.type != "bar") {
					var voice = currentVisualArray[selectVisualDataIndex-1].absEl.counters.voice;
				} else {
					var voice = currentVisualArray[selectVisualDataIndex+1].absEl.counters.voice;
				}
				
				if (voice == 0) {
					setDisabledSelBarLine(false);
				}
				//音符・休符、装飾ボタン等の無効設定
				setDisabledNoteRestButton("auto")
	        }

			//追加のアーティキュレーションを非表示
			document.getElementById("divOptionArticulation").style.display = "none";
		}

		setTimeout( function() {
			let scrollTop = document.getElementById(editorId).scrollTop;
	    	document.getElementById(editorId).focus();
	    	document.getElementById(editorId).setSelectionRange(selectNoteStartIndex, selectNoteEndIndex);
			document.getElementById(editorId).scrollTop = scrollTop;
			
			document.getElementById("txtLyric_1").disabled = true;
			document.getElementById("txtLyric_2").disabled = true;
			document.getElementById("txtLyric_3").disabled = true;

			v_haveCounterpointByLine = haveCounterpointByLine();		// 0=ない、1=あり
			v_haveCounterpointByMeasure = haveCounterpointByMeasure();	// 0=ない、1=あり
			v_isTrebleLine = isTrebleLine();							// true=ト音記号の段、false=ヘ音記号段
			v_isUpperLine = isUpperLine();								// true=上段、false=下段
			v_isMainVoice = isMainVoice();								// true=主旋律、false=副旋律

			//主旋律の音符選択時は、歌詞を入力エリアに表示
			if (selectNoteOrRest == "note" && v_isMainVoice == true) {
				for (let i = 0; i < currentLyricNumber; i++) {
					if (abcelem.lyric) {
						document.getElementById("txtLyric_" + (i+1)).value = abcelem.lyric[i].syllable;
					} else {
						document.getElementById("txtLyric_" + (i+1)).value = "";
					}
					document.getElementById("txtLyric_" + (i+1)).disabled = false;
				}
			
			//音符以外選択時は、歌詞を入力エリアをクリア
			} else {
				document.getElementById("txtLyric_1").value = "";
				document.getElementById("txtLyric_2").value = "";
				document.getElementById("txtLyric_3").value = "";
			}
			document.getElementById("divOptionNoteAndRest").style.display = tmpDisp;
		}, 0);
    }
}

//============================================================
//	選択範囲（startChar、endChar）から、各データ（音符、休符、小節線のクリック時に取得するデータ）を取得
//============================================================
function getDataFromRange(startChar, endChar) {

	//エディタ上の選択範囲の設定
    let abcEditor = document.getElementById("abc-editor");
//    abcEditor.focus();
//    abcEditor.setSelectionRange(startChar, endChar);

	//選択中の音符index（選択中のVisualArrayデータのcurrentVisualArrayに対するindex）を取得
	selectVisualDataIndex = -1;
	for (let i = 0; i < currentVisualArray.length; i++) {
		if (startChar == currentVisualArray[i].absEl.abcelem.startChar && endChar == currentVisualArray[i].absEl.abcelem.endChar) {
			selectVisualDataIndex = i;
			break;
		}
	}
	
	if (selectVisualDataIndex == -1) {
		abcjsBodyMouseDown(true);
		return;
	}

	//選択中のVisualArrayデータの取得
	let abcelem = currentVisualArray[selectVisualDataIndex].absEl.abcelem;
	selectVisualData = abcelem;

    //選択範囲のindex
    selectNoteStartIndex = abcelem.startChar;
    selectNoteEndIndex = abcelem.endChar;

    //選択範囲のabc文字列
    selectNoteStr = abcEditor.value.substring(selectNoteStartIndex, selectNoteEndIndex);

	if (abcelem.el_type == "bar") {
        selectBarStartIndex = -1;
        selectBarEndIndex = -1;
        selectBarStr = "";
        selectBarBeforeLen = -1;
        selectBarAfterLen = -1;

	} else {
        //小節の先頭index
        var pos = selectNoteStartIndex;
        while (true) {
        	//if (abcEditor.value.substr(pos-6, 3) == "[V:") break;		//@@@@@@@@@@@@@@@@@
        	if (abcEditor.value.substr(pos-1, 1) == "\n") break;
        	if (abcEditor.value.substr(pos-1, 1) == "]") break;		//2?
        	if (abcEditor.value.substr(pos-1, 1) == "|") break;
        	if (abcEditor.value.substr(pos-1, 1) == ":") break;
        	pos--;
        }
        selectBarStartIndex = pos;

        //小節の末尾index
        var pos = selectNoteEndIndex-1;
        while (true) {
        	if (abcEditor.value.substr(pos+1, 1) == "|") break;
        	if (abcEditor.value.substr(pos+1, 1) == ":") break;
        	pos++;
        }
        selectBarEndIndex = pos+1;

        //選択範囲の小節のabc文字列
        selectBarStr = abcEditor.value.substring(selectBarStartIndex, selectBarEndIndex);

        //選択範囲の小節内の、選択範囲までの音長（八分音符単位）選択範囲は含まない
        if (selectNoteStr.trim() == "Z") {
        	selectBarBeforeLen = 0;
        	selectBarAfterLen = 0;
        	
        } else {
        	//選択範囲の小節の先頭から、選択範囲までの音長（八分音符単位）選択範囲は含まない
	        selectBarBeforeLen = -1;
	        var cVoice = -1;
	        var iVoice = -1;
	        var cMeasure = -1;
	        var iMeasure = -1;
	        for (let i = currentVisualArray.length-1; i >= 0; i--) {
	        	if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
	        		iMeasure = currentVisualArray[i].absEl.counters.measure;
	        		iVoice = currentVisualArray[i].absEl.counters.voice;
	        	}
	        	if (currentVisualArray[i].absEl.abcelem.startChar == selectNoteStartIndex) {
	        		selectBarBeforeLen = 0;
	        		cMeasure = iMeasure;
	        		cVoice = iVoice;
	        	
	        	} else if (selectBarBeforeLen != -1 && currentVisualArray[i].absEl.type == "bar") {
					break;
				
				} else if (cMeasure != -1 && (cMeasure != iMeasure || cVoice != iVoice)) {
					break;
	        	
	        	} else if (selectBarBeforeLen != -1 && cMeasure == iMeasure && cVoice == iVoice) {
	        		selectBarBeforeLen += currentVisualArray[i].absEl.duration*8;		//OK
	        	}
	        }
	        selectBarBeforeLen = roundToFive(selectBarBeforeLen);


	        //選択範囲の小節の末尾から、選択範囲までの音長（八分音符単位）選択範囲は含まない
	        selectBarAfterLen = -1;
	        var cVoice = -1;
	        var iVoice = -1;
	        var cMeasure = -1;
	        var iMeasure = -1;
	        for (let i = 0; i < currentVisualArray.length-1; i++) {
	        	if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
	        		iMeasure = currentVisualArray[i].absEl.counters.measure;
	        		iVoice = currentVisualArray[i].absEl.counters.voice;
	        	}
	        	if (currentVisualArray[i].absEl.abcelem.startChar == selectNoteStartIndex) {
	        		selectBarAfterLen = 0;
	        		cMeasure = iMeasure;
	        		cVoice = iVoice;
	        	
	        	} else if (selectBarAfterLen != -1 && currentVisualArray[i].absEl.type == "bar") {
					break;
				
				} else if (cMeasure != -1 && (cMeasure != iMeasure || cVoice != iVoice)) {
					break;
	        	
	        	} else if (selectBarAfterLen != -1 && cMeasure == iMeasure && cVoice == iVoice) {
	        		selectBarAfterLen += currentVisualArray[i].absEl.duration*8;		//OK
	        	}
	        }
	        selectBarAfterLen = roundToFive(selectBarAfterLen);
	    }
    }

    //選択範囲が音符
    if (abcelem.pitches) {
    	selectNoteOrRest = "note";
		//行番号（０～）、小節番号（０～）、段番号（ 0 | 1 ）
		//if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
			currentLineNo = abcelem.abselem.counters.line;
		//} else {
		//	currentLineNo = abcelem.abselem.counters.line * 2 + abcelem.abselem.counters.voice;
		//}
		currentMeasureNo = abcelem.abselem.counters.measure;
		currentVoice = abcelem.abselem.counters.voice;
		//選択範囲の音階
		selectPitches = abcelem.pitches;
		//選択範囲の音階文字列
		selectPitchesStr = "";
		for (let i = 0; i < selectPitches.length; i++) {
			selectPitchesStr += selectPitches[i].name;
		}
		if (selectPitches.length > 1) {
			selectPitchesStr = "[" + selectPitchesStr + "]";
		}
		//選択範囲の音長（八分音符単位）
		selectDuration = abcelem.duration * 8;		//??
		//選択範囲の装飾
		if (abcelem.decoration) {
			selectDecoration = abcelem.decoration;
		} else {
			selectDecoration = [];
		}
		//選択範囲の区切り線種
		selectBarType = "";

	//選択範囲が休符
    } else if (abcelem.rest) {
    	selectNoteOrRest = "rest";
		//行番号（０～）、小節番号（０～）、段番号（ 0 | 1 ）
		//if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
			currentLineNo = abcelem.abselem.counters.line;
		//} else {
		//	currentLineNo = abcelem.abselem.counters.line * 2 + abcelem.abselem.counters.voice;
		//}
		currentMeasureNo = abcelem.abselem.counters.measure;
		currentVoice = abcelem.abselem.counters.voice;
		//選択範囲の音階
		selectPitches = [];
		//選択範囲の音階文字列
		selectPitchesStr = "";
		//選択範囲の音長（八分音符単位）
		selectDuration = abcelem.duration * 8;		//??
		//選択範囲の装飾
		if (abcelem.decoration) {
			selectDecoration = abcelem.decoration;
		} else {
			selectDecoration = [];
		}
		//選択範囲の区切り線種
		selectBarType = "";

    //選択範囲が小節線
    } else {
    	selectNoteOrRest = "bar";
		//行番号（０～）、小節番号（０～）、段番号（ 0 | 1 ）
		currentLineNo = -1;
		currentMeasureNo = -1;
		currentVoice = -1;
		//選択範囲の音階
		selectPitches = [];
		//選択範囲の音階文字列
		selectPitchesStr = "";
		//選択範囲の音長
		selectDuration = 0;
		//選択範囲の装飾
		selectDecoration = [];
		//選択範囲の区切り線種
		selectBarType = abcelem.type;
    }
}


//##########################################################################
//##########################################################################
//	楽譜操作関連の関数
//		楽譜コンテナーのスクロール							abcjsContainerScroll();
//		一部のシンボルの表示位置や表示状態を調整			adjustSymbolPosition()
//		楽譜のレンダリング									renderScore(abcString=currentAbcString, body=bodyId, editor=editorId);
//		引数のabcStringを、要素に分解して、配列で戻す		tokenize(str);
//		音階の移動（高・低）								moveNote(note, step);
//		音長の分割											splitNoteDuration(oldStr, oldLen, newLen, conv)
//		休符を同長（len）の音符（音階はscale）				cnveRestToNoteForSame(oldStr, oldScale, oldLen, scale, len);
//		指定長（len）の音符（音階はscale）＋差分の休符		cnveRestToNoteForShort(oldStr, oldScale, oldLen, scale, len);
//		指定長の音符（元の音階）＋差分の音符（元の音階）	cnveNoteToNoteForShort(oldStr, oldScale, oldLen, scale, len);
//		指定長の音符（音階はscale）＋ 合計長（oldLen）に対する差分の休符
//															cnveRestToNoteForLong(oldStr, oldScale, oldLen, scale, len);
//		指定長の音符（元の音階）＋ 合計長（oldLen）に対する差分の休符
//															cnveNoteToNoteForLong(oldStr, oldScale, oldLen, scale, len);
//		音符を同長（len）の休符								cnveNoteToRestForSame(oldStr, oldScale, oldLen, len);
//		指定長（len）の音符（音階はscale）＋差分の休符		cnveRestToRestForShort(oldStr, oldScale, oldLen, len);
//		指定長の休符＋差分の音符（元の音階）				cnveNoteToRestForShort(oldStr, oldScale, oldLen, len);
//		指定長の休符＋ 合計長（oldLen）に対する差分の休符	cnveRestToRestForLong(oldStr, oldScale, oldLen, len);
//		指定長の休符＋ 合計長（oldLen）に対する差分の休符	cnveNoteToRestForLong(oldStr, oldScale, oldLen, len);
//		エディタの選択範囲を引数文字列で置換				replaceAbcStr(str, start, end);
//		この小節の歌詞文字列を生成							setLyricStrByBar();
//##########################################################################

//============================================================
//	楽譜コンテナーのスクロール（演奏時の楽譜カバーの位置設定）
//============================================================
var stopScrollAdjust = false;
var prevScrollTop = 0;
function abcjsContainerScroll() {
	let elemContainer = document.getElementById("abcjs-container");
	let elemCover = document.getElementById("abcjs-body_cover");

	//演奏中
	if (document.getElementById("divPlayer").style.display != "none") {
		elemCover.style.top = elemContainer.scrollTop + "px";
		elemCover.style.height = elemContainer.clientHeight + "px";;
		prevScrollTop = elemContainer.scrollTop;

	//編集中
	} else {
		let scrollTop = elemContainer.scrollTop;
		//カーソル飛びの防止
		if (Math.abs(scrollTop - prevScrollTop) > 200 && stopScrollAdjust == false) {
			//prevScrollTop = scrollTop;
			elemContainer.scrollTop = prevScrollTop;
		} else {
			prevScrollTop = scrollTop;
		}
	}
}

//============================================================
//	一部のシンボルの表示位置や表示状態を調整
//		〇各段の先頭小節以外の小節番号を非表示とする（X座標が一定以上の小節番号を非表示にする）
//		〇レンダリング後に特定のテキスト要素（ブレス）の y 属性を変更
//		〇abcjs-ending クラスを持つ要素（「1、「2＝繰り返し記号）を下に移動
//		〇【歌詞設定がある場合のみ】data-name="dynamics" を持つすべての要素（mf、mp、＜ など）を下に移動
//============================================================
function adjustSymbolPosition() {

	//------------------------------------------------------------------
    //	各段の先頭小節以外の小節番号を非表示とする（X座標が一定以上の小節番号を非表示にする）
	//------------------------------------------------------------------
    const thresholdX = 50; // ここでX座標の閾値を設定
    document.querySelectorAll('.abcjs-bar-number').forEach(function(barNumber) {
        let xCoord = parseFloat(barNumber.getAttribute('x'));
        if (xCoord >= thresholdX) {
            //barNumber.style.display = 'none';
            barNumber.style.visibility = 'hidden';
            barNumber.style.fontSize = '6px';
        }
    });


	//------------------------------------------------------------------
	//	レンダリング後に特定のテキスト要素（ブレス）の y 属性を変更
	//	"V" を含む text 要素を取得
	//------------------------------------------------------------------
	document.querySelectorAll('text.abcjs-chord').forEach(function(textElement) {
	    if (textElement.textContent.includes('V')) {
	        // 親要素を辿って、grandparentGroupを取得
	        let parentGroup = textElement.parentElement;
	        let grandparentGroup = parentGroup.parentElement;

	        if (grandparentGroup) {
	            // grandparentGroup 内のすべての子 g 要素を取得
	            let childGroups = Array.from(grandparentGroup.querySelectorAll('g'));

	            let closestTopLinePath = null;
	            let smallestDistance = Infinity;  // 無限大で初期化

	            childGroups.forEach(group => {
	                // 各グループ内の abcjs-top-line 要素を取得
	                let topLinePath = group.querySelector('path.abcjs-top-line');
	                
	                if (topLinePath) {
	                    // topLinePath と textElement の距離を計算
	                    let topLineRect = topLinePath.getBoundingClientRect();
	                    let textRect = textElement.getBoundingClientRect();
	                    let distance = Math.abs(topLineRect.top - textRect.top);
	                    
	                    // 最も近い topLinePath を選択
	                    if (distance < smallestDistance) {
	                        smallestDistance = distance;
	                        closestTopLinePath = topLinePath;
	                    }
	                }
	            });

	            if (closestTopLinePath) {
	                // 最も近い abcjs-top-line を使用
	                let svgRect = textElement.ownerSVGElement.getBoundingClientRect();
	                let topLineY = closestTopLinePath.getBoundingClientRect().top - svgRect.top;

	                // テキスト要素の Y 座標を水平線の直上に設定
	                textElement.setAttribute('y', topLineY - 5);  // 5px 上に配置
	            } else {
	                //console.log("No abcjs-top-line found");
	            }
	        } else {
	            //console.log("grandparentGroup not found");
	        }
	    }
	});

	//------------------------------------------------------------------
    //	abcjs-ending クラスを持つ要素（「1、「2＝繰り返し記号）を下に移動
	//------------------------------------------------------------------
    document.querySelectorAll('.abcjs-ending').forEach(function(element) {
        let currentTransform = element.getAttribute('transform') || "";
        element.setAttribute('transform', currentTransform + ' translate(0, 10)');
    });

	//------------------------------------------------------------------
	//	data-name="dynamics" を持つすべての要素（mf、mp、＜ など）を下に移動
	//	歌詞設定がある場合のみ
	//------------------------------------------------------------------
	if (currentLyricNumber != 0) {
		document.querySelectorAll('[data-name="dynamics"]').forEach(function(element) {
		    // 既存の transform 属性を取得（ない場合は空の文字列を使用）
		    let currentTransform = element.getAttribute('transform') || "";

		    // Y軸方向に10px下げる
		    let newTransform = currentTransform + " translate(0, 10)";

		    // 新しい transform を設定
		    element.setAttribute('transform', newTransform);
		});
	}
	
	//------------------------------------------------------------------
	//	下段のテンポを表示しない
	//------------------------------------------------------------------
	let elems = document.querySelectorAll('g.abcjs-tempo.abcjs-v1');
	for (let i = 0; i < elems.length; i++) {
		elems[i].setAttribute('display', 'none');
	}
}

//============================================================
//	楽譜のレンダリング
//============================================================
function renderScore(abcString=currentAbcString, body=bodyId, editor=editorId) {

	if (stopRender == true) return;

	currentAbcString = abcString;
	bodyId = body;
	editorId = editor;
	
/*
	let options = {
		add_classes: true,
		selectionColor: "red",
		dragColor: "red",
		clickListener: onNoteClick,
		dragging: true,
		selectTypes: [ 'note', 'bar' ],
	};

 	//楽譜のレンダリング
    let currentVisualObjs = ABCJS.renderAbc(bodyId, abcString, options);
    //現在表示中の楽譜データ配列を取得
    currentVisualArray = currentVisualObjs[0].getSelectableArray();
*/
    //エディターのデータ更新
	document.getElementById(editorId).value = abcString;

	if (abcEditor !== null) abcEditor = null;

	abcEditor = new ABCJS.Editor(editorId, { paper_id: bodyId,
		//synth: {
		//	el: "#audio",
		//	options: { displayLoop: true, displayRestart: true, displayPlay: true, displayProgress: true, displayWarp: true }
		//},
		generate_warnings: false,

//		onchange: changeAbcString,

		abcjsParams: {
			staffwidth: 740,  // 五線の幅を指定
			
			generateDownload: true,
			add_classes: true,
			selectionColor: "red",
			dragColor: "red",
			selectTypes: [ 'note', 'bar' ],
			dragging: true,
			clickListener: onNoteClick,
			

			paddingtop: 30,      // 上の余白を50pxに設定
			paddingbottom: 50,   // 下の余白を50pxに設定
			/*
	        generateInline: true,  // 小節番号を生成
	        inlineControls: {
	            startMeasureNumber: true  // 各段の先頭小節に番号を表示
	        }
	        */
		}
	});

console.log("@abcEditor", abcEditor);

	//------------------------------------------------------------------
	//	小節内の八分音符の数の配列 countByBarArr[line][Measure]を取得
	//------------------------------------------------------------------
	let len = countByBar;
	for (let i = 0; i < abcEditor.tunes[0].lines.length; i++) {
		if (!abcEditor.tunes[0].lines[i].staff) continue;
		
		let skipBar = true;
		let measure = 0;
		let voices = abcEditor.tunes[0].lines[i].staff[0].voices[0];
		countByBarArr[i][measure] = len;
		for (let j = 0; j < voices.length; j++) {
			let voice = voices[j];

			if (voice.el_type == "bar" && skipBar == true) {
				skipBar = false;
			
			} else if (voice.el_type == "bar") {
				measure++;
				countByBarArr[i][measure] = len;
			
			} else if (voice.el_type == "timeSignature") {
				let tmp = currentAbcString.substring(voice.startChar, voice.endChar);
				tmp = tmp.replace("[M:", "").replace("]", "");
				if (tmp == "C" || tmp == "C|" || tmp == "2/2" || tmp == "4/4") {
					len = 8;
				} else if (tmp == "3/2" || tmp == "6/4" || tmp == "12/8") {
					len = 12;
				} else if (tmp == "2/4") {
					len = 4;
				} else if (tmp == "3/4" || tmp == "6/8") {
					len = 6;
				} else if (tmp == "3/8") {
					len = 3;
				} else if (tmp == "9/8") {
					len = 9;
				} else if (tmp == "5/4") {
					len = 10;
				} else if (tmp == "5/8") {
					len = 5;
				} else if (tmp == "7/8") {
					len = 7;
				}
				countByBarArr[i][measure] = len;
				skipBar = false;
			
			} else if (voice.el_type == "note") {
				skipBar = false;
			}
		}
	}

	//------------------------------------------------------------------
	//	一部のシンボルの表示位置や表示状態を調整
	//------------------------------------------------------------------
	adjustSymbolPosition();

	currentVisualArray = abcEditor.tunes[0].getSelectableArray();
	
	
	
	
	pushUndo(currentAbcString);
}




//============================================================
//	引数のabcStringを、要素に分解して、配列で戻す
//============================================================
function tokenize(str) {
	//------------------------------------------------
	//	配列の"_", "__" で始まる要素を分離
	//		下記の正規表現で、_ だけ分離できないことへの対応
	//------------------------------------------------
	function splitElements(arr) {
	    let result = [];
	    arr.forEach(function(element) {
	        if (element.startsWith('__')) {
	            result.push('__', element.substring(2));
	        } else if (element.startsWith('_')) {
	            result.push('_', element.substring(1));
	        } else {
	            result.push(element);
	        }
	    });
	    return result;
	}
	//------------------------------------------------

	var arr = str.split(/(!.+?!|".+?")/);

	var output = [];
	for (let i = 0; i < arr.length; i++) {
		var token = arr[i];
		if (token.length > 0) {
			if (token[0] !== '"' && token[0] !== '!') {
				
				//var arr2 = arr[i].split(/([A-Ga-g][,']*)/);		//'
				//var arr2 = arr[i].split(/(\[[A-Ga-g]+\]|[A-Ga-g][,']*)/);	//'和音対応
				var arr2 = arr[i].split(/(\[\s*(?:[_=^]{0,2}[A-Ga-g][,']*\s*)+\]|\b[_=^]{0,2}[A-Ga-g][,']*)\s*(\d*)/);		//和音＋補助記号対応（ _ は分離できないので、別途対応）

				var arr2 = arr2.filter(function(element) {
				    return element !== null && element !== undefined && element.trim() !== "";
				});
				
				var arr2 = splitElements(arr2);		// _ が分離できないことへの対応

				output = output.concat(arr2);

			} else {
				output.push(token);
			}
		}
	}
	
	//３連符・５連符の先頭が分離できないことへの対応
	output2 = [];
	for (let i = 0; i < output.length; i++) {
		if (output[i].substr(0, 3) == " (3") {
			output2.push(" (3");
			let idx = output[i].substr(3).indexOf("/");
			if (idx == -1) {
				output2.push(output[i].substr(3));
			} else {
				output2.push(output[i].substr(3, idx));
				output2.push(output[i].substr(3+idx));
			}
		} else if (output[i].substr(0, 2) == "(3") {
			output2.push("(3");
			let idx = output[i].substr(2).indexOf("/");
			if (idx == -1) {
				output2.push(output[i].substr(2));
			} else {
				output2.push(output[i].substr(2, idx));
				output2.push(output[i].substr(2+idx));
			}

		} else if (output[i].substr(0, 5) == " (5:4") {
			output2.push(" (5:4");
			let idx = output[i].substr(5).indexOf("/");
			if (idx == -1) {
				output2.push(output[i].substr(5));
			} else {
				output2.push(output[i].substr(5, idx));
				output2.push(output[i].substr(5+idx));
			}
		} else if (output[i].substr(0, 4) == "(5:4") {
			output2.push("(5:4");
			let idx = output[i].substr(4).indexOf("/");
			if (idx == -1) {
				output2.push(output[i].substr(4));
			} else {
				output2.push(output[i].substr(4, idx));
				output2.push(output[i].substr(4+idx));
			}

		} else {
			output2.push(output[i]);
		}
	}

	return output2;
}

//============================================================
//	音階の移動（高・低）
//============================================================
function moveNote(note, step) {
	var x = allPitches.indexOf(note);
	if (x >= 0) {
		return allPitches[x-step];
	}
	return note;
}

//============================================================
//	音長の分割
//		conv	== note_note : すべて音符に分割
//				== note_rest : [0]音符、以降休符
//				== rest_note
//============================================================
function splitNoteDuration(oldStr, oldLen, newLen, conv) {
	//-----------------------------------------------------
	//	音休符文字列の取得（引数長の音符を、単純長の音符（or休符）に分解した文字列を取得）
	//-----------------------------------------------------
	function splitNoteLen(baseLen, newLen) {
		let res = [];
		if (newLen == 1) {
			res.push("");
		} else {
			res.push(decimalToFraction(newLen).replace("1/", "/"));
		}
		
		if (baseLen > newLen) {
			let notes = decomposeToSums(baseLen - newLen).split("+");

			for (let i = 0; i < notes.length; i++) {
				if (notes[i] == "1" || notes[i] == "") {
					res.push("");
				} else {
					res.push(notes[i].replace("1/", "/"));
				}
			}
		}
		return res;
	}
	//-----------------------------------------------------

	let lens = splitNoteLen(oldLen, newLen);
	let arr = tokenize(oldStr);

	lenIdx = -1;
	for (let i = 0; i < arr.length; i++) {
		//arr[i] が allPitches 配列に含まれている、または、arr[i] が [ で始まり ] で終わっている場合
		if ((allPitches.indexOf(arr[i]) != -1) || (arr[i].startsWith("[") && arr[i].endsWith("]"))) {
			lenIdx = i+1;
			break;
		}
	}

	if (lenIdx == -1) {
		return oldStr;
	}

	let note = arr.slice(0, lenIdx).join("");
	res = "";
	for (let i = 0; i < lens.length; i++) {
		if (conv == "note_note" || (conv == "note_rest" && i == 0) || (conv == "rest_note" && i != 0)) {
			res += note + lens[i];
		} else {
			res += "z" + lens[i] + " ";
		}
	}

	return res;
}

//============================================================
//	休符を同長（len）の音符（音階はscale）
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		scale		返還後の音階
//		len			返還後の音長
//============================================================
function cnveRestToNoteForSame(oldStr, oldScale, oldLen, scale, len) {
	let res =  scale + decimalToFraction(len);
	return res;
}

//============================================================
//	指定長（len）の音符（音階はscale）＋差分の休符
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		scale		返還後の音階
//		len			返還後の音長
//============================================================
function cnveRestToNoteForShort(oldStr, oldScale, oldLen, scale, len) {
	let res = scale + decimalToFraction(len);
	res += makeRestStr(oldLen　-　len);
	return res;
}

//============================================================
//	指定長の音符（元の音階）＋差分の音符（元の音階）
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		scale		返還後の音階
//		len			返還後の音長
//============================================================
function cnveNoteToNoteForShort(oldStr, oldScale, oldLen, scale, len) {
	res = splitNoteDuration(oldStr, oldLen, len, "note_note");
	return res;
}

//============================================================
//	指定長の音符（音階はscale）＋ 合計長（oldLen）に対する差分の休符
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		scale		返還後の音階
//		len			返還後の音長
//============================================================
function cnveRestToNoteForLong(oldStr, oldScale, oldLen, scale, len) {
	let res = scale + decimalToFraction(len);
	res += makeRestStr(oldLen　-　len);
	return res;
}

//============================================================
//	指定長の音符（元の音階）＋ 合計長（oldLen）に対する差分の休符
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		scale		返還後の音階
//		len			返還後の音長
//============================================================
function cnveNoteToNoteForLong(oldStr, oldScale, oldLen, scale, len) {
	res = splitNoteDuration(oldStr, oldLen, len, "note_rest");
	return res;
}

//============================================================
//	音符を同長（len）の休符
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		len			返還後の音長
//============================================================
function cnveNoteToRestForSame(oldStr, oldScale, oldLen, len) {
	let res =  "z" + decimalToFraction(len) + " ";
	return res;
}

//============================================================
//	指定長（len）の音符（音階はscale）＋差分の休符
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		len			返還後の音長
//============================================================
function cnveRestToRestForShort(oldStr, oldScale, oldLen, len) {
	let res = "z" + decimalToFraction(len) + " ";
	res += makeRestStr(oldLen　-　len);
	return res;
}

//============================================================
//	指定長の休符＋差分の音符（元の音階）
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		len			返還後の音長
//============================================================
function cnveNoteToRestForShort(oldStr, oldScale, oldLen, len) {
	res = splitNoteDuration(oldStr, oldLen, len, "rest_note");
	return res;
}

//============================================================
//	指定長の休符＋ 合計長（oldLen）に対する差分の休符
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		len			返還後の音長
//============================================================
function cnveRestToRestForLong(oldStr, oldScale, oldLen, len) {
	res = "z" + decimalToFraction(len) + " " + makeRestStr(oldLen - len);
	return res;
}

//============================================================
//	指定長の休符＋ 合計長（oldLen）に対する差分の休符
//		oldStr		変換前のabcString
//		oldScale	返還後の音階（C [CD] .....）
//		oldLen		変換前の音長
//		len			返還後の音長
//============================================================
function cnveNoteToRestForLong(oldStr, oldScale, oldLen, len) {
	res = "z" + decimalToFraction(len) + " " + makeRestStr(oldLen - len);
	return res;
}

//============================================================
//	エディタの選択範囲を引数文字列で置換
//============================================================
function replaceAbcStr(str, start, end) {
	let oldStr = document.getElementById("abc-editor").value;

    const lastChar = str.charAt(str.length - 1);      // 最後の文字
    const secondLastChar = str.charAt(str.length - 2); // 最後から2番目の文字
	
	//8分音符等を３連符と結合させない処理
	if ((isNaN(lastChar) || secondLastChar === '/') && oldStr.substr(end, 2) == "(3") {
		var newStr = oldStr.substring(0, start) + str + " " + oldStr.substring(end);
	} else {
		var newStr = oldStr.substring(0, start) + str + oldStr.substring(end);
	}

	document.getElementById("abc-editor").value = newStr;

	//再レンダリング
	setTimeout( function() {
		renderScore(currentAbcString);
		//この小節の歌詞文字列を生成（指定行・小節の歌詞文字列生成とabcStringへの反映）
		setLyricStrByBar();
	}, 0);
}

//============================================================
//	この小節の歌詞文字列を生成（指定行・小節の歌詞文字列生成とabcStringへの反映）
//		〇３連符設定時
//		〇エディタの選択範囲を引数文字列で置換時
//		に呼ばれる
//============================================================
function setLyricStrByBar() {

	//複旋律の場合、処理不要
	if (v_isMainVoice == false) return;


	//この小節の歌詞文字列を生成（指定行・小節の歌詞文字列生成とabcStringへの反映）
	if (currentLyricNumber > 0) {

		if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
			var currentLineNo2 = currentLineNo;

		} else {
			if (v_isUpperLine == true) {
				var currentLineNo2 = currentLineNo*2;
			} else {
				var currentLineNo2 = currentLineNo*2 + 1;
			}
		}

		//currentVisualArrayの、現在行、現在小節の lyric から、この小節の歌詞文字列を生成
		let lyricStr = getDefaultLyricData(currentLineNo2, currentMeasureNo);

		//abcStringへのセット
		let lines = document.getElementById("abc-editor").value.split("\n");

		let countW = 0;
		var idx = 0;
		for (let i = 0; i < lines.length; i++) {
			if (lines[i].substr(0, 3) == "w: ") {
				if (countW == currentLineNo2 * currentLyricNumber) {
					idx = i;
					break;
				}
				countW++;
			}
		}
		
		for (let i = 0; i < currentLyricNumber; i++) {
			let line = lines[idx + i];
			let notes = line.substr(3).split("|");
			notes[currentMeasureNo] = lyricStr[i];
			line = "w: " + notes.join("|");
			lines[idx + i] = line;
		}
		
		currentAbcString = lines.join("\n");
		document.getElementById("abc-editor").value = currentAbcString;
		
		//再レンダリング
		renderScore(currentAbcString);
	}
}


//##########################################################################
//##########################################################################
//	楽譜関係のユーティリティ関数
//		休符文字列の取得							makeRestStr(len);
//		歌詞のデフォルトデータの取得				getDefaultLyricData(row, col);
//		選択中の小節線のタイプは？					getBarType();
//		選択中の音符は、３連符の何番目の音符か？	getCurrentTripletsNumber()
//##########################################################################

//============================================================
//	休符文字列の取得（引数長の休符を、単純長休符に分解した文字列を取得）
//============================================================
function makeRestStr(len) {
	if (len == 0) return "";
	
	let res = "";
	let rests = decomposeToSums(len).split("+");
	for (let i = 0; i < rests.length; i++) {
		if (rests[i] == "1") {
			res += "z ";
		} else {
			res += "z" + rests[i].replace("1/", "/") + " ";
		}
	}
	return res;
}

//============================================================
//	歌詞のデフォルトデータの取得
//		row		行index（ト音記号行とヘ音記号行を、それそれカウントした行数）
//		col		小節index
//============================================================
function getDefaultLyricData(row, col) {

	let lyricStr = [];
	lyricStr[0] = " ";
	lyricStr[1] = " ";
	lyricStr[2] = " ";

	if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
		var line = row;
		var dan = 0;
		var measure = col;
	} else {
		var line = Math.floor(row/2);
		var dan = row % 2;
		var measure = col;
	}

	for (let i = 0; i < currentVisualArray.length; i++) {

		if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {

			if (currentVisualArray[i].absEl.counters.line == line && currentVisualArray[i].absEl.counters.measure == measure && currentVisualArray[i].absEl.counters.note == 0) {

				//上段の場合
				if ( (dan == 0 && currentVisualArray[i].absEl.counters.voice == 0) ||
				//下段の場合
					 (dan == 1 && currentVisualArray[i].absEl.counters.voice != 0 && isUpperLine(line, currentVisualArray[i].absEl.counters.voice, measure) == 1) ) {
					


					var ii = i;
					
					while (true) {
						
						if (currentVisualArray[ii].absEl.type != "note" && currentVisualArray[ii].absEl.type != "rest") {
							break;
						}
						
						if (currentVisualArray[ii].absEl.counters.line > line) {
							break;
						}
					
						if (currentVisualArray[ii].absEl.type == "note") {
							
							if (currentVisualArray[ii].absEl.abcelem.lyric) {
								for (let j = 0; j < currentVisualArray[ii].absEl.abcelem.lyric.length; j++) {
									if (currentVisualArray[ii].absEl.abcelem.lyric[j].syllable == "") {
										var lyric = "_";
									} else {
										var lyric = currentVisualArray[ii].absEl.abcelem.lyric[j].syllable;
									}
									
									lyricStr[j] += lyric + " ";
								}
								for (let j = currentVisualArray[ii].absEl.abcelem.lyric.length; j < 3; j++) {
									lyricStr[j] += "_ ";
								}
							//lyricなし
							} else {
								lyricStr[0] += "_ ";
								lyricStr[1] += "_ ";
								lyricStr[2] += "_ ";
							}
							
							
						}
						
						ii++;
					}
				}
			}
			
			if (currentVisualArray[i].absEl.counters.line > line) {
				break;
			}
		}
	}

	return lyricStr;
}

//============================================================
//	選択中の小節線のタイプは？
//		""		選択中は、小節線ではない
//		|、||、|]、|:、:|、:||:
//============================================================
function getBarType() {
	res = "";
	
	if (selectVisualDataIndex > -1) {
		if (currentVisualArray[selectVisualDataIndex].absEl.type == "bar") {
			if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.type == "bar_thin") {
				res = "|";
			} else if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.type == "bar_thin_thin") {
				res = "||";
			} else if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.type == "bar_thin_thick") {
				res = "|]";
			} else if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.type == "bar_left_repeat") {
				res = "|:";
			} else if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.type == "bar_right_repeat") {
				res = ":|";
			} else if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.type == "bar_dbl_repeat") {
				res = ":||:";
			}
		}
	}
	
	return res;
}

//============================================================
//	選択中の音符は、３連符の何番目の音符か？
//		0	３連符音符ではない
//		1-3	番目の音符（1は先頭、3は右端）
//============================================================
function getCurrentTripletsNumber() {
	var res = 0;
	
	//３連符である？
	if (selectVisualDataIndex > -1) {
		//１番目？
		if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.startTriplet) {
			if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.startTriplet == 3) {
				res = 1;
			}
		} else if (selectVisualDataIndex > 0) {
			//２番目？
			if (currentVisualArray[selectVisualDataIndex-1].absEl.abcelem.startTriplet) {
				if (currentVisualArray[selectVisualDataIndex-1].absEl.abcelem.startTriplet == 3) {
					res = 2;
				}
			} else if (selectVisualDataIndex > 1) {
				//３番目？
				if (currentVisualArray[selectVisualDataIndex-2].absEl.abcelem.startTriplet) {
					if (currentVisualArray[selectVisualDataIndex-2].absEl.abcelem.startTriplet == 3) {
						res = 3;
					}
				}
			}
		}
	}

	return res;
}

//============================================================
//	選択中の音符は、５連符の何番目の音符か？
//		0	５連符音符ではない
//		1-3	番目の音符（1は先頭、5は右端）
//============================================================
function getCurrentQuintupletNumber() {
	var res = 0;
	
	//３連符である？
	if (selectVisualDataIndex > -1) {
		//１番目？
		if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.startTriplet) {
			if (currentVisualArray[selectVisualDataIndex].absEl.abcelem.startTriplet == 5) {
				res = 1;
			}
		} else if (selectVisualDataIndex > 0) {
			//２番目？
			if (currentVisualArray[selectVisualDataIndex-1].absEl.abcelem.startTriplet) {
				if (currentVisualArray[selectVisualDataIndex-1].absEl.abcelem.startTriplet == 5) {
					res = 2;
				}
			} else if (selectVisualDataIndex > 1) {
				//３番目？
				if (currentVisualArray[selectVisualDataIndex-2].absEl.abcelem.startTriplet) {
					if (currentVisualArray[selectVisualDataIndex-2].absEl.abcelem.startTriplet == 5) {
						res = 3;
					}
				} else if (selectVisualDataIndex > 2) {
					//４番目？
					if (currentVisualArray[selectVisualDataIndex-3].absEl.abcelem.startTriplet) {
						if (currentVisualArray[selectVisualDataIndex-3].absEl.abcelem.startTriplet == 5) {
							res = 4;
						}
					} else if (selectVisualDataIndex > 3) {
						//５番目？
						if (currentVisualArray[selectVisualDataIndex-4].absEl.abcelem.startTriplet) {
							if (currentVisualArray[selectVisualDataIndex-4].absEl.abcelem.startTriplet == 5) {
								res = 5;
							}
						}
					}
				}
			}
		}
	}

	return res;
}

//============================================================
//	現在のline（currentLineNo）に複旋律はあるか？
//		return	0=ない、1=あり			//1=上段にあり、2=下段にあり、上段・下段ともにあり
//============================================================
function haveCounterpointByLine() {
	let maxVoice = 0;
	for (let i = 0; i < currentVisualArray.length; i++) {
		if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
			if (currentVisualArray[i].absEl.counters.line == currentLineNo) {
				if (currentVisualArray[i].absEl.counters.voice > maxVoice) {
					maxVoice = currentVisualArray[i].absEl.counters.voice;
				}
			}
		}
	}

	if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
		return (maxVoice > 0);
	} else {
		return (maxVoice > 1);
	}
}

//============================================================
//	現在の小節（選択中の音符・休符のある小説）に複旋律はあるか？
//		return	0=ない、1=あり
//============================================================
function haveCounterpointByMeasure() {
	let tmp = currentAbcString.substring(selectBarStartIndex, selectBarEndIndex);
	return (tmp.indexOf("&") == -1) ? 0 : 1;
}

//============================================================
//	選択中の音符・休符は、ト音記号の段かヘ音記号段か
//		return  true=ト音記号の段、false=ヘ音記号段
//============================================================
function isTrebleLine() {

	let res = true;
	
	let pos = currentAbcString.lastIndexOf("K:clef=", selectNoteStartIndex);
	if (pos == -1) {
		res = (selectClefSymbol == "treble");
	
	} else if (currentAbcString.substr(pos+7, 6) == "treble") {
		res = true;
	
	} else if (currentAbcString.substr(pos+7, 4) == "bass") {
		res = false;
	}

	return res;

/*
	if (currentClefSymbol == "treble" || currentClefSymbol == "treble_treble") {
		return true;
	} else if (currentClefSymbol == "bass") {
		return false;
	} else if (currentVoice == 0) {
		return true;
	} else if (currentVoice == 1) {
		//主旋律の場合は、下段
		return (v_isMainVoice == false);
	} else {
		return false;
	}
*/
}


//============================================================
//	idx（currentVisualArrayに対するindex）の音符や休符、小節線が上段か否か
//============================================================
function isUpperLineByArrIndex(idx) {

	if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
		return true;
	
	} else {
		let pos = currentAbcString.lastIndexOf("[V:", currentVisualArray[idx].absEl.abcelem.startChar);
		if (pos != -1) {
			if (currentAbcString[pos + 4] == "1") {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}

//============================================================
//	idx（startChar, endChar）の位置が上段か否か
//============================================================
function isUpperLineByCharIndex(idx) {

	if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
		return true;
	
	} else {
		let pos = currentAbcString.lastIndexOf("[V:", idx);
		if (pos != -1) {
			if (currentAbcString[pos + 4] == "1") {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}





//============================================================
//	引数がない場合：	選択中の音符・休符は、上段かヘ下段か
//		return  true=上段、false=下段
//	引数がある場合：	line、voice は、上段かヘ下段か
//		return  0=上段、1=下段
//============================================================
function isUpperLine(line=-1, voice=-1, measure=-1) {
	//引数なし（選択中の音符・休符）
	if (line == -1) {

		if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
			return true;
		} else if (currentVoice == 0) {
			return true;
		} else if (currentVoice == 1) {
			//主旋律の場合は、下段
			return (isMainVoice() == false);
		} else {
			return false;
		}
	
	//引数あり（line、voice, measure）
	} else {
		if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
			return 0;
		} else if (voice == 0) {
			return 0;
		} else if (voice == 1) {
			let res = 0;
			//barがない場合は、複旋律なので、上段
			for (let i = 0; i < currentVisualArray.length; i++) {
				if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
					if (currentVisualArray[i].absEl.counters.line == line && currentVisualArray[i].absEl.counters.voice == voice && currentVisualArray[i].absEl.counters.measure == measure) {
						let st = currentVisualArray[i].absEl.abcelem.startChar;
						res = 1;
						while (true) {
							st--;
							if (st == 0) break;
							if (currentAbcString[st] == "\n") break;
							if (currentAbcString[st] == "|") break;
							if (currentAbcString[st] == "&") {
								res = 0;
								break;
							}
						}
						break;
					}
				}
			}
			return res;
		} else {
			return 1;
		}
	}
}

//============================================================
//	選択中の音符・休符は、主旋律か？
//		return  true=主旋律、false=副旋律
//============================================================
function isMainVoice() {
	let tmp = currentAbcString.substring(selectBarStartIndex, selectNoteStartIndex);
	return (tmp.indexOf("&") == -1);
}


//============================================================
//	選択領域の直後の、音部記号、調号、拍子記号、速度の設定値を取得
//		return [ 0:st, 1:ed, 2:"none | treble | bass", 3:"C | Cf | .... ", 4:" C | 3/4 | ...", 5:" Largo | Lent | ...", 6:"1/4=72 | 1/8=120 | ....", 7:"音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列"]
//============================================================
function getAfterSettings() {
	//selectVisualDataIndexが最終要素でない場合は、
	//	selectNoteEndIndexから（currentVisualArray[selectVisualDataIndex+1]）のstartChar間のstring
	//selectVisualDataIndexが最終要素の場合は、
	//	selectNoteEndIndexからcurrentAbcStringの終端の間のstring
	//を対象に、設定値を検索する。

	let res = [];

	//-------------------------------------------------------------
	//	１段の場合
	//-------------------------------------------------------------
	if (currentClefSymbol == "treble" || currentClefSymbol == "bass") {
		
		let topBar = false;
		let btmBar = false;
		
		if (selectNoteOrRest == "bar") {
			//現在、小節線選択で、段の先頭の小節線か否か（先頭＝前の小節線がない、又は、前の小節線との間に改行がある）
			let prevBarIdx = -1;
			for (let i = selectVisualDataIndex-1; i >= 0; i--) {
				if (currentVisualArray[i].absEl.type == "bar") {
					prevBarIdx = currentVisualArray[i].absEl.abcelem.startChar;
					break;
				} else if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
					prevBarIdx = 0;
					break;
				}
			}
			if (prevBarIdx == 0) {
				topBar = false;
			} else if (prevBarIdx == -1) {
				topBar = true;
			} else {
				if (currentAbcString.substring(prevBarIdx, selectNoteStartIndex).indexOf("\n") != -1) {
					topBar = true;
				}
			}
			//現在、小節線選択で、段の終端の小節線か否か（最終＝次の小節線がない、又は、次の小節線との間に改行がある）
			let nextBarIdx = -1;
			for (let i = selectVisualDataIndex+1; i < currentVisualArray.length; i++) {
				if (currentVisualArray[i].absEl.type == "bar") {
					nextBarIdx = currentVisualArray[i].absEl.abcelem.startChar;
					break;
				}
			}
			if (nextBarIdx == -1) {
				btmBar = true;
			} else {
				if (currentAbcString.substring(selectNoteStartIndex, nextBarIdx).indexOf("\n") != -1) {
					btmBar = true;
				}
			}
		}

		//選択が、最終の小節線（音部記号、調号、拍子記号、速度記号）
		//	次段の先頭が、[V][K:clef=bass][K:F][M:3/4][Q:"Largo"] のような構成
		if (btmBar == true) {
			//対象文字列は、selectNoteEndIndex+2から、currentVisualArray[selectVisualDataIndex+1] まで
			var st = selectNoteEndIndex + 1; //この小節線の直後には速度記号がないので、次行の先頭を採用する。
			if (selectVisualDataIndex < currentVisualArray.length-1) {
				var ed = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
			} else {
				var ed = st;
			}
			var kind = "btmBar";
		
		//選択が、先頭の小節線（音部記号、調号、拍子記号、速度記号）
		//	小節線の直後が、[K:clef=bass][K:F][M:3/4][Q:"Largo"] のような構成
		} else if (topBar == true) {
			//対象文字列は、selectNoteStartIndex+1から、currentVisualArray[selectVisualDataIndex+1] まで
			var st = selectNoteEndIndex;
			var ed = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
			var kind = "topBar";
		
		//選択が、先頭でも最終でもない小節線（音部記号、拍子記号、速度記号）
		//	小節線の直後が、[K:clef=bass][Q:"Largo"] のような構成
		} else if (selectNoteOrRest == "bar") {
			//対象文字列は、selectNoteStartIndex+1から、currentVisualArray[selectVisualDataIndex+1] まで
			var st = selectNoteEndIndex;
			var ed = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
			var kind = "midBar";
		
		//選択が、音符・休符（音部記号、速度記号）
		//	音符・休符の直後が、[K:clef=bass][Q:"Largo"] のような構成
		} else {
			//対象文字列は、selectNoteStartIndex+1から、currentVisualArray[selectVisualDataIndex+1] まで
			var st = selectNoteEndIndex;
			var ed = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
			var kind = selectNoteOrRest;
		}

		//対象文字列に対して、設定値を取得
		var str = currentAbcString.substring(st, ed);
		
		//対象文字列範囲
		res.push(st);
		res.push(ed);

		//音部記号
		var match = str.match(/\[K:clef=[^\]]+\]/);
		if (match) {
			var clef = match[0].replace("[K:clef=", "").replace("]", "");
		} else {
			var clef = "none";
		}
		res.push(clef);

		//調号
		var cleanedStr = str.replace(/\[K:clef=[^\]]+\]/g, "");  // [K:clef=...] を除去
		var matches = cleanedStr.match(/\[K:[^\]]+\]/g);  // 残りの [K:...] を取得
		if (matches) {
			var keySignature = matches[0].replace("[K:", "").replace("]", "");
		} else {
			var keySignature = "none";
		}
		res.push(keySignature);

		//拍子記号
		var match = str.match(/\[M:[^\]]+\]/);
		if (match) {
			res.push(match[0].replace("[M:", "").replace("]", ""));
		} else {
			res.push("none");
		}

		//速度（文字）
		//１段の場合、２段の最終小節以外の場合
		var match = str.match(/\[Q:[^\]]+\]/);  // [Q: と ] で囲まれた部分を取得
		if (match) {
		    let qContent = match[0];  // 取得した [Q:～] の内容
		    let textPart = qContent.match(/\"([^\"]+)\"/);  // "" で囲まれた部分を取得
		    //let tempoPart = qContent.match(/1\/4=([\d]+)/);  // 1/4=以降の数値を取得
			let tempoPart = qContent.replace(textPart[1].trim(), "").replace(/\"/g, "").replace("[Q:", "").replace("]", "");		//"

		    if (textPart) {
		    	res.push(textPart[1].trim());
		    } else {
		    	res.push("none");
		    }
		    
		    if (tempoPart) {
		    	res.push(tempoPart.trim());
		    } else {
		    	res.push("none");
		    }
		} else {
	    	res.push("none");
	    	res.push("none");
		}
			
		//音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列
		var val = "";
		if (clef != "none" && keySignature != "none") {
			val = "[K:clef=" + clef + "][K:" + keySignature + "]";
			
		} else if (clef != "none") {
			val = "[K:clef=" + clef + "]";
		
		} else if (keySignature != "none") {
			val = "[K:" + keySignature + "]";
		}
		res.push(val);

		res.push(kind);
		//console.log("getAfterSettings() 1段", str, res);

	//-------------------------------------------------------------
	//	２段の場合
	//-------------------------------------------------------------
	} else {
		let topBar = false;
		let btmBar = false;
		let danUp = false;
	
		if (selectNoteOrRest == "bar") {
			//現在、小節線選択で、上段・下段の取得
			let idx = currentAbcString.lastIndexOf("[V:", selectNoteStartIndex);
			if (currentAbcString[idx + 4] == "1") {
				danUp = true;
			} else {
				danUp = false;
			}

			//現在、小節線選択で、段の先頭の小節線か否か（先頭＝前の小節線がない、又は、前の小節線との間に改行がある）
			let prevBarIdx = -1;
			for (let i = selectVisualDataIndex-1; i >= 0; i--) {
				if (currentVisualArray[i].absEl.type == "bar") {
					prevBarIdx = currentVisualArray[i].absEl.abcelem.startChar;
					break;
				} else if (currentVisualArray[i].absEl.type == "note" || currentVisualArray[i].absEl.type == "rest") {
					prevBarIdx = 0;
					break;
				}
			}
			if (prevBarIdx == 0) {
				topBar = false;
			} else if (prevBarIdx == -1) {
				topBar = true;
			} else {
				if (currentAbcString.substring(prevBarIdx, selectNoteStartIndex).indexOf("\n") != -1) {
					topBar = true;
				}
			}
			//現在、小節線選択で、段の終端の小節線か否か（最終＝次の小節線がない、又は、次の小節線との間に改行がある）
			let nextBarIdx = -1;
			for (let i = selectVisualDataIndex+1; i < currentVisualArray.length; i++) {
				if (currentVisualArray[i].absEl.type == "bar") {
					nextBarIdx = currentVisualArray[i].absEl.abcelem.startChar;
					break;
				}
			}
			if (nextBarIdx == -1) {
				btmBar = true;
			} else {
				if (currentAbcString.substring(selectNoteStartIndex, nextBarIdx).indexOf("\n") != -1) {
					btmBar = true;
				}
			}
		}
	
		//選択が、最終の小節線（音部記号、調号、拍子記号、速度記号）
		//	次段の先頭が、[V][K:clef=bass][K:F][M:3/4][Q:"Largo"] のような構成
		if (btmBar == true) {
			//対象文字列は、selectNoteEndIndex+2から、currentVisualArray[selectVisualDataIndex+1] まで
			if (danUp == true) {
				var st = currentAbcString.indexOf("[V: 1", selectNoteEndIndex);
			} else {
				var st = currentAbcString.indexOf("[V: 2", selectNoteEndIndex);
			}
			if (st != -1) {
				var ed = st;
				for (let i = selectVisualDataIndex; i < currentVisualArray.length; i++) {
					if (currentVisualArray[i].absEl.abcelem.startChar > st) {
						var ed = currentVisualArray[i].absEl.abcelem.startChar;
						break;
					}
				}
			} else {
				var ed = st;
			}
			var kind = "btmBar";
		
		//選択が、先頭の小節線（音部記号、調号、拍子記号、速度記号）
		//	小節線の直後が、[K:clef=bass][K:F][M:3/4][Q:"Largo"] のような構成
		} else if (topBar == true) {
			//対象文字列は、selectNoteStartIndex+1から、currentVisualArray[selectVisualDataIndex+1] まで
			var st = selectNoteEndIndex;
			var ed = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
			var kind = "topBar";
		
		//選択が、先頭でも最終でもない小節線（音部記号、拍子記号、速度記号）
		//	小節線の直後が、[K:clef=bass][Q:"Largo"] のような構成
		} else if (selectNoteOrRest == "bar") {
			//対象文字列は、selectNoteStartIndex+1から、currentVisualArray[selectVisualDataIndex+1] まで
			var st = selectNoteEndIndex;
			var ed = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
			var kind = "midBar";
		
		//選択が、音符・休符（音部記号、速度記号）
		//	音符・休符の直後が、[K:clef=bass][Q:"Largo"] のような構成
		} else {
			//対象文字列は、selectNoteStartIndex+1から、currentVisualArray[selectVisualDataIndex+1] まで
			var st = selectNoteEndIndex;
			var ed = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
			var kind = selectNoteOrRest;
		}


		//対象文字列に対して、設定値を取得
		var str = currentAbcString.substring(st, ed);

//	console.log("@@@", str, st, ed, kind, topBar, btmBar, danUp);
		
		//対象文字列範囲
		res.push(st);
		res.push(ed);

		if (selectVisualDataIndex < currentVisualArray.length-1) {
			var st0 = selectNoteStartIndex;
			var ed0 = currentVisualArray[selectVisualDataIndex+1].absEl.abcelem.startChar;
		} else {
			st0 = selectNoteStartIndex;
			ed0 = st0;
		}

		//音部記号
		var match = currentAbcString.substring(st0, ed0).match(/\[K:clef=[^\]]+\]/);		//(/\[V: [12] K:clef=[^\]]+\]/);
		if (match) {
			var clef = match[0].replace("[K:clef=", "").replace("]", "");
		} else {
			var clef = "none";
		}
		res.push(clef);

		//調号
		//var cleanedStr = currentAbcString.substring(st0, ed0).replace(/\[K:clef=[^\]]+\]/g, "");  // [K:clef=...] を除去
		//var matches = cleanedStr.match(/\[K:[^\]]+\]/g);  // 残りの [K:...] を取得
		var cleanedStr = str.replace(/\[K:clef=[^\]]+\]/g, "");  // [K:clef=...] を除去
		var matches = cleanedStr.match(/\[K:[^\]]+\]/g);  // 残りの [K:...] を取得
		if (matches) {
			var keySignature = matches[0].replace("[K:", "").replace("]", "");
		} else {
			var keySignature = "none";
		}
		res.push(keySignature);

		//拍子記号
		var match = currentAbcString.substring(st0, ed0).match(/\[M:[^\]]+\]/);
		if (match) {
			res.push(match[0].replace("[M:", "").replace("]", ""));
		} else {
			res.push("none");
		}

		//速度（文字）
		//１段の場合、２段の最終小節以外の場合
		if (danUp == true) {
			var match = str.match(/\[Q:[^\]]+\]/);  // [Q: と ] で囲まれた部分を取得
		} else {
			var match = currentAbcString.substring(st0, ed0).match(/\[Q:[^\]]+\]/);  // [Q: と ] で囲まれた部分を取得
		}
		if (match) {
		    let qContent = match[0];  // 取得した [Q:～] の内容
		    let textPart = qContent.match(/\"([^\"]+)\"/);  // "" で囲まれた部分を取得
		    //let tempoPart = qContent.match(/1\/4=([\d]+)/);  // 1/4=以降の数値を取得
			let tempoPart = qContent.replace(textPart[1].trim(), "").replace(/\"/g, "").replace("[Q:", "").replace("]", "");		//"
		    
		    if (textPart) {
		    	res.push(textPart[1].trim());
		    } else {
		    	res.push("none");
		    }
		    
		    if (tempoPart) {
		    	res.push(tempoPart.trim());
		    } else {
		    	res.push("none");
		    }
		} else {
	    	res.push("none");
	    	res.push("none");
		}
			
		//音部記号と調号を組み合わせて、音部記号・調号設定イメージセレクトのvalue値にした文字列
		var val = "";
		if (clef != "none" && keySignature != "none") {
			val = "[K:clef=" + clef + "][K:" + keySignature + "]";
			
		} else if (clef != "none") {
			val = "[K:clef=" + clef + "]";
		
		} else if (keySignature != "none") {
			val = "[K:" + keySignature + "]";
		}
		res.push(val);			//[7]

		res.push(kind);			//[8]
		res.push(danUp);		//[9]
		//console.log("getAfterSettings() 1段", str, res);
	}

	return res;
}















//##########################################################################
//##########################################################################
//	汎用ユーティリティ関数
//		四捨五入により、小数以下５桁までを求める	roundToFive(num);
//		小数を分数表記の文字列に変換				decimalToFraction(decimal);
//		整数部分を2の倍数の和に分解し、
//		　小数部分を含む数値を0.25 + 1 + 2 + 4 
//		　のような形式の文字列に変換				decomposeToSums(n);
//		入力された文字列から、正規表現を使って整数や分数を抽出（未使用）
//													sumNumbersInString(input);
//##########################################################################

//============================================================
//	四捨五入により、小数以下５桁までを求める
//============================================================
function roundToFive(num) {
	return Math.round(num * 100000) / 100000;
}

//============================================================
//	小数を分数表記の文字列に変換
//============================================================
function decimalToFraction(decimal) {
	//-------------------------------------------
	//最大公約数を計算（ユークリッドの互除法）
	//-------------------------------------------
	function gcd(a, b) {
		if (b === 0) {
			return a;
		}
		return gcd(b, a % b);
	}
	//-------------------------------------------
    if (decimal % 1 === 0) {
		let res = decimal.toString();
		res = res.replace("1", "");
        return res; // すでに整数ならそのまま返す
    }

    const precision = 1e9; // 許容される精度
    let numerator = Math.round(decimal * precision);
    let denominator = precision;

    // 分母と分子の最大公約数で割る
    const divisor = gcd(numerator, denominator);
    numerator /= divisor;
    denominator /= divisor;

	let res = `${numerator}/${denominator}`;
	res = res.replace("1/", "/");
	res = res.replace("1", "");

    return res;
}

//============================================================
//	数値（小数以下あり）を、
//	8, 4, 2, 1, 0.5, 0.25, 0.125 の和に分解
//============================================================
function decomposeToSums(n) {
	let terms = [8, 4, 2, 1, 0.5, 0.25, 0.125];

    let result = [];
    
    for (let term of terms) {
        while (n >= term) {
            n -= term;
            result.push(decimalToFraction(term));
        }
    }

    // 結果を逆順にして結合
    return result.reverse().join('+');
}

//============================================================
//	操作説明
//============================================================
function openHelp() {
	if (paramMSCMode.substr(0, 10) == "wbtbuilder") {
		var url = "./MSC/manual/operationManual.html";
	} else {
		var url = "./manual/operationManual.html";
	}
	
	if (location.href.indexOf("/office/") != -1) {
		url = "." + url;
	};
	window.open(url, "winMscHelp", "width=642,height=720,toolbar=no,menubar=no,scrollbars=no");
}

//============================================================
//	パラメータに基づく、メニューの表示設定
//============================================================
var cfgSelClefSymbolDisabled = false;						//音部記号
var cfgSelKeySignatureDisabled = false;						//調号
var cfgSelTimeSignatureSymbolDisabled = false;				//拍子記号
var cfgBtnTitleAndAuthorDisabled = false;					//曲名・作者

var cfgSelTempoMarkingsDisabled = false;					//速度記号
var cfgOptTempoMarkingsLargoDisabled = false;				//速度記号　Largo
var cfgOptTempoMarkingsLentoDisabled = false;				//速度記号　Lento
var cfgOptTempoMarkingsAdagioDisabled = false;				//速度記号　Adagio
var cfgOptTempoMarkingsAndanteDisabled = false;				//速度記号　Andante
var cfgOptTempoMarkingsModeratoDisabled = false;			//速度記号　Moderato
var cfgOptTempoMarkingsAllegrettoDisabled = false;			//速度記号　Allegretto
var cfgOptTempoMarkingsAllegroDisabled = false;				//速度記号　Allegro
var cfgOptTempoMarkingsVivaceDisabled = false;				//速度記号　Vivace
var cfgOptTempoMarkingsPrestoDisabled = false;				//速度記号　Presto

var cfgBtnTempoMarkings2BaseDisabled = false;				//メトロノーム基準音符
var cfgBtnTempoMarkings2Base1Disabled = false;				//メトロノーム基準音符　付点２分音符
var cfgBtnTempoMarkings2Base2Disabled = false;				//メトロノーム基準音符　２分音符
var cfgBtnTempoMarkings2Base3Disabled = false;				//メトロノーム基準音符　付点４分音符
var cfgBtnTempoMarkings2Base4Disabled = false;				//メトロノーム基準音符　４分音符
var cfgBtnTempoMarkings2Base5Disabled = false;				//メトロノーム基準音符　８分音符

var cfgTxtTempoMarkings2Disabled = false;					//メトロノーム記号
var cfgSelRowsCountDisabled = false;						//段数

var cfgBtnMeasuresCountDisabled = false;					//各段の小節数
var cfgMeasuresEditable = [];								//編集を禁止する小節
for (let i = 0; i < cMaxLines; i++) {
	cfgMeasuresEditable[i] = [];
	for (let k = 0; k < 2; k++) {
		cfgMeasuresEditable[i][k] = [];
		for (let j = 0; j < cMaxMeasures; j++) {
			cfgMeasuresEditable[i][k][j] = true;
		}
	}
}

var cfgSelLyricDisabled = false;							//歌詞番数
var cfgSelBarLineDisabled = false;							//小節線
var cfgBtnIncompleteMeasureDisabled = false;				//不完全小節

var cfgBtnNoteDisabled = false;								//音符
var cfgBtnNote8Disabled = false;
var cfgBtnNote6Disabled = false;
var cfgBtnNote4Disabled = false;
var cfgBtnNote3Disabled = false;
var cfgBtnNote2Disabled = false;
var cfgBtnNote1_5Disabled = false;
var cfgBtnNote1Disabled = false;
var cfgBtnNote0_75Disabled = false;
var cfgBtnNote0_5Disabled = false;
var cfgBtnNote0_375Disabled = false;
var cfgBtnNote0_25Disabled = false;
var cfgBtnNote0_125Disabled = false;

var cfgBtnRestDisabled = false;								//休符
var cfgBtnRest8Disabled = false;
var cfgBtnRest6Disabled = false;
var cfgBtnRest4Disabled = false;
var cfgBtnRest3Disabled = false;
var cfgBtnRest2Disabled = false;
var cfgBtnRest1_5Disabled = false;
var cfgBtnRest1Disabled = false;
var cfgBtnRest0_75Disabled = false;
var cfgBtnRest0_5Disabled = false;
var cfgBtnRest0_375Disabled = false;
var cfgBtnRest0_25Disabled = false;
var cfgBtnRest0_125Disabled = false;

var cfgBtnSharpFlatDisabled = false;						//臨時記号
var cfgBtnSharpFlatSharpDisabled = false;
var cfgBtnSharpFlatFlatDisabled = false;
var cfgBtnSharpFlatNaturalDisabled = false;

var cfgBtnTaiSlurDisabled = false;							//タイ・スラー
var cfgBtnTaiSlurTaiDisabled = false;
var cfgBtnTaiSlurSlurDisabled = false;

var cfgBtnBreathDisabled = false;							//ブレス記号

var cfgBtnArticulationDisabled = false;						//アーティキュレーション
var cfgBtnArticulationAccentDisabled = false;
var cfgBtnArticulationStaccatoDisabled = false;
var cfgBtnArticulationStaccatissimoDisabled = false;
var cfgBtnArticulationUpbowDisabled = false;
var cfgBtnArticulationDownbowDisabled = false;
var cfgBtnArticulationRollDisabled = false;
var cfgBtnArticulationTenutoDisabled = false;
var cfgBtnArticulationLowermordentDisabled = false;
var cfgBtnArticulationUppermordentDisabled = false;
var cfgBtnArticulationTrillDisabled = false;
var cfgBtnArticulationTurnDisabled = false;
var cfgBtnArticulationFermataDisabled = false;

var cfgBtnChordDisabled = false;							//和音
var cfgBtnNoteArtDisabled = false;							//装飾音符
var cfgBtnNoteSeparateJoinDisabled = false;					//８分音符等の分離・結合
var cfgBtnTripletsDisabled = false;							//３連符
var cfgBtnQuintupletDisabled = false;						//５連符
var cfgBtnNoteAddDisabled = false;							//複旋律

var cfgSelDynamicsDisabled = false;							//強弱記号

var cfgOptDynamicsSbDisabled = false;						//強弱記号　<
var cfgOptDynamicsBsDisabled = false;						//強弱記号　>
var cfgOptDynamicsFfffDisabled = false;						//強弱記号　ffff
var cfgOptDynamicsFffDisabled = false;						//強弱記号　fff
var cfgOptDynamicsFfDisabled = false;						//強弱記号　ff
var cfgOptDynamicsFDisabled = false;						//強弱記号　f
var cfgOptDynamicsMfDisabled = false;						//強弱記号　mf
var cfgOptDynamicsMpDisabled = false;						//強弱記号　mp
var cfgOptDynamicsPDisabled = false;						//強弱記号　p
var cfgOptDynamicsPpDisabled = false;						//強弱記号　pp
var cfgOptDynamicsPppDisabled = false;						//強弱記号　ppp
var cfgOptDynamicsPpppDisabled = false;						//強弱記号　pppp
var cfgOptDynamicsFpDisabled = false;						//強弱記号　fp
var cfgOptDynamicsFzDisabled = false;						//強弱記号　fz
var cfgOptDynamicsSfDisabled = false;						//強弱記号　sf
var cfgOptDynamicsSfpDisabled = false;						//強弱記号　sfp
var cfgOptDynamicsSfzDisabled = false;						//強弱記号　sfz
var cfgOptDynamicsRfDisabled = false;						//強弱記号　rf
var cfgOptDynamicsRfzDisabled = false;						//強弱記号　rfz

var cfgSelRepeatSignsDisabled = false;						//反復記号

var cfgOptRepeatSignsDcDisabled = false;					//反復記号	DC
var cfgOptRepeatSignsFineDisabled = false;					//反復記号	fine
var cfgOptRepeatSignsDsDisabled = false;					//反復記号	DS
var cfgOptRepeatSignsSegnoDisabled = false;					//反復記号	segno
var cfgOptRepeatSignsCodaDisabled = false;					//反復記号	coda
var cfgOptRepeatSigns1Disabled = false;						//反復記号	「1
var cfgOptRepeatSigns2Disabled = false;						//反復記号	「2

var cfgBtnNewDisabled = false;								//新規
var cfgBtnOpenDisabled = false;								//開く
var cfgBtnSaveDisabled = false;								//保存
var cfgBtnPrintDisabled = false;							//印刷
var cfgBtnPlayDisabled = false;								//演奏
var cfgChkAbcEditorDisabled = false;						//abcエディタ
var cfgBtnHelpDisabled = false;								//操作説明

function setMenuSetting(para) {
	//------------------------------------------------------------
	//	16進数文字列を2進数文字列に戻す関数 (BigInt使用)
	//------------------------------------------------------------
	function hexToBinary(hexStr) {
		const binaryStr = BigInt("0x" + hexStr).toString(2); // 16進数をBigIntに変換し、2進数文字列に変換
		return binaryStr;
	}
	//------------------------------------------------------------

	//------------------------------------------------------------
	//パラメータがない場合は、全メニューを有効とする
	//------------------------------------------------------------
	if (para == "" || paramMSCMode == "wbtbuilderKadaiToi") {
		//音部記号
		cfgSelClefSymbolDisabled = false;
		setDisabledSelClefSymbol(false);
		//調号
		cfgSelKeySignatureDisabled = false;
		setDisabledSelKeySignature(false);
		//拍子記号
		cfgSelTimeSignatureSymbolDisabled = false;
		setDisabledSelTimeSignatureSymbol(false);
		//曲名・作者
		cfgBtnTitleAndAuthorDisabled = false;
		document.getElementById("btnTitle").disabled = false;

		//速度記号
		cfgSelTempoMarkingsDisabled = false;
		document.getElementById("selTempoMarkings").disabled = false;
		//速度記号	Largo
		cfgOptTempoMarkingsLargoDisabled = false;
		document.getElementById("selTempoMarkings").options[1].style.display = "";
		//速度記号	Lento
		cfgOptTempoMarkingsLentoDisabled = false;
		document.getElementById("selTempoMarkings").options[2].style.display = "";
		//速度記号	Adagio
		cfgOptTempoMarkingsAdagioDisabled = false;
		document.getElementById("selTempoMarkings").options[3].style.display = "";
		//速度記号	Andante
		cfgOptTempoMarkingsAndanteDisabled = false;
		document.getElementById("selTempoMarkings").options[4].style.display = "";
		//速度記号	Moderato
		cfgOptTempoMarkingsModeratoDisabled = false;
		document.getElementById("selTempoMarkings").options[5].style.display = "";
		//速度記号	Allegretto
		cfgOptTempoMarkingsAllegrettoDisabled = false;
		document.getElementById("selTempoMarkings").options[6].style.display = "";
		//速度記号	Allegro
		cfgOptTempoMarkingsAllegroDisabled = false;
		document.getElementById("selTempoMarkings").options[7].style.display = "";
		//速度記号	Vivace
		cfgOptTempoMarkingsVivaceDisabled = false;
		document.getElementById("selTempoMarkings").options[8].style.display = "";
		//速度記号	Presto
		cfgOptTempoMarkingsPrestoDisabled = false;
		document.getElementById("selTempoMarkings").options[9].style.display = "";

		//メトロノーム記号の基準音符
		cfgBtnTempoMarkings2BaseDisabled = false;
		document.getElementById("btnTempoMarkings2").disabled = false;
		
		//メトロノーム基準音符　付点２分音符
		cfgBtnTempoMarkings2Base1Disabled = false;
		document.getElementById("btnTempoMarkings2_1").disabled = false;
		//メトロノーム基準音符　２分音符
		cfgBtnTempoMarkings2Base2Disabled = false;
		document.getElementById("btnTempoMarkings2_2").disabled = false;
		//メトロノーム基準音符　付点４分音符
		cfgBtnTempoMarkings2Base3Disabled = false;
		document.getElementById("btnTempoMarkings2_3").disabled = false;
		//メトロノーム基準音符　４分音符
		cfgBtnTempoMarkings2Base4Disabled = false;
		document.getElementById("btnTempoMarkings2_4").disabled = false;
		//メトロノーム基準音符　８分音符
		cfgBtnTempoMarkings2Base5Disabled = false;
		document.getElementById("btnTempoMarkings2_5").disabled = false;

		//メトロノーム記号
		cfgTxtTempoMarkings2Disabled = false;
		document.getElementById("txtTempoMarkings2").disabled = false;

		//段数
		cfgSelRowsCountDisabled = false;
		document.getElementById("selRowsCount").disabled = false;
		//各段の小節数
		cfgBtnMeasuresCountDisabled = false;
		document.getElementById("btnMeasuresCount").disabled = false;
		//編集を禁止する小節
		for (let i = 0; i < cMaxLines; i++) {
			for (let k = 0; k < 2; k++) {
				for (let j = 0; j < cMaxMeasures; j++) {
					cfgMeasuresEditable[i][k][j] = true;
				}
			}
		}

		//歌詞番数
		cfgSelLyricDisabled = false;
		document.getElementById("selLyric").disabled = false;

		//小節線
		cfgSelBarLineDisabled = false;
		setDisabledSelBarLine(false);

		//不完全小節
		cfgBtnIncompleteMeasureDisabled = false;
		document.getElementById("btnNoteDel").disabled = false;
		document.getElementById("btnNoteOrg").disabled = false;

		//音符
		cfgBtnNoteDisabled = false;
		cfgBtnNote8Disabled = false;
		cfgBtnNote6Disabled = false;
		cfgBtnNote4Disabled = false;
		cfgBtnNote3Disabled = false;
		cfgBtnNote2Disabled = false;
		cfgBtnNote1_5Disabled = false;
		cfgBtnNote1Disabled = false;
		cfgBtnNote0_75Disabled = false;
		cfgBtnNote0_5Disabled = false;
		cfgBtnNote0_375Disabled = false;
		cfgBtnNote0_25Disabled = false;
		cfgBtnNote0_125Disabled = false;

		//休符
		cfgBtnRestDisabled = false;
		cfgBtnRest8Disabled = false;
		cfgBtnRest6Disabled = false;
		cfgBtnRest4Disabled = false;
		cfgBtnRest3Disabled = false;
		cfgBtnRest2Disabled = false;
		cfgBtnRest1_5Disabled = false;
		cfgBtnRest1Disabled = false;
		cfgBtnRest0_75Disabled = false;
		cfgBtnRest0_5Disabled = false;
		cfgBtnRest0_375Disabled = false;
		cfgBtnRest0_25Disabled = false;
		cfgBtnRest0_125Disabled = false;
		
		//臨時記号
		cfgBtnSharpFlatDisabled = false;
		cfgBtnSharpFlatSharpDisabled = false;
		cfgBtnSharpFlatFlatDisabled = false;
		cfgBtnSharpFlatNaturalDisabled = false;
		
		//タイ・スラー
		cfgBtnTaiSlurDisabled = false;							//タイ・スラー
		cfgBtnTaiSlurTaiDisabled = false;
		cfgBtnTaiSlurSlurDisabled = false;
		
		//ブレス記号
		cfgBtnBreathDisabled = false;
		
		//アーティキュレーション
		cfgBtnArticulationDisabled = false;
		cfgBtnArticulationAccentDisabled = false;
		cfgBtnArticulationStaccatoDisabled = false;
		cfgBtnArticulationStaccatissimoDisabled = false;
		cfgBtnArticulationUpbowDisabled = false;
		cfgBtnArticulationDownbowDisabled = false;
		cfgBtnArticulationRollDisabled = false;
		cfgBtnArticulationTenutoDisabled = false;
		cfgBtnArticulationLowermordentDisabled = false;
		cfgBtnArticulationUppermordentDisabled = false;
		cfgBtnArticulationTrillDisabled = false;
		cfgBtnArticulationTurnDisabled = false;
		cfgBtnArticulationFermataDisabled = false;
		
		//和音
		cfgBtnChordDisabled = false;
		
		//装飾音符
		cfgBtnNoteArtDisabled = false;
		
		//８分音符等の分離・結合
		cfgBtnNoteSeparateJoinDisabled = false;
		
		//３連符
		cfgBtnTripletsDisabled = false;	
		
		//５連符
		cfgBtnQuintupletDisabled = false;	
		
		//複旋律
		cfgBtnNoteAddDisabled = false;	
		
		//強弱記号
		cfgSelDynamicsDisabled = false;
		document.getElementById("selDynamics").options[1].style.display = "";
		document.getElementById("selDynamics").options[2].style.display = "";
		document.getElementById("selDynamics").options[3].style.display = "";
		document.getElementById("selDynamics").options[4].style.display = "";
		document.getElementById("selDynamics").options[5].style.display = "";
		document.getElementById("selDynamics").options[6].style.display = "";
		document.getElementById("selDynamics").options[7].style.display = "";
		document.getElementById("selDynamics").options[8].style.display = "";
		document.getElementById("selDynamics").options[9].style.display = "";
		document.getElementById("selDynamics").options[10].style.display = "";
		document.getElementById("selDynamics").options[11].style.display = "";
		document.getElementById("selDynamics").options[12].style.display = "";
		document.getElementById("selDynamics").options[13].style.display = "";
		document.getElementById("selDynamics").options[14].style.display = "";
		document.getElementById("selDynamics").options[15].style.display = "";
		document.getElementById("selDynamics").options[16].style.display = "";
		document.getElementById("selDynamics").options[17].style.display = "";
		document.getElementById("selDynamics").options[18].style.display = "";
		document.getElementById("selDynamics").options[19].style.display = "";
		document.getElementById("selDynamics").options[20].style.display = "";
		document.getElementById("selDynamics").options[21].style.display = "";
		
		//反復記号
		cfgSelRepeatSignsDisabled = false;
		document.getElementById("selRepeatSigns").options[1].style.display = "";
		document.getElementById("selRepeatSigns").options[2].style.display = "";
		document.getElementById("selRepeatSigns").options[3].style.display = "";
		document.getElementById("selRepeatSigns").options[4].style.display = "";
		document.getElementById("selRepeatSigns").options[5].style.display = "";
		document.getElementById("selRepeatSigns").options[6].style.display = "";
		document.getElementById("selRepeatSigns").options[7].style.display = "";
		
		//新規
		cfgBtnNewDisabled = false;
		document.getElementById("btnNew").disabled = false;
		//開く
		cfgBtnOpenDisabled = false;
		document.getElementById("btnOpen").disabled = false;
		//保存
		cfgBtnSaveDisabled = false;
		document.getElementById("btnSave").disabled = false;
		//印刷
		cfgBtnPrintDisabled = false;
		document.getElementById("btnPrint").disabled = false;
		//演奏
		cfgBtnPlayDisabled = false;
		document.getElementById("btnPlay").disabled = false;

		//abcエディタ
		cfgChkAbcEditorDisabled = false;
		document.getElementById("spanAbcEditor").style.visibility = "visible";
		//操作説明
		cfgBtnHelpDisabled = false;
		document.getElementById("btnHelp").style.visibility = "visible";

	} else {
		
		let bPara = hexToBinary(para);
		let idx = 1;

		//音部記号
		cfgSelClefSymbolDisabled = (bPara.substr(idx++, 1) == "0");
		setDisabledSelClefSymbol(cfgSelClefSymbolDisabled);
		//調号
		cfgSelKeySignatureDisabled = (bPara.substr(idx++, 1) == "0");
		setDisabledSelKeySignature(cfgSelKeySignatureDisabled);
		//拍子記号
		cfgSelTimeSignatureSymbolDisabled = (bPara.substr(idx++, 1) == "0");
		setDisabledSelTimeSignatureSymbol(cfgSelTimeSignatureSymbolDisabled);
		//曲名・作者
		cfgBtnTitleAndAuthorDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnTitle").disabled = cfgBtnTitleAndAuthorDisabled;

		//速度記号
		cfgSelTempoMarkingsDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("selTempoMarkings").disabled = cfgSelTempoMarkingsDisabled;
		//速度記号	Largo
		document.getElementById("selTempoMarkings").options[1].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		//速度記号	Lento
		document.getElementById("selTempoMarkings").options[2].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		//速度記号	Adagio
		document.getElementById("selTempoMarkings").options[3].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		//速度記号	Andante
		document.getElementById("selTempoMarkings").options[4].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		//速度記号	Moderato
		document.getElementById("selTempoMarkings").options[5].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		//速度記号	Allegretto
		document.getElementById("selTempoMarkings").options[6].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		//速度記号	Allegro
		document.getElementById("selTempoMarkings").options[7].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		//速度記号	Vivace
		document.getElementById("selTempoMarkings").options[8].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		//速度記号	Presto
		document.getElementById("selTempoMarkings").options[9].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";

		//メトロノーム記号の基準音符
		cfgBtnTempoMarkings2BaseDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnTempoMarkings2").disabled = cfgBtnTempoMarkings2BaseDisabled;
		//メトロノーム基準音符　付点２分音符
		cfgBtnTempoMarkings2Base1Disabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnTempoMarkings2_1").disabled = cfgBtnTempoMarkings2Base1Disabled;
		//メトロノーム基準音符　２分音符
		cfgBtnTempoMarkings2Base2Disabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnTempoMarkings2_2").disabled = cfgBtnTempoMarkings2Base2Disabled;
		//メトロノーム基準音符　付点４分音符
		cfgBtnTempoMarkings2Base3Disabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnTempoMarkings2_3").disabled = cfgBtnTempoMarkings2Base3Disabled;
		//メトロノーム基準音符　４分音符
		cfgBtnTempoMarkings2Base4Disabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnTempoMarkings2_4").disabled = cfgBtnTempoMarkings2Base4Disabled;
		//メトロノーム基準音符　８分音符
		cfgBtnTempoMarkings2Base5Disabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnTempoMarkings2_5").disabled = cfgBtnTempoMarkings2Base5Disabled;

		//メトロノーム記号
		cfgTxtTempoMarkings2Disabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("txtTempoMarkings2").disabled = cfgTxtTempoMarkings2Disabled;

		//段数
		cfgSelRowsCountDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("selRowsCount").disabled = cfgSelRowsCountDisabled;
		//各段の小節数
		cfgBtnMeasuresCountDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnMeasuresCount").disabled = cfgBtnMeasuresCountDisabled;
		//編集を禁止する小節
		for (let i = 0; i < cMaxLines; i++) {
			for (let k = 0; k < 2; k++) {
				for (let j = 0; j < cMaxMeasures; j++) {
					cfgMeasuresEditable[i][k][j] = (bPara.substr(idx++, 1) == "1");
				}
			}
		}

		//歌詞番数
		cfgSelLyricDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("selLyric").disabled = cfgSelLyricDisabled;
		//小節線
		cfgSelBarLineDisabled = (bPara.substr(idx++, 1) == "0");
		setDisabledSelBarLine(cfgSelBarLineDisabled);

		//不完全小節
		cfgBtnIncompleteMeasureDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnNoteDel").disabled = cfgBtnIncompleteMeasureDisabled;
		document.getElementById("btnNoteOrg").disabled = cfgBtnIncompleteMeasureDisabled;

		//音符
		cfgBtnNoteDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote8Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote6Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote4Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote3Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote2Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote1_5Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote1Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote0_75Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote0_5Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote0_375Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote0_25Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnNote0_125Disabled = (bPara.substr(idx++, 1) == "0");

		//休符
		cfgBtnRestDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest8Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest6Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest4Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest3Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest2Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest1_5Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest1Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest0_75Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest0_5Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest0_375Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest0_25Disabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnRest0_125Disabled = (bPara.substr(idx++, 1) == "0");

		//臨時記号
		cfgBtnSharpFlatDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnSharpFlatSharpDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnSharpFlatFlatDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnSharpFlatNaturalDisabled = (bPara.substr(idx++, 1) == "0");

		//タイ・スラー
		cfgBtnTaiSlurDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnTaiSlurTaiDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnTaiSlurSlurDisabled = (bPara.substr(idx++, 1) == "0");

		//ブレス記号
		cfgBtnBreathDisabled = (bPara.substr(idx++, 1) == "0");

		//アーティキュレーション
		cfgBtnArticulationDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationAccentDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationStaccatoDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationStaccatissimoDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationUpbowDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationDownbowDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationRollDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationTenutoDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationLowermordentDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationUppermordentDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationTrillDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationTurnDisabled = (bPara.substr(idx++, 1) == "0");
		cfgBtnArticulationFermataDisabled = (bPara.substr(idx++, 1) == "0");

		//和音
		cfgBtnChordDisabled = (bPara.substr(idx++, 1) == "0");
		//装飾音符
		cfgBtnNoteArtDisabled = (bPara.substr(idx++, 1) == "0");
		//８分音符等の分離・結合
		cfgBtnNoteSeparateJoinDisabled = (bPara.substr(idx++, 1) == "0");
		//３連符
		cfgBtnTripletsDisabled = (bPara.substr(idx++, 1) == "0");
		//５連符
		cfgBtnQuintupletDisabled = (bPara.substr(idx++, 1) == "0");
		//複旋律
		cfgBtnNoteAddDisabled = (bPara.substr(idx++, 1) == "0");

		//強弱記号
		cfgSelDynamicsDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("selDynamics").options[1].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[2].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[3].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[4].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[5].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[6].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[7].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[8].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[9].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[10].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[11].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[12].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[13].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[14].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[15].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[16].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[17].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[18].style.display = (bPara.substr(idx, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[19].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[20].style.display = (bPara.substr(idx, 1) == "0") ? "none" : "";
		document.getElementById("selDynamics").options[21].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";

		//反復記号
		cfgSelRepeatSignsDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("selRepeatSigns").options[1].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selRepeatSigns").options[2].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selRepeatSigns").options[3].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selRepeatSigns").options[4].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selRepeatSigns").options[5].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selRepeatSigns").options[6].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";
		document.getElementById("selRepeatSigns").options[7].style.display = (bPara.substr(idx++, 1) == "0") ? "none" : "";

		//新規
		cfgBtnNewDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnNew").disabled = cfgBtnNewDisabled;
		//開く
		cfgBtnOpenDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnOpen").disabled = cfgBtnOpenDisabled;
		//保存
		cfgBtnSaveDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnSave").disabled = cfgBtnSaveDisabled;
		//印刷
		cfgBtnPrintDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnPrint").disabled = cfgBtnPrintDisabled;
		//演奏
		cfgBtnPlayDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("btnPlay").disabled = cfgBtnPlayDisabled;

		//abcエディタ
		cfgChkAbcEditorDisabled = (bPara.substr(idx++, 1) == "0");
		document.getElementById("spanAbcEditor").style.visibility = (cfgChkAbcEditorDisabled == true) ? "hidden" : "visible";
		//操作説明
		cfgBtnHelpDisabled =(bPara.substr(idx++, 1) == "0");
		document.getElementById("btnHelp").style.visibility = (cfgBtnHelpDisabled == true) ? "hidden" : "visible";
	}
}

//============================================================
//	未使用
//
//	入力された文字列から、正規表現を使って整数や分数を抽出
//	すべてのマッチを parseFraction を用いて数値に変換し、その合計を計算
//============================================================
function sumNumbersInString(input) {
	//-----------------------------------------
	//文字列で表現された分数や整数を数値に変換
	//-----------------------------------------
	function parseFraction(fraction) {
	    if (fraction === '//') {
	        return 1 / 4; // 1/4
	    } else if (fraction === '/') {
	        return 1 / 2; // 1/2
	    } else if (fraction.includes('/')) {
	        const [numerator, denominator] = fraction.split('/');
	        if (numerator === '') {
	            return 1 / parseInt(denominator, 10); // "/" is 1/denominator
	        } else {
	            return parseInt(numerator, 10) / parseInt(denominator, 10);
	        }
	    } else {
	        return parseFloat(fraction); // Regular numbers
	    }
	}
	//-----------------------------------------
    // 正規表現を修正して、指定された文字が直前にある場合のみマッチする
    const regex = /[cdefgabCDEFGAB](\d+\/\d+|\d*\/\/|\d*\/|\d+(\.\d+)?)/g;
    let matches = input.match(regex);
    if (matches === null) {
        return 0; // マッチがなければ0を返す
    }

    let sum = 0;

    for (let match of matches) {
        // 先頭の文字 (cdefgabCDEFGAB) を取り除いて数値部分を処理
        let value = match.slice(1);
        sum += parseFraction(value);
    }
            
    return sum;
}

//##########################################################################
//##########################################################################
//	イメージ select コンポーネント
//		https://mo2nabe.com/demo-image-selector/
//##########################################################################
class MSC_ImageSelector{
	#el_pulldown;
	#els_option;
	#el_preview;
	#funcOnChange;
	constructor(el_parent){
		if(!el_parent instanceof HTMLElement) return undefined;
		el_parent.classList.add('MSC_ImageSelector');
		this.#els_option = el_parent.getElementsByClassName('MSC_ImageSelector__option');
		if(this.#els_option.length<1) return undefined;
		//プルダウン作成
		this.#el_pulldown = document.createElement('div');
		this.#el_pulldown.classList.add('MSC_ImageSelector__pulldown');

		//選択中要素+アイコンスペース
		const el_display = document.createElement('div');
		el_display.classList.add('MSC_ImageSelector__display');
		el_display.addEventListener('click',()=>{
			
			//if (el_parent.id != "divBarLineLeft" || disabledSelBarLine == false) {
			if ( !( (el_parent.id == "divBarLineLeft" && disabledSelBarLine == true) || 
					(el_parent.id == "divClefSymbol" && disabledSelClefSymbol == true) || 
					(el_parent.id == "divKeySignature" && disabledSelKeySignature == true) || 
					(el_parent.id == "divClefAndKeySignature" && disabledSelClefAndKeySignature == true) || 
					(el_parent.id == "divTimeSignatureSymbol" && disabledSelTimeSignatureSymbol == true) ) ) {
				this.#el_pulldown.classList.toggle('MSC_ImageSelector__s-spread');
			}
		})
		el_parent.appendChild(el_display);

		//選択中要素欄
		this.#el_preview = document.createElement('div');
		this.#el_preview.classList.add('MSC_ImageSelector__preview');
		const els_selected = el_parent.getElementsByClassName('MSC_ImageSelector__s-selected');
		if(els_selected.length===0) this.#els_option[0].classList.add('MSC_ImageSelector__s-selected');
		const el_clone_option_first = (els_selected.length===0) ? this.#els_option[0].cloneNode(true) : els_selected[0].cloneNode(true);
		el_clone_option_first.classList.add('MSC_ImageSelector__preview-child');
		el_clone_option_first.classList.remove('MSC_ImageSelector__option');
		el_clone_option_first.classList.remove('MSC_ImageSelector__s-selected');
		this.value = el_clone_option_first.dataset.value;
		this.#el_preview.appendChild(el_clone_option_first);
		el_display.appendChild(this.#el_preview);

		//プルダウン追加
		el_parent.appendChild(this.#el_pulldown);
		[...this.#els_option].forEach(el_option=>{
			el_option.addEventListener('click',()=>{
				this.#selectOption(el_option);
			});
			this.#el_pulldown.appendChild(el_option);
		});

		//セレクトアイコン追加
		const el_icon = document.createElement('div');
		el_icon.classList.add('MSC_ImageSelector__icon');
		el_display.appendChild(el_icon);

		//外部クリック処理
		const css_celector = (el_parent.id==='') ? '.MSC_ImageSelector' : '#'+el_parent.id;
		window.addEventListener('click',(e)=>{
			if(e.target.closest(css_celector)===null) this.#el_pulldown.classList.remove('MSC_ImageSelector__s-spread');
		});
		//
	}
	#selectOption(el_option){
		//s-selected処理
		[...this.#els_option].forEach(el=>{
			el.classList.remove('MSC_ImageSelector__s-selected');
		});
		el_option.classList.add('MSC_ImageSelector__s-selected');
		//表示要素作成
		const el_clone_option = el_option.cloneNode(true);
		el_clone_option.classList.add('MSC_ImageSelector__preview-child');
		el_clone_option.classList.remove('MSC_ImageSelector__option');
		el_clone_option.classList.remove('MSC_ImageSelector__s-selected');
		this.#el_preview.textContent = '';
		this.#el_preview.appendChild(el_clone_option);
		//
		this.value = el_option.dataset.value;
		this.#el_pulldown.classList.remove('MSC_ImageSelector__s-spread');
		this.onChange();
	}
	setHeight(num){
		if(Number.isInteger(num)&&num>0) this.#el_pulldown.style.maxHeight = num +'px';
	}
	setValue(val){
		for(let i=0;i<this.#els_option.length;i++){
			if(this.#els_option[i].dataset.value===val){
				this.#selectOption(this.#els_option[i]);
				break;
			}
		}
	}
	setOnChange(func){
		this.#funcOnChange = func;
	}
	onChange(){
		if(typeof this.#funcOnChange === 'function') this.#funcOnChange();
	}
}


//##########################################################################
//##########################################################################
//	MSC-Editor 本体のHTML
//##########################################################################
var editorHtml = `

		<!-- ======================================================== -->
		<!-- エディター全体                                           -->
		<!-- ======================================================== -->
		<div class="no-print" id ="divEditor" style="background: #FFFFFF; display: none;">

			<!-- ======================================================== -->
			<!-- タイトルバー                                             -->
			<!-- ======================================================== -->
			<div id="divEditorTitle">
				<img id="imgEditorTitle" src="./imgMSC/iconTitle_24.png"/>
				<span class="spanEditorTitle MSC_lang" id="spanEditorTitle">MSC-Editor for School</span>
				
				<span class="spanEditorTitle">&nbsp;&nbsp;-&nbsp;&nbsp;</span>
				<span class="spanEditorTitle MSC_lang" id="spanEditorTitleFileName">新規楽曲.msd</span>
				
				<div style="position: absolute; right: 4px; display: inline-block;">
					<!--
					<a href="javascript: openHelp()">
						<img id="imgEditorHelp" style="position: relative; cursor: pointer;" title="操作説明" src="./imgMSC/iconHelp_24.png"/>
					</a>
					-->
					<button class="btnHelp" id="btnHelp" value="0" onclick="openHelp()" title="操作説明"><img src="./imgMSC/help22.png"></button>
				</div>
			</div>

			<!-- ======================================================== -->
			<!-- メニュー全体                                             -->
			<!-- ======================================================== -->
			<div id="divEditorMenu" style="position: relative; z-index: 1000;">
				
				<!-- メニューバー １段目 -->
				<div id="menybar1" style="width: 610px; border: 1px solid #808080; padding: 4px;">
					
					<!-- メニュー 音部記号 -->
					<div id="divClefSymbol" style="display: inline-block;" title="音部記号">
						<!-- ト音記号 -->
						<div class="MSC_ImageSelector__option selectDiv32 MSC_ImageSelector__s-selected" data-value="treble">
							<img src="./imgMSC/clef_treble48.png" class="selectImg32 imgClefSymbol">
						</div>
						<!-- ヘ音記号 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="bass">
							<img src="./imgMSC/clef_bass48.png" class="selectImg32 imgClefSymbol">
						</div>
						<!-- ト音記号＋ト音記号 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="treble_treble" id="crefTrebleTreble">
							<img src="./imgMSC/clef_treble_treble48.png" class="selectImg32 imgClefSymbol">
						</div>
						<!-- ト音記号＋ヘ音記号 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="treble_bass" id="crefTrebleBass">
							<img src="./imgMSC/clef_treble_bass48.png" class="selectImg32 imgClefSymbol">
						</div>
					</div>

					<!-- メニュー 調号 -->
					<div id="divKeySignature" style="display: inline-block;" title="調号">
						<!-- ハ長調・イ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32 MSC_ImageSelector__s-selected" data-value="C">
							<img id="imgKey_C" src="./imgMSC/key_C_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- ト長調・ホ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="G">
							<img id="imgKey_G" src="./imgMSC/key_G_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- ニ長調・ロ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="D">
							<img id="imgKey_D" src="./imgMSC/key_D_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- イ長調・嬰ヘ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="A">
							<img id="imgKey_A" src="./imgMSC/key_A_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- ホ長調・嬰ハ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="E">
							<img id="imgKey_E" src="./imgMSC/key_E_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- ロ長調・嬰ト短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="B">
							<img id="imgKey_B" src="./imgMSC/key_B_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- 嬰ヘ長調・嬰ニ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="F#">
							<img id="imgKey_Fs" src="./imgMSC/key_Fs_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- 嬰ハ長調・嬰イ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="C#">
							<img id="imgKey_Cs" src="./imgMSC/key_Cs_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- ヘ長調・ニ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="F">
							<img id="imgKey_F" src="./imgMSC/key_F_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- 変ロ長調・ト短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="Bb">
							<img id="imgKey_Bf" src="./imgMSC/key_Bf_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- 変ホ長調・ハ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="Eb">
							<img id="imgKey_Ef" src="./imgMSC/key_Ef_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- 変イ長調・ヘ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="Ab">
							<img id="imgKey_Af" src="./imgMSC/key_Af_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- 変ニ長調・変ロ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="Db">
							<img id="imgKey_Df" src="./imgMSC/key_Df_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- 変ト長調・変ホ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="Gb">
							<img id="imgKey_Gf" src="./imgMSC/key_Gf_ja.png" class="selectImg32 imgKeySignature">
						</div>
						<!-- 変ハ長調・変イ短調 -->
						<div class="MSC_ImageSelector__option selectDiv32" data-value="Cb">
							<img id="imgKey_Cf" src="./imgMSC/key_Cf_ja.png" class="selectImg32 imgKeySignature">
						</div>
					</div>

					<!-- メニュー 音部記号・調号設定 -->
					<div id="divClefAndKeySignature" style="display: none;" title="音部記号・調号設定">
						<!-- 削除（五線譜のみ） -->
						<div class="MSC_ImageSelector__option selectDiv32 MSC_ImageSelector__s-selected" id="div_tb_None" data-value="">
							<img id="img_tb_None" src="./imgMSC/tb_None.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- treble only -->
						<div class="MSC_ImageSelector__option selectDiv32" id="div_t_key_C" data-value="[K:clef=treble]">
							<img id="img_t_key_C" src="./imgMSC/t_key_C.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- bass only -->
						<div class="MSC_ImageSelector__option selectDiv32" id="div_b_key_C" data-value="[K:clef=bass]">
							<img id="img_b_key_C" src="./imgMSC/b_key_C.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- ハ長調・イ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Cn" data-value="[K:clef=treble][K:C]">
							<img id="img_t_key_Cn" src="./imgMSC/t_key_Cn.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ハ長調・イ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Cn" data-value="[K:C]">
							<img id="img_nt_key_Cn" src="./imgMSC/nt_key_Cn.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ハ長調・イ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Cn" data-value="[K:clef=bass][K:C]">
							<img id="img_b_key_Cn" src="./imgMSC/b_key_Cn.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ハ長調・イ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Cn" data-value="[K:C]">
							<img id="img_nb_key_Cn" src="./imgMSC/nb_key_Cn.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- ト長調・ホ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_G" data-value="[K:clef=treble][K:G]">
							<img id="img_t_key_G" src="./imgMSC/t_key_G.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ト長調・ホ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_G" data-value="[K:G]">
							<img id="img_nt_key_G" src="./imgMSC/nt_key_G.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ト長調・ホ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_G" data-value="[K:clef=bass][K:G]">
							<img id="img_b_key_G" src="./imgMSC/b_key_G.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ト長調・ホ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_G" data-value="[K:G]">
							<img id="img_nb_key_G" src="./imgMSC/nb_key_G.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- ニ長調・ロ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_D" data-value="[K:clef=treble][K:D]">
							<img id="img_t_key_D" src="./imgMSC/t_key_D.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ニ長調・ロ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_D" data-value="[K:D]">
							<img id="img_nt_key_D" src="./imgMSC/nt_key_D.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ニ長調・ロ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_D" data-value="[K:clef=bass][K:D]">
							<img id="img_b_key_D" src="./imgMSC/b_key_D.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ニ長調・ロ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_D" data-value="[K:D]">
							<img id="img_nb_key_D" src="./imgMSC/nb_key_D.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- イ長調・嬰ヘ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_A" data-value="[K:clef=treble][K:A]">
							<img id="img_t_key_A" src="./imgMSC/t_key_A.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- イ長調・嬰ヘ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_A" data-value="[K:A]">
							<img id="img_nt_key_A" src="./imgMSC/nt_key_A.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- イ長調・嬰ヘ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_A" data-value="[K:clef=bass][K:A]">
							<img id="img_b_key_A" src="./imgMSC/b_key_A.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- イ長調・嬰ヘ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_A" data-value="[K:A]">
							<img id="img_nb_key_A" src="./imgMSC/nb_key_A.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- ホ長調・嬰ハ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_E" data-value="[K:clef=treble][K:E]">
							<img id="img_t_key_E" src="./imgMSC/t_key_E.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ホ長調・嬰ハ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_E" data-value="[K:E]">
							<img id="img_nt_key_E" src="./imgMSC/nt_key_E.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ホ長調・嬰ハ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_E" data-value="[K:clef=bass][K:E]">
							<img id="img_b_key_E" src="./imgMSC/b_key_E.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ホ長調・嬰ハ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_E" data-value="[K:E]">
							<img id="img_nb_key_E" src="./imgMSC/nb_key_E.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- ロ長調・嬰ト短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_B" data-value="[K:clef=treble][K:B]">
							<img id="img_t_key_B" src="./imgMSC/t_key_B.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ロ長調・嬰ト短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_B" data-value="[K:B]">
							<img id="img_nt_key_B" src="./imgMSC/nt_key_B.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ロ長調・嬰ト短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_B" data-value="[K:clef=bass][K:B]">
							<img id="img_b_key_B" src="./imgMSC/b_key_B.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ロ長調・嬰ト短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_B" data-value="[K:B]">
							<img id="img_nb_key_B" src="./imgMSC/nb_key_B.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- 嬰ヘ長調・嬰ニ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Fs" data-value="[K:clef=treble][K:F#]">
							<img id="img_t_key_Fs" src="./imgMSC/t_key_Fs.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 嬰ヘ長調・嬰ニ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Fs" data-value="[K:F#]">
							<img id="img_nt_key_Fs" src="./imgMSC/nt_key_Fs.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 嬰ヘ長調・嬰ニ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Fs" data-value="[K:clef=bass][K:F#]">
							<img id="img_b_key_Fs" src="./imgMSC/b_key_Fs.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 嬰ヘ長調・嬰ニ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Fs" data-value="[K:F#]">
							<img id="img_nb_key_Fs" src="./imgMSC/nb_key_Fs.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- 嬰ハ長調・嬰イ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Cs" data-value="[K:clef=treble][K:C#]">
							<img id="img_t_key_Cs" src="./imgMSC/t_key_Cs.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 嬰ハ長調・嬰イ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Cs" data-value="[K:C#]">
							<img id="img_nt_key_Cs" src="./imgMSC/nt_key_Cs.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 嬰ハ長調・嬰イ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Cs" data-value="[K:clef=bass][K:C#]">
							<img id="img_b_key_Cs" src="./imgMSC/b_key_Cs.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 嬰ハ長調・嬰イ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Cs" data-value="[K:C#]">
							<img id="img_nb_key_Cs" src="./imgMSC/nb_key_Cs.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- ヘ長調・ニ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_F" data-value="[K:clef=treble][K:F]">
							<img id="img_t_key_F" src="./imgMSC/t_key_F.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ヘ長調・ニ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_F" data-value="[K:F]">
							<img id="img_nt_key_F" src="./imgMSC/nt_key_F.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ヘ長調・ニ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_F" data-value="[K:clef=bass][K:F]">
							<img id="img_b_key_F" src="./imgMSC/b_key_F.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- ヘ長調・ニ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_F" data-value="[K:F]">
							<img id="img_nb_key_F" src="./imgMSC/nb_key_F.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- 変ロ長調・ト短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Bf" data-value="[K:clef=treble][K:Bb]">
							<img id="img_t_key_Bf" src="./imgMSC/t_key_Bf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ロ長調・ト短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Bf" data-value="[K:Bb]">
							<img id="img_nt_key_Bf" src="./imgMSC/nt_key_Bf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ロ長調・ト短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Bf" data-value="[K:clef=bass][K:Bb]">
							<img id="img_b_key_Bf" src="./imgMSC/b_key_Bf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ロ長調・ト短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Bf" data-value="[K:Bb]">
							<img id="img_nb_key_Bf" src="./imgMSC/nb_key_Bf.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- 変ホ長調・ハ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Ef" data-value="[K:clef=treble][K:Eb]">
							<img id="img_t_key_Ef" src="./imgMSC/t_key_Ef.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ホ長調・ハ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Ef" data-value="[K:Eb]">
							<img id="img_nt_key_Ef" src="./imgMSC/nt_key_Ef.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ホ長調・ハ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Ef" data-value="[K:clef=bass][K:Eb]">
							<img id="img_b_key_Ef" src="./imgMSC/b_key_Ef.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ホ長調・ハ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Ef" data-value="[K:Eb]">
							<img id="img_nb_key_Ef" src="./imgMSC/nb_key_Ef.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- 変イ長調・ヘ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Af" data-value="[K:clef=treble][K:Ab]">
							<img id="img_t_key_Af" src="./imgMSC/t_key_Af.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変イ長調・ヘ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Af" data-value="[K:Ab]">
							<img id="img_nt_key_Af" src="./imgMSC/nt_key_Af.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変イ長調・ヘ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Af" data-value="[K:clef=bass][K:Ab]">
							<img id="img_b_key_Af" src="./imgMSC/b_key_Af.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変イ長調・ヘ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Af" data-value="[K:Ab]">
							<img id="img_nb_key_Af" src="./imgMSC/nb_key_Af.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- 変ニ長調・変ロ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Df" data-value="[K:clef=treble][K:Db]">
							<img id="img_t_key_Df" src="./imgMSC/t_key_Df.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ニ長調・変ロ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Df" data-value="[K:Db]">
							<img id="img_nt_key_Df" src="./imgMSC/nt_key_Df.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ニ長調・変ロ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Df" data-value="[K:clef=bass][K:Db]">
							<img id="img_b_key_Df" src="./imgMSC/b_key_Df.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ニ長調・変ロ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Df" data-value="[K:Db]">
							<img id="img_nb_key_Df" src="./imgMSC/nb_key_Df.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- 変ト長調・変ホ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Gf" data-value="[K:clef=treble][K:Gb]">
							<img id="img_t_key_Gf" src="./imgMSC/t_key_Gf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ト長調・変ホ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Gf" data-value="[K:Gb]">
							<img id="img_nt_key_Gf" src="./imgMSC/nt_key_Gf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ト長調・変ホ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Gf" data-value="[K:clef=bass][K:Gb]">
							<img id="img_b_key_Gf" src="./imgMSC/b_key_Gf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ト長調・変ホ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Gf" data-value="[K:Gb]">
							<img id="img_nb_key_Gf" src="./imgMSC/nb_key_Gf.png" class="selectImg32 imgClefAndKeySignature">
						</div>

						<!-- 変ハ長調・変イ短調	treble with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_t_key_Cf" data-value="[K:clef=treble][K:Cb]">
							<img id="img_t_key_Cf" src="./imgMSC/t_key_Cf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ハ長調・変イ短調	treble without clif -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nt_key_Cf" data-value="[K:Cb]">
							<img id="img_nt_key_Cf" src="./imgMSC/nt_key_Cf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ハ長調・変イ短調	bass with clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_b_key_Cf" data-value="[K:clef=bass][K:Cb]">
							<img id="img_b_key_Cf" src="./imgMSC/b_key_Cf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
						<!-- 変ハ長調・変イ短調	bass without clef -->
						<div class="MSC_ImageSelector__option selectDiv32 keySignature" id="div_nb_key_Cf" data-value="[K:Cb]">
							<img id="img_nb_key_Cf" src="./imgMSC/nb_key_Cf.png" class="selectImg32 imgClefAndKeySignature">
						</div>
					</div>

					<!-- メニュー 拍子記号 -->
					<div id="divTimeSignatureSymbol" style="display: inline-block;" title="拍子記号">
						<div class="MSC_ImageSelector__option selectDiv32" data-value="0,0" id="divTimeSignatureSymbolNone" style="display; none;">
							<img src="./imgMSC/timing_0_0.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32 MSC_ImageSelector__s-selected" data-value="C,8">
							<img src="./imgMSC/timing_c_4.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="C|,8">
							<img src="./imgMSC/timing_c_2.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="2/2,8">
							<img src="./imgMSC/timing_2_2.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="3/2,12">
							<img src="./imgMSC/timing_3_2.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="4/2,16">
							<img src="./imgMSC/timing_4_2.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						
						<div class="MSC_ImageSelector__option selectDiv32" data-value="2/4,4">
							<img src="./imgMSC/timing_2_4.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="3/4,6">
							<img src="./imgMSC/timing_3_4.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="4/4,8">
							<img src="./imgMSC/timing_4_4.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="5/4,10">
							<img src="./imgMSC/timing_5_4.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="6/4,12">
							<img src="./imgMSC/timing_6_4.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="3/8,3">
							<img src="./imgMSC/timing_3_8.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						
						<!--
						<div class="MSC_ImageSelector__option selectDiv32" data-value="5/8,5">
							<img src="./imgMSC/timing_5_8.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						-->
						
						<div class="MSC_ImageSelector__option selectDiv32" data-value="6/8,6">
							<img src="./imgMSC/timing_6_8.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						
						<!--
						<div class="MSC_ImageSelector__option selectDiv32" data-value="7/8,7">
							<img src="./imgMSC/timing_7_8.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						-->
						
						<div class="MSC_ImageSelector__option selectDiv32" data-value="9/8,9">
							<img src="./imgMSC/timing_9_8.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="12/8,12">
							<img src="./imgMSC/timing_12_8.png" class="selectImg32 imgTimeSignatureSymbol">
						</div>
					</div>

					<!-- メニュー 上段 -->
					<div id="divMenu1" style="position: relative; max-height: 50px; display: inline-block; vertical-align: top;">
						
						<!-- メニュー 曲名・作者 -->
						<button id="btnTitle" onclick="clkBtnTitle()" title="曲名・作者"><img id="imgTitle" src="./imgMSC/title_ja.png"></button>

						<!-- メニュー 速度記号 -->
						<select id="selTempoMarkings" onchange="chgTempoMarkings(this.value)" title="速度記号">
							<option value="" selected>速度指定なし</option>
							<option value="Largo">Largo</option>
							<option value="Lento">Lento</option>
							<option value="Adagio">Adagio</option>
							<option value="Andante">Andante</option>
							<option value="Moderato">Moderato</option>
							<option value="Allegretto">Allegretto</option>
							<option value="Allegro">Allgro</option>
							<option value="Vivace">Vivace</option>
							<option value="Presto">Presto</option>
						</select>
						
						<!-- メトロノーム記号　♪♩ -->
						<!--
						<span style="position: relative; top: -5px; font-size: 18px;">♩</span><span style="position: relative; left: -6px; top: -4px; font-size: 18px;">=</span>
						-->
						<button id="btnTempoMarkings2" onclick="clkBtnTempoMarkings2()" title="メトロノーム記号の基準音符"><img id="imgTempoMarkings2" src="./imgMSC/note4EqSel_22.png"></button>
						<input type="number" id="txtTempoMarkings2" min="0" max="240" value="" onchange="chgTempoMarkings2(this.value)" title="メトロノーム記号">

						<!-- 楽譜段数 -->
						<select id="selRowsCount" onchange="chgRowsCount(this.value)" title="楽譜段数">
						</select>
						
						<!-- 小節数 -->
						<button id="btnMeasuresCount" onclick="clkMeasuresCount()" title="小節数">...</button>
						
						<br>
						
						<!-- 歌詞番数 -->
						<select id="selLyric" onchange="chgLyric(this.value)" title="歌詞番数">
							<option value="0" selected>歌詞なし</option>
							<option value="1">１番まで</option>
							<option value="2">２番まで</option>
							<option value="3">３番まで</option>
						</select>
						<span id="spanLyric_1st" style="position: relative; top: -3px;">
							<span class="MSC_lang" style="position: relative; top: 1px; font-size: 13px;">１番</span>
							<input type="text" id="txtLyric_1" style="width: 38px; height: 24px;" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off" onkeydown="keydownLyric(1)" oninput="inputLyricText(0, this)" disabled>
						</span>
						<span id="spanLyric_2nd" style="position: relative; top: -3px;">
							<span class="MSC_lang" style="position: relative; top: 1px; font-size: 13px;">２番</span>
							<input type="text" id="txtLyric_2" style="width: 38px; height: 24px;" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off" onkeydown="keydownLyric(2)" oninput="inputLyricText(1, this)" disabled>
						</span>
						<span id="spanLyric_3rd" style="position: relative; top: -3px;">
							<span class="MSC_lang" style="position: relative; top: 1px; font-size: 13px;">３番</span>
							<input type="text" id="txtLyric_3" style="width: 38px; height: 24px;" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off" onkeydown="keydownLyric(3)" oninput="inputLyricText(2, this)" disabled>
						</span>
					</div>
				</div>

				<!-- メニューバー ２段目 -->
				<div id="menybar2" style="width: 610px; border: 1px solid #808080; padding: 4px;">
					
					<!-- 小節線 -->
					<div id="divBarLineLeft" style="display: inline-block; margin-right: 1px;" title="小節線">
						<div class="MSC_ImageSelector__option selectDiv32" data-value="" id="imgNoBar">
							<img src="./imgMSC/barline_n.png" class="selectImg32 imgBar">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32 MSC_ImageSelector__s-selected" data-value="|">
							<img src="./imgMSC/barline_s.png" class="selectImg32 imgBar">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="||">
							<img src="./imgMSC/barline_w.png" class="selectImg32 imgBar">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="|]">
							<img src="./imgMSC/barline_e.png" class="selectImg32 imgBar">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value="|:">
							<img src="./imgMSC/barline_rl.png" class="selectImg32 imgBar">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value=":|">
							<img src="./imgMSC/barline_rr.png" class="selectImg32 imgBar">
						</div>
						<div class="MSC_ImageSelector__option selectDiv32" data-value=":||:">
							<img src="./imgMSC/barline_rw.png" class="selectImg32 imgBar">
						</div>
					</div>

					<!-- 音符・休符 -->
					<div style="display: inline-block">
						<!-- 音符 -->
						<button class="btnNoteRest noRest" value="0" onclick="clkNoteUpDown(1)" title="上へ"><img src="./imgMSC/note_up.png"></button>

						<button class="btnNoteRest" id="btnNote8" value="8" onclick="clkNote(8)" title="全音符"><img src="./imgMSC/note1_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNote6" value="6" onclick="clkNote(6)" title="付点２分音符"><img src="./imgMSC/note2d_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNote4" value="4" onclick="clkNote(4)" title="２分音符"><img src="./imgMSC/note2_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNote3" value="3" onclick="clkNote(3)" title="付点４分音符"><img src="./imgMSC/note4d_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNote2" value="2" onclick="clkNote(2)" title="４分音符"><img src="./imgMSC/note4_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNote1_5" value="1.5" onclick="clkNote(1.5)" title="付点８分音符"><img src="./imgMSC/note8d_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNote1" value="1" onclick="clkNote(1)" title="８分音符"><img src="./imgMSC/note8_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNote0_5" value="0.5" onclick="clkNote(0.5)" title="16分音符"><img src="./imgMSC/note16_22.png"></button><!--
						
						--><button class="btnNoteRestNarrow noRest" style="visibility: hidden;" value="0"><img src="./imgMSC/moreArticulation.png"></button>

						<button class="btnNoteRest noRest" id="btnSharpFlatSharp" value="0" onclick="clkSharpFlat('sharp')" title="シャープ"><img id="imgSharpFlatSharp" src="./imgMSC/sharp22.png"></button><!--
						--><button class="btnNoteRest noRest" id="btnSharpFlatNatural" value="0" onclick="clkSharpFlat('natural')" title="ナチュラル"><img src="./imgMSC/natural22.png"></button>

						<button class="btnNoteRest noRest" id="btnTaiSlurSt" value="0" onclick="clkTaiSlur('st')" title="タイ/スラーの開始"><img src="./imgMSC/tie_slurSt.png"></button><!--
						--><button class="btnNoteRest noRest" id="btnTaiSlurEd" value="0" onclick="clkTaiSlur('ed')" title="スラーの終了"><img src="./imgMSC/tie_slurEd.png"></button>
						
						<button class="btnNoteRest noRest" id="btnNoBreath" value="0" onclick="clkBreath('none')" title="ブレスの削除"><img src="./imgMSC/noBreath.png"></button><!--
						--><button class="btnNoteRest noRest" id="btnBreath" value="0" onclick="clkBreath('breath')" title="ブレス"><img src="./imgMSC/breath.png"></button><!--
						--><button class="btnNoteRestNarrow noRest" style="visibility: hidden;" value="0"><img src="./imgMSC/moreArticulation.png"></button>

						<button class="btnNoteRest noRest" id="btnChordSet" value="0" onclick="clkChord()" title="和音の設定"><img src="./imgMSC/chord_22.png"></button><!--
						--><button class="btnNoteRest noRest" id="btnNoteSeparate" value="0" onclick="clkNoteSeparateJoin('separate')" title="分離"><img id="imgSeparate" src="./imgMSC/separate22.png"></button><!--
						--><button class="btnNoteRest noRest" id="btnSetTriplets" value="0" onclick="clkTriplets('set')" title="３連符設定"><img src="./imgMSC/triplets.png"></button><!--
						
						--><button class="btnNoteRest noRest" id="btnNoteAdd" value="0" onclick="clkNoteAdd('set')" title="複旋律の追加"><img src="./imgMSC/noteAdd_22.png"></button>

						<!-- 休符 -->
						<br>
						<button class="btnNoteRest noRest" value="0" onclick="clkNoteUpDown(-1)" title="下へ"><img src="./imgMSC/note_down.png"></button>

						<button class="btnNoteRest" id="btnRest8" value="8" onclick="clkRest(8)" title="全休符"><img src="./imgMSC/rest1_22.png"></button><!--
						--><button class="btnNoteRest" id="btnRest6" value="6" onclick="clkRest(6)" title="付点２分休符"><img src="./imgMSC/rest2d_22.png"></button><!--
						--><button class="btnNoteRest" id="btnRest4" value="4" onclick="clkRest(4)" title="２分休符"><img src="./imgMSC/rest2_22.png"></button><!--
						--><button class="btnNoteRest" id="btnRest3" value="3" onclick="clkRest(3)" title="付点４分休符"><img src="./imgMSC/rest4d_22.png"></button><!--
						--><button class="btnNoteRest" id="btnRest2" value="2" onclick="clkRest(2)" title="４分休符"><img src="./imgMSC/rest4_22.png"></button><!--
						--><button class="btnNoteRest" id="btnRest1_5" value="1.5" onclick="clkRest(1.5)" title="付点８分休符"><img src="./imgMSC/rest8d_22.png"></button><!--
						--><button class="btnNoteRest" id="btnRest1" value="1" onclick="clkRest(1)" title="８分休符"><img src="./imgMSC/rest8_22.png"></button><!--
						--><button class="btnNoteRest radius14" id="btnRest0_5" value="0.5" onclick="clkRest(0.5)" title="16分休符"><img src="./imgMSC/rest16_22.png"></button><!--

						--><button class="btnNoteRestNarrow" id="btnOtherNoteAndRest" value="0" onclick="clkOptionNoteAndRest()" title="その他の音符・休符"><img src="./imgMSC/moreArticulation.png"></button>

						<button class="btnNoteRest noRest" id="btnSharpFlatFlat" value="0" onclick="clkSharpFlat('flat')" title="フラット"><img id="imgSharpFlatFlat" src="./imgMSC/flat22.png"></button><!--
						--><button class="btnNoteRest noRest" id="btnSharpFlatRemove" value="0" onclick="clkSharpFlat('remove')" title="臨時記号の削除"><img src="./imgMSC/none22.png"></button>

						<button class="btnNoteRest noRest" value="0" id="btnTaiSlurStDel" value="0" onclick="clkTaiSlur('stdel')" title="タイ/スラーの開始を削除"><img src="./imgMSC/tie_slurStDel.png"></button><!--
						--><button class="btnNoteRest noRest" value="0" id="btnTaiSlurEdDel" value="0" onclick="clkTaiSlur('eddel')" title="スラーの終了を削除"><img src="./imgMSC/tie_slurEdDel.png"></button>
						
						<button class="btnNoteRest noRest" id="btnNoArticulation" value="0" onclick="clkArticulation('none')" title="アーティキュレーションの削除"><img src="./imgMSC/noArticulation.png"></button><!--
						--><button class="btnNoteRest noRest radius14" id="btnArticulationAccent" value="0" onclick="clkArticulation('accent')" title="アクセント"><img src="./imgMSC/accentH.png"></button><!--
						--><button class="btnNoteRestNarrow noRest" id="btnOptionArticulation" value="0" onclick="clkOptionArticulation()" title="その他のアーティキュレーション"><img src="./imgMSC/moreArticulation.png"></button>

						<button class="btnNoteRest noRest" id="btnNoteArt" value="0" onclick="clkNoteArt()" title="装飾音符の設定"><img src="./imgMSC/noteArt_22.png"></button><!--
						--><button class="btnNoteRest noRest" id="btnNoteJoin" value="0" onclick="clkNoteSeparateJoin('join')" title="結合"><img id="imgJoin" src="./imgMSC/join22.png"></button><!--
						--><button class="btnNoteRest noRest" id="btnDelTriplets" value="0" onclick="clkTriplets('del')" title="３連符の解除"><img src="./imgMSC/noTriplets.png"></button><!--

						--><button class="btnNoteRest noRest" id="btnNoteAddDel" value="0" onclick="clkNoteAdd('remove')" title="複旋律の削除"><img src="./imgMSC/noteAddDel_22.png"></button>
					</div>

				</div>

				<!-- メニューバー ３段目 -->
				<div id="menybar3" style="position: relative; width: 610px; border: 1px solid #808080; padding: 4px;">
					<!-- 強弱記号 https://w3c.github.io/smufl/latest/tables/dynamics.html -->
					<select class="bravura" id="selDynamics" onchange="chgDynamics(this)" title="強弱記号">
						<hr>
						<option value="none" style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">強弱なし</option>
						<hr>
						<option value="crescendo("   class="bravura">始点　&#xE53E;</option>
						<option value="crescendo)"   class="bravura">&#xE53E;　終点</option>
						<hr>
						<option value="diminuendo("   class="bravura">始点　&#xE53F;</option>
						<option value="diminuendo)"   class="bravura">&#xE53F;　終点</option>
						<hr>
						<option value="ffff" class="bravura">&#xE531;</option>
						<option value="fff"  class="bravura">&#xE530;</option>
						<option value="ff"   class="bravura">&#xE52F;</option>
						<option value="f"    class="bravura">&#xE522;</option>
						<option value="mf"   class="bravura">&#xE52D;</option>
						<option value="mp"   class="bravura">&#xE52C;</option>
						<option value="p"    class="bravura">&#xE520;</option>
						<option value="pp"   class="bravura">&#xE52B;</option>
						<option value="ppp"  class="bravura">&#xE52A;</option>
						<option value="pppp" class="bravura">&#xE529;</option>
						<hr>
						<option value="fp"   class="bravura">&#xE534;</option>
						<option value="fz"   class="bravura">&#xE535;</option>
						<option value="sf"   class="bravura">&#xE536;</option>
						<option value="sfp"  class="bravura">&#xE537;</option>
						<option value="sfz"  class="bravura">&#xE539;</option>
						<option value="rf"   class="bravura">&#xE53C;</option>
						<option value="rfz"  class="bravura">&#xE53D;</option>
					</select>
					
					<!-- 反復記号 -->
					<select class="bravura" id="selRepeatSigns" onchange="chgRepeatSigns(this)" title="反復記号">
						<hr>
						<option value="none" style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">反復なし</option>
						<hr>
						<option value="D.C." class="crimson-text-bold-italic">D.C.</option>
						<option value="fine" class="crimson-text-bold-italic">Fine</option>
						<option value="D.S." class="crimson-text-bold-italic">D.S.</option>
						<!--
						<option value="segno" style="font-family: 'BravuraText';     font-style: normal; font-weight: 400; font-size: 18px;"></option>
						<option value="coda"  style="font-family: 'BravuraText';     font-style: normal; font-weight: 400; font-size: 15px;"></option>
						-->
						<option value="segno" style="font-family: 'BravuraText';     font-style: normal; font-weight: 400; font-size: 18px;">&#xE047;</option>
						<option value="coda"  style="font-family: 'BravuraText';     font-style: normal; font-weight: 400; font-size: 15px;">&#xE048;</option>
						<hr>
						<option value="[1"  style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">⎾￣￣ 1&nbsp;&nbsp;&nbsp;</option>
						<option value="[2"  style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">⎾￣￣ 2&nbsp;&nbsp;&nbsp;</option>
						
						<!--
						<option value="[3"  style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">⎾￣￣ 3&nbsp;&nbsp;&nbsp;</option>
						<option value="[1,2" style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">⎾￣￣ 1,2</option>
						<option value="[1,3" style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">⎾￣￣ 1,3</option>
						<option value="[2,3" style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">⎾￣￣ 2,3</option>
						-->
						<!--
						<hr>
						<option value="]"     style="font-family: Arial, sans-serif; font-style: normal; font-weight: 400; font-size: 13px;">￣￣⏋</option>
						-->
					</select>
					
					<!-- abc-editor -->
					<div style="position: absolute; top: 6px; right: 6px; font-size: 14px;">
						<button class="btnMenuJob" id="btnUndo" onclick="undoButton()" title="Undo" disabled><img src="./imgMSC/undo22.png"></button>
						<button class="btnMenuJob" id="btnRedo" onclick="redoButton()" title="Redo" disabled><img src="./imgMSC/redo22.png"></button>
						
						<span style="position: relative; top: -2px; font-size: 22px">｜</span>
						
						<button class="btnMenuJob" id="btnNew" style="margin-right: 8px;" onclick="newButton()" title="新規"><img src="./imgMSC/new22.png"></button>
						<button class="btnMenuJob" id="btnOpen" onclick="openButton()" title="開く"><img src="./imgMSC/open22.png"></button>
						<button class="btnMenuJob" id="btnSave" onclick="saveButton()" title="保存"><img src="./imgMSC/save22.png"></button>
						<button class="btnMenuJob" id="btnPrint" style="margin-left: 8px;" onclick="printButton()" title="印刷"><img src="./imgMSC/print22.png"></button>
						
						<span style="position: relative; top: -2px; font-size: 22px">｜</span>
						
						<button class="btnMenuJob" id="btnPlay" onclick="playButton()" title="演奏"><img src="./imgMSC/sound22.png"></button>
						&nbsp;
						<span id="spanAbcEditor" style="position: relative; top: -4px;" title="abcエディタの表示/非表示">
							<label style="cursor: pointer;">
							<span class="MSC_lang">abcエディタ</span><input type="checkbox" id="chkAbcEditor" style="position: relative; top: 2px; width: 16px; height: 16px; cursor: pointer;" onclick="clkAbcEditor(this)">
							</label>
						</span>
					</div>

					<!-- ======================================================== -->
					<!-- プレーヤーダイアログ                                     -->
					<!-- ======================================================== -->
					<div id="divPlayer" style="position: absolute; top: 5px; left: 6px; width: 604px; height: 30px; ; background: #FFFFFF; overflow: hidden; display: none;">

						<div style="width: 564px; max-width: 564px; margin-top: 2px; overflow: hidden; display: inline-block;">
							<div id="audio" style="width: 564px;"></div>
						</div>

						<button class="btnMenuJob" style="position:relative; left: 6px; top: -3px;" onclick="clkClosePlayer()" title="演奏の終了"><img src="./imgMSC/soundOff22.png"></button>
					</div>

				</div>	<!-- メニューバー ３段目 -->

				<!-- メトロノーム記号基準音符選択ダイアログ -->
				<div id="divTempoMarkings2">
					<button class="btnNoteRest tempo2" id="btnTempoMarkings2_1" value="0" onclick="clkChangeTempoMarkings2('2d')" title="付点２分音符"><img src="./imgMSC/note2dEq_22.png"></button><!--
					--><button class="btnNoteRest tempo2" id="btnTempoMarkings2_2" value="0" onclick="clkChangeTempoMarkings2('2')" title="２分音符"><img src="./imgMSC/note2Eq_22.png"></button><!--
					--><button class="btnNoteRest tempo2" id="btnTempoMarkings2_3" value="0" onclick="clkChangeTempoMarkings2('4d')" title="付点４分音符"><img src="./imgMSC/note4dEq_22.png"></button><!--
					--><button class="btnNoteRest tempo2" id="btnTempoMarkings2_4" value="0" onclick="clkChangeTempoMarkings2('4')" title="４分音符"><img src="./imgMSC/note4Eq_22.png"></button><!--
					--><button class="btnNoteRest tempo2" id="btnTempoMarkings2_5" value="0" onclick="clkChangeTempoMarkings2('8')" title="８分音符"><img src="./imgMSC/note8Eq_22.png"></button>
				</div>



				<!-- 追加の音符・休符ダイアログ -->
				<div id="divOptionNoteAndRest">
					<button class="btnNoteRest" id="btnNoteDel" value="0" onclick="clkNoteDel()" title="音符・休符の削除（不完全小節化）"><img src="./imgMSC/noteDel_22.png"></button>
					
					<button class="btnNoteRest" id="btnNote1o" value="1" onclick="clkNote(1)" title="８分音符"><img src="./imgMSC/note8_22.png"></button><!--
					--><button class="btnNoteRest" id="btnNote0_75" value="0.75" onclick="clkNote(0.75)" title="付点16分音符"><img src="./imgMSC/note16d_22.png"></button><!--
					--><button class="btnNoteRest" id="btnNote0_5o" value="0.5" onclick="clkNote(0.5)" title="16分音符"><img src="./imgMSC/note16_22.png"></button><!--
					--><button class="btnNoteRest" id="btnNote0_375" value="0.375" onclick="clkNote(0.375)" title="付点32分音符"><img src="./imgMSC/note32d_22.png"></button><!--
					--><button class="btnNoteRest" id="btnNote0_25" value="0.25" onclick="clkNote(0.25)" title="32分音符"><img src="./imgMSC/note32_22.png"></button><!--
					--><button class="btnNoteRest" id="btnNote0_125" value="0.125" onclick="clkNote(0.125)" title="64分音符"><img src="./imgMSC/note64_22.png"></button>
					
					<button class="btnNoteRest noRest" id="btnSetTriplets2" value="0" onclick="clkTriplets('set')" title="３連符設定"><img src="./imgMSC/triplets.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnSetQuintuplet2" value="0" onclick="clkQuintuplet('set')" title="５連符設定"><img src="./imgMSC/quintuplet.png"></button>
					<br>
					<button class="btnNoteRest" id="btnNoteOrg" value="0" onclick="clkNoteOrg()" title="完全小節に戻す"><img src="./imgMSC/noteOrg_22.png"></button>
					
					<button class="btnNoteRest" id="btnRest1o" value="1" onclick="clkRest(1)" title="８分休符"><img src="./imgMSC/rest8_22.png"></button><!--
					--><button class="btnNoteRest" id="btnRest0_75" value="0.75" onclick="clkRest(0.75)" title="付点16分休符"><img src="./imgMSC/rest16d_22.png"></button><!--
					--><button class="btnNoteRest" id="btnRest0_5o" value="0.5" onclick="clkRest(0.5)" title="16分休符"><img src="./imgMSC/rest16_22.png"></button><!--
					--><button class="btnNoteRest" id="btnRest0_375" value="0.375" onclick="clkRest(0.375)" title="付点32分休符"><img src="./imgMSC/rest32d_22.png"></button><!--
					--><button class="btnNoteRest" id="btnRest0_25" value="0.25" onclick="clkRest(0.25)" title="32分休符"><img src="./imgMSC/rest32_22.png"></button><!--
					--><button class="btnNoteRest" id="btnRest0_125" value="0.125" onclick="clkRest(0.125)" title="64分休符"><img src="./imgMSC/rest64_22.png"></button>
					
					<button class="btnNoteRest noRest" id="btnDelTriplets2" value="0" onclick="clkTriplets('del')" title="３連符の解除"><img src="./imgMSC/noTriplets.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnDelQuintuplet2" value="0" onclick="clkQuintuplet('del')" title="５連符の解除"><img src="./imgMSC/noQuintuplet.png"></button>
				
				</div>

				<!-- 追加のアーティキュレーションダイアログ -->
				<div id="divOptionArticulation">
					<button class="btnNoteRest noRest" id="btnNoArticulation2" value="0" onclick="clkArticulation('none')" title="アーティキュレーションの削除"><img src="./imgMSC/noArticulation.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationStaccato" value="0" onclick="clkArticulation('.')" title="スタッカート"><img src="./imgMSC/staccato.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationStaccatissimo" value="0" onclick="clkArticulation('wedge')" title="スタッカーティッシモ"><img src="./imgMSC/staccatissimo.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationUpbow" value="0" onclick="clkArticulation('upbow')" title="アップボー"><img src="./imgMSC/upbow.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationDownbow" value="0" onclick="clkArticulation('downbow')" title="ダウンボー"><img src="./imgMSC/downbow.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationRoll" value="0" onclick="clkArticulation('roll')" title="ロール"><img src="./imgMSC/roll.png"></button>
					<br>
					<button class="btnNoteRest noRest" id="btnArticulationTenuto" value="0" onclick="clkArticulation('tenuto')" title="テヌート"><img src="./imgMSC/tenuto.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationLowermordent" value="0" onclick="clkArticulation('lowermordent')" title="アッパーモルデント"><img src="./imgMSC/uppermordent.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationUppermordent" value="0" onclick="clkArticulation('uppermordent')" title="ロワーモルデント"><img src="./imgMSC/lowermordent.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationTrill" value="0" onclick="clkArticulation('trill')" title="トリル"><img src="./imgMSC/trill.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationTurn" value="0" onclick="clkArticulation('turn')" title="ターン"><img src="./imgMSC/turn.png"></button><!--
					--><button class="btnNoteRest noRest" id="btnArticulationFermata" value="0" onclick="clkArticulation('fermata')" title="フェルマータ"><img src="./imgMSC/fermata.png"></button>
				</div>

				<!-- ======================================================== -->
				<!-- 和音設定ダイアログ                                       -->
				<!-- ======================================================== -->
				<div id="divChord" style="cursor: default;">
					<div id="divChordMenu">
						<button id="btnDlgChordSharp" class="btnNoteRest noRest" value="0" onmousedown="clkChordSharpFlat('sharp')" title="シャープ"><img src="./imgMSC/sharp22.png"></button><!--
						--><button id="btnDlgChordFlat" class="btnNoteRest noRest" value="0" onmousedown="clkChordSharpFlat('flat')" title="フラット"><img src="./imgMSC/flat22.png"></button><!--
						--><button id="btnDlgChordNatural" class="btnNoteRest noRest" value="0" onmousedown="clkChordSharpFlat('natural')" title="ナチュラル"><img src="./imgMSC/natural22.png"></button>
						<button id="btnDlgChordRemove" class="btnNoteRest noRest" value="0" onmousedown="clkChordSharpFlat('remove')" title="臨時記号の削除"><img src="./imgMSC/none22.png"></button>
					</div>
					<div id="divChordBody">
						<img class="chordImg" id="chordImg_0" src="./imgMSC/none10x20.png" style="top: 7px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_0" style="top: 5px; left: 75px;" onclick="clkChkChord(this, 0)" ondblclick="dclkChkChord(this, 0)">
						<img class="chordImg" id="chordImg_1" src="./imgMSC/none10x20.png" style="top: 14px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_1" style="top: 12px; left: 62px;" onclick="clkChkChord(this, 1)" ondblclick="dclkChkChord(this, 1)">
						<br>
						
						<img class="chordImg" id="chordImg_2" src="./imgMSC/none10x20.png" style="top: 1px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_2" style="top: -1px; left: 75px;" onclick="clkChkChord(this, 2)" ondblclick="dclkChkChord(this, 2)">
						<img class="chordImg" id="chordImg_3" src="./imgMSC/none10x20.png" style="top: 8px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_3" style="top: 6px; left: 62px;" onclick="clkChkChord(this, 3)" ondblclick="dclkChkChord(this, 3)">
						<br>
						
						<img class="chordImg" id="chordImg_4" src="./imgMSC/none10x20.png" style="top: -5px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_4" style="top: -7px; left: 75px;" onclick="clkChkChord(this, 4)" ondblclick="dclkChkChord(this, 4)">
						<img class="chordImg" id="chordImg_5" src="./imgMSC/none10x20.png" style="top: 2px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_5" style="top: 0px; left: 62px;" onclick="clkChkChord(this, 5)" ondblclick="dclkChkChord(this, 5)">
						<br>
						
						<img class="chordImg" id="chordImg_6" src="./imgMSC/none10x20.png" style="top: -11px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_6" style="top: -13px; left: 75px;" onclick="clkChkChord(this, 6)" ondblclick="dclkChkChord(this, 6)">
						<img class="chordImg" id="chordImg_7" src="./imgMSC/none10x20.png" style="top: -4px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_7" style="top: -6px; left: 62px;" onclick="clkChkChord(this, 7)" ondblclick="dclkChkChord(this, 7)">
						<br>
						
						<img class="chordImg" id="chordImg_8" src="./imgMSC/none10x20.png" style="top: -17px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_8" style="top: -19px; left: 75px;" onclick="clkChkChord(this, 8)" ondblclick="dclkChkChord(this, 8)">
						<img class="chordImg" id="chordImg_9" src="./imgMSC/none10x20.png" style="top: -10px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_9" style="top: -12px; left: 62px;" onclick="clkChkChord(this, 9)" ondblclick="dclkChkChord(this, 9)">
						<br>
						
						<img class="chordImg" id="chordImg_10" src="./imgMSC/none10x20.png" style="top: -24px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_10" style="top: -26px; left: 75px;" onclick="clkChkChord(this, 10)" ondblclick="dclkChkChord(this, 10)">
						<img class="chordImg" id="chordImg_11" src="./imgMSC/none10x20.png" style="top: -17px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_11" style="top: -19px; left: 62px;" onclick="clkChkChord(this, 11)" ondblclick="dclkChkChord(this, 11)">
						<br>
						
						<img class="chordImg" id="chordImg_12" src="./imgMSC/none10x20.png" style="top: -30px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_12" style="top: -32px; left: 75px;" onclick="clkChkChord(this, 12)" ondblclick="dclkChkChord(this, 12)">
						<img class="chordImg" id="chordImg_13" src="./imgMSC/none10x20.png" style="top: -23px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_13" style="top: -25px; left: 62px;" onclick="clkChkChord(this, 13)" ondblclick="dclkChkChord(this, 13)">
						<br>
						
						<img class="chordImg" id="chordImg_14" src="./imgMSC/none10x20.png" style="top: -36px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_14" style="top: -38px; left: 75px;" onclick="clkChkChord(this, 14)" ondblclick="dclkChkChord(this, 14)">
						<img class="chordImg" id="chordImg_15" src="./imgMSC/none10x20.png" style="top: -29px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_15" style="top: -31px; left: 62px;" onclick="clkChkChord(this, 15)" ondblclick="dclkChkChord(this, 15)">
						<br>
						
						<img class="chordImg" id="chordImg_16" src="./imgMSC/none10x20.png" style="top: -42px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_16" style="top: -44px; left: 75px;" onclick="clkChkChord(this, 16)" ondblclick="dclkChkChord(this, 16)">
						<img class="chordImg" id="chordImg_17" src="./imgMSC/none10x20.png" style="top: -35px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_17" style="top: -37px; left: 62px;" onclick="clkChkChord(this, 17)" ondblclick="dclkChkChord(this, 17)">
						<br>
						
						<img class="chordImg" id="chordImg_18" src="./imgMSC/none10x20.png" style="top: -49px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_18" style="top: -51px; left: 75px;" onclick="clkChkChord(this, 18)" ondblclick="dclkChkChord(this, 18)">
						<img class="chordImg" id="chordImg_19" src="./imgMSC/none10x20.png" style="top: -42px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_19" style="top: -44px; left: 62px;" onclick="clkChkChord(this, 19)" ondblclick="dclkChkChord(this, 19)">
						<br>
						
						<img class="chordImg" id="chordImg_20" src="./imgMSC/none10x20.png" style="top: -55px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_20" style="top: -57px; left: 75px;" onclick="clkChkChord(this, 20)" ondblclick="dclkChkChord(this, 20)">
						<img class="chordImg" id="chordImg_21" src="./imgMSC/none10x20.png" style="top: -48px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_21" style="top: -50px; left: 62px;" onclick="clkChkChord(this, 21)" ondblclick="dclkChkChord(this, 21)">
						<br>
						
						<img class="chordImg" id="chordImg_22" src="./imgMSC/none10x20.png" style="top: -61px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_22" style="top: -63px; left: 75px;" onclick="clkChkChord(this, 22)" ondblclick="dclkChkChord(this, 22)">
						<img class="chordImg" id="chordImg_23" src="./imgMSC/none10x20.png" style="top: -54px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_23" style="top: -56px; left: 62px;" onclick="clkChkChord(this, 23)" ondblclick="dclkChkChord(this, 23)">
						<br>
						
						<img class="chordImg" id="chordImg_24" src="./imgMSC/none10x20.png" style="top: -67px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_24" style="top: -69px; left: 75px;" onclick="clkChkChord(this, 24)" ondblclick="dclkChkChord(this, 24)">
						<img class="chordImg" id="chordImg_25" src="./imgMSC/none10x20.png" style="top: -60px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_25" style="top: -62px; left: 62px;" onclick="clkChkChord(this, 25)" ondblclick="dclkChkChord(this, 25)">
						<br>
						
						<img class="chordImg" id="chordImg_26" src="./imgMSC/none10x20.png" style="top: -73px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_26" style="top: -75px; left: 75px;" onclick="clkChkChord(this, 26)" ondblclick="dclkChkChord(this, 26)">
						<img class="chordImg" id="chordImg_27" src="./imgMSC/none10x20.png" style="top: -66px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_27" style="top: -68px; left: 62px;" onclick="clkChkChord(this, 27)" ondblclick="dclkChkChord(this, 27)">
						<br>
						
						<img class="chordImg" id="chordImg_28" src="./imgMSC/none10x20.png" style="top: -79px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_28" style="top: -81px; left: 75px;" onclick="clkChkChord(this, 28)" ondblclick="dclkChkChord(this, 28)">
						<img class="chordImg" id="chordImg_29" src="./imgMSC/none10x20.png" style="top: -72px; left: 69px;">
						<input type="checkbox" class="chordChk" id="chordChk_29" style="top: -74px; left: 62px;" onclick="clkChkChord(this, 29)" ondblclick="dclkChkChord(this, 29)">
						<br>
						
						<img class="chordImg" id="chordImg_30" src="./imgMSC/none10x20.png" style="top: -85px; left: 82px;">
						<input type="checkbox" class="chordChk" id="chordChk_30" style="top: -87px; left: 75px;" onclick="clkChkChord(this, 30)" ondblclick="dclkChkChord(this, 30)">
					</div>
					<div id="divChordButton">
						<button class="btnChord MSC_lang" id="btnChordOK" onclick="clkChordOK()">OK</button>
						<button class="btnChord MSC_lang" id="btnChordCancel" onclick="clkChordCancel()">キャンセル</button>
					</div>
				</div>	<!-- 和音設定ダイアログ -->

				<!-- ======================================================== -->
				<!-- 装飾音符設定ダイアログ                                   -->
				<!-- ======================================================== -->
				<div id="divNoteArt" style="cursor: default;">
					<div id="divNoteArtMenu">
						<button class="btnNoteRest" id="btnNoteArtNote1" value="1" onmousedown="clkNoteArtNote(1)" title="８分音符"><img src="./imgMSC/note8_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNoteArtNote0_5" value="0.5" onmousedown="clkNoteArtNote(0.5)" title="16分音符"><img src="./imgMSC/note16_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNoteArtNote0_25" value="0.25" onmousedown="clkNoteArtNote(0.25)" title="32分音符"><img src="./imgMSC/note32_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNoteArtNoteSlash" value="0" onmousedown="clkNoteArtNote(0)" title="短前打音"><img src="./imgMSC/slash_22.png"></button><!--
						--><button class="btnNoteRest" id="btnNoteArtNoteSlashDel" value="0" onmousedown="clkNoteArtNote(-1)" title="短前打音の削除"><img src="./imgMSC/slashDel_22.png"></button>
						
						<button id="btnDlgNoteArtSharp" class="btnNoteRest noRest" value="0" onmousedown="clkNoteArtSharpFlat('sharp')" title="シャープ"><img src="./imgMSC/sharp22.png"></button><!--
						--><button id="btnDlgNoteArtFlat" class="btnNoteRest noRest" value="0" onmousedown="clkNoteArtSharpFlat('flat')" title="フラット"><img src="./imgMSC/flat22.png"></button><!--
						--><button id="btnDlgNoteArtNatural" class="btnNoteRest noRest" value="0" onmousedown="clkNoteArtSharpFlat('natural')" title="ナチュラル"><img src="./imgMSC/natural22.png"></button><!--
						--><button id="btnDlgNoteArtRemove" class="btnNoteRest noRest" value="0" onmousedown="clkNoteArtSharpFlat('remove')" title="臨時記号の削除"><img src="./imgMSC/none22.png"></button>
					</div>
					<div id="divNoteArtBody">
						<img class="noteArtImg" id="noteArtImg_0" src="./imgMSC/none10x20.png" style="top: 7px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_0" style="top: 5px; left: 138px;" onclick="clkChkNoteArt(this, 1)">
						<img class="noteArtImg" id="noteArtImg_1" src="./imgMSC/none10x20.png" style="top: 14px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_1" style="top: 12px; left: 125px;" onclick="clkChkNoteArt(this, 1)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_2" src="./imgMSC/none10x20.png" style="top: 1px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_2" style="top: -1px; left: 138px;" onclick="clkChkNoteArt(this, 2)">
						<img class="noteArtImg" id="noteArtImg_3" src="./imgMSC/none10x20.png" style="top: 8px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_3" style="top: 6px; left: 125px;" onclick="clkChkNoteArt(this, 3)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_4" src="./imgMSC/none10x20.png" style="top: -5px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_4" style="top: -7px; left: 138px;" onclick="clkChkNoteArt(this, 4)">
						<img class="noteArtImg" id="noteArtImg_5" src="./imgMSC/none10x20.png" style="top: 2px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_5" style="top: 0px; left: 125px;" onclick="clkChkNoteArt(this, 5)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_6" src="./imgMSC/none10x20.png" style="top: -11px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_6" style="top: -13px; left: 138px;" onclick="clkChkNoteArt(this, 6)">
						<img class="noteArtImg" id="noteArtImg_7" src="./imgMSC/none10x20.png" style="top: -4px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_7" style="top: -6px; left: 125px;" onclick="clkChkNoteArt(this, 7)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_8" src="./imgMSC/none10x20.png" style="top: -17px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_8" style="top: -19px; left: 138px;" onclick="clkChkNoteArt(this, 8)">
						<img class="noteArtImg" id="noteArtImg_9" src="./imgMSC/none10x20.png" style="top: -10px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_9" style="top: -12px; left: 125px;" onclick="clkChkNoteArt(this, 9)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_10" src="./imgMSC/none10x20.png" style="top: -24px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_10" style="top: -26px; left: 138px;" onclick="clkChkNoteArt(this, 10)">
						<img class="noteArtImg" id="noteArtImg_11" src="./imgMSC/none10x20.png" style="top: -17px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_11" style="top: -19px; left: 125px;" onclick="clkChkNoteArt(this, 11)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_12" src="./imgMSC/none10x20.png" style="top: -30px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_12" style="top: -32px; left: 138px;" onclick="clkChkNoteArt(this, 12)">
						<img class="noteArtImg" id="noteArtImg_13" src="./imgMSC/none10x20.png" style="top: -23px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_13" style="top: -25px; left: 125px;" onclick="clkChkNoteArt(this, 13)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_14" src="./imgMSC/none10x20.png" style="top: -36px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_14" style="top: -38px; left: 138px;" onclick="clkChkNoteArt(this, 14)">
						<img class="noteArtImg" id="noteArtImg_15" src="./imgMSC/none10x20.png" style="top: -29px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_15" style="top: -31px; left: 125px;" onclick="clkChkNoteArt(this, 15)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_16" src="./imgMSC/none10x20.png" style="top: -42px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_16" style="top: -44px; left: 138px;" onclick="clkChkNoteArt(this, 16)">
						<img class="noteArtImg" id="noteArtImg_17" src="./imgMSC/none10x20.png" style="top: -35px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_17" style="top: -37px; left: 125px;" onclick="clkChkNoteArt(this, 17)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_18" src="./imgMSC/none10x20.png" style="top: -49px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_18" style="top: -51px; left: 138px;" onclick="clkChkNoteArt(this, 18)">
						<img class="noteArtImg" id="noteArtImg_19" src="./imgMSC/none10x20.png" style="top: -42px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_19" style="top: -44px; left: 125px;" onclick="clkChkNoteArt(this, 19)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_20" src="./imgMSC/none10x20.png" style="top: -55px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_20" style="top: -57px; left: 138px;" onclick="clkChkNoteArt(this, 20)">
						<img class="noteArtImg" id="noteArtImg_21" src="./imgMSC/none10x20.png" style="top: -48px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_21" style="top: -50px; left: 125px;" onclick="clkChkNoteArt(this, 21)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_22" src="./imgMSC/none10x20.png" style="top: -61px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_22" style="top: -63px; left: 138px;" onclick="clkChkNoteArt(this, 22)">
						<img class="noteArtImg" id="noteArtImg_23" src="./imgMSC/none10x20.png" style="top: -54px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_23" style="top: -56px; left: 125px;" onclick="clkChkNoteArt(this, 23)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_24" src="./imgMSC/none10x20.png" style="top: -67px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_24" style="top: -69px; left: 138px;" onclick="clkChkNoteArt(this, 24)">
						<img class="noteArtImg" id="noteArtImg_25" src="./imgMSC/none10x20.png" style="top: -60px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_25" style="top: -62px; left: 125px;" onclick="clkChkNoteArt(this, 25)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_26" src="./imgMSC/none10x20.png" style="top: -73px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_26" style="top: -75px; left: 138px;" onclick="clkChkNoteArt(this, 26)">
						<img class="noteArtImg" id="noteArtImg_27" src="./imgMSC/none10x20.png" style="top: -66px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_27" style="top: -68px; left: 125px;" onclick="clkChkNoteArt(this, 27)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_28" src="./imgMSC/none10x20.png" style="top: -79px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_28" style="top: -81px; left: 138px;" onclick="clkChkNoteArt(this, 28)">
						<img class="noteArtImg" id="noteArtImg_29" src="./imgMSC/none10x20.png" style="top: -72px; left: 132px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_29" style="top: -74px; left: 125px;" onclick="clkChkNoteArt(this, 29)">
						<br>
						
						<img class="noteArtImg" id="noteArtImg_30" src="./imgMSC/none10x20.png" style="top: -85px; left: 145px;">
						<input type="checkbox" class="noteArtChk" id="noteArtChk_30" style="top: -87px; left: 138px;" onclick="clkChkNoteArt(this, 30)">

						<!-- 装飾音符　各行４個 -->
						<span id="spanNoteArt">
						</span>
						
						<!-- 左上プレビュー -->
						<img class="imgNoteArtPrview" id="imgNoteArtPrview" src="./imgMSC/noteArt_0-0-0-0.png">
						<img class="imgNoteArtPrview" id="imgNoteArtPrviewSlash" src="./imgMSC/noteArt_0-0-0-0.png">
					</div>
					<div id="divNoteArtButton">
						<button class="btnNoteArt MSC_lang" id="btnNoteArtOK" onclick="clkNoteArtOK()">OK</button>
						<button class="btnNoteArt MSC_lang" id="btnNoteArtCancel" onclick="clkNoteArtCancel()">キャンセル</button>
					</div>
				</div>	<!-- 装飾音符設定ダイアログ -->

				<!-- ======================================================== -->
				<!-- 小節数設定ダイアログ                                     -->
				<!-- ======================================================== -->
				<dialog id="divMeasuresCount" style="width: 200px; padding: 16px; margin-top: 10px;" oncancel="event.preventDefault();">
					<table id="tableMeasuresCount" style="width: 100%; font-size: 14px;">
					</table>
					
					<div class="MSC_lang" style="font-size: 12px; color: #FF0000;">６小節以上を指定すると、当初は段が画面に収まりませんが、音符や休符を設定すれば、収まります。</div>
					
					
					<hr>
					<div style="width: 100%; text-align: right; padding: 0p 8px;">
						<button class="buttonDialogYes MSC_lang" id="btnMeasuresCountOK">OK</button>
						<button class="buttonDialogNo MSC_lang" id="btnMeasuresCountCancel">キャンセル</button>
					</div>
				</dialog>	<!-- 小節数設定ダイアログ -->
				
				
				<!-- ======================================================== -->
				<!-- 和音設定ダイアログ表示時の背景カバー                     -->
				<!-- ======================================================== -->
				<div class="divBackCover" id="divBackCover"></div>
				
			</div>	<!-- メニュー全体 -->

			<!-- ======================================================== -->
			<!-- abcエディタ、abc楽譜表示部                               -->
			<!-- ======================================================== -->
			<div id="divAbcJs">
				<textarea id="abc-editor" style="display: none;" onblur="changeAbcString()" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off"></textarea>
				
				<div id="divQuestion"></div>

				<div id="abcjs-container" style="position: relative;" onscroll="abcjsContainerScroll()" onkeydown="containerKeydown(event)">
					<div id="abcjs-body" onmousedown="abcjsBodyMouseDown()"></div>
					
					<!-- 演奏時の楽譜カバー -->
					<div id="abcjs-body_cover" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; background-color: rgba(255, 255, 200, 0.2); z-index: 100; display: none;">
						<span class="textoutline MSC_lang" >演奏モード</span>

						<!-- MIDI 音色選択		%%midi program 1 6 % harpsichord -->
						<select id="selMidiNo" onchange="chgMidiNo(this)">
						  <!-- Piano Category -->
						  <option value="" disabled style="background-color: lightgray;">ピアノ</option>
						  <option value="1" selected>アコースティック ピアノ</option>
						  <option value="2">ブライトピアノ</option>
						  <option value="3">エレクトリック グランドピアノ</option>
						  <option value="4">ホンキートンク ピアノ</option>
						  <option value="5">エレクトリック ピアノ</option>
						  <option value="6">エレクトリック ピアノ2</option>
						  <option value="7">ハープシコード（チェンバロ）</option>
						  <option value="8">クラビコード</option>

						  <!-- Chromatic Percussion Category -->
						  <option value="" disabled style="background-color: lightgray;">音階付き打楽器</option>
						  <option value="9">チェレスタ</option>
						  <option value="10">グロッケンシュピール</option>
						  <option value="11">オルゴール</option>
						  <option value="12">ビブラフォン</option>
						  <option value="13">マリンバ</option>
						  <option value="14">シロフォン（木琴）</option>
						  <option value="15">チューブラーベル</option>
						  <option value="16">ダルシマー</option>

						  <!-- Organ Category -->
						  <option value="" disabled style="background-color: lightgray;">オルガン</option>
						  <option value="17">ドローバーオルガン</option>
						  <option value="18">パーカッシブオルガン</option>
						  <option value="19">ロックオルガン</option>
						  <option value="20">チャーチ オルガン</option>
						  <option value="21">リード オルガン</option>
						  <option value="22">アコーディオン</option>
						  <option value="23">ハーモニカ</option>
						  <option value="24">タンゴアコーディオン（バンドネオン）</option>

						  <!-- Guitar Category -->
						  <option value="" disabled style="background-color: lightgray;">ギター</option>
						  <option value="25">クラシックギター（ナイロン弦）</option>
						  <option value="26">アコースティックギター（スチール弦）</option>
						  <option value="27">ジャズギター</option>
						  <option value="28">クリーン ギター</option>
						  <option value="29">ミュート ギター</option>
						  <option value="30">オーバードライブ ギター</option>
						  <option value="31">ディストーション ギター</option>
						  <option value="32">ギター ハーモニクス</option>

						  <!-- Bass Category -->
						  <option value="" disabled style="background-color: lightgray;">ベース</option>
						  <option value="33">アコースティック ベース</option>
						  <option value="34">フィンガー ベース</option>
						  <option value="35">ピック ベース</option>
						  <option value="36">フレットレス ベース</option>
						  <option value="37">スラップベース</option>
						  <option value="38">スラップベース 2</option>
						  <option value="39">シンセベース 1</option>
						  <option value="40">シンセベース 2</option>

						  <!-- Strings Category -->
						  <option value="" disabled style="background-color: lightgray;">ストリングス</option>
						  <option value="41">バイオリン</option>
						  <option value="42">ビオラ</option>
						  <option value="43">チェロ</option>
						  <option value="44">コントラバス</option>
						  <option value="45">トレモロ</option>
						  <option value="46">ピッチカート</option>
						  <option value="47">オーケストラ ハープ</option>
						  <option value="48">ティンパニ</option>

						  <!-- Ensemble Category -->
						  <option value="" disabled style="background-color: lightgray;">アンサンブル</option>
						  <option value="49">ストリング アンサンブル 1</option>
						  <option value="50">ストリング アンサンブル 2</option>
						  <option value="51">シンセストリングス 1</option>
						  <option value="52">シンセストリングス 2</option>
						  <option value="53">「あー」という人の声</option>
						  <option value="54">「おー」という人の声</option>
						  <option value="55">シンセ ボイス</option>
						  <option value="56">オーケストラ ヒット</option>

						  <!-- Brass Category -->
						  <option value="" disabled style="background-color: lightgray;">ブラス</option>
						  <option value="57">トランペット</option>
						  <option value="58">トロンボーン</option>
						  <option value="59">チューバ</option>
						  <option value="60">ミュート トランペット</option>
						  <option value="61">フレンチ ホルン</option>
						  <option value="62">ブラス セクション</option>
						  <option value="63">シンセブラス 1</option>
						  <option value="64">シンセブラス 2</option>

						  <!-- Reed Category -->
						  <option value="" disabled style="background-color: lightgray;">リード</option>
						  <option value="65">ソプラノ サックス</option>
						  <option value="66">アルト サックス</option>
						  <option value="67">テナー サックス</option>
						  <option value="68">バリトン サックス</option>
						  <option value="69">オーボエ</option>
						  <option value="70">イングリッシュ ホルン</option>
						  <option value="71">バスーン／ファゴット</option>
						  <option value="72">クラリネット</option>

						  <!-- Pipe Category -->
						  <option value="" disabled style="background-color: lightgray;">笛／木管</option>
						  <option value="73">ピッコロ</option>
						  <option value="74">フルート</option>
						  <option value="75">リコーダー</option>
						  <option value="76">パンフルート</option>
						  <option value="77">ボトル</option>
						  <option value="78">尺八</option>
						  <option value="79">口笛</option>
						  <option value="80">オカリナ</option>

						  <!-- Synth Lead Category -->
						  <option value="" disabled style="background-color: lightgray;">シンセリード</option>
						  <option value="81">矩形波</option>
						  <option value="82">ノコギリ波</option>
						  <option value="83">カリオペ</option>
						  <option value="84">チフ</option>
						  <option value="85">チャラング</option>
						  <option value="86">声</option>
						  <option value="87">フィフスズ</option>
						  <option value="88">バス + リード</option>

						  <!-- Synth Pad Category -->
						  <option value="" disabled style="background-color: lightgray;">シンセパッド</option>
						  <option value="89">ファンタジア</option>
						  <option value="90">ウォーム</option>
						  <option value="91">ポリシンセ</option>
						  <option value="92">クワイア</option>
						  <option value="93">ボウ</option>
						  <option value="94">メタリック</option>
						  <option value="95">ハロー</option>
						  <option value="96">スウィープ</option>

						  <!-- Synth Effects Category -->
						  <option value="" disabled style="background-color: lightgray;">シンセエフェクト</option>
						  <option value="97">雨</option>
						  <option value="98">サウンドトラック</option>
						  <option value="99">クリスタル</option>
						  <option value="100">アトモスフィア</option>
						  <option value="101">ブライトネス</option>
						  <option value="102">ゴブリン</option>
						  <option value="103">エコー</option>
						  <option value="104">サイファイ</option>

						  <!-- Ethnic Category -->
						  <option value="" disabled style="background-color: lightgray;">エスニック／民族楽器</option>
						  <option value="105">シタール</option>
						  <option value="106">バンジョー</option>
						  <option value="107">三味線</option>
						  <option value="108">琴／箏</option>
						  <option value="109">カリンバ</option>
						  <option value="110">バグパイプ</option>
						  <option value="111">フィドル</option>
						  <option value="112">シャハナイ</option>

						  <!-- Percussive Category -->
						  <option value="" disabled style="background-color: lightgray;">打楽器</option>
						  <option value="113">ティンクルベル</option>
						  <option value="114">アゴゴ ベル</option>
						  <option value="115">スチールパン</option>
						  <option value="116">ウッド ブロック</option>
						  <option value="117">太鼓</option>
						  <option value="118">メロディックタム</option>
						  <option value="119">シンセドラム</option>
						  <option value="120">リバースシンバル</option>

						  <!-- Sound effects Category -->
						  <option value="" disabled style="background-color: lightgray;">効果音</option>
						  <option value="121">ギターフレットノイズ</option>
						  <option value="122">ブレスノイズ</option>
						  <option value="123">海岸</option>
						  <option value="124">鳥のさえずり</option>
						  <option value="125">電話のベル</option>
						  <option value="126">ヘリコプター</option>
						  <option value="127">拍手</option>
						  <option value="128">ガンショット（銃声）</option>
						  <option value="129">パーカッション</option>
						</select>

					</div>
				</div>
			</div>

			<!-- ======================================================== -->
			<!-- 挿入ボタン・version 表示                                 -->
			<!-- ======================================================== -->
			<div class="no_print" style="position: absolute; left: 0px; bottom: 0px; width: 100%;">
				
				<div id="divInsert">
					<!-- 挿入ボタン -->
					<button class="btn MSC_lang" id="insertButton" style="position: relative; left: 4px; bottom: 4px;" onclick="clkMSC_Insert()">挿入</button>
					&nbsp;
					<label id="labelInsertTitle" style="cursor: pointer;">
						<input type="checkbox" id="chkInsertTitle" style="width: 16px; height: 16px; cursor: pointer;"><span class="MSC_lang" id="spanInsert" style="position: relative; top: -3px; color: #000000;">曲名・作者を含める</span>
					</label>
					
					<!-- キャンセルボタン -->
					<span id="spanMSC_BtnCancel" style="display: none;">
						&nbsp;｜
						<button class="btnWhite MSC_lang" id="MSC_cancelButton" style="position: relative; left: 4px; bottom: 4px;" onclick="clkMSC_Cancel()">キャンセル</button>
					</span>
					
					<!-- メニュー設定ボタン -->
					<div id="spanMSC_BtnMenuConfig" style="position: absolute; right: 12px; display: none;">
						<button class="btnWhite MSC_lang" id="MSC_menuconfigButton" style="position: relative; bottom: 4px;" onclick="clkMSC_MenuConfig()">メニュー設定</button>
					</div>
				</div>

				<!-- version 表示 -->
				<div id="divVersion" style="position: absolute; right: 4px; bottom: 4px;"></div>
			</div>

			<!-- ======================================================== -->
			<!-- 和音設定ダイアログ表示時の背景カバー                     -->
			<!-- ======================================================== -->
			<div class="divBackCover" id="divBackCover2"></div>
		</div>	<!-- エディター全体 -->

		<!-- ======================================================== -->
		<!-- 起動時Waitアニメ                                         -->
		<!-- ======================================================== -->
		<div id="divWaitAnime" style="max-width: 620px; margin-top: 120px; background: #FFFFFF;">
			<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="144" height="144" fill="#2589d0">
				<path transform="translate(2)" d="M0 12 V20 H4 V12z">
					<animate attributeName="d" values="M0 12 V20 H4 V12z; M0 4 V28 H4 V4z; M0 12 V20 H4 V12z; M0 12 V20 H4 V12z"
						 dur="1.2s" calcMode="spline" begin="0" repeatCount="indefinite"
						 keytimes="0;.2;.5;1" keySplines=".2 .2 .4 .8;.2 0.6 .4 .8;.2 .8 .4 .8"/>
				</path>
				<path transform="translate(8)" d="M0 12 V20 H4 V12z">
					<animate attributeName="d" values="M0 12 V20 H4 V12z; M0 4 V28 H4 V4z; M0 12 V20 H4 V12z; M0 12 V20 H4 V12z"
						dur="1.2s" calcMode="spline" begin=".2" repeatCount="indefinite"
						keytimes="0;.2;.5;1" keySplines=".2 .2 .4 .8;.2 0.6 .4 .8;.2 .8 .4 .8"/>
				</path>
				<path transform="translate(14)" d="M0 12 V20 H4 V12z">
					<animate attributeName="d" values="M0 12 V20 H4 V12z; M0 4 V28 H4 V4z; M0 12 V20 H4 V12z; M0 12 V20 H4 V12z"
						dur="1.2s" calcMode="spline" begin=".4" repeatCount="indefinite"
						keytimes="0;.2;.5;1" keySplines=".2 .2 .4 .8;.2 0.6 .4 .8;.2 .8 .4 .8"/>
				</path>
				<path transform="translate(20)" d="M0 12 V20 H4 V12z">
					<animate attributeName="d" values="M0 12 V20 H4 V12z; M0 4 V28 H4 V4z; M0 12 V20 H4 V12z; M0 12 V20 H4 V12z"
						dur="1.2s" calcMode="spline" begin=".6" repeatCount="indefinite"
						keytimes="0;.2;.5;1" keySplines=".2 .2 .4 .8;.2 0.6 .4 .8;.2 .8 .4 .8"/>
				</path>
				<path transform="translate(26)" d="M0 12 V20 H4 V12z">
					<animate attributeName="d" values="M0 12 V20 H4 V12z; M0 4 V28 H4 V4z; M0 12 V20 H4 V12z; M0 12 V20 H4 V12z"
						dur="1.2s" calcMode="spline" begin=".8" repeatCount="indefinite"
						keytimes="0;.2;.5;1" keySplines=".2 .2 .4 .8;.2 0.6 .4 .8;.2 .8 .4 .8"/>
				</path>
			</svg>
		</div>

		<!-- ======================================================== -->
		<!-- メッセージダイアログ（はい・いいえ付き）                 -->
		<!-- ======================================================== -->
		<dialog id="dialogMessageYesNo" style="width: 300px; padding: 16px; margin-top: 90px;" oncancel="event.preventDefault();">
			<div style="cursor: default;">
				<span id="spanMessageYesNo"></span>
				<br><br>
				<div style="width: 100%; text-align: right; padding: 0p 8px;">
					<button class="buttonDialogYes MSC_lang" id="btnMessageYesNoYes">はい</button>
					<button class="buttonDialogNo MSC_lang" id="btnMessageYesNoNo">いいえ</button>
				</div>
			</div>
		</dialog>

		<!-- ======================================================== -->
		<!-- 曲名・作者ダイアログ（含む、タイトル・著者入力、ソース・楽譜印刷） -->
		<!-- ======================================================== -->
		<dialog id="dialogTitleAndAuthor" style="width: 360px;">
			<div style="cursor: default;">
				<span class="MSC_lang">タイトル</span>：<br>
				<!--
				<input type="text" id="txtTitle" style="width:100%; height: 26px; padding-left: 4px;" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off" oninput="textareaMaxLines(this, 2)">
				-->
				<textarea  id="txtTitle" style="width:100%; height: 38px; padding: 4px; line-height: 1.4em; resize: none;" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off" oninput="textareaMaxLines(this, 2)"></textarea>

				<span class="MSC_lang">作者</span>：<br>
				<!--
				<input type="text" id="txtAuthor" style="width:100%; height: 26px;" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off" oninput="textareaMaxLines(this, 3)">
				-->
				<textarea  id="txtAuthor" style="width:100%; height: 56px; padding: 4px; line-height: 1.4em; resize: none;" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off" oninput="textareaMaxLines(this, 3)"></textarea>
				<br><br>
				
				<!-- 曲名・作者登録時用 -->
				<div id="divForTitleInput" style="display: none;">
					<label style="cursor: pointer;">
						<input type="checkbox" id="chkTitleDisp" style="width: 16px; height: 16px; cursor: pointer;"><span class="MSC_lang" style="position: relative; top: -2px;">楽譜編集画面に表示</span>
					</label>
				</div>
				
				<!-- 印刷時用 -->
				<div id="divForPrint" style="display: none;">
					<span class="MSC_lang">印刷内容</span>：
					<label style="cursor: pointer;">
					<input type="radio" name="radioPrintKind" id="radioPrintKindScore" style="width: 15px; height:15px; cursor: pointer;" checked><span class="MSC_lang">楽譜</span>
					</label>

					<label style="margin-left: 12px; cursor: pointer;">
					<input type="radio" name="radioPrintKind" id="radioPrintKindSource" style="width: 15px; height:15px; cursor: pointer;"><span class="MSC_lang">abcソース</span>
					</label>
				</div>
				
				<hr style="margin: 16px 0px;">
				
				<div style="width: 100%; text-align: right; padding: 0p 8px;">
					<button class="buttonDialogYes MSC_lang" id="btnPrintOK">印刷</button>
					<button class="buttonDialogNo MSC_lang" id="btnPrintCancel">キャンセル</button>
				</div>
			</div>
		</dialog>

		<!-- ======================================================== -->
		<!-- PNGイメージ印刷用DIV（非表示）                           -->
		<!-- ======================================================== -->
		<div id="divImagePrint" style="display: none;">
			<img id="imageToPrint" />
		</div>

		<!-- ======================================================== -->
		<!-- テキスト印刷用DIV（非表示）                              -->
		<!-- ======================================================== -->
		<div id="divTextPrint" style="font-size: 13px; color: black; text-align: left; vertical-align: top; display: none; line-height: 24px;">
		</div>

		<!-- ======================================================== -->
		<!-- pngイメージ生成用canvas（非表示）                       -->
		<!-- ======================================================== -->
		<canvas id="canvasPng" style="display: none;"></canvas>

		<!-- ======================================================== -->
		<!-- ファイルopenダイアログ用（非表示）                       -->
		<!-- ======================================================== -->
		<input type="file" id="fileOpenDialog" accept=".msd" onchange="openAbcData(event)" style="display: none;">`;
