(function() {
	var headerLines = "";
	var initLines = "";
	var mainLines = "";
	var endLines = "";
	var usageLines = "";
	var errorLines = "";

	function updateOutTextarea() {
		clearLines();

		setEchoOff();
		setDefaultEnv();
		setUsage();
		setArgsCheck();
		setStartPause();
		setStartMessage();
		setDummyProcess();
		setEndMessage();
		setEndPause();

		$("#outTextarea").text( //
		headerLines + "\n" + //
		":INIT\n" + initLines + "\n" + //
		":MAIN\n" + mainLines + "\n" + //
		":END\n" + endLines + "exit /b 0\n" + "\n" + //
		":USAGE\n" + usageLines + "exit /b 0\n" + "\n" + //
		":ERROR\n" + errorLines + "exit /b -1\n" + "\n" + //
		":EOF\n");
	}

	function clearLines() {
		headerLines = "";
		initLines = "";
		mainLines = "";
		endLines = "";
		usageLines = "";
		errorLines = "";
	}

	function setEchoOff() {
		headerLines += "@echo off\n";
	}

	function setDefaultEnv() {
		headerLines += "set basedir=%~dp0\n";
		headerLines += "set batname=%~n0%~x0\n";
		headerLines += "set datestr=%DATE:/=%\n";
		headerLines += "set timestrtmp=%TIME: =0%\n";
		headerLines += "set timestr=%timestrtmp:~0,2%%timestrtmp:~3,2%%timestrtmp:~6,2%\n";
		headerLines += "set timestamp=%datestr%-%timestr%\n";
	}

	function setArgsCheck() {
		var args = $("#inArgs:checked").val();
		if (args) {
			initLines += "if \"%1\"==\"\" goto USAGE\n";
		}
	}

	function setUsage() {
		usageLines += "echo 使い方：%batname%\n";
	}

	function setStartMessage() {
		mainLines += "echo 処理開始します。\n";
	}

	function setEndMessage() {
		endLines += "echo 正常終了です。\n";
		errorLines += "echo エラー終了です。\n";
	}

	function setDummyProcess() {
		mainLines += "rem <<< ここに処理を書きます >>>\n";
	}

	function setStartPause() {
		var startPause = $("#inStartPause:checked").val();
		if (startPause) {
			initLines += "set /p input=開始してよろしいですか？ (y/n)\n";
			initLines += "if not \"%input%\"==\"y\" goto EOF\n";
		}
	}

	function setEndPause() {
		var endPause = $("#inEndPause:checked").val();
		if (endPause) {
			endLines += "pause\n";
		}
	}

	$(function() {
		$("#inTitle").keyup(function() {
			updateOutTextarea();
		});
		$("#inArgs, #inStartPause, #inEndPause").click(function() {
			updateOutTextarea();
		});
		$("#inSubmit").click(function() {
			updateOutTextarea();
		});
		$("#outTextarea").click(function() {
			$(this).select();
		});

		// 初期表示で生成処理を行う
		$("#inSubmit").click();
	});
})();