/******************************************************************************
  Crossday Discuz! Board - Common Modules for Discuz!
  Copyright 2001-2006 Comsenz Inc. (http://www.comsenz.com)
*******************************************************************************/

var sPop = null;
var postSubmited = false;

var userAgent = navigator.userAgent.toLowerCase();
var is_opera = (userAgent.indexOf('opera') != -1);
var is_saf = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_webtv = (userAgent.indexOf('webtv') != -1);
var is_ie = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv));
var is_ie4 = ((is_ie) && (userAgent.indexOf('msie 4.') != -1));
var is_moz = ((navigator.product == 'Gecko') && (!is_saf));
var is_kon = (userAgent.indexOf('konqueror') != -1);
var is_ns = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_saf));
var is_ns4 = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var is_mac = (userAgent.indexOf('mac') != -1);



function fetchCheckbox(cbn) {
	return $(cbn) && $(cbn).checked==true ? 1 : 0;
} 

function ctlent(event,objfrm) {
	if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83)) {
		if (objfrm){
			if (validate(objfrm))
				objfrm.submit();
		}
		else{
			objfrm = $("title").form;
			if (objfrm){
				if (validate(objfrm)){
					objfrm.submit();
				}
			}
		}
	}
}

function storeCaret(textEl){
	if(textEl.createTextRange){
		textEl.caretPos = document.selection.createRange().duplicate();
	}
}


function findobj(n, d) {
	var p, i, x;
	if(!d) d = document;
	if((p = n.indexOf("?"))>0 && parent.frames.length) {
		d = parent.frames[n.substring(p + 1)].document;
		n = n.substring(0, p);
	}
	if(x != d[n] && d.all) x = d.all[n];
	for(i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
	for(i = 0; !x && d.layers && i < d.layers.length; i++) x = findobj(n, d.layers[i].document);
	if(!x && document.getElementById) x = document.getElementById(n);
	return x;
}

function arraypop(a) {
	if(typeof a != 'object' || !a.length) {return null;}
	else {
		var response = a[a.length - 1];
		a.length--;
		return response;
	}
}

function arraypush(a, value)
{
	a[a.length] = value;
	return a.length;
}

function doane(eventobj) {
	if(!eventobj || is_ie)	{
		window.event.returnValue = false;
		window.event.cancelBubble = true;
		return window.event;
	} else {
		eventobj.stopPropagation();
		eventobj.preventDefault();
		return eventobj;
	}
}

function findtags(parentobj, tag) {
	if(typeof parentobj.getElementsByTagName != 'undefined') {return parentobj.getElementsByTagName(tag);}
	else if(parentobj.all && parentobj.all.tags) {return parentobj.all.tags(tag);}
	else {return null;}
}

function copycode(obj) {
	var rng = document.body.createTextRange();
	rng.moveToElementText(obj);
	rng.scrollIntoView();
	rng.select();
	rng.execCommand("Copy");
	rng.collapse(false);
}

function toggle_collapse(objname) {
	obj = findobj(objname);
	img = findobj(objname+"_img");
	//collapsed = getcookie("discuz_collapse");
	//cookie_start = collapsed ? collapsed.indexOf(objname) : -1;
	//cookie_end = cookie_start + objname.length + 1;

	if(obj.style.display == "none") {
		obj.style.display = "";
		img_re = new RegExp("_yes\\.gif$");
		img.src = img.src.replace(img_re, '_no.gif');
		//if(cookie_start != -1) collapsed = collapsed.substring(0, cookie_start) + collapsed.substring(cookie_end, collapsed.length);
	} else {
		obj.style.display = "none";
		img_re = new RegExp("_no\\.gif$");
		img.src = img.src.replace(img_re, '_yes.gif');
		//if(cookie_start == -1) collapsed = collapsed + objname + " ";
	}

	//expires = new Date();
	//expires.setTime(expires.getTime() + (collapsed ? 86400 * 30 : -(86400 * 30 * 1000)));
	//document.cookie = "discuz_collapse=" + escape(collapsed) + "; expires=" + expires.toGMTString() + "; path=/";
}

function imgzoom(o) {
	if(event.ctrlKey) {
		var zoom = parseInt(o.style.zoom, 10) || 100;
		zoom -= event.wheelDelta / 12;
		if(zoom > 0) {
			o.style.zoom = zoom + '%';
		}
		return false;
	} else {
		return true;
	}
}

function getcookie(name) {
	var cookie_start = document.cookie.indexOf(name);
	var cookie_end = document.cookie.indexOf(";", cookie_start);
	return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
}





function AddText(txt) {
	obj = $("title").form.message;
	selection = document.selection;
	setfocus();
	if(typeof(obj.selectionStart) != 'undefined') {
		var opn = obj.selectionStart + 0;
		obj.value = obj.value.substr(0, obj.selectionStart) + txt + obj.value.substr(obj.selectionEnd);
	} else if(selection && selection.createRange) {
		var sel = selection.createRange();
		sel.text = txt;
		sel.moveStart('character', -mb_strlen(txt));
	} else {
		obj.value += txt;
	}
} 

function insertAtCaret (textEl,	text){
	if(textEl.createTextRange && textEl.caretPos){
		var caretPos = textEl.caretPos;
		caretPos.text += caretPos.text.charAt(caretPos.text.length - 2)	== ' ' ? text +	' '	: text;
	} else if(textEl) {
		textEl.value +=	text;
	} else {
		textEl.value = text;
	}
}

function setfocus() {
	objfrm = $("title").form;
	objfrm.message.focus();
}


function mb_strlen(str) {
	return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}



function $(id) {
	return document.getElementById(id);
}




function Trim(str){
	if (str){
		return (str.replace(/(\s+)$/g, '')).replace(/^\s+/g, '');
	}
	return "";
}

function RTrim(str){
	str="|" + str;
	str=Trim(str);
	return str.substr(1);
}




if(typeof editor_id == 'undefined') {
	var editor_id = 0;
}

if(typeof bbinsert == 'undefined') {
	var bbinsert = 1;
}

if(typeof smileyinsert == 'undefined') {
	var smileyinsert = 0;
}





function smiliewindow_onunload(e) {
	if(typeof smilie_window != 'undefined' && !smilie_window.closed) {
		smilie_window.close();
	}
}

function open_smilie_window(width, height) {
	smilie_window = window.open('showsmilies.aspx?editid=' + editor_id, 'Popup', 'width=200,height=500,resizable=yes,scrollbars=yes');
	window.onunload = smiliewindow_onunload;
}

function smiley_insert() {
	if(smileyinsert) {
		showsmilies();
		var smilie_container = findobj(editor_id + '_smiliebox');
		if(smilie_container != null) {
			var smilies = findtags(smilie_container, 'img');
			for(var i = 0; i < smilies.length; i++) {
				if(smilies[i].id && smilies[i].id.indexOf('_smilie_') != false) {
					smilies[i].style.cursor = is_ie ? 'hand' : 'pointer';
					smilies[i].onclick = function() {AddText(this.pop ? this.pop : this.alt);};
					
				}
			}
		}

		var smilie_container2 = findobj('smilietable');
		if(smilie_container2 != null) {
			var smilies = findtags(smilie_container2, 'img');
			for(var i = 0; i < smilies.length; i++) {
				if(smilies[i].id && smilies[i].id.indexOf('_smilie_') != false) {
					smilies[i].style.cursor = is_ie ? 'hand' : 'pointer';
					smilies[i].onclick = function() {
						opener.document.form1.message.value += this.pop ? this.pop : this.alt;
					};
				}
			}
		}
	}
}


function showsmilies(){
	var row=null;
	var col=null;
	var img=null;
	var rowIndex=0;
	var colIndex=0;
	
	if(undefined(smiliesIsCreate)) {
		var smiliesIsCreate = 0;
	}
	
	if(undefined(showsmiliestitle)) {
		var showsmiliestitle = 1;
	}
	
	if(undefined(title)) {
		var title = "";
	}
	
	if(undefined(editor_id)) {
		return;
	}
	
	if (smiliesIsCreate!=0){
		return;
	}
	
	

	try{
		if (!smilies.length){
			return;
		}
		
		var smilie_container = findobj(editor_id + '_smiliebox');
		var smilieytable = document.createElement('table');
				smilieytable.cellPadding="3";
				smilieytable.cellSpacing="0";
				smilieytable.width="100%";
				smilieytable.border=0;
				smilieytable.className="altbg1";
				
				smilieytable.style.border="0px";
				
				smilieytable.id=editor_id + "_smilieytable";
				
			if (showsmiliestitle==1){
				//top行
				row=smilieytable.insertRow(-1);			
				col=row.insertCell(-1);
				col.colSpan=4
				col.align="center";
				col.className="altbg1";
				col.innerHTML="";
			}
		
			
		//smilies行

		sCount=smilies.length;
		if (sCount>smiliesCount){
			sCount=smiliesCount;
		}
		
		var temp_sCount = 0
		for(i=0;i<smilies.length;i++)
		{
		
			if (smilies[i]){
				temp_sCount ++;
				if (temp_sCount>sCount){
					break;
				}
				if (colIndex>colCount || colIndex<1){
					row=smilieytable.insertRow(-1);			
					colIndex=1;
				}
				col=row.insertCell(-1);
				col.vAlign="top";
				img=document.createElement('img');
				img.src="editor/images/smilies/" + smilies[i][2];
				img.alt=smilies[i][1];
				img.id=editor_id + "_smilie_" + smilies[i][0];
				img.border=0;
				col.appendChild(img);
				
				colIndex++;
				
			}
		}
		
		for (i=colIndex;i<colCount;i++)
		{
			if (row!=null){
				col=row.insertCell(-1);
				col.vAlign="top";
				col.innerHTML="&nbsp;";
			}
		}
		
			//bottom行
			row=smilieytable.insertRow(-1);
			col=row.insertCell(-1);
			col.colSpan=4
			col.align="center";
			col.height=24;
				var a=document.createElement('a');
				a.href="#";
				a.onclick=function(){open_smilie_window(200, 500); return false;};
					var span=document.createElement('span');
					span.className="bold";
					span.innerHTML="更多表情";
				a.appendChild(span);
			col.appendChild(a);
		
		smilie_container.appendChild(smilieytable);
		
		smiliesIsCreate=1;
	}
	catch(e){
		alert(e.message);
		return;
	}
}




function stripos(haystack, needle, offset) {
	if(typeof offset == 'undefined') {
		offset = 0;
	}
	index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

	return (index == -1 ? false : index);
}















/******************************************************************************
  Crossday Discuz! Board - HTML <=> BB Code for Discuz!
  Copyright 2001-2006 Comsenz Inc. (http://www.comsenz.com)
*******************************************************************************/

var pcodecount = '-1';
var codecount = 0;
var codehtml = new Array();
var prependtags = '';
var appendtags = '';

function atag(aoptions, text) {
	if(trim(text) == '') {
		return '';
	}

	href = getoptionvalue('href', aoptions);

	if(href.substr(0, 11) == 'javascript:') {
		return trim(recursion('a', text, 'atag'));
	} else if(href.substr(0, 7) == 'mailto:') {
		tag = 'email';
		href = href.substr(7);
	} else {
		tag = 'url';
	}

	return '[' + tag + '=' + href + ']' + trim(recursion('a', text, 'atag')) + '[/' + tag + ']';
}

	//codehtml[pcodecount] = "<br><br><div style=\"" + msgheader + "\"><div class=\"right\"><a href=\"###\" class=\"smalltxt\">[Copy to clipboard]</a></div>CODE:</div><div style=\"" + msgborder + "\">" + text + "</div>";

function parsecode(text) {
	pcodecount++;

	text = text.replace(/^[\n\r]*([\s\S]+?)[\n\r]*$/ig, '$1');
	text = htmlspecialchars(text);

	codehtml[pcodecount] = '[code]' + text + '[/code]';

	codecount++;
	return "[\tDISCUZ_CODE_" + pcodecount + "\t]";
}

function codetag(text) {
	pcodecount++;

	text = text.replace(/<br[^\>]*>/ig, "\n");
	text = text.replace(/^[\n\r]*([\s\S]+?)[\n\r]*$/ig, '$1');
	text = text.replace(/<(\/|)[A-Za-z].*?>/ig, '');

	codehtml[pcodecount] = "[code]" + text + "[/code]";
	codecount++;
	return "[\tDISCUZ_CODE_" + pcodecount + "\t]";
}

function divtag(divoptions, text) {
	prepend = '';
	append = '';

	parsestyle(divoptions, prepend, append);
	align = getoptionvalue('align', divoptions);

	switch(align) {
		case 'left':
		case 'center':
		case 'right':
			break;
		default:
			align = '';
	}

	if(align) {
		prepend += '[align=' + align + ']';
		append += '[/align]';
	}
	append += "\n";

	return prepend + recursion('div', text, 'divtag') + append;
}

function fetchoptionvalue(option, text) {
	if((position = strpos(text, option)) !== false) {
		delimiter = position + option.length;
		if(text.charAt(delimiter) == '"') {
			delimchar = '"';
		} else if(text.charAt(delimiter) == '\'') {
			delimchar = '\'';
		} else {
			delimchar = ' ';
		}
		delimloc = strpos(text, delimchar, delimiter + 1);
		if(delimloc === false) {
			delimloc = text.length;
		} else if(delimchar == '"' || delimchar == '\'') {
			delimiter++;
		}
		return trim(text.substr(delimiter, delimloc - delimiter));
	} else {
		return '';
	}
}

function parsestyle(tagoptions, prependtags, appendtags) {
	var searchlist = [
		['align', true, 'text-align:\\s*(left|center|right);?', 1],
		['color', true, '^(?:\\s|)color:\\s*([^;]+);?', 1],
		['font', true, 'font-family:\\s*([^;]+);?', 1],
		['size', true, 'font-size:\\s*(\\d+(px|pt|in|cm|mm|pc|em|ex|%|));?', 1],
		['b', false, 'font-weight:\\s*(bold);?'],
		['i', false, 'font-style:\\s*(italic);?'],
		['u', false, 'text-decoration:\\s*(underline);?']
	];

	style = getoptionvalue('style', tagoptions);
	re = /^(?:\s|)color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)(;?)/ig;
	style = style.replace(re, function($1, $2, $3, $4, $5) {return("color:#" + parseInt($2).toString(16) + parseInt($3).toString(16) + parseInt($4).toString(16) + $5);});

	for(var i = 0; i < searchlist.length; i++) {
		re = new RegExp(searchlist[i][2], "ig");
		match = re.exec(style);

		if(match != null) {
			opnvalue = match[searchlist[i][3]];

			re = /([\d]+)p([x|t])/ig;
			matches = re.exec(opnvalue);
			if(matches != null) {
				if(matches[2] == 'x') {
					matches[1] = matches[1] * 0.75;
				}
				switch(matches[1]) {
					case matches[1] < 10: opnvalue = 1; break;
					case matches[1] < 12: opnvalue = 2; break;
					case matches[1] < 14: opnvalue = 3; break;
					case matches[1] < 18: opnvalue = 4; break;
					case matches[1] < 24: opnvalue = 5; break;
					case matches[1] < 36: opnvalue = 6; break;
					case matches[1] >= 36: opnvalue = 7; break;
					default:     opnvalue = 2; break;
				}
			}
			prependtags += '[' + searchlist[i][0] + (searchlist[i][1] == true ? '=' + opnvalue + ']' : ']');
			appendtags = '[/' + searchlist[i][0] + ']' + appendtags;
		}
	}
	return {'prepend' : prependtags, 'append' : appendtags};
}

function getoptionvalue(option, text) {

	re = new RegExp(option + "(\s+?)?\=(\s+?)?[\"']?(.+?)([\"']|$|>)", "ig");
	var matches = re.exec(text);
	if(matches != null && matches.length) {
		return trim(matches[3]);
	}
	return '';
}

function fonttag(fontoptions, text) {
	var prepend = '';
	var append = '';
	var tags = new Array();
	tags = {'font' : 'face=', 'size' : 'size=', 'color' : 'color='};
	for(bbcode in tags) {
		optionvalue = fetchoptionvalue(tags[bbcode], fontoptions);
		if(optionvalue) {
			prepend += '[' + bbcode + '=' + optionvalue + ']';
			append = '[/' + bbcode + ']' + append;
		}
	}
	parsestyle(fontoptions, prepend, append);
	return prepend + recursion('font', text, 'fonttag') + append;
}

function simpletag(options, text, tagname, parseto) {
	if(trim(text) == '') {
		return '';
	}
	text = recursion(tagname, text, 'simpletag', parseto);
	return '[' + parseto + ']' + text + '[/' + parseto + ']';
}

function spantag(spanoptions, text) {
	prepend = '';
	append = '';
	parsestyle(spanoptions, prepend, append);
	return prepend + recursion('span', text, 'spantag') + append;
}

function dpstag(options, text, tagname) {
	if(trim(text) == '') {
		return '';
	}
	var pend = parsestyle(options, '', '');
	var prepend = pend['prepend'];
	var append = pend['append'];
	if(in_array(tagname, ['div', 'p'])) {
		align = getoptionvalue('align', options);
		if(in_array(align, ['left', 'center', 'right'])) {
			prepend = '[align=' + align + ']' + prepend;
			append += '[/align]';
		} else {
			append += "\n";
		}
	}
	return prepend + recursion(tagname, text, 'dpstag') + append;
}

function ptag(poptions, text) {
	align = getoptionvalue('align', poptions);

	switch(align) {
		case 'left':
		case 'center':
		case 'right':
			break;
		default:
			align = '';
	}

	prepend = '';
	append = '';
	parsestyle(poptions, prepend, append);
	if(align) {
		prepend += '[align=' + align + ']';
		append += '[/align]';
	}
	append += "\n";

	return prepend + recursion('p', text, 'ptag') + append;
}

function litag(listoptions, text) {
	return '[*]' + text.replace(/(\s+)$/g, '');
}

function listtag(listoptions, text, tagname) {

	text = text.replace(/<li>((.(?!<\/li))*)(?=<\/?ol|<\/?ul|<li|\[list|\[\/list)/ig, '<li>$1</li>') + (is_opera ? '</li>' : '');

	text = recursion('li', text, 'litag');

	if(tagname == 'ol') {
		listtype = fetchoptionvalue('type=', listoptions) ? fetchoptionvalue('type=', listoptions) : 1;
		if(listtype == '1' || listtype == 'a' || listtype == 'A') {
			opentag = '[list=' + listtype + ']';
		}
	} else {
		opentag = '[list]';
	}
	return text ? opentag + recursion(tagname, text, 'listtag') + '[/list]' : false;
}

function recursion(tagname, text, dofunction, extraargs) {
	if(extraargs == null) {
		extraargs = '';
	}
	tagname = tagname.toLowerCase();

	var open_tag = '<' + tagname;
	var open_tag_len = open_tag.length;
	var close_tag = '</' + tagname + '>';
	var close_tag_len = close_tag.length;
	var beginsearchpos = 0;

	do {
		var textlower = text.toLowerCase();
		var tagbegin = textlower.indexOf(open_tag, beginsearchpos);
		if(tagbegin == -1) {
			break;
		}

		var strlen = text.length;

		var inquote = '';
		var found = false;
		var tagnameend = false;
		var optionend = 0;
		var t_char = '';

		for(optionend = tagbegin; optionend <= strlen; optionend++) {
			t_char = text.charAt(optionend);
			if((t_char == '"' || t_char == "'") && inquote == '') {
				inquote = t_char;
			} else if((t_char == '"' || t_char == "'") && inquote == t_char) {
				inquote = '';
			} else if(t_char == '>' && !inquote) {
				found = true;
				break;
			} else if((t_char == '=' || t_char == ' ') && !tagnameend) {
				tagnameend = optionend;
			}
		}

		if(!found) {
			break;
		}
		if(!tagnameend) {
			tagnameend = optionend;
		}

		var offset = optionend - (tagbegin + open_tag_len);
		var tagoptions = text.substr(tagbegin + open_tag_len, offset)
		var acttagname = textlower.substr(tagbegin * 1 + 1, tagnameend - tagbegin - 1);

		if(acttagname != tagname) {
			beginsearchpos = optionend;
			continue;
		}

		var tagend = textlower.indexOf(close_tag, optionend);
		if(tagend == -1) {
			break;
		}

		var nestedopenpos = textlower.indexOf(open_tag, optionend);
		while(nestedopenpos != -1 && tagend != -1) {
			if(nestedopenpos > tagend) {
				break;
			}
			tagend = textlower.indexOf(close_tag, tagend + close_tag_len);
			nestedopenpos = textlower.indexOf(open_tag, nestedopenpos + open_tag_len);
		}

		if(tagend == -1) {
			beginsearchpos = optionend;
			continue;
		}



		var localbegin = optionend + 1;
		var localtext = eval(dofunction)(tagoptions, text.substr(localbegin, tagend - localbegin), tagname, extraargs);

		text = text.substring(0, tagbegin) + localtext + text.substring(tagend + close_tag_len);

		beginsearchpos = tagbegin + localtext.length;

	} while(tagbegin != -1);

	return text;
}

function imgtag(attributes) {
	var width = '';
	var height = '';

	re = /src=(["']?)([\s\S]*?)(\1)/i;
	var matches = re.exec(attributes);
	if(matches != null) {
		var src = matches[2];
	} else {
		return '';
	}

	re = /width\s?:\s?(\d{1,3})px/ig;
	var matches = re.exec(attributes);
	if(matches != null) {
		width = matches[1];
	}

	re = /height\s?:\s?(\d{1,3})px/ig;
	var matches = re.exec(attributes);
	if(matches != null) {
		height = matches[1];
	}

	if(!width || !height) {
		re = /width=(["']?)(\d+)(\1)/i;
		var matches = re.exec(attributes);
		if(matches != null) {
			width = matches[2];
		}

		re = /height=(["']?)(\d+)(\1)/i;
		var matches = re.exec(attributes);
		if(matches != null) {
			height = matches[2];
		}
	}

	re = /aid=(["']?)attach_(\d+)(\1)/i;
	var matches = re.exec(attributes);
	var imgtag = 'img';
	if(matches != null) {
		imgtag = 'localimg';
		src = matches[2];
	}
	re = /aid=(["']?)attachimg_(\d+)(\1)/i;
	var matches = re.exec(attributes);
	if(matches != null) {
		return '[attachimg]' + matches[2] + '[/attachimg]';
	}
	return width > 0 && height > 0 ?
		'[' + imgtag + '=' + width + ',' + height + ']' + src + '[/' + imgtag + ']' :
		'[img]' + src + '[/img]';
}


function tabletag(attributes) {
	var width = '';
	re = /width=(["']?)(\d{1,3}%?)(\1)/ig;
	var matches = re.exec(attributes);
	if(matches != null && matches.length) {
		width = matches[2].substr(matches[2].length - 1, matches[2].length) == '%' ?
			(matches[2].substr(0, matches[2].length - 1) <= 98 ? matches[2] : '98%') :
			(matches[2] <= 560 ? matches[2] : '560');
	} else {
		re = /width\s?:\s?(\d{1,3})([px|%])/ig;
		var matches = re.exec(attributes);
		if(matches != null && matches.length) {
			width = matches[2] == '%' ? (matches[1] <= 98 ? matches[1] : '98%') : (matches[1] <= 560 ? matches[1] : '560');
		}
	}
	return width == '' ? '[table]' : '[table=' + width + ']';
}

function tdtag(attributes) {

	var colspan = 1;
	var rowspan = 1;
	var width = '';

	re = /colspan=(["']?)(\d{1,2})(\1)/ig;
	var matches = re.exec(attributes);
	if(matches != null) {
		colspan = matches[2];
	}

	re = /rowspan=(["']?)(\d{1,2})(\1)/ig;
	var matches = re.exec(attributes);
	if(matches != null) {
		rowspan = matches[2];
	}

	re = /width=(["']?)(\d{1,3}%?)(\1)/ig;
	var matches = re.exec(attributes);
	if(matches != null) {
		width = matches[2];
	}

	return width == '' || width == 0 || width == '100%' ?
		(colspan == 1 && rowspan == 1 ? '[td]' : '[td=' + colspan + ',' + rowspan + ']') :
		'[td=' + colspan + ',' + rowspan + ',' + width + ']';
}


function ParseSmilies(){
	if (!smilies.length){
		return;
	}
	
	//document.write(arguments[0]);
	for (i=0;i<smilies.length;i++){
		if (smilies[i][0]==arguments[1]){
			return smilies[i][1];
		}
	}
	
	return arguments[0];
}

function html2bbcode(str) {

	str = trim(str);

	if(str == '') {
		return str;
	}

	str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return codetag($2);});

	str = str.replace(/<style.*?>[\s\S]*?<\/style>/ig, '');
	str = str.replace(/<script.*?>[\s\S]*?<\/script>/ig, '');
	str = str.replace(/<noscript.*?>[\s\S]*?<\/noscript>/ig, '');
	str = str.replace(/<select.*?>[\s\S]*?<\/select>/ig, '');
	str = str.replace(/<object.*?>[\s\S]*?<\/object>/ig, '');
	str = str.replace(/<!--[\s\S]*?-->/ig, '');
	str = str.replace(/on(mousewheel|mouseover|click|load|unload|submit|focus|blur)="[^"]*"/ig, '');
	str = str.replace(/(\r\n|\n|\r)/ig, '');

	str = str.replace(/<table([^>]*width[^>]*)>/ig, function($1, $2) {return tabletag($2);});
	str = str.replace(/<table[^>]*>/ig, '[table]');
	str = str.replace(/<tr[^>]*>/ig, '[tr]');
	str = str.replace(/<td>/ig, '[td]');
	str = str.replace(/<td([^>]+)>/ig, function($1, $2) {return tdtag($2);});
	str = str.replace(/<\/td>/ig, '[/td]');
	str = str.replace(/<\/tr>/ig, '[/tr]');
	str = str.replace(/<\/table>/ig, '[/table]');

	str = str.replace(/<h([0-9]+)[^>]*>(.*)<\/h\\1>/ig, "[size=$1]$2[/size]\n\n");
	//str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {alert($3);alert(smilies[$3][1]);return smilies[$3]['code'];});
	str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return ParseSmilies($1,$3);});
	str = str.replace(/<img([^>]*src[^>]*)>/ig, function($1, $2) {return imgtag($2);});
	str = str.replace(/<a\s+?name=(["']?)(.+?)(\1)[\s\S]*?>([\s\S]*?)<\/a>/ig, "$3");
	str = str.replace(/<br[^\>]*>/ig, "\n");

	str = recursion('b', str, 'simpletag', 'b');
	str = recursion('strong', str, 'simpletag', 'b');
	str = recursion('i', str, 'simpletag', 'i');
	str = recursion('em', str, 'simpletag', 'i');
	str = recursion('u', str, 'simpletag', 'u');
	str = recursion('a', str, 'atag');
	str = recursion('font', str, 'fonttag');
	str = recursion('blockquote', str, 'simpletag', 'indent');
	str = recursion('ol', str, 'listtag');
	str = recursion('ul', str, 'listtag');
	str = recursion('div', str, 'dpstag');
	str = recursion('span', str, 'dpstag');
	str = recursion('p', str, 'dpstag');

	str = str.replace(/<[\/\!]*?[^<>]*?>/ig, '');

	for(var i = 0; i <= pcodecount; i++) {
		str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", codehtml[i]);
	}

	str = str.replace(/&amp;/ig, '&');
	str = str.replace(/&nbsp;/ig, ' ');
	str = str.replace(/&lt;/ig, '<');
	str = str.replace(/&gt;/ig, '>');

	return trim(str)
}


function addslashes(str) {
	var searcharray = ['\\', '\'', '/', '(', ')', '[', ']', '{', '}', '^', '$', '?', '.', '*', '+', '|']
	var replacearray = ['\\\\', '\\\'', '\\/', '\\(', '\\)', '\\[', '\\]', '\\{', '\\}', '\\^', '\\$', '\\?', '\\.', '\\*', '\\+', '\\|']
	var len = searcharray.length

	for(var i = 0; i < len; i++) {
		str = str.replace(searcharray[i], replacearray[i]);
	}

	return str;
} 

function bbcode2html(str) {

	var re;

	if(str == '') {
		return '';
	}

	if(!fetchCheckbox('bbcodeoff') && Allowbbcode) {
		str= str.replace(/\[code\]([\s\S]+?)\[\/code\]/ig, function($1, $2) {return parsecode($2);});
	}

	if (smilies.length && !findobj("smileyoff").checked && Allowsmilies){
		
		for (i=0;i<smilies.length;i++){
			s=addslashes(smilies[i][1]) 
			re = new RegExp(s, "g");			
			s="[IMG src=\"editor/images/smilies/" + smilies[i][2] + "\" border=0 smilieid=\"" + smilies[i][0] + "\"]";
			str=str.replace(re,s);
		}


	}
	
	//if (!Allowhtml){
		str = str.replace(/</ig, '&lt;')
		str = str.replace(/>/ig, '&gt;')
	//}

	re=/\[img\ssrc=\"(.*?)\"\sborder=0\ssmilieid=\"(.*?)\"\]/ig;
	str=str.replace(re,"<img smilieid=\"$2\" src=\"$1\" border=\"0\">");
	

	if(!fetchCheckbox('parseurloff')) {
		str = str.replace(/^((http|https|ftp|rtsp|mms):\/\/[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)/ig, "<a target=_blank href=$1>$1</a>")
		str = str.replace(/((http|https|ftp|rtsp|mms):\/\/[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)$/ig, "<a target=_blank href=$1>$1</a>")
		str = str.replace(/[^>=\]""]((http|https|ftp|rtsp|mms):\/\/[A-Za-z0-9\.\/=\?%\-&_~`@':+!]+)/ig, "<a target=_blank href=$1>$1</a>")
	}

	if(!fetchCheckbox('bbcodeoff') && Allowbbcode) {
		str= str.replace(/(\[url\])(.*?)(\[\/url\])/ig, '<a href="$2" target="_blank">$2</a>')
		str= str.replace(/(\[url=(.[^\[]*)\])(.*?)(\[\/url\])/ig, '<a href="$2" target="_blank">$3</a>')
		str= str.replace(/(\[email\])(.*?)(\[\/email\])/ig, '<a href="mailto:$2">$2</a>')
		str= str.replace(/(\[email=(.[^\[]*)\])(.*?)(\[\/email\])/ig, '<a href="mailto:$2" target="_blank">$3</a>')
		str = str.replace(/\[color=([^\[\<]+?)\]/ig, '<font color="$1">')
		str = str.replace(/\[size=([^\[\<]+?)\]/ig, '<font size="$1">')
		str = str.replace(/\[font=([^\[\<]+?)\]/ig, '<font face="$1">')
		str = str.replace(/\[align=([^\[\<]+?)\]/ig, '<p align="$1">')

		re = /\s*\[table(=(\d{1,3}%?))?\][\n\r]*([\s\S]+?)[\n\r]*\[\/table\]\s*/ig
		str = str.replace(re, function($1, $2, $3, $4) {return parsetable($3, $4);})
		str = str.replace(re, function($1, $2, $3, $4) {return parsetable($3, $4);})

		var searcharray = new Array(
			'\\\[\\\/color\\\]', '\\\[\\\/size\\\]', '\\\[\\\/font\\\]', '\\\[\\\/align\\\]', '\\\[b\\\]', '\\\[\\\/b\\\]',
			'\\\[i\\\]', '\\\[\\\/i\\\]', '\\\[u\\\]', '\\\[\\\/u\\\]', '\\\[list\\\]', '\\\[list=1\\\]', '\\\[list=a\\\]',
			'\\\[list=A\\\]', '\\\[\\\*\\\]', '\\\[\\\/list\\\]', '\\\[indent\\\]', '\\\[\\\/indent\\\]'
		);
		var replacearray = new Array(
			'</font>', '</font>', '</font>', '</p>', '<b>', '</b>', '<i>',
			'</i>', '<u>', '</u>', '<ul>', '<ol type=1>', '<ol type=a>',
			'<ol type=A>', '<li>', '</ul></ol>', '<blockquote>', '</blockquote>'
		);
		var len = searcharray.length;
		for(var i = 0; i < len; i++) {
			re = new RegExp(searcharray[i], "ig");
			str = str.replace(re, replacearray[i]);
		}
	}

	if(!fetchCheckbox('bbcodeoff')) {
		if (Allowimgcode){
			str = str.replace(/\[localimg=(\d{1,3}),(\d{1,3})\](\d+)\[\/localimg\]/ig, function ($1, $2, $3, $4) {if($('attach_' + $4)) {var src = $('attach_' + $4).value; if(src != '') return '<img style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'scale\',src=\'' + src + '\');width:' + $2 + ';height=' + $3 + '" src=\'images/common/none.gif\' border="0" aid="attach_' + $4 + '"  />';}});
			str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img src=\"$1\" border=\"0\" onload=\"if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt=\'Click here to open new window\\nCTRL+Mouse wheel to zoom in/out\';}\" onmouseover=\"if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor=\'hand\'; this.alt=\'Click here to open new window\\nCTRL+Mouse wheel to zoom in/out\';}\" onclick=\"if(!this.resized) {return true;} else {window.open(\'$1\');}\" onmousewheel=\"return imgzoom(this);\" alt=\"\" />');
			//str = str.replace(/\[attachimg\](\d+)\[\/attachimg\]/ig, '<img src="attachment.aspx?attachmentid=$1" border="0" aid="attachimg_$1" alt="" />');
			str = str.replace(/\[img=(\d{1,3})[x|\,](\d{1,3})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img width=\"$1\" height=\"$2\" src=\"$3\" border=\"0\" alt=\"\" />');

		} else {
			str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
			str = str.replace(/\[img=(\d{1,3})[x|\,](\d{1,3})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
		}
	}

	for(var i = 0; i <= pcodecount; i++) {
		str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", codehtml[i]);
	}

	if (Allowhtml){
		str = str.replace(/\t/ig, '&nbsp; &nbsp; &nbsp; &nbsp; ')
		str = str.replace(/   /ig, '&nbsp; &nbsp;')
		str = str.replace(/  /ig, '&nbsp;&nbsp;')
		str = str.replace(/\r\n/ig, '<br />')
		str = str.replace(/[\r\n]/ig, '<br />')
	}

	return(str);
}

function parsetable(width, str) {
	if(typeof width == 'undefined') {
		var width = '';
	} else {
		width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '560');
	}

	var string = '<table cellspacing="1" cellpadding="4" '
		+ (width == '' ? '' : 'width="' + width + '" ')
		+ 'align="center" style="background: ' + INNERBORDERCOLOR + ';border: ' + BORDERWIDTH + 'px solid ' + BORDERCOLOR + ';">';

	str = str.replace(/\[td=(\d{1,2}),(\d{1,2})(,(\d{1,3}%?))?\]/ig, '<td colspan="$1" rowspan="$2" width="$4" style="background: ' + ALTBG2 + ';font: ' + FONTSIZE + ' ' + FONT + ';">');
	str = str.replace(/\[tr\]/ig, '<tr>');
	str = str.replace(/\[td\]/ig, '<td style="background: ' + ALTBG2 + ';font: ' + FONTSIZE + ' ' + FONT + ';">');
	str = str.replace(/\[\/td\]/ig, '</td>');
	str = str.replace(/\[\/tr\]/ig, '</tr>');

	string += str;
	string += '</table>';

	return string;
}


function trim(str) {
	return (str.replace(/(\s+)$/g, '')).replace(/^\s+/g, '');
}

function htmlspecialchars(str) {

	var f = new Array(
		(is_mac && is_ie ? new RegExp('&', 'g') : new RegExp('&(?!#[0-9]+;)', 'g')),
		new RegExp('<', 'g'),
		new RegExp('>', 'g'),
		new RegExp('"', 'g')
	);
	var r = new Array(
		'&amp;',
		'&lt;',
		'&gt;',
		'&quot;'
	);

	for(var i = 0; i < f.length; i++) {
		str = str.replace(f[i], r[i]);
	}

	return str;
}

function strpos(haystack, needle, offset) {
	if(typeof offset == 'undefined') {
		offset = 0;
	}

	index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

	return index == -1 ? false : index;
}

function in_array(needle, haystack) {
	if(typeof needle == 'string') {
		for(var i in haystack) {
			if(haystack[i] == needle) {
					return true;
			}
		}
	}
	return false;
}


