﻿////////////////////////////////////
var userAgent = navigator.userAgent.toLowerCase();
var is_webtv = userAgent.indexOf('webtv') != -1;
var is_kon = userAgent.indexOf('konqueror') != -1;
var is_mac = userAgent.indexOf('mac') != -1;
var is_saf = userAgent.indexOf('applewebkit') != -1 || navigator.vendor == 'Apple Computer, Inc.';
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko' && !is_saf) && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ns = userAgent.indexOf('compatible') == -1 && userAgent.indexOf('mozilla') != -1 && !is_opera && !is_webtv && !is_saf;
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera && !is_saf && !is_webtv) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
///////////////////////////////////////////

	function $(id) {
		return document.getElementById(id);
	}
var g_strFamily = "";
var g_strBrand = "";
function xmlhttpxmlhttp()
{
	this.new2=function()
	{
		return document.all?_IE_xmlhttp():_FF_xmlhttp();
	}
 };

 //
_IE_xmlhttp.prototype = new xmlhttpxmlhttp;
 //
 function _IE_xmlhttp()
 {
 	var xmlhttp=null;
 	try
	{
		xmlhttp= new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e)
	{
		try
		{
			xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (err){
			return xmlhttp;
		}
	}
	return 	xmlhttp;
 }

 //
_FF_xmlhttp.prototype  = new xmlhttpxmlhttp;
 //
  function _FF_xmlhttp()
 {
 	var xmlhttp=null;
	xmlhttp= new XMLHttpRequest();
	if (!xmlhttp)
		return null;
	return xmlhttp;
 }

function getbrand()
{
	var strFamily = $('input_family').value;
	if(strFamily == "")
	{
		$('input_brand_list').innerHTML = "<li>请先选择分类，届时品牌会出现选项。</li>";
		return;
	}
	if(strFamily == g_strFamily)
	{
		return;
	}
	var strURL = "/ajax_getbrand2.php?family=";
	strURL += encodeURI(strFamily);
	strURL += "&rand=";
	strURL += Math.random()*150;
//	strURL += $('input_family').value;
//	alert(strURL);

	xmlhttp_c=new xmlhttpxmlhttp().new2();

	xmlhttp_c.open('GET', strURL, true);
	xmlhttp_c.setRequestHeader('Content-Type', 'text/html;charset=utf-8');
	xmlhttp_c.onreadystatechange =function()
	{
			if (xmlhttp_c.readyState==4)
				if (xmlhttp_c.status==200)
				 {
					g_strFamily = strFamily;
			//		alert(xmlhttp_c.responseText);
					$('input_brand_list').innerHTML =  xmlhttp_c.responseText ;
				//	itItem.innerHTML=xmlhttp_c.responseText;
				 }
	 }
	xmlhttp_c.send(null);
}

function getproduct()
{
	var strFamily = $('input_family').value;
	if(strFamily == "")
	{
//		$('input_brand_menu').innerHTML = "请先选择族群，届时品牌会出现选项。";
		$('input_product_list').innerHTML = "<li>请先选择分类和品牌，届时产品会出现选项。</li>";
		return;
	}

	var strBrand = $('input_brand').value;
	if(strBrand == "")
	{
		$('input_product_list').innerHTML = "<li>请先选择品牌，届时产品会出现选项。</li>";
		return;
	}

	if(strBrand == g_strBrand)
	{
		return;
	}
	var strURL = "/ajax_getproduct2.php?family=";
	strURL += encodeURI($('input_family').value);
	strURL += "&brand=";
	strURL += encodeURI(strBrand);
	strURL += "&rand=";
	strURL += Math.random()*150;
//	alert(strURL);

	xmlhttp_c=new xmlhttpxmlhttp().new2();

	xmlhttp_c.open('GET', strURL, true);
	xmlhttp_c.setRequestHeader('Content-Type', 'text/html;charset=utf-8');
	xmlhttp_c.onreadystatechange =function()
	{
			if (xmlhttp_c.readyState==4)
				if (xmlhttp_c.status==200)
				 {
			//		alert(xmlhttp_c.responseText);
					g_strBrand = strBrand;
					$('input_product_list').innerHTML =  xmlhttp_c.responseText;
				//	itItem.innerHTML=xmlhttp_c.responseText;
				 }
	 }
	xmlhttp_c.send(null);
}

function get_toolbar(itItem, strURL)
{
	xmlhttp_c=new xmlhttpxmlhttp().new2();

	xmlhttp_c.open('GET', strURL, true);
	xmlhttp_c.setRequestHeader('Content-Type', 'text/html;charset=utf-8');
	xmlhttp_c.onreadystatechange =function()
	{
			if (xmlhttp_c.readyState==4)
				if (xmlhttp_c.status==200)
				 {
					alert(xmlhttp_c.responseText);
					itItem.innerHTML=xmlhttp_c.responseText;
				 }
	 }
	xmlhttp_c.send(null);
}

///////////////////////////



var aid = 1;
var thumbwidth = parseInt(400);
var thumbheight = parseInt(300);
var attachexts = new Array();
var attachwh = new Array();


function isUndefined(variable) {
	return typeof variable == 'undefined' ? true : false;
}

function findtags(parentobj, tag) {
	if(!isUndefined(parentobj.getElementsByTagName)) {
		return parentobj.getElementsByTagName(tag);
	} else if(parentobj.all && parentobj.all.tags) {
		return parentobj.all.tags(tag);
	} else {
		return null;
	}
}

function in_array(needle, haystack) {
	if(typeof needle == 'string') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}

function delAttach(id)
{
	$('attachbody').removeChild($('attach_' + id).parentNode.parentNode);
	$('attachbody').innerHTML == '' && addAttach();
	$('localimgpreview_' + id + '_menu') ? document.body.removeChild($('localimgpreview_' + id + '_menu')) : null;
}

function addAttach()
{
	newnode = $('attachbodyhidden').firstChild.cloneNode(true);
	var id = aid;
	var tags;
	tags = findtags(newnode, 'input');
	for(i in tags)
	{
		if(tags[i].name == 'attach[]')
		{
			tags[i].id = 'attach_' + id;
			tags[i].onchange = function() {insertAttach(id)};
//			tags[i].unselectable = 'on';
		}
		if(tags[i].name == 'localid[]')
		{
			tags[i].value = id;
		}

		if(tags[i].name == 'localpath[]')
		{
			tags[i].id = 'localpath_' + id;
		}
	}
	tags = findtags(newnode, 'span');
	for(i in tags)
	{
		if(tags[i].id == 'localfile[]')
		{
			tags[i].id = 'localfile_' + id;
		}
	}
	aid++;
	$('attachbody').appendChild(newnode);
}


function insertAttach(id)
{
	var localimgpreview = '';
	var path = $('attach_' + id).value;
	var extensions = 'jpg, gif, jpeg, mid, rar, zip, png, bmp';
	var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
	var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
	var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);

	$('localpath_' + id).value = $('attach_' + id).value;

	if(path == '')
	{
		return;
	}

	if(extensions != '' && (re.exec(extensions) == null || ext == ''))
	{
		alert('对不起，不支持上传此类扩展名的附件。');
		return;
	}
	attachexts[id] = is_ie && in_array(ext, ['gif', 'jpg', 'png', 'bmp']) && typeof supe == 'undefined' ? 2 : 1;

	if(attachexts[id] == 2)
	{
		$('img_hidden').alt = id;
		$('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod =	'image';
		var imgurl = $('attach_' + id).value;
		try
		{
			$('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgurl;
		}
		catch (e)
		{
	//		alert('无效的图片文件。');
	//		return;
		}
		var wh = {'w' : $('img_hidden').offsetWidth, 'h' : $('img_hidden').offsetHeight};
		var aid = $('img_hidden').alt;
		if(wh['w'] >= thumbwidth || wh['h'] >= thumbheight)
		{
			wh = thumbImg(wh['w'], wh['h']);
		}
		attachwh[id] = wh;
		$('img_hidden').style.width = wh['w']
		$('img_hidden').style.height = wh['h'];
		$('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = 'scale';
		div = document.createElement('div');
		div.id = 'localimgpreview_' + id + '_menu';
		div.style.display = 'none';
		div.style.marginLeft = '20px';
		div.className = 'popupmenu_popup';
		div.style.position = 'absolute';
		document.body.appendChild(div);
		div.innerHTML = '<IMG style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\'' + $('attach_' + id).value+'\');width:'+wh['w']+';height:'+wh['h']+'"  src=\'/style/img/none.gif\'>';
	}

	$('localfile_' + id).innerHTML = '<a href="###delAttach" onclick="delAttach(' + id + ')">[删除]</a> <a href="###insert" title="点击这里将本图片插入正文当前光标的位置" onclick="insertAttachtext(' + id + ');hideMenu();return false;">[插入]</a> ' +
	(attachexts[id] == 2 ? '<span id="localimgpreview_' + id + '" onmouseover="showMenu(this.id)" onmousemove="showMenu(this.id)"> <span class="smalltxt">[' + id + ']</span> <a href="###attachment" onclick="insertAttachtext(' + id + ');hideMenu();return false;">' + localfile + '</a></span>' : '<span class="smalltxt">[' + id + ']</span> ' + localfile);

//	$('localfile_' + id).innerHTML = '<a href="###delAttach" onclick="delAttach(' + id + ')">[删除]</a> ' +
//	(attachexts[id] == 2 ? '<span id="localimgpreview_' + id + '" onmouseover="showPreview(this.id)" onmousemove="showPreview(this.id)" onmouseout="hidePreview(this.id)"> <span class="smalltxt">[' + id + ']</span> <a href="###attachment" onclick="insertAttachtext(' + id + ');return false;">' + localfile + '</a></span>' : '<span class="smalltxt">[' + id + ']</span> ' + localfile);
	$('attach_' + id).style.display = 'none';
	addAttach();
}


function insertAttachtext(id)
{
	if(!attachexts[id])
	{
		return;
	}

	checkFocus();

	if(attachexts[id] == 2)
	{
		//var html = "<IMG src='" + $('attach_' + id).value +"'>";
		//insertText(html, false);

		insertText($('localimgpreview_' + id + '_menu').innerHTML, false);// :						//AddText('[localimg=' + attachwh[id]['w'] + ',' + attachwh[id]['h'] + ']' + id + '[/localimg]');
	}
	else
	{
		//alert("aaa");

		insertText('[local]' + id + '[/local]', false);// : AddText('[local]' + id + '[/local]');
	}

	editframe_jiajia();
}

function thumbImg(w, h)
{
	var x_ratio = thumbwidth / w;
	var y_ratio = thumbheight / h;
	var wh = new Array();

	if((x_ratio * h) < thumbheight)
	{
		wh['h'] = Math.ceil(x_ratio * h);
		wh['w'] = thumbwidth;
	}
	else
	{
		wh['w'] = Math.ceil(y_ratio * w);
		wh['h'] = thumbheight;
	}
	return wh;
}

//////////////

function addAttach2(attachid,attach,localpath,descrip,del)
{
	newnode = $('attachbodyhidden2').firstChild.cloneNode(true);
	var id = aid;
	var tags;
	tags = findtags(newnode, 'input');
	for(i in tags)
	{
		if(tags[i].name == 'attach2[]')
		{
			tags[i].id = 'attach2_' + id;
//			tags[i].onchange = function() {insertAttach(id)};
//			tags[i].unselectable = 'on';
			tags[i].value = attach;
//			tags[i].style.display = "none";
		}
		if(tags[i].name == 'localid2[]')
		{
			tags[i].id = 'localid2_' + id;
			tags[i].value = id;
		}

		if(tags[i].name == 'localpath2[]')
		{
			tags[i].id = 'localpath2_' + id;
			tags[i].value = localpath;
		}

		if(tags[i].name == 'attachdesc2[]')
		{
			tags[i].id = 'attachdesc2_' + id;
			tags[i].value = descrip;
		}

		if(tags[i].name == 'attachnow[]')
		{
			tags[i].id = 'attachnow_' + id;
			tags[i].value = 0;
		}

		if(tags[i].name == 'del[]')
		{
			tags[i].id = 'del_' + id;
			tags[i].value = 0;
		}

		if(tags[i].name == 'aid[]')
		{
			tags[i].id = 'aid_' + id;
			tags[i].value = attachid;
		}
	}
	tags = findtags(newnode, 'span');
	for(i in tags)
	{
		if(tags[i].id == 'localfile2[]')
		{
			tags[i].id = 'localfile2_' + id;
		}
	}
	aid++;
	$('attachbody').appendChild(newnode);
}

function delAttach2(id)
{
	if($('delbutton' + id).innerText == '[删除]')
	{
		$('delbutton' + id).innerText = '[恢复]';
		$('del_' + id).value = '1';

		$('localimgpreview_' + id).style.textDecoration = 'line-through';

	}
	else
	{
		$('delbutton' + id).innerText = '[删除]';
		$('del_' + id).value = '0';

		$('localimgpreview_' + id).style.textDecoration = 'none';
	}

//	$('attachbody').removeChild($('attach2_' + id).parentNode.parentNode);
//	$('attachbody').innerHTML == '' && addAttach();
//	$('localimgpreview_' + id + '_menu') ? $('img_hidden2').removeChild($('localimgpreview_' + id + '_menu')) : null;
}

function insertAttach2(id,localfile,del)
{
	var path = $('attach2_' + id).value;
	var extensions = 'jpg, gif, jpeg, mid, rar, zip, png, bmp';
	var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
	var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
//	var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);

	$('localpath2_' + id).value = $('attach2_' + id).value;
	$('del_' + id).value = del;
	var strDel = "删除";
	if(del == 1)
	{
		strDel = "恢复";
	}

	if(path == '')
	{
		return;
	}

	if(extensions != '' && (re.exec(extensions) == null || ext == ''))
	{
		alert('对不起，不支持上传此类扩展名的附件。');
		return;
	}
	attachexts[id] = is_ie && in_array(ext, ['gif', 'jpg', 'png', 'bmp']) && typeof supe == 'undefined' ? 2 : 1;

	if(attachexts[id] == 2)
	{
//		$('img_hidden').alt = id;
//		$('img_hidden').filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod =	'image';
		var imgurl = "/photo/upload" +$('attach2_' + id).value;
//		alert(imgurl);
		div = document.createElement('div');
		div.id = 'localimgpreview_' + id + '_menu';
		div.style.display = 'none';
		div.style.marginLeft = '20px';
		div.className = 'popupmenu_popup';
		div.style.position = 'absolute';
//		document.body.appendChild(div);
		$('img_hidden2').appendChild(div);
		div.innerHTML = '<IMG src="'+imgurl+'" class=imgpreview>';
//		alert(div.innerHTML);
		//style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\'' + $('attach_' + id).value+'\');width:'+wh['w']+';height:'+wh['h']+'"  src=\'/style/img/none.gif\' border="0" aid="attach_'+ aid +'" alt="" />';
	}

	$('localfile2_' + id).innerHTML = '<a id="delbutton'+id+'" href="###delAttach" onclick="delAttach2(' + id + ')">['+strDel+']</a> <a href="###insert" title="点击这里将本图片插入正文内容中当前光标的位置" onclick="insertAttachtext(' + id + ');hideMenu();return false;">[插入]</a> ' +
	(attachexts[id] == 2 ? '<span id="localimgpreview_' + id + '" onmouseover="showMenu(this.id)" onmousemove="showMenu(this.id)"> <span class="smalltxt">[' + id + ']</span> <a href="###attachment" onclick="insertAttachtext(' + id + ');hideMenu();return false;">' + localfile + '</a></span>' : '<span class="smalltxt">[' + id + ']</span> ' + localfile);
//*/
//	$('localfile_' + id).innerHTML = '<a href="###delAttach" onclick="delAttach(' + id + ')">[删除]</a> ' +
//	(attachexts[id] == 2 ? '<span id="localimgpreview_' + id + '" onmouseover="showPreview(this.id)" onmousemove="showPreview(this.id)" onmouseout="hidePreview(this.id)"> <span class="smalltxt">[' + id + ']</span> <a href="###attachment" onclick="insertAttachtext(' + id + ');return false;">' + localfile + '</a></span>' : '<span class="smalltxt">[' + id + ']</span> ' + localfile);
	$('attach2_' + id).style.display = 'none';

	if(del == 1)
	{
		$('localimgpreview_' + id).style.textDecoration = 'line-through';
	}
}



//menu//////////////////////////
var jsmenu = new Array();
jsmenu['active'] = new Array();
jsmenu['timer'] = new Array();
jsmenu['iframe'] = new Array();

function initCtrl(ctrlobj, click, duration, timeout, layer) {
	if(ctrlobj && !ctrlobj.initialized) {
		ctrlobj.initialized = true;
		ctrlobj.unselectable = false;

		ctrlobj.outfunc = typeof ctrlobj.onmouseout == 'function' ? ctrlobj.onmouseout : null;
		ctrlobj.onmouseout = function() {
			if(this.outfunc) this.outfunc();
			if(duration < 3) jsmenu['timer'][ctrlobj.id] = setTimeout('hideMenu(' + layer + ')', timeout);
		}

		if(click && duration) {
			ctrlobj.clickfunc = typeof ctrlobj.onclick == 'function' ? ctrlobj.onclick : null;
			ctrlobj.onclick = function (e) {
				doane(e);
				if(jsmenu['active'][layer] == null || jsmenu['active'][layer].ctrlkey != this.id) {
					if(this.clickfunc) this.clickfunc();
					else showMenu(this.id, true);
				} else {
					hideMenu(layer);
				}
			}
		}

		ctrlobj.overfunc = typeof ctrlobj.onmouseover == 'function' ? ctrlobj.onmouseover : null;
		ctrlobj.onmouseover = function(e) {
			doane(e);
			if(this.overfunc) this.overfunc();
			if(click) {
				clearTimeout(jsmenu['timer'][this.id]);
			} else {
				for(var id in jsmenu['timer']) {
					if(jsmenu['timer'][id]) clearTimeout(jsmenu['timer'][id]);
				}
			}
		}
	}
}

function initMenu(ctrlid, menuobj, duration, timeout, layer) {
	if(menuobj && !menuobj.initialized) {
		menuobj.initialized = true;
		menuobj.ctrlkey = ctrlid;
		menuobj.onclick = ebygum;
		menuobj.style.position = 'absolute';
		if(duration < 3) {
			if(duration > 1) {
				menuobj.onmouseover = function() {
					clearTimeout(jsmenu['timer'][ctrlid]);
				}
			}
			if(duration != 1) {
				menuobj.onmouseout = function() {
					jsmenu['timer'][ctrlid] = setTimeout('hideMenu(' + layer + ')', timeout);
				}
			}
		}
		menuobj.style.zIndex = 50;
		if(is_ie && !is_mac) {
			menuobj.style.filter += "progid:DXImageTransform.Microsoft.shadow(direction=135,color=#CCCCCC,strength=2)";
		}
		initMenuContents(menuobj);
	}
}

function initMenuContents(menuobj) {
	if(menuobj.title == 'menu') {
		menuobj.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity=100,finishOpacity=100,style=0)";
		menuobj.style.opacity = 0.85;
		menuobj.title = '';
	} else {
		var tds = findtags(menuobj, 'td');
		for(var i = 0; i < tds.length; i++) {
			if(tds[i].className == 'popupmenu_option' || tds[i].className == 'editor_colornormal') {
				if(is_ie && !is_mac) {
					tds[i].style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity=100,finishOpacity=100,style=0)";
				}
				tds[i].style.opacity = 0.85;
				if(tds[i].title && tds[i].title == 'nohighlight') {
					tds[i].title = '';
				} else {
					tds[i].ctrlkey = this.ctrlkey;
					if(tds[i].className != 'editor_colornormal') {
						tds[i].onmouseover = menuoption_onmouseover;
						tds[i].onmouseout = menuoption_onmouseout;
					}
					if(typeof tds[i].onclick == 'function') {
						tds[i].clickfunc = tds[i].onclick;
						tds[i].onclick = menuoption_onclick_function;
					} else {
						tds[i].onclick = menuoption_onclick_link;
					}
					if(!is_saf && !is_kon)	{
						try {
							links = findtags(tds[i], 'a');
							for(var j = 0; j < links.length; j++) {
								if(isUndefined(links[j].onclick)) {
									links[j].onclick = ebygum;
								}
							}
						}
						catch(e) {}
					}
				}
			}
		}
	}
}

function showMenu(ctrlid, click, offset, duration, timeout, layer, showid, maxh) {
	var ctrlobj = $(ctrlid);
	if(!ctrlobj) return;
	if(isUndefined(click)) click = false;
	if(isUndefined(offset)) offset = 0;
	if(isUndefined(duration)) duration = 2;
	if(isUndefined(timeout)) timeout = 500;
	if(isUndefined(layer)) layer = 0;
	if(isUndefined(showid)) showid = ctrlid;
	var showobj = $(showid);
	var menuobj = $(showid + '_menu');
	if(!showobj|| !menuobj) return;
	if(isUndefined(maxh)) maxh = 550;

	hideMenu(layer);

	for(var id in jsmenu['timer']) {
		if(jsmenu['timer'][id]) clearTimeout(jsmenu['timer'][id]);
	}

	initCtrl(ctrlobj, click, duration, timeout, layer);
	initMenu(ctrlid, menuobj, duration, timeout, layer);

	menuobj.style.display = '';
	if(!is_opera) {
		menuobj.style.clip = 'rect(auto, auto, auto, auto)';
	}

	var showobj_pos = fetchOffset(showobj);
	var showobj_x = showobj_pos['left'];
	var showobj_y = showobj_pos['top'];
	var showobj_w = showobj.offsetWidth;
	var showobj_h = showobj.offsetHeight;
	var menuobj_w = menuobj.offsetWidth;
	var menuobj_h = menuobj.offsetHeight;

	menuobj.style.left = (showobj_x + menuobj_w > document.body.clientWidth) && (showobj_x + showobj_w - menuobj_w >= 0) ? showobj_x + showobj_w - menuobj_w + 'px' : showobj_x + 'px';
	menuobj.style.top = offset == 1 ? showobj_y + 'px' : (offset == 2 || ((showobj_y + showobj_h + menuobj_h > document.body.scrollTop + document.body.clientHeight) && (showobj_y - menuobj_h >= 0)) ? (showobj_y - menuobj_h) + 'px' : showobj_y + showobj_h + 'px');

	if(menuobj.style.clip && !is_opera) {
		menuobj.style.clip = 'rect(auto, auto, auto, auto)';
	}

	if(is_ie && is_ie < 7) {
		if(!jsmenu['iframe'][layer]) {
			var iframe = document.createElement('iframe');
			iframe.style.display = 'none';
			iframe.style.position = 'absolute';
			iframe.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
			$('jsmenu_parent') ? $('jsmenu_parent').appendChild(iframe) : menuobj.parentNode.appendChild(iframe);
			jsmenu['iframe'][layer] = iframe;
		}
		jsmenu['iframe'][layer].style.top = menuobj.style.top;
		jsmenu['iframe'][layer].style.left = menuobj.style.left;
		jsmenu['iframe'][layer].style.width = menuobj_w;
		jsmenu['iframe'][layer].style.height = menuobj_h;
		jsmenu['iframe'][layer].style.display = 'block';
	}

	if(maxh && menuobj.scrollHeight > maxh) {
		menuobj.style.height = maxh + 'px';
		if(is_opera) {
			menuobj.style.overflow = 'auto';
		} else {
			menuobj.style.overflowY = 'auto';
		}
	}

	if(!duration) {
		setTimeout('hideMenu(' + layer + ')', timeout);
	}

	jsmenu['active'][layer] = menuobj;
}


function showMenu2(ctrlid, click, offset, duration, timeout, layer, showid, maxh) {

	var ctrlobj = $(ctrlid);

	if(!ctrlobj) return;
	if(isUndefined(click)) click = false;
	if(isUndefined(offset)) offset = 0;
	if(isUndefined(duration)) duration = 2;
	if(isUndefined(timeout)) timeout = 500;
	if(isUndefined(layer)) layer = 0;
	if(isUndefined(showid)) showid = ctrlid;
	var showobj = $(showid);
	var menuobj = $(showid + '_menu');
	if(!showobj|| !menuobj) return;
	if(isUndefined(maxh)) maxh = 400;

	hideMenu(layer);

	for(var id in jsmenu['timer']) {
		if(jsmenu['timer'][id]) clearTimeout(jsmenu['timer'][id]);
	}

	initCtrl(ctrlobj, click, duration, timeout, layer);
	initMenu(ctrlid, menuobj, duration, timeout, layer);

	menuobj.style.display = '';
	if(maxh && menuobj.scrollHeight > maxh) {
		menuobj.style.height = maxh + 'px';
		if(is_opera) {
			menuobj.style.overflow = 'auto';
		} else {
			menuobj.style.overflowY = 'auto';
		}
	}

	if(!duration) {
		setTimeout('hideMenu(' + layer + ')', timeout);
	}

	jsmenu['active'][layer] = menuobj;
}




function hideMenu(layer) {
	if(isUndefined(layer)) layer = 0;
	if(jsmenu['active'][layer]) {
		clearTimeout(jsmenu['timer'][jsmenu['active'][layer].ctrlkey]);
		jsmenu['active'][layer].style.display = 'none';
		if(is_ie && is_ie < 7 && jsmenu['iframe'][layer]) {
			jsmenu['iframe'][layer].style.display = 'none';
		}
		jsmenu['active'][layer] = null;
	}
}

function fetchOffset(obj) {
	var left_offset = obj.offsetLeft;
	var top_offset = obj.offsetTop;
	while((obj = obj.offsetParent) != null) {
		left_offset += obj.offsetLeft;
		top_offset += obj.offsetTop;
	}
	return { 'left' : left_offset, 'top' : top_offset };
}

function ebygum(eventobj) {
	if(!eventobj || is_ie) {
		window.event.cancelBubble = true;
		return window.event;
	} else {
		if(eventobj.target.type == 'submit') {
			eventobj.target.form.submit();
		}
		eventobj.stopPropagation();
		return eventobj;
	}
}

function menuoption_onclick_function(e) {
	this.clickfunc();
	hideMenu();
}

function menuoption_onclick_link(e) {
	choose(e, this);
}

function menuoption_onmouseover(e) {
	this.className = 'popupmenu_highlight';
}

function menuoption_onmouseout(e) {
	this.className = 'popupmenu_option';
}

function choose(e, obj) {
	var links = findtags(obj, 'a');
	if(links[0]) {
		if(is_ie) {
			links[0].click();
			window.event.cancelBubble = true;
		} else {
			if(e.shiftKey) {
				window.open(links[0].href);
				e.stopPropagation();
				e.preventDefault();
			} else {
				window.location = links[0].href;
				e.stopPropagation();
				e.preventDefault();
			}
		}
		hideMenu();
	}
}

function editorMenu(obj) {
	showMenu(obj.id, true);
}

function doane(event) {
	e = event ? event : window.event;
	if(is_ie) {
		e.returnValue = false;
		e.cancelBubble = true;
	} else if(e) {
		e.stopPropagation();
		e.preventDefault();
	}
}



//menu over//////////////////////////////////


//工具栏按钮
var editorid = 'posteditor';
//var editormenushow = 0;

var lang = new Array();
lang['enter_link_url']			= "请输入链接的地址:";
lang['enter_image_url']			= "请输入图片链接地址:";
lang['enter_email_link']		= "请输入此链接的邮箱地址:";
lang['fontname']			= "字体";
lang['fontsize']			= "大小";
lang['post_advanceeditor']		= "全部功能";
lang['post_simpleeditor']		= "简单功能";
lang['submit']				= "提交";
lang['cancel']				= "取消";



function wrapTags(tagname, useoption, selection) {

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

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

	var closetag = '[/' + tagname + ']';
	var text = opentag + selection + closetag;
	insertText(text, strlen(opentag), strlen(closetag), in_array(tagname, ['code', 'quote', 'free', 'hide']) ? true : false);

	return false;
}

function applyFormat(cmd, dialog, argument) {

//	if(wysiwyg) {
		editdoc.execCommand(cmd, (isUndefined(dialog) ? false : dialog), (isUndefined(argument) ? true : argument));
		return false;
//	}
/*	switch(cmd) {
		case 'bold':
		case 'italic':
		case 'underline':
			wrapTags(cmd.substr(0, 1), false);
			break;
		case 'justifyleft':
		case 'justifycenter':
		case 'justifyright':
			wrapTags('align', cmd.substr(7));
			break;
		case 'floatleft':
		case 'floatright':
			wrapTags('float', cmd.substr(5));
			break;
		case 'indent':
			wrapTags(cmd, false);
			break;
		case 'fontname':
			wrapTags('font', argument);
			break;
		case 'fontsize':
			wrapTags('size', argument);
			break;
		case 'forecolor':
			wrapTags('color', argument);
			break;
		case 'createlink':
			var sel = getSel();
			if(sel) {
				wrapTags('url', argument);
			} else {
				wrapTags('url', argument, argument);
			}
			break;
		case 'insertimage':
			wrapTags('img', false, argument);
			break;
	}*/
}

function getSel() {
//	if(wysiwyg) {
		if(is_moz || is_opera) {
			selection = editwin.getSelection();
			checkFocus();
			range = selection ? selection.getRangeAt(0) : editdoc.createRange();
			return readNodes(range.cloneContents(), false);
		} else {
			var range = editdoc.selection.createRange();
			if(range.htmlText && range.text) {
				return range.htmlText;
			} else {
				var htmltext = '';
				for(var i = 0; i < range.length; i++) {
					htmltext += range.item(i).outerHTML;
				}
				return htmltext;
			}
		}
/*	} else {
		if(!isUndefined(editdoc.selectionStart)) {
			return editdoc.value.substr(editdoc.selectionStart, editdoc.selectionEnd - editdoc.selectionStart);
		} else if(document.selection && document.selection.createRange) {
			return document.selection.createRange().text;
		} else if(window.getSelection) {
			return window.getSelection() + '';
		} else {
			return false;
		}
	}
	*/
}
function trim(str) {
	return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}
function showPrompt(dialogtxt, defaultval) {
	return trim(prompt(dialogtxt, defaultval) + '');
}

function verifyPrompt(str) {
	if(in_array(str, ['http://', 'null', 'undefined', 'false', '']) || str == null || str == false) {
		return false;
	} else {
		return str;
	}
}

function promptLink(tagname, phrase, iprompt) {
	var value = showPrompt(phrase, iprompt);
	if((value = verifyPrompt(value)) !== false) {
		if(getSel()) {
			applyFormat('unlink');
			wrapTags(tagname, value);
		} else {
			wrapTags(tagname, value, value);
		}
	}
	return true;
}

function stripSimple(tag, str, iterations) {
	var opentag = '[' + tag + ']';
	var closetag = '[/' + tag + ']';

	if(isUndefined(iterations)) {
		iterations = -1;
	}
	while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
		iterations --;
		if((stopindex = stripos(str, closetag)) !== false) {
			var text = str.substr(startindex + opentag.length, stopindex - startindex - opentag.length);
			str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
		} else {
			break;
		}
	}
	return str;
}


function stripComplex(tag, str, iterations) {
	var opentag = '[' + tag + '=';
	var closetag = '[/' + tag + ']';

	if(isUndefined(iterations)) {
		iterations = -1;
	}
	while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
		iterations --;
		if((stopindex = stripos(str, closetag)) !== false) {
			var openend = stripos(str, ']', startindex);
			if(openend !== false && openend > startindex && openend < stopindex) {
				var text = str.substr(openend + 1, stopindex - openend - 1);
				str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
			} else {
				break;
			}
		} else {
			break;
		}
	}
	return str;
}



function stripos(haystack, needle, offset) {
	if(isUndefined(offset)) {
		offset = 0;
	}
	var index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

	return (index == -1 ? false : index);
}

function getEditorContents() {
	return editdoc.body.innerHTML;
}

//undo...需要快照
var cursor = -1;
var stack = new Array();

function moveCursor(increment) {
	var test = cursor + increment;
	if(test >= 0 && stack[test] != null && !isUndefined(stack[test])) {
		cursor += increment;
	}
}

function addSnapshot(str) {
	if(stack[cursor] == str) {
		return;
	} else {
		cursor++;
		stack[cursor] = str;

		if(!isUndefined(stack[cursor + 1])) {
			stack[cursor + 1] = null;
		}
	}
}

function getSnapshot() {
	if(!isUndefined(stack[cursor]) && stack[cursor] != null) {
		return stack[cursor];
	} else {
		return false;
	}
}


function discuzcode(cmd, arg) {
	if(cmd != 'redo') {
		addSnapshot(getEditorContents());
	}

	checkFocus();

/*	if(in_array(cmd, ['quote', 'code', 'free', 'hide']))
	{
		var ret = wrapTags(cmd, false);
	}
	else if(cmd.substr(0, 6) == 'custom')
	{
		var ret = customTags(cmd.substr(8), cmd.substr(6, 1));
	} else if(!wysiwyg && cmd == 'removeformat') {
		var simplestrip = new Array('b', 'i', 'u');
		var complexstrip = new Array('font', 'color', 'size');

		var str = getSel();
		if(str === false) {
			return;
		}
		for(var tag in simplestrip) {
			str = stripSimple(simplestrip[tag], str);
		}
		for(var tag in complexstrip) {
			str = stripComplex(complexstrip[tag], str);
		}
		insertText(str);
	} else if(!wysiwyg && cmd == 'undo') {
		addSnapshot(getEditorContents());
		moveCursor(-1);
		if((str = getSnapshot()) !== false) {
			editdoc.value = str;
		}
	} else if(!wysiwyg && cmd == 'redo') {
		moveCursor(1);
		if((str = getSnapshot()) !== false) {
			editdoc.value = str;
		}
	} else if(!wysiwyg && in_array(cmd, ['insertorderedlist', 'insertunorderedlist'])) {
		var listtype = cmd == 'insertorderedlist' ? '1' : '';
		var opentag = '[list' + (listtype ? ('=' + listtype) : '') + ']\n';
		var closetag = '[/list]';

		if(txt = getSel()) {
			var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
			txt = opentag + trim(txt).replace(regex, '$1[*]') + '\n' + closetag;
			insertText(txt, strlen(txt), 0);
		} else {
			insertText(opentag + closetag, opentag.length, closetag.length);

			while(listvalue = prompt(lang['enter_list_item'], '')) {
				if(is_opera > 8) {
					listvalue = '\n' + '[*]' + listvalue;
					insertText(listvalue, strlen(listvalue) + 1, 0);
				} else {
					listvalue = '[*]' + listvalue + '\n';
					insertText(listvalue, strlen(listvalue), 0);
				}
			}
		}
	} else if(!wysiwyg && cmd == 'outdent') {
		var sel = getSel();
		sel = stripSimple('indent', sel, 1);
		insertText(sel);
	}
	else */
	if(cmd == 'removeformat')
	{
		applyFormat('removeformat');
	}
	else if(cmd == 'createlink')
	{
	//	if(wysiwyg) {
			if(is_moz || is_opera)
			{
				var url = showPrompt(lang['enter_link_url'], 'http://');
				if((url = verifyPrompt(url)) !== false)
				{
					if(getSel())
					{
						applyFormat('unlink');
						applyFormat('createlink', is_ie, (isUndefined(url) ? true : url));
					}
					else
					{
						insertText('<a href="' + url + '">' + url + '</a>');
					}
				}
			}
			else
			{
				applyFormat('createlink', is_ie, (isUndefined(url) ? true : url));
			}
	//	} else {
	//		promptLink('url', lang['enter_link_url'], 'http://');
	//	}
	} /*else if(!wysiwyg && cmd == 'unlink') {
		var sel = getSel();
		sel = stripSimple('url', sel);
		sel = stripComplex('url', sel);
		insertText(sel);
	}*/
	else if(cmd == 'email')
	{
	//	if(wysiwyg) {
			var email = showPrompt(lang['enter_email_link'], '');
			email = verifyPrompt(email);

			if(email === false)
			{
				applyFormat('unlink');
			}
			else
			{
				var selection = getSel();
				insertText('<a href="mailto:' + email + '">' + (selection ? selection : email) + '</a>', (selection ? true : false));
			}
	//	} else {
	//		promptLink('email', lang['enter_email_link'], '');
	//	}
	}
	else if(cmd == 'insertimage')
	{
		var img = showPrompt(lang['enter_image_url'], 'http://');
		if(img = verifyPrompt(img))
		{
			insertText('<img src="' + img + '" class=imgpreview>');
			return false;
//			return applyFormat('insertimage', false, img);
		}
		else
		{
			return false;
		}
	}
	else if(cmd == 'table')
	{
	//	if(wysiwyg) {
			var rows = $(editorid + '_table_rows').value;
			var columns = $(editorid + '_table_columns').value;
			var width = $(editorid + '_table_width').value;
			var bgcolor = $(editorid + '_table_bgcolor').value;
			rows = /^[-\+]?\d+$/.test(rows) && rows > 0 && rows <= 30 ? rows : 2;
			columns = /^[-\+]?\d+$/.test(columns) && columns > 0 && columns <= 30 ? columns : 2;
			width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
			bgcolor = /[\(\)%,#\w]+/.test(bgcolor) ? bgcolor : '';
			var html = '<table cellspacing="1" cellpadding="4" width="' + (width ? width : '50%') + '" align="center" class="t_table"' + (bgcolor ? 'style="background: ' + bgcolor + '"' : '') + '>';
			for (var row = 0; row < rows; row++) {
				html += '<tr>\n';
				for (col = 0; col < columns; col++) {
					html += '<td>&nbsp;</td>\n';
				}
				html+= '</tr>\n';
			}
			html += '</table>\n';
			insertText(html);
			hideMenu();
	//	}
		return false;
	}
	else if(cmd == 'floatleft' || cmd == 'floatright')
	{
			var selection = getSel();
			if(selection)
			{
				insertText('<br style="clear: both"><span style="float: ' + cmd.substr(5) + '">' + selection + '</span>', true);
			}
	}
	else
	{
		try {
			var ret = applyFormat(cmd, false, (isUndefined(arg) ? true : arg));
		} catch(e) {
			var ret = false;
		}
	}

	if(cmd != 'undo') {
		addSnapshot(getEditorContents());
	}
//	if(wysiwyg) {
		setContext(cmd);
		if(cmd == 'forecolor') {
			$(editorid + '_color_bar').style.backgroundColor = arg;
		}
//	}
	checkFocus();
	return ret;
}
/*
function editorMenu(spanid)
{
	var span = $(spanid);
	var   y=span.offsetTop;
	var   x=span.offsetLeft;
	while(span=span.offsetParent)
	{
		  y+=span.offsetTop;
		  x+=span.offsetLeft;
	}
	var menu = $(spanid+"_menu");
	if(menu.innerHTML=='')
		return true;
	var MouseX=x;
	var MouseY=y;
	menu.style.display = 'block';
	var popHeight=menu.clientHeight;
	var popWidth=menu.clientWidth;
	if(MouseY+popHeight>document.body.clientHeight)
	{
	  	popTopAdjust=-popHeight;
	}
	else
	{
		popTopAdjust = 20;
	}

	if(MouseX+popWidth>document.body.clientWidth)
	{
		popLeftAdjust=-popWidth;
	}
	else
	{
		popLeftAdjust=0;
	}
	menu.style.left=MouseX+document.body.scrollLeft+popLeftAdjust;
	menu.style.top=MouseY+document.body.scrollTop+popTopAdjust;
  	return true;
}
*/
function setContext(cmd) {
	var contextcontrols = new Array('bold', 'italic', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist');
	for(var i in contextcontrols) {
		var obj = $(editorid + '_cmd_' + contextcontrols[i]);
		if(obj != null) {
			try {
				var state = editdoc.queryCommandState(contextcontrols[i]);
			} catch(e) {
				var state = false;
			}
			if(isUndefined(obj.state)) {
				obj.state = false;
			}
			if(obj.state != state) {
				obj.state = state;
				buttonContext(obj, (obj.id.substr(obj.id.indexOf('_cmd_') + 5) == cmd ? 'mouseover' : 'mouseout'));
			}
		}
	}

	var fs = editdoc.queryCommandValue('fontname');
	if(fs == '' && !is_ie && window.getComputedStyle) {
		fs = editdoc.body.style.fontFamily;
	} else if(fs == null) {
		fs = '';
	}
	if(fs != $(editorid + '_font_out').fontstate) {
		thingy = fs.indexOf(',') > 0 ? fs.substr(0, fs.indexOf(',')) : fs;
		$(editorid + '_font_out').innerHTML = thingy;
		$(editorid + '_font_out').fontstate = fs;
	}

	var ss = editdoc.queryCommandValue('fontsize');
	if(ss == null || ss == '') {
		ss = formatFontsize(editdoc.body.style.fontSize);
	}
	if(ss != $(editorid + '_size_out').sizestate) {
		if($(editorid + '_size_out').sizestate == null) {
			$(editorid + '_size_out').sizestate = '';
		}
		$(editorid + '_size_out').innerHTML = ss;
		$(editorid + '_size_out').sizestate = ss;
	}

	var cs = editdoc.queryCommandValue('forecolor');
	$(editorid + '_color_bar').style.backgroundColor = rgbToColor(cs);
}

function buttonContext(obj, state) {
	if(state == 'mouseover') {
		obj.style.cursor = 'pointer';
		var mode = obj.state ? 'down' : 'hover';
		if(obj.mode != mode) {
			obj.mode = mode;
			obj.className = 'editor_button' + mode;
		}
	} else {
		var mode = obj.state ? 'selected' : 'normal';
		if(obj.mode != mode) {
			obj.mode = mode;
			obj.className = mode == 'selected' ? 'editor_buttonselected' : 'editor_button' + 'normal';
		}
	}
}

function menuContext(obj, state) {
	obj.style.cursor = 'pointer';
	var mode = state == 'mouseover' ? 'hover' : 'normal';
	obj.className = 'editor_button' + mode;
	var tds = findtags(obj, 'td');
	for(var i = 0; i < tds.length; i++) {
		if(tds[i].id.substr(0, tds[i].id.lastIndexOf('_')) == editorid + '_menu') {
			tds[i].className = 'editor_menu' + mode;
		} else if(tds[i].id == editorid + '_colormenu') {
			tds[i].className = 'editor_colormenu' + mode;
		}
	}
}

function colorContext(obj, state) {
	obj.style.cursor = 'pointer';
	var mode = state == 'mouseover' ? 'hover' : 'normal';
	obj.className = 'editor_color' + mode;
}

//颜色
function rgbToColor(forecolor) {
	if(!is_moz && !is_opera) {
		return rgbhexToColor((forecolor & 0xFF).toString(16), ((forecolor >> 8) & 0xFF).toString(16), ((forecolor >> 16) & 0xFF).toString(16));
	}
	if(forecolor == '' || forecolor == null) {
		forecolor = window.getComputedStyle(editdoc.body, null).getPropertyValue('color');
	}
	if(forecolor.toLowerCase().indexOf('rgb') == 0) {
		var matches = forecolor.match(/^rgb\s*\(([0-9]+),\s*([0-9]+),\s*([0-9]+)\)$/);
		if(matches) {
			return rgbhexToColor((matches[1] & 0xFF).toString(16), (matches[2] & 0xFF).toString(16), (matches[3] & 0xFF).toString(16));
		} else {
			return rgbToColor(null);
		}
	} else {
		return forecolor;
	}
}

function rgbhexToColor(r, g, b) {
	var coloroptions = {'#000000' : 'Black', '#a0522d' : 'Sienna', '#556b2f' : 'DarkOliveGreen', '#006400' : 'DarkGreen', '#483d8b' : 'DarkSlateBlue', '#000080' : 'Navy', '#4b0082' : 'Indigo', '#2f4f4f' : 'DarkSlateGray', '#8b0000' : 'DarkRed', '#ff8c00' : 'DarkOrange', '#808000' : 'Olive', '#008000' : 'Green', '#008080' : 'Teal', '#0000ff' : 'Blue', '#708090' : 'SlateGray', '#696969' : 'DimGray', '#ff0000' : 'Red', '#f4a460' : 'SandyBrown', '#9acd32' : 'YellowGreen', '#2e8b57' : 'SeaGreen', '#48d1cc' : 'MediumTurquoise', '#4169e1' : 'RoyalBlue', '#800080' : 'Purple', '#808080' : 'Gray', '#ff00ff' : 'Magenta', '#ffa500' : 'Orange', '#ffff00' : 'Yellow', '#00ff00' : 'Lime', '#00ffff' : 'Cyan', '#00bfff' : 'DeepSkyBlue', '#9932cc' : 'DarkOrchid', '#c0c0c0' : 'Silver', '#ffc0cb' : 'Pink', '#f5deb3' : 'Wheat', '#fffacd' : 'LemonChiffon', '#98fb98' : 'PaleGreen', '#afeeee' : 'PaleTurquoise', '#add8e6' : 'LightBlue', '#dda0dd' : 'Plum', '#ffffff' : 'White'};
	return coloroptions['#' + (str_pad(r, 2, 0) + str_pad(g, 2, 0) + str_pad(b, 2, 0))];
}

function str_pad(text, length, padstring) {
	text += '';
	padstring += '';

	if(text.length < length) {
		padtext = padstring;

		while(padtext.length < (length - text.length)) {
			padtext += padstring;
		}

		text = padtext.substr(0, (length - text.length)) + text;
	}

	return text;
}

////////////////////////////////////////


function checkFocus() {
	var obj = editwin;//$('uc').message //: editwin;
	if(!obj.hasfocus) {
		obj.focus();
	}
}

function insertNodeAtSelection(text) {
	checkFocus();

	var sel = editwin.getSelection();
	var range = sel ? sel.getRangeAt(0) : editdoc.createRange();
	sel.removeAllRanges();
	range.deleteContents();

	var node = range.startContainer;
	var pos = range.startOffset;

	switch(node.nodeType) {
		case Node.ELEMENT_NODE:
			if(text.nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
				selNode = text.firstChild;
			} else {
				selNode = text;
			}
			node.insertBefore(text, node.childNodes[pos]);
			add_range(selNode);
			break;

		case Node.TEXT_NODE:
			if(text.nodeType == Node.TEXT_NODE) {
				var text_length = pos + text.length;
				node.insertData(pos, text.data);
				range = editdoc.createRange();
				range.setEnd(node, text_length);
				range.setStart(node, text_length);
				sel.addRange(range);
			} else {
				node = node.splitText(pos);
				var selNode;
				if(text.nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
					selNode = text.firstChild;
				} else {
					selNode = text;
				}
				node.parentNode.insertBefore(text, node);
				add_range(selNode);
			}
			break;
	}
}

function add_range(node) {
	checkFocus();
	var sel = editwin.getSelection();
	var range = editdoc.createRange();
	range.selectNodeContents(node);
	sel.removeAllRanges();
	sel.addRange(range);
}



function insertText(text, movestart, moveend, select)
{
	//if(wysiwyg) {
		if(is_moz || is_opera)
		{
			applyFormat('removeformat');
			var fragment = editdoc.createDocumentFragment();
			var holder = editdoc.createElement('span');
			holder.innerHTML = text;

			while(holder.firstChild)
			{
				fragment.appendChild(holder.firstChild);
			}
			insertNodeAtSelection(fragment);
		}
		else
		{
			checkFocus();
			if(!isUndefined(editdoc.selection) && editdoc.selection.type != 'Text' && editdoc.selection.type != 'None') {
				movestart = false;
				editdoc.selection.clear();
			}

			var sel = editdoc.selection.createRange();

			sel.pasteHTML(text);

			if(text.indexOf('\n') == -1)
			{
				try
				{
					if(!isUndefined(movestart))
					{
						sel.moveStart('character', -strlen(text) + movestart);
						sel.moveEnd('character', -moveend);
					}
					else if(movestart != false)
					{
						sel.moveStart('character', -strlen(text));
					}
				}
				catch(e)
				{}
				if(!isUndefined(select) && select) {
					sel.select();
				}
			}
		}
}
