/*
 * entity.js
 * 
 * Copyright (c) Takao Tagawa (dounokouno.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Since:     2009-04-21
 * Modified:  2010-12-10
 *
 * jQuery 1.6.4
 * 
*/

(function($){
	$(function(){
		// 初期状態で変換前へフォーカス
		$("#befor").focus();
		
		// 変換ボタン
		$("#convert").click($.entity.convert);
		
		// リセットボタン
		$("#reset").click($.entity.reset);
		
		// 検証ボタン
		$("#verify").click($.entity.verify);
		
		// 選択ボタン
		$("#select").click(function(){
			$("#after").select();
			return false;
		});
		
		// ダイアログの設定
		$("#dialog").dialog({
			draggable: false,
			autoOpen: false,
			modal: true,
			width: 400,
			title: "検証"
		});
		
	});
	
	// 処理
	$.entity={
		// 生成
		convert:function(){
			// -------------------------------------------------------
			// 変換
			// -------------------------------------------------------
			
			var t = $("#befor").val();
			var r = "";
			
			// 半角スペース、タブ、改行の除去にチェックが入っている場合
			if ($("#remove").attr("checked")) {
				t = t.replace(/[\n\r\s" "]/g, "");
			}
			
			// エンティティ化
			for (i=0;i<t.length;i++) {
				r += "&#" + t.charCodeAt(i) + ";";
			}
			
			// a要素で囲むにチェックが入っている場合
			if ($("#a").attr("checked")) {
				// mailto:をエンティティ化
				var mt = "mailto:";
				var mtr = "";
				for (i=0;i<mt.length;i++) {
					mtr += "&#" + mt.charCodeAt(i) + ";";
				}
				
				// a要素で囲む
				r = "<a href=\"" + mtr + r + "\">" + r + "</a>";
			}
			
			// 変換後へ出力、選択
			$("#after").val(r);
			$("#after").select();
			
			return false;
		},
		
		// 検証
		verify:function(){
			// -------------------------------------------------------
			// 検証
			// -------------------------------------------------------
			
			var t = $("#after").val();
			
			// 検証ボタンクリック
			$("#dialog > p").html(t);
			$("#dialog").dialog("open");
			return false;
			
		},
		
		// リセット
		reset:function(){
			$("#befor").val("");
			$("#after").val("");
			$("#befor").focus();
			return false;
		}
	};
})(jQuery);
