/**
 *************************************************************************************
 * [标题：ExmayUI JQuery Code Eidtor 插件]<br>
 *************************************************************************************
 * [描述：ExmayUI JQuery Code Eidtor 插件]<br>
 *************************************************************************************
 * @author Exmay Team / 亿美团队
 *************************************************************************************
 * @version Version 1.0.1 Beta / v1.0.1 测试版
 *************************************************************************************
 */

/*
 * ***********************************************************************************
 * 版权：Copyright © 2012 Exmay Inc. All Rights Reserved. 长沙亿美软件有限公司　版权所有
 * ***********************************************************************************
 * 企业文化：专注　创新　分享　共赢
 * ***********************************************************************************
 * 官方网站：http://www.exmay.com
 * ***********************************************************************************
 * 官方邮箱：service@exmay.com
 * ***********************************************************************************
 */


(function($) {

	/*
	<input type="button" value="加粗" onclick="Bold()"> 
	<script> 
	myEditer.document.designMode = "on"; 
	function Bold(){ 
	var sel = myEditer.document.selection.createRange(); 
	//alert(sel.text); 
	sel.execCommand("Bold") 
	} 
	</script> 
	
	execCommand()的常用用法： 
	字体--宋体、黑体、楷体等 
	execCommand("fontname","",字体) 
	字号--字号大小 
	execCommand("fontsize","",字号) 
	加重 
	execCommand("Bold") 
	斜体 
	execCommand("Italic") 
	下划线 
	execCommand("Underline") 
	删除线 
	execCommand("StrikeThrough") 
	居左 
	execCommand("JustifyLeft") 
	居右 
	execCommand("JustifyRight") 
	居中 
	execCommand("JustifyCenter") 
	剪切 
	execCommand("Cut") 
	拷贝 
	execCommand("Copy") 
	粘贴 
	execCommand("Paste") 
	取消操作--IE5.0以后可以无限取消 
	execCommand("Undo") 
	重复操作 
	execCommand("Redo") 
	 */

	/*
	Visula mode / Source mode
	Design / Code / Preview
	 */
	var EXMAY_CODE_EDITOR = "exmayCodeEditor", TEXTAREA = "TEXTAREA";
 	var CARET_CHAR = "\u2009";	// 光标插入符
	
	//var _document;

	var syntax = [ { 
		input : /(&lt;[^!#]*?&gt;)/g,
		output : '<span class="exmay-ui-html-tag">$1</span>'
	}, // all tags
			{
				input : /(&lt;a .*?&gt;|&lt;\/a&gt;)/g,
				output : '<span class="exmay-ui-html-anchor">$1</span>'
			}, // links
			{
				input : /(&lt;img .*?&gt;)/g,
				output : '<span class="exmay-ui-html-image">$1</span>'
			}, // images
			{
				input : /(&lt;\/?(button|textarea|form|input|select|option|label).*?&gt;)/g,
				output : '<span class="exmay-ui-html-form">$1</span>'
			}, // forms
			{
				input : /(&lt;\/?(table|th|tr|td|caption|col|colgroup|thead|tbody|tfoot).*?&gt;)/ig,
				output : '<span class="exmay-ui-html-table">$1</span>'
			}, // table(表格)
			//{ input : /(&lt;style.*?&gt;)(.*?)(&lt;\/style&gt;)/g, output : '<em>$1</em><em>$2</em><em>$3</em>' }, // style tags
			//{ input : /(&lt;script.*?&gt;)(.*?)(&lt;\/script&gt;)/g, output : '<strong>$1</strong><tt>$2</tt><strong>$3</strong>' }, // script tags
			//{
			//	input : /=(&quot;.*?&quot;)/g,
			//	output : '=<span class="exmay-ui-html-string">$1</span>'
			//}, // atributes double quote
//			{
//				input : /=('.*?')/g,
//				output : '=<span class="exmay-ui-html-string">$1</span>'
//			}, // atributes single quote
			{
				input : /(&lt;!--.*?--&gt.)/g,
				output : '<span class="exmay-ui-html-comment">$1</span>'
			}, // html comments 
			{
				input : /(&lt;\/@exmay.*?&gt;)/g,
				output : '<span class="exmay-ui-exmay-tag">$1</span>'
			}, // exmay end tags
			{
				input : /(&lt;#--.*?--&gt.)/g,
				output : '<span class="exmay-ui-freemarker-comment">$1</span>'
			}, // freemarker comments 
			{
				input : /(\${.*?})/g,
				output : '<span class="exmay-ui-freemarker-variable">$1</span>'
			}, {
				input : /(&lt;\/#[^--].*?&gt;)/g,
				output : '<span class="exmay-ui-freemarker-tag">$1</span>'
			}, //freemaerker end tags
			{
				input : /(&lt;#include\s*)([&quot;|'].*?[&quot;|'])(\s*\/&gt;)/g,
				output : '$1<span class="exmay-ui-freemarker-string">$2</span>$3'
			} //freemaerker tags
			
	]

	var cssSyntax = [
	//{ input : /(<br.*?\s*)(.*?\s*})/ig, output : '$1<span class="exmay-ui-css-selector">$2</span>' }, // style(样式)
	//{ input : /([^=s]*)(\s*)({)/ig, output : '<span class="exmay-ui-css-selector">$1</span>$2$3' }, // style(样式)
	//{ input : /({)([\s|<\/li>|<li>]*)([\w|-]*)(\s*)(:)/ig, output : '$1$2<span class="exmay-ui-css-property">$3</span>$4$5' } // style(样式)
	//{ input : /([\w|-]*)(\s*)({)([\s|<\/li>|<li>]*)([\w|-]*)(\s*)(:)(\s*)([\w|-]*)(\s*)(;)(\s*)(})/ig, output : '<span class="exmay-ui-css-selector">$1</span>$2'+'<span class="exmay-ui-css-selector">$3</span>$4<span class="exmay-ui-css-property">$5</span>$6<span class="exmay-ui-css-selector">$7</span>$8<span class="exmay-ui-css-value">$9</span>$10<span class="exmay-ui-css-selector">$11</span>$12<span class="exmay-ui-css-selector">$13</span>' } // style(样式)
	//		{ input : /([\w|-]*)([\s|<\/li>|<li>]*)({)([\s|<\/li>|<li>]*)([\w|-]*)([\s|<\/li>|<li>]*)(:)([\s|<\/li>|<li>]*)([\w|-]*)([\s|<\/li>|<li>]*)(;)([\s|<\/li>|<li>]*)(})/ig, output : '<span class="exmay-ui-css-selector">$1</span>$2'+'<span class="exmay-ui-css-selector">$3</span>$4<span class="exmay-ui-css-property">$5</span>$6<span class="exmay-ui-css-selector">$7</span>$8<span class="exmay-ui-css-value">$9</span>$10<span class="exmay-ui-css-selector">$11</span>$12<span class="exmay-ui-css-selector">$13</span>' }, // style(样式)
	//{ input : /(&lt;style.*?&gt;)(.*?)(&lt;\/style&gt;)/ig, output : 'a$1<span class="exmay-ui-html-selector">a$2</span>b$3' }
	//{ input : /(&lt;style.*?&gt;)(.*?)(&lt;\/style&gt;)/ig, output : '$1<span class="exmay-ui-css-selector">$2</span>$3' }
	//		{ input : /\/\*(.*?)\*\//g, output : '<i>/*$1*/</i>'} // comments
	//{ input : /([\w-]*?):([^\/])/g,output : '<span class="exmay-ui-css-property">$1</span>:$2' }, // keys 属性
	//{ input : /\((.*?)\)/g,output : '(<span class="exmay-ui-parameter">$1</span>)' }, // parameters 括号里的参数
	//{ input : /([^<>]*?){(.*?)}/g,output : '<span class="exmay-ui-css-selector">$1{$2}</span>' }, // tags, ids, classes, values
	//{ input : /\/\*(.*?)\*\//g,output : '<span class="exmay-ui-css-comment">/*$1*/</span>'} // comments 注释
	//{ input : /\/\*(.*?)\*\//g,output : '<span class="exmay-ui-css-comment">/*$1*/</span>'} // comments 注释
	//{ input : /([^;{\s]*?)(\s*:\s*)([^;}\s]*?)/g,output : 'AAAAAAAAAAAA$1BBBBBBBBBBBB$2CCCCCCCCCCCCCCCCCC$3DDDDDDDDDDDDDDDDDDD'} // comments 注释
	//{ input : /([\w|-]*)([\s|<br]*)({)([\s|<br]*)([\w|-]*)([\s|<br]*)(:)([\s|<br]*)([\w|-]*)([\s|<br]*)(;)([\s|<br]*)(})/ig, output : '<span class="exmay-ui-css-selector">$1</span>$2'+'<span class="exmay-ui-css-selector">$3</span>$4<span class="exmay-ui-css-property">$5</span>$6<span class="exmay-ui-css-selector">$7</span>$8<span class="exmay-ui-css-value">$9</span>$10<span class="exmay-ui-css-selector">$11</span>$12<span class="exmay-ui-css-selector">$13</span>' }, // style(样式)

	];
	var javascriptSyntax = [
		{ input : /(&quot;.*?&quot;)|\b(Exmay|break|continue|do|for|new|this|void|case|default|else|function|return|typeof|while|if|label|switch|var|with|catch|boolean|int|try|false|throws|null|true|goto)\b|\b(alert|isNaN|parent|Array|parseFloat|parseInt|blur|clearTimeout|prompt|prototype|close|confirm|length|Date|location|Math|document|element|name|self|elements|setTimeout|navigator|status|String|escape|Number|submit|eval|Object|event|onblur|focus|onerror|onfocus|onclick|top|onload|toString|onunload|unescape|open|valueOf|window|onmouseover)\b|(\d)|\b(abs)\b|(\/\*(\s|.)*?\*\/)|((\/\/.*?))/gm, output : '<span class="exmay-ui-javascript-string">$1</span><span class="exmay-ui-javascript-reserved">$2</span><span class="exmay-ui-javascript-client">$3</span><span class="exmay-ui-javascript-native">$5</span><span class="exmay-ui-html-anchor">$6</span><span class="exmay-ui-javascript-string">$7</span><span class="exmay-ui-javascript-string">$8</span>'}
		
	];
	var exmaySyntax = [ {
		input : /(&lt;@exmay.*?&gt;)/g,
		output : '<span class="exmay-ui-exmay-tag">$1</span>'
	}, // all tags
			//		{ input : /([^<>"'\s]+)(\s*)(\=)(\s*)("[^<>"'\s]+"|'[^<>\s]+'|[^<>"'\s]+)/ig, 
			{
				input : /(\w+)(\s*)(\=)(\s*)(&quot;[\s\S]+?&quot;|'\w+'|[\.\w]+)/ig,
				output : '<span class="exmay-ui-exmay-property">$1</span>$2<span class="exmay-ui-exmay-operator">$3</span>$4<span class="exmay-ui-exmay-string">$5</span>'
			}
	//{ input : /(&lt;)(@exmay\.\w*)([\s\S]*?)(\/\s*&gt;)/ig, 
	//output : '<span class="exmay-ui-exmay-tag">$1$2</span>$3<span class="exmay-ui-exmay-tag">$4</span>' },
	//		{ input : /(&lt;)(@exmay\.\w*)([\s\S]*?)(&gt;)([\s\S]*?)(\1\/\2\s*&gt;)/ig, 
	//{ input : /(&lt;)(@exmay\.\w*)([\s\S]*?)(&gt;)([\s\S]*?)(\/\s*&gt;|\1\/\2\s*&gt;)/ig, 
	//		 output : '<span class="exmay-ui-exmay-tag">$1$2</span>$3<span class="exmay-ui-exmay-tag">$4</span>$5<span class="exmay-ui-exmay-tag">$6</span>' },
	//{ input : /(&lt;)(@exmay\.\w*)([\s\S]*)(\1\/\2\s*&gt;)/ig, 
	// output : '<span class="exmay-ui-exmay-tag">$1$2</span>$3<span class="exmay-ui-exmay-tag">$4</span>' }
	// (<)(@em\.\w*)(.*)(\w*=".*"|\w*='.*')*(\/\s*>|\1\/\2\s*>)
	//{ input : /([^\s]*?)(=[^"])/g, output : '<span class="exmay-ui-exmay-property">$1</span>$2' } // atributes double quote "
	];
	var freemakerSyntax = [
	//{ input : /(&quot;.*?&quot;)/g, output : '<span class="exmay-ui-freemarker-string">$1</span>' },
			{
				input : /(&lt;#[^--].*?&gt;)/g,
				output : '<span class="exmay-ui-freemarker-tag">$1</span>'
			}, //freemaerker tags
			{
				input : /(\w+)(\s*)(\=)(\s*)(&quot;[\s\S]+?&quot;|'\w+'|[\.\w]+)/ig,
				output : '<span class="exmay-ui-freemarker-property">$1</span>$2<span class="exmay-ui-freemarker-operator">$3</span>$4<span class="exmay-ui-freemarker-string">$5</span>'
			} ];
	var ssiSyntax = [

	];
	// 初始化亿美富文本编辑器
	function initExmayCodeEditor(target, opts) {
		var $target = $(target);
		$target.hide();
		var id = $target.attr("id");
		var $design = $('<iframe frameborder="0" name="exmay-editor-design-iframe"></iframe>');
		$design.css( {
			border : "1px solid #ccc",
			//overflow : "auto",
			//display : "block",
			width : "100%",
			height : opts.height
		}).attr("id", id + "-design-iframe");
		if (!opts.design) {
			$design.hide();
		}
		var $code = $('<iframe frameborder="0" name="exmay-editor-code-iframe"></iframe>');
		$code.css( {
			//border : "1px solid #BED8FE",
			//overflow : "auto",
			//display : "block",
			width : "100%",
			height : opts.height
		}).attr("id", id + "-code-iframe");
		$code.insertAfter(target);
		$design.insertAfter($code);
		var designWindow = $design[0].contentWindow; // 用 designWindow 变量代替 iframe的window 
		var designDocument = designWindow.document; // 用 designDocument 变量代替 iframe的document 
		var codeWindow = $code[0].contentWindow; // 用 codeWindow 变量代替 iframe的window 
		var codeDocument = codeWindow.document; // 用 codeDocument 变量代替 iframe的document 
		//		$target.data("exmayCodeEditor", {
		//			iframe : $iframe[0],
		//			win : designDocument,
		//			doc : designDocument
		//		});
		designDocument.designMode = "On";
		codeDocument.designMode = "On";
		codeDocument.contentEditable = true;
		//  style="word-wrap:break-word;text-align: left; background-color: #fff; border:1px solid #CCC; margin:0px; padding:0px;overflow:hidden;"
		designDocument.write('<html><body></body></html>');
		//codeDocument.focus();
		//codeDocument.open();
		codeDocument.write('<html><head><title>亿美代码编辑器</title><link id="cp-lang-style" rel="stylesheet" href="${sitePath}/exmay/framework/jquery-exmayui-1.0.1/exmayui-editor/code/languages/html.css" type="text/css" /></head><body></body></html>');
		//codeDocument.close();
		//designDocument.contentEditable = true;
		//codeDocument.contentEditable = true;
		var main = '<html><head><title>亿美代码编辑器</title><link id="cp-lang-style" rel="stylesheet" href="${sitePath}/exmay/framework/jquery-exmayui-1.0.1/exmayui-editor/code/languages/html.css" type="text/css" /></head><body></body></html>';
		if ($.browser.msie) {
			//alert("IE");
			//return false;
			designDocument.body.contentEditable = true;
			codeDocument.body.contentEditable = true;
			designDocument.open();
			//designDocument.write("亿美软件");
			//designDocument.write('<img src="http://www.exmay.com/skin/default/images/logoxxx.png"/> <h1>亿美软件</h1>');
			designDocument.write($target.val());
			designDocument.close();
			codeDocument.open();
			codeDocument.write(main);
			//codeDocument.write("亿美软件");
			//codeDocument.write('<pre>&lt;img src="http://www.exmay.com/skin/default/images/logoxxx.png"/&gt; &lt;h1/&gt;代码&lt;/h1&gt;</pre>');
			/*var html = $target.val();
				html = html.replace(/\u2009/gi,'');
				html = html.replace(/&/gi,'&amp;');
				html = html.replace(/</g, "&lt;");
				html = html.replace(/>/g, "&gt;");
				html = html.replace(/([^\n]*?\n)/g,'<li>$1</li>');
				html = html.replace(/\n\r/g,'<P></P>');
				html = html.replace(/\n/g,'<P>');
				html = html.replace(/"/g,'&quot;');
			for(var i=0; i<syntax.length; i++) {
				html = html.replace(syntax[i].input, syntax[i].output);
			}
			//alert(html);*/
			var code = $target.val();
			var html = exmaySyntaxHighilight(code,"init");
			codeDocument.write('<pre class="exmayui-code-editor-highlighter">' + html + '</pre>');
			codeDocument.close();
		} else {
			//alert("F");
			designDocument.open();
			//designDocument.write('<img src="http://www.exmay.com/skin/default/images/logoxxx.png"/> <h1>亿美软件</h1>');
			designDocument.write($target.val());
			designDocument.close();
			codeDocument.open();
			//codeDocument.write('<pre>&lt;img src="http://www.exmay.com/skin/default/images/logoxxx.png"/&gt; &lt;h1/&gt;代码&lt;/h1&gt;</pre>');
			var code = $target.val();
			var html = exmaySyntaxHighilight(code,"init");
			codeDocument.write('<pre class="exmayui-code-editor-highlighter">' + html + '</pre>');
			codeDocument.close();
		}
		exmayBindExmayCodeEditorEvents(target, opts, $code[0]);
		if(opts.readOnly) {
			codeDocument.designMode = "Off";
		}
		return {
			design : $design,
			code : $code
		};
	}
	;

	function exmayBindExmayCodeEditorEvents(target, opts, codeEditor) {
		var codeWindow = codeEditor.contentWindow;
		var codeDocument = codeWindow.document;
		var doc = codeDocument;

		if (doc) {
			if (doc.addEventListener) {
				doc.addEventListener('keypress', keyHandler, true);
			} else if (doc.attachEvent) {
				doc.attachEvent('onkeypress', function() {
					keyHandler(codeWindow.event);
				});
			} else {
				doc.onkeypress = keyHandler;
			}
		}

		function keyHandler(event) {
			var keyCode = event.keyCode;
			var charCode = event.charCode;
			var fromChar = String.fromCharCode(charCode);
			//$("#debug").append(keyCode + " " + charCode + " "+ fromChar);
			if (keyCode == 9) {
				exmayInsertHtml($code[0], "\ \ \ \ ");
			}
			if (keyCode == 62 || charCode == 62 || fromChar == ">") {
				//exmaySyntaxHighilight(target);
				if ($.browser.msie) {
					codeDocument.selection.createRange().text = CARET_CHAR;
				}else {
					codeWindow.getSelection().getRangeAt(0).insertNode(codeDocument.createTextNode(CARET_CHAR));
				}
				var html = exmayGetCodeEditorHtml(codeEditor);
				//insertHTML(codeEditor,CARET_CHAR);
				//var code = exmayGetCodeFragment(html,"");
				//var highilightCode = exmaySyntaxHighilight(code);
				//html = html.replace(code, highilightCode);
				//exmaySetCodeEditorHtml(codeEditor, html);
				
			}
			//alert(keyCode);
			if (opts.chars.indexOf('|' + charCode + '|') != -1 || keyCode == 13) {
				//top.setTimeout(function(){syntaxHighlight(target, 'generic');},100);
			}
			//alert(fromChar);
			//alert("ABC");
			//var html = designDocument.body.innerHTML;
			//insertHTML($design[0], "ABC");
		}
		;

	}
	;

	/*var doc1 = designDocument;
	if (doc1) {
		if (doc1.addEventListener) {
			doc1.addEventListener(
			'keypress',
			key1Handler,
			false
			);
		}
		else if (doc1.attachEvent) {
			doc1.attachEvent(
			'onkeypress',
			function() {
				key1Handler(designWindow.event);
			}
			);
		}
		else {
			doc1.onkeypress = key1Handler;
		}
	};
	
	function key1Handler() {
		alert(123);
		var html = $target.val();
		if ($.browser.mozilla || $.browser.safari) {
			//if($.trim(text)===""){text="&nbsp;";}
			//designDocument.open('text/html', 'replace');
			designDocument.open();
			designDocument.write(html);
			designDocument.close();
		} else {
			
			designDocument.body.innerHTML = "";
			if (html !== "") {
				designDocument.write(html);
			}
		}
	};*/
	
	// 获取代码编辑器高亮标签原始代码
	function exmayGetCodeEditorHtml(codeEditor){
		var html = $(".exmayui-code-editor-highlighter", codeEditor.contentWindow.document.body).html();
		return html;
	}
	
	function exmaySetCodeEditorHtml(codeEditor, html){
		$(".exmayui-code-editor-highlighter", codeEditor.contentWindow.document.body).html(html);
	}

	function exmayInsertHtml(editArea, html) {
		var editAreaWindow = editArea.contentWindow;
		var editAreaDocument = editAreaWindow.document;
		editAreaWindow.focus();
		if ($.browser.msie) {
			editAreaDocument.selection.createRange().pasteHTML(html);
		} else {
			editAreaDocument.execCommand("InsertHtml", "", html);
		}
		editAreaWindow.focus();
	}

	//		function insertHTML(html){
	//		   _window.focus(); 
	//		   if($.browser.msie){
	//				designDocument.selection.createRange().pasteHTML(html) ;
	//		   }else{ 
	//				designDocument.execCommand("InsertHtml", "", html);
	//		   }
	//		}

	//insertHTML('<img src="http://www.exmay.com/skin/default/images/logoxxx.png"/>');

	
	// split big files, highlighting parts of it
	function exmayGetCodeFragment(code,flag) {
		if (flag == 'scroll') {
			//this.scrolling = true;
			return code;
		} else {
			//alert(code);
			//this.scrolling = false;
			var middle = code.indexOf(CARET_CHAR);
			//alert(middle);
			var begin = 0;
			var end = 0;
			if (middle - 2500 < 0) {
				end = middle;
			} else if (middle + 2500 > code.length) {
				begin = code.length - 5000;
				end = code.length;
			} else {
				begin = middle - 2500;
				end = middle + 2500;
			}
			code = code.substring(begin, end);
			return code;
		}
	};
	
	// 语法高亮
	function exmaySyntaxHighilight(code, type) {
		//var $target = $(target);
		//alert(code);
		var html = code;
		html = html.replace(/\u2009/gi, '');
		if(type=="init") {
			html = html.replace(/&/gi, '&amp;');
			html = html.replace(/</g, "&lt;");
			html = html.replace(/>/g, "&gt;");
			//html = html.replace(/\n\r/g,'<li></li>');
			html = html.replace(/([^\n]*?\n)/g, '$1<br/>');
			html = html.replace(/\n/g, '');
			html = html.replace(/\"/g, '&quot;');
			//alert(html);
		}
		
		for ( var i = 0; i < syntax.length; i++) {
			html = html.replace(syntax[i].input, syntax[i].output);
		}

		//var regex1 = "(&lt;)(@exmay\\.((?!&gt;)\\S)+)((?!&gt;|\\/&gt)[\\s\\S])+(/\\&gt;)";
		// (&lt;)(@exmay\.((?!&gt;)\S)+)((?!&gt;|\/&gt)[\s\S])+(\s*)(&gt;)([\s\S]*)(\1\/\2\s*&gt;)
		//var exmayPattern1 = new RegExp(regex1, "gi");
		//var isExmayTag = /(&lt;)(@exmay\.\w*)([\s\S]*?)(\/\s*&gt;|\1\/\2\s*&gt;)/ig.test(html);
		//var isExmayTag = /(&lt;)(@exmay\.\w*)([\s\S]*?)(\/\s*&gt;)/ig.test(html);
		var isExmayTag = exmaySyntax[0].input.test(html);
		//var isExmayTag = exmayPattern1.test(html);
		//alert(isExmayTag);
		//alert(isExmayTag);
		if (isExmayTag) {
			var exmayTags = html.match(exmaySyntax[0].input);
			//alert(exmayTags.length); //|\1\/\2\s*&gt;
			for ( var m = 0; m < exmayTags.length; m++) {
				for ( var n = 0; n < exmaySyntax.length; n++) {
					html = html.replace(exmayTags[m], exmayTags[m].replace(exmaySyntax[n].input, exmaySyntax[n].output));
					exmayTags[m] = exmayTags[m].replace(exmaySyntax[n].input, exmaySyntax[n].output);
					//alert("第"+m+"中"+n+"次  :   "+script[m]+ "########################" + script[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
				}
			}
			//				var exmayTag2 =  html.match(/(&lt;)(@exmay\.\w*)([\s\S]*?)(&gt;)([\s\S]*?)(\1\/\2\s*&gt;)/ig);
			//				alert(exmayTag2.length);
			//				for(var m=0; m<exmayTag2.length; m++) {
			//					for(var n=0; n<exmaySyntax.length; n++) {
			//						alert(exmayTag2[m]);
			//						html = html.replace(exmayTag2[m], exmayTag2[m].replace(exmaySyntax[n].input, exmaySyntax[n].output));
			//						exmayTag2[m] = exmayTag2[m].replace(exmaySyntax[n].input, exmaySyntax[n].output);
			//						//alert("第"+m+"中"+n+"次  :   "+script[m]+ "########################" + script[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
			//					}
			//				}
		}

		// Css Style代码块
		var hasStyleTag = /(&lt;style.*?&gt;)(.*?)(&lt;\/style&gt;)/.test(html);
		if (hasStyleTag) {
			var styleTags = html.match(/(&lt;style.*?&gt;)(.*?)(&lt;\/style&gt;)/ig);
			for ( var i = 0; i < styleTags.length; i++) {
				for ( var j = 0; j < cssSyntax.length; j++) {
					html = html.replace(styleTags[i], styleTags[i].replace(cssSyntax[j].input, cssSyntax[j].output));
				}
			}
		}

		// Javascript代码块
		var hasJavascriptTag = /(&lt;script.*?&gt;)(.*?)(&lt;\/script&gt;)/.test(html);
		if (hasJavascriptTag) {
			var javascriptTags = html.match(/(&lt;script.*?&gt;)(.*?)(&lt;\/script&gt;)/ig);
			for ( var m = 0; m < javascriptTags.length; m++) {
				for ( var n = 0; n < javascriptSyntax.length; n++) {
					html = html.replace(javascriptTags[m], javascriptTags[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
					//alert("第"+m+"中"+n+"次  :   "+script[m]+ "########################" + script[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
				}
			}
		}

		// Freemarker代码块
		var hasFreemarkerTag = freemakerSyntax[0].input.test(html);
		if (hasFreemarkerTag) {
			var freemarkerTags = html.match(freemakerSyntax[0].input);
			for ( var m = 0; m < freemarkerTags.length; m++) {
				for ( var n = 0; n < freemakerSyntax.length; n++) {
					html = html.replace(freemarkerTags[m], freemarkerTags[m].replace(freemakerSyntax[n].input, freemakerSyntax[n].output));
				}
			}
		}

		/*for(var n=0; n<exmaySyntax.length; n++) {
			html = html.replace(exmaySyntax[n].input, exmaySyntax[n].output);
			//exmayTag[m] = exmayTag[m].replace(exmaySyntax[n].input, exmaySyntax[n].output);
			//alert("第"+m+"中"+n+"次  :   "+script[m]+ "########################" + script[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
		}*/

		//alert(html);
		return html;
	}

	// syntax highlighting parser
	function syntaxHighlight(flag) {
		//if(document.designMode=='off') document.designMode='on'
		//if(flag != 'init') { window.getSelection().getRangeAt(0).insertNode(document.createTextNode(cc));}
		editor = CodePress.getEditor();
		o = editor.innerHTML;
		o = o.replace(/<br>/g, '\n');
		o = o.replace(/<.*?>/g, '');
		x = z = this.split(o, flag);
		x = x.replace(/\n/g, '<br>');

		if (arguments[1] && arguments[2])
			x = x.replace(arguments[1], arguments[2]);

		for (i = 0; i < Language.syntax.length; i++)
			x = x.replace(Language.syntax[i].input, Language.syntax[i].output);

		editor.innerHTML = this.actions.history[this.actions.next()] = (flag == 'scroll') ? x : o.split(z).join(x);
		if (flag != 'init')
			this.findString();
	}

	/*function syntaxHighlight(target, flag){
			var $target = $(target);
			var $exmayCodeEditor = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor;
			var $design = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor.design;
			var designWindow = $design[0].contentWindow;
			var designDocument = designWindow.document;
			var $code = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor.code;
			var codeWindow = $code[0].contentWindow;
			var codeDocument = codeWindow.document;
			codeDocument.open();
			codeDocument.write('<html><body><head><title>亿美代码编辑器</title><link id="cp-lang-style" rel="stylesheet" href="${sitePath}/exmay/framework/jquery-exmayui-1.0.1/exmayui-editor/code/languages/html.css" type="text/css" /></head></body></html>'); 
			 //codeDocument.write('<pre>&lt;img src="http://www.exmay.com/skin/default/images/logoxxx.png"/&gt; &lt;h1/&gt;代码&lt;/h1&gt;</pre>');
			var html = $target.val();
				html = html.replace(/\u2009/gi,'');
				html = html.replace(/&/gi,'&amp;');
				html = html.replace(/</g, "&lt;");
				html = html.replace(/>/g, "&gt;");
				//html = html.replace(/\n\r/g,'<li></li>');
				//html = html.replace(/([^\n]*?\n)/g,'<li>$1</li>');
				html = html.replace(/([^\n]*?\n)/g,'$1<br/>');
				html = html.replace(/\n/g,'');
				html = html.replace(/\"/g,'&quot;'); 
				//alert(html);
					
			for(var i=0; i<syntax.length; i++) {
				html = html.replace(syntax[i].input, syntax[i].output);
			}
			
			var flag = /(&lt;style.*?&gt;)(.*?)(&lt;\/style&gt;)/.test(html);
			if(flag) {
				var style =	html.match(/(&lt;style.*?&gt;)(.*?)(&lt;\/style&gt;)/ig);
				for(var i=0; i<style.length; i++) {
					for(var j=0; j<cssSyntax.length; j++) {
						html = html.replace(style[i], style[i].replace(cssSyntax[j].input, cssSyntax[j].output));
					}
				}
			}
			
			// javascript
			var jflag = /(&lt;script.*?&gt;)(.*?)(&lt;\/script&gt;)/.test(html);
			if(jflag) {
				var script = html.match(/(&lt;script.*?&gt;)(.*?)(&lt;\/script&gt;)/ig);
				for(var m=0; m<script.length; m++) {
					for(var n=0; n<javascriptSyntax.length; n++) {
						html = html.replace(script[m], script[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
						//alert("第"+m+"中"+n+"次  :   "+script[m]+ "########################" + script[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
					}
				}
			}

				
			//var regex1 = "(&lt;)(@exmay\\.((?!&gt;)\\S)+)((?!&gt;|\\/&gt)[\\s\\S])+(/\\&gt;)";
			// (&lt;)(@exmay\.((?!&gt;)\S)+)((?!&gt;|\/&gt)[\s\S])+(\s*)(&gt;)([\s\S]*)(\1\/\2\s*&gt;)
			//var exmayPattern1 = new RegExp(regex1, "gi");
			//var isExmayTag = /(&lt;)(@exmay\.\w*)([\s\S]*?)(\/\s*&gt;|\1\/\2\s*&gt;)/ig.test(html);
			var isExmayTag = /(&lt;)(@exmay\.\w*)([\s\S]*?)(\/\s*&gt;)/ig.test(html);
			//var isExmayTag = exmayPattern1.test(html);
			//alert(isExmayTag);
			//alert(isExmayTag);
			if(isExmayTag) {
				var exmayTag = html.match(/(&lt;)(@exmay\.\w*)(.*?)(\/\s*&gt;)/ig);
				//alert(exmayTag.length); //|\1\/\2\s*&gt;
				for(var m=0; m<exmayTag.length; m++) {
					for(var n=0; n<exmaySyntax.length; n++) {
						html = html.replace(exmayTag[m], exmayTag[m].replace(exmaySyntax[n].input, exmaySyntax[n].output));
						exmayTag[m] = exmayTag[m].replace(exmaySyntax[n].input, exmaySyntax[n].output);
						//alert("第"+m+"中"+n+"次  :   "+script[m]+ "########################" + script[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
					}
				}
	//				var exmayTag2 =  html.match(/(&lt;)(@exmay\.\w*)([\s\S]*?)(&gt;)([\s\S]*?)(\1\/\2\s*&gt;)/ig);
	//				alert(exmayTag2.length);
	//				for(var m=0; m<exmayTag2.length; m++) {
	//					for(var n=0; n<exmaySyntax.length; n++) {
	//						alert(exmayTag2[m]);
	//						html = html.replace(exmayTag2[m], exmayTag2[m].replace(exmaySyntax[n].input, exmaySyntax[n].output));
	//						exmayTag2[m] = exmayTag2[m].replace(exmaySyntax[n].input, exmaySyntax[n].output);
	//						//alert("第"+m+"中"+n+"次  :   "+script[m]+ "########################" + script[m].replace(javascriptSyntax[n].input, javascriptSyntax[n].output));
	//					}
	//				}
			}
			
			//alert(html);
			//codeDocument.write('<pre class="highlighter"><ol>' + html + '</ol></pre>');
			codeDocument.write('<pre class="highlighter">' + html + '</pre>');
			codeDocument.close();
	}*/

	function getHtml(target) {
		var $target = $(target);
		//var $iframe = $target.data("exmayCodeEditor").iframe;
		//alert($target.data("exmayCodeEditor"));
		//var _document = $target.data("exmayCodeEditor").doc;
		var $design = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor.design;
		var _window = $design[0].contentWindow;
		var _document = _window.document;
		//alert(_document.body.innerHTML);
		return _document.body.innerHTML;
	}
	;

	function setHtml(target, html) {
		var $target = $(target);
		var $design = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor.design;
		var _window = $design[0].contentWindow;
		var _document = _window.document;
		_document.body.innerHTML = html;
	}
	;

	function getSelection(target) {
		var $target = $(target);
		var $design = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor.design;
		var _window = $design[0].contentWindow;
		var _document = _window.document;
		var range;
		if ($.browser.msie) {
			range = _document.selection.createRange();
			if (range.htmlText && range.text) {
				return range.htmlText;
			}
		} else {
			if (_window.getSelection) {
				var selection = _window.getSelection();
				if (selection.rangeCount > 0 && window.XMLSerializer) {
					range = selection.getRangeAt(0);
					var html = new XMLSerializer().serializeToString(range.cloneContents());
					return html;
				}
				if (selection.rangeCount > 0) {
					range = selection.getRangeAt(0);
					var clonedSelection = range.cloneContents();
					var div = document.createElement('div');
					div.appendChild(clonedSelection);
					return div.innerHTML;
				}
			}
		}
	}
	;
	function code(target) {
		var $target = $(target);
		var $exmayCodeEditor = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor;
		var $design = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor.design;
		var designWindow = $design[0].contentWindow;
		var designDocument = designWindow.document;
		var $code = $target.data(EXMAY_CODE_EDITOR).exmayCodeEditor.code;
		var codeWindow = $code[0].contentWindow;
		var codeDocument = codeWindow.document;

		//alert(get_html());
		var text = get_html();
		if ($code.is(":visible")) {
			$target.hide();
			$design.show();
			$code.hide();
			set_text(text);
		} else {
			$target.show()
			$design.hide();
			$code.show();
			set_text(text);
			$target.focus();
			$code.focus();
		}
		function get_html() {
			var html;
			if ($code.is(":visible")) {
				//html = $target.val();
				html = codeDocument.body.innerHTML;
				html = html.replace(/<br>/g, '\n');
				html = html.replace(/<.*?>/g, '');
				//x = z = this.split(o,flag);
				html = html.replace(/\n/g, '<br>');
				html = html.replace(/&lt;/g, "<");
				html = html.replace(/&gt;/g, ">");
			} else {
				html = designDocument.body.innerHTML;
			}
			if (typeof getXHTML === "function") {
				return getXHTML(html);
			} else {
				return html;
			}
		}
		;
		function set_text(txt) {
			var text = (undefined === txt) ? "" : txt;
			if (text == "" && $.browser.safari) {
				text = "&nbsp;";
			}// Bug in Chrome and Safari
			// Is textarea visible? Writing to it.
			//			designDocument.designMode = "On";
			//			codeDocument.designMode = "On";
			if ($code.is(":visible")) {
				$target.val(text);
				if ($.browser.mozilla || $.browser.safari) {
					//if($.trim(text)===""){text="&nbsp;";}
					//designDocument.open('text/html', 'replace');
					//designDocument.write(text);
					//designDocument.close();
					//					codeDocument.open('text/html', 'replace');
					//					codeDocument.write(text);
					//					codeDocument.close();
					text = text.replace(/</g, "&lt;");
					text = text.replace(/>/g, "&gt;");
					var style = '<link rel="stylesheet" href="codepress.css?ts=1286650684479" type="text/css"><link id="cp-lang-style" rel="stylesheet" href="${sitePath}/exmay/framework/jquery-exmayui-1.0.1/exmayui-editor/code/languages/html.css?ts=1286649586968" type="text/css">';
					var js = '<script src="${sitePath}/exmay/framework/jquery-exmayui-1.0.1/exmayui-editor/code/languages/html.js?ts=1286649586968" type="text/javascript"></script>';
					var test = '<br/><b><strong>&lt;script type=<s>"text/javascript"</s>&gt;</strong><tt></tt></b><tt><br>	<i>function</i> getCode() {<br>		<i>alert</i>(textWithoutHighlighting);<br>	}<br><b></b></tt><b><strong>&lt;/script&gt;</strong></b>';
					codeDocument.open();
					codeDocument.write(style + js + text + test);
					codeDocument.close();
				} else {
					//designDocument.body.innerHTML = "";
					//codeDocument.body.innerHTML = "";
					text = text.replace(/</g, "&lt;");
					text = text.replace(/>/g, "&gt;");
					codeDocument.body.innerHTML = "";
					if (text !== "") {
						//designDocument.write(text);
						//codeDocument.write(text);
						codeDocument.write(text);
					}
				}
			} else {
				//alert("----" + text);
				// Textarea not visible. write to iframe
				if ($.browser.mozilla || $.browser.safari) {
					//if($.trim(text)===""){text="&nbsp;";}
					//designDocument.open('text/html', 'replace');
					designDocument.open();
					designDocument.write(text);
					designDocument.close();
				} else {
					designDocument.body.innerHTML = "";
					if (text !== "") {
						designDocument.write(text);
					}
				}
				//style(); // Setting the CSS style for the iframe
				designDocument.body.contentEditable = true;

			}
			//			if (urm) {
			//				urm.add(get_html());
			//			}
			//			if (undefined !== d.change) {
			//				d.change();
			//			}
			return this;
		}
		;

		function get_text() {

		}
		;
		function set_text() {

		}
		;

	}
	;

	//	// syntax highlighting parser
	//	syntaxHighlight : function(flag) {
	//		//if(document.designMode=='off') document.designMode='on'
	//		if(flag != 'init') { window.getSelection().getRangeAt(0).insertNode(document.createTextNode(cc));}
	//		editor = CodePress.getEditor();
	//		o = editor.innerHTML;
	//		o = o.replace(/<br>/g,'\n');
	//		o = o.replace(/<.*?>/g,'');
	//		x = z = this.split(o,flag);
	//		x = x.replace(/\n/g,'<br>');
	//
	//		if(arguments[1]&&arguments[2]) x = x.replace(arguments[1],arguments[2]);
	//	
	//		for(i=0;i<Language.syntax.length;i++) 
	//			x = x.replace(Language.syntax[i].input,Language.syntax[i].output);
	//
	//		editor.innerHTML = this.actions.history[this.actions.next()] = (flag=='scroll') ? x : o.split(z).join(x);
	//		if(flag!='init') this.findString();
	//	};

	// 定义亿美富文本编辑器插件
	$.fn.exmayCodeEditor = function(options, data) {
		if (typeof options == "string") {
			return $.fn.exmayCodeEditor.methods[options](this, data);
		}
		options = options || {};
		return this.each(function() {
			if (this.tagName != TEXTAREA)
				return;
			var $this = $(this);
			//alert(EXMAY_CODE_EDITOR);
				var cache = $this.data(EXMAY_CODE_EDITOR);
				var opts;
				if (cache) {
					opts = $.extend(cache.options, options);
					cache.options = opts;
				} else {
					opts = $.extend( {}, $.fn.exmayCodeEditor.defaults, $.fn.exmayCodeEditor.parseOptions(this), options);
					cache = $this.data(EXMAY_CODE_EDITOR, {
						options : opts,
						exmayCodeEditor : initExmayCodeEditor(this, opts)
					});
					//alert($($this.data(EXMAY_CODE_EDITOR).exmayCodeEditor).attr("name"));
				}
			});
	};

	$.fn.exmayCodeEditor.methods = {
		getHtml : function(target) {
			//			return $(target).each(function() {
		//				getHtml(this);
		//			});
		return getHtml(target[0]);
	},
	setHtml : function(target, data) {
		return $(target).each(function() {
			setHtml(this, data);
		});
	},
	insertHtml : function (target, data) {
		var editArea = $(target).data(EXMAY_CODE_EDITOR).exmayCodeEditor.code[0];
		exmayInsertHtml(editArea, data);
	},
	getSelection : function(target) {
		//			return $(target).each(function() {
		//				getSelection(this);
		//			});
		return getSelection(target[0]);
	},
	code : function(target) {
		return $(target).each(function() {
			code(this);
		});
	}
	};

	$.fn.exmayCodeEditor.parseOptions = function(target) {
		var $target = $(target);
		return {
			width : (parseInt(target.style.width) || undefined),
			height : (parseInt(target.style.height) || undefined)
		}
	}

	$.fn.exmayCodeEditor.defaults = {
		width : "auto",
		height : "auto",
		chars : '|32|46|62|8|', // charcodes that trigger syntax highlighting
		autocomplete : true,
		design : false,
		readOnly : false
	};

	$.fn.exmayCodeEditor.codeLanguages = {
		csharp : 'C#',
		css : 'CSS',
		generic : 'Generic',
		html : 'HTML',
		java : 'Java',
		javascript : 'JavaScript',
		perl : 'Perl',
		ruby : 'Ruby',
		php : 'PHP',
		text : 'Text',
		sql : 'SQL',
		vbscript : 'VBScript'
	}

})(jQuery);