
function getEditorobj() {
	return $('g_editor_doc');
}


function initEditor() {
	var g_editor_id="g_editor";
	var g_editor_doc=$(g_editor_id + '_doc');
	var buttons = $(g_editor_id + '_toolbar').getElementsByTagName('a');
	for(var i = 0; i < buttons.length; i++) {
		if(buttons[i].id.indexOf(g_editor_id + '_cmd_') != -1) {
			buttons[i].href = '###';
			buttons[i].onclick = function(e) {gateweicode(this.id.substr(this.id.lastIndexOf('_cmd_') + 5))};
		} 
	}
	var selects = $(g_editor_id + '_toolbar').getElementsByTagName('select');
	for(var i = 0; i < selects.length; i++) {
		if(selects[i].id.indexOf(g_editor_id + '_cmd_') != -1) {
			selects[i].onchange = function(e) {gateweicode(this.id.substr(this.id.lastIndexOf('_cmd_') + 5))};
		} 
	}
}

function editorMenu(ctrlid, str) {
	var div = document.createElement('div');
	div.id = ctrlid + '_menu';
	div.style.display = 'none';
	div.className = 'popupmenu_popup';
	document.body.appendChild(div);
	div.innerHTML = '<div class="popupmenu_option" unselectable="on">' + str + '<br /><center><input type="button" id="' + ctrlid + '_submit" value="确定" /> &nbsp; <input type="button" onClick="hideMenu();try{document.body.removeChild(' + div.id + ')}catch(e){}" value="取消" /></center></div>';
	showMenu(ctrlid, true, 0, 3);
	return div;
}

function wrapTags(tagname, useoption, selection) {

	if(isUndefined(selection)) {
		var sel = getSelection();
		if(sel === false) {
			sel = '';
		} else {
			sel += '';
		}
	}

	if(useoption !== false) {
		var opentag = '[' + tagname + '=' + useoption + ']';
	} else {
		var opentag = '[' + tagname + ']';
	}

	var closetag = '[/' + tagname + ']';
	var text = opentag + sel + closetag;

	insertText(text, strlen(opentag), strlen(closetag), false);

}

function applyFormat(cmd, arg) {

	switch(cmd) {
		case 'bold':
		case 'italic':
		case 'underline':
			wrapTags(cmd.substr(0, 1), false);
			break;
		case 'align_left':
		case 'align_center':
		case 'align_right':
			wrapTags('align', cmd.substr(6));
			break;
		case 'float_left':
		case 'float_right':
			wrapTags('float', cmd.substr(6));
			break;
		case 'qq':
		case 'code':
		case 'flash':
		case 'indent':
			wrapTags(cmd, false);
			break;
		case 'font_name':
			wrapTags('font', arg);
			break;
		case 'font_size':
			wrapTags('size', arg);
			break;
		case 'font_color':
			wrapTags('color', arg);
			break;
		case 'url_link':
			var Selection = getSelection();
			if(Selection) {
				wrapTags('url', arg);
			} else {
				wrapTags('url', arg, arg);
			}
			break;
		case 'insert_image':
			wrapTags('img', false, arg);
			break;
	}
}

function getSelection() {
	var g_editor_doc=$('g_editor_doc');
		if(!isUndefined(g_editor_doc.selectionStart)) {
			return g_editor_doc.value.substr(g_editor_doc.selectionStart, g_editor_doc.selectionEnd - g_editor_doc.selectionStart);
		} else if(document.selection && document.selection.createRange) {
			return document.selection.createRange().text;
		} else if(window.getSelection) {
			return window.getSelection() + '';
		} else {
			return false;
		}
	}

function insertText(text, movestart, moveend, select, sel) {
	    var g_editor_doc=$('g_editor_doc');
		checkFocus();
		if(!isUndefined(g_editor_doc.selectionStart)) {
			var opn = g_editor_doc.selectionStart + 0;
			g_editor_doc.value = g_editor_doc.value.substr(0, g_editor_doc.selectionStart) + text + g_editor_doc.value.substr(g_editor_doc.selectionEnd);

			if(!isUndefined(movestart)) {
				g_editor_doc.selectionStart = opn + movestart;
				g_editor_doc.selectionEnd = opn + strlen(text) - moveend;
			} else if(movestart !== false) {
				g_editor_doc.selectionStart = opn;
				g_editor_doc.selectionEnd = opn + strlen(text);
			}
		} else if(document.selection && document.selection.createRange) {
			if(isUndefined(sel)) {
				sel = document.selection.createRange();
			}
			sel.text = text.replace(/\r?\n/g, '\r\n');
			if(!isUndefined(movestart)) {
				sel.moveStart('character', -strlen(text) +movestart);
				sel.moveEnd('character', -moveend);
			} else if(movestart !== false) {
				sel.moveStart('character', -strlen(text));
			}
			sel.select();
		} else {
			g_editor_doc.value += text;
		}
	}

	function editorMenuEvent_onkeydown(e) {
	e = e ? e : event;
	var ctrlid = this.id.substr(0, this.id.lastIndexOf('_param_'));
	if((this.type == 'text' && e.keyCode == 13) || (this.type == 'textarea' && e.ctrlKey && e.keyCode == 13)) {
		$(ctrlid + '_submit').click();
		doane(e);
	} else if(e.keyCode == 27) {
		hideMenu();
		document.body.removeChild($(ctrlid + '_menu'));
	}
}

function getCaret() {
		var obj = getEditorobj();
		var wR = document.selection.createRange();
		obj.select();
		var aR = document.selection.createRange();
		wR.setEndPoint("StartToStart", aR);
		var len = wR.text.replace(/\r?\n/g, ' ').length;
		wR.collapse(false);
		wR.select();
		return len;
}

function gateweicode(cmd, arg) {
	var g_editor_doc=$('g_editor_doc');
	checkFocus();
    if(cmd == 'url_link') {
		insertlink('url_link');
	} else if(cmd == 'qq') {
		insertlink('qq');
	} else if(cmd == 'flash') {
		insertlink('flash');
	} else if(cmd == 'insert_image') {
		insertlink('insert_image');
	}else if(cmd == 'faq') {
		window.open("http://www.gatewei.com/index.php");
	}else if(cmd == 'font_total') {
		alert('当前字符数：' + char_strlen(g_editor_doc.value) + '字符' + '\r\n最大字符长度为：15000字符');
	}else if(cmd == 'float_left' || cmd == 'float_right') {
		return applyFormat(cmd, false);
	} else if(cmd == 'font_name' || cmd == 'font_size' || cmd == 'font_color') {
		if ($('g_editor_cmd_' + cmd).value == 0){
			return false;
		}
		else{
		return applyFormat(cmd, $('g_editor_cmd_' + cmd).value);
		}
	} else {
		try {
			var ret = applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
		} catch(e) {
			var ret = false;
		}
	}
	return ret;
}


function setCaret(pos) {
	var obj = getEditorobj();
	var r = obj.createTextRange();
	r.moveStart('character', pos);
	r.collapse(true);
	r.select();
}

function insertlink(cmd) {
	var sel;
	var editorid = "g_editor";
	if(is_ie) {
		sel = document.selection.createRange();
		var pos = getCaret();
	}
	var selection = sel ? sel.text : getSelection();
	var ctrlid = editorid + '_cmd_' + cmd;
	var tag = cmd == 'insert_image' ? 'img' : (cmd == 'url_link' ? 'url' : (cmd == 'flash' ? 'flash' : 'qq'));
	var str = (tag == 'img' ? "请插入图片url地址" : (tag == 'url' ? "请插入url地址" : (tag == 'flash' ? "请插入flash媒体url":"请插入QQ号"))) + '<br /><input type="text" id="' + ctrlid + '_param_1" size="30" value="">';
	var div = editorMenu(ctrlid, str);
	$(ctrlid + '_param_1').focus();
	$(ctrlid + '_param_1').onkeydown = editorMenuEvent_onkeydown;
	$(ctrlid + '_submit').onclick = function() {
		checkFocus();
		if(is_ie) {
			setCaret(pos);
		}
		var input = $(ctrlid + '_param_1').value;
		if(input != '') {
			var v = selection ? selection : input;
			var href = /^(www\.)/.test(input) ? 'http://' + input : input;
			var text = tag == 'img' || tag == 'qq' || tag == 'flash' ? '[' + tag + ']' + input + '[/' + tag + ']' : '[' + tag + '=' + href + ']' + v + '[/' + tag + ']';
			var closetaglen = tag == 'qq' ? 5 : (tag=='flash' ? 8 : 6);
			insertText(text, text.length - v.length - closetaglen, closetaglen, (selection ? true : false), sel);
		}
		hideMenu();
		document.body.removeChild(div);
	}
}


function parseurl(){
	var str = $("g_editor_doc").value;
	str = str.replace(/([^>=\]"'\/@]|^)((((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|synacast):\/\/))([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!#]*)*)/ig,'$1[url]$2[/url]');
	str = str.replace(/([^\w>=\]"'\/@]|^)((www\.)([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!#]*)*)/ig,'$1[url]$2[/url]');
    $("g_editor_doc").value=str;
}