﻿// Editor control
// originally by subBlue design (www.subBlue.com)
// edited by jcisio for my own using

// Startup variables
var theSelection = false;
inEditor = 1;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Define the bbCode tags
nl = String.fromCharCode(13)
bbcode = new Array();
bbtags = new Array('[b]','[/b]', '[i]','[/i]', '[u]','[/u]', '[quote]','[/quote]', '[code]'+nl,nl+'[/code]', '[html]'+nl, nl+'[/html]', '[sql]'+nl, nl+'[/sql]', '[url]','[/url]', '[img]','[/img]', '[flash=600,450]','[/flash]', '[media]', '[/media]', '[F=sub]', '[/F]', '[F=sup]', '[/F]', '[TEX]', '[/TEX]');

// Replacement for arrayname.length property
function getarraysize(thearray)
{
	for (i = 0; i < thearray.length; i++)
	{
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
	}
	return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value)
{
	thearray[getarraysize(thearray)] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray)
{
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}

function checkForm(frm)
{
	formErrors = false;
	if (!frm) var frm=document.post;
//	if (document.post.message.value.length<3) {formErrors = "Please enter your message"}
	
	if (formErrors) {alert(formErrors);return false;}
	else
	{
		bbstyle(-1);
		disable_submit(frm);
		return true;
	}
}

function emoticon(text)
{
	text = ' ' + text + ' '
	if (document.post.message.createTextRange && document.post.message.caretPos)
	{
		var caretPos = document.post.message.caretPos
		caretPos.text += caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text
		document.post.message.focus()
	}
	else
	{
		var selStart = document.post.message.selectionStart;
		var selEnd = document.post.message.selectionEnd;

		mozWrap(document.post.message, text, '')
		document.post.message.focus();
		document.post.message.selectionStart = selStart + text.length;
		document.post.message.selectionEnd = selEnd + text.length;
	}
}

function bbfontstyle(bbopen, bbclose)
{
	if (bbopen.match(/=\]$/))
	{
		return
	}
	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text
		if (!theSelection)
		{
			document.post.message.value += bbopen + bbclose
			document.post.message.focus()
			return
		}
		if (bbopen.match(/=-\]$/))
		{
			document.selection.createRange().text = theSelection.replace(/^([^\[]*)(\[[^\[]+\])(.*)\[\/F\]([^\[]*)$/i, "$1$3$4")
		}
		else
		{
			document.selection.createRange().text = bbopen + theSelection + bbclose
		}
		document.selection.createRange().text = bbopen + theSelection + bbclose;
		document.post.message.focus()
		return
	}
	else
	{
		//insert_text(bbopen + bbclose);
		mozWrap(document.post.message, bbopen, bbclose);
		document.post.message.focus()
		return
	}
	storeCaret(document.post.message)
}

function bbstyle(bbnumber)
{
	donotinsert = false;
	theSelection = false;
	bblast = 0;
	document.post.message.focus();

	if (bbnumber == -1)		// Close all open tags
	{
		while (bbcode[0])
		{
			butnumber = arraypop(bbcode)-1
			document.post.message.value += bbtags[butnumber*2 + 1]
			toggle(document.getElementById(BUTTON_DIV_PREFIX+butnumber))
		}
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text	// Get text selection
		
		if (theSelection)
		{
			re = /^(\[[^\[]+\])(.*)(\[\/[^\[]+\])$/i;
			if (theSelection.replace(re, "$1$3")==bbtags[bbnumber*2]+bbtags[bbnumber*2+1])
			{
				// apply a tag twice will remove it
				theSelection = theSelection.replace(re, "$2");
			}
			else
			{
				// Add tags around selection
				theSelection = bbtags[bbnumber*2] + theSelection + bbtags[bbnumber*2+1];
			}
			document.selection.createRange().text = theSelection;
			theSelection = '';
			return;
		}
	}	
	else if (document.post.message.selectionEnd && (document.post.message.selectionEnd - document.post.message.selectionStart > 0))
	{
		mozWrap(document.post.message, bbtags[bbnumber*2], bbtags[bbnumber*2+1]);
		theSelection = '';
		return;
	}
	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++)
	{
		if (bbcode[i] == bbnumber+1)
		{
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert)
	{
		// Close all open tags up to the one just clicked
		while (bbcode[bblast])
		{
			butnumber = arraypop(bbcode)-1;
			insert_text(bbtags[butnumber*2+1]);
			toggle(document.getElementById(BUTTON_DIV_PREFIX+butnumber));
		}
		toggle(document.getElementById(BUTTON_DIV_PREFIX+butnumber));
		return;
	}
	else
	{
		// Open tag
		insert_text(bbtags[bbnumber*2]);
		arraypush(bbcode, bbnumber+1);		// simply bbnumber+1 'coz 0 is an empty value, must avoid it
		toggle(document.getElementById(BUTTON_DIV_PREFIX+bbnumber));
		return;
	}
	storeCaret(document.post.message);
}

function insert_text(text) {
	if (document.post.message.createTextRange && document.post.message.caretPos) {
		var caretPos = document.post.message.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
	} else {
		var selStart = document.post.message.selectionStart;
		var selEnd = document.post.message.selectionEnd;

		mozWrap(document.post.message, text, '')
		document.post.message.selectionStart = selStart + text.length;
		document.post.message.selectionEnd = selEnd + text.length;
	}
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2) 
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

function toggle(el)
{
	el.statusDown = !el.statusDown;
	buttonOut(el);
}

function showHelp(txt) {
	document.getElementById('helpbox').innerHTML = txt;
}

function buttonOver(el)
{
	el.className = 'TB_Button_On';
}

function buttonOut(el)
{
	el.className = el.statusDown ? 'TB_Button_On' : 'TB_Button_Off';
}
function buttonDown(el)
{
	el.className = 'TB_Button_On';
	el.statusDown = true;
}
function buttonUp(el)
{
	el.className = 'TB_Button_Off';
	el.statusDown = false;
}

function select_color()
{
	var hexa = "0123456789ABCDEF"
//	var color = new Array('black', 'white', 'darkred', 'red', 'orange', 'brown', 'yellow', 'green', 'olive', 'cyan', 'blue', 'darkblue', 'indigo', 'violet')
	var html = "<html><head><meta charset='utf-8'><link rel='stylesheet' href='/skin/vn.css'/></head>"

	html += "<body><div style='margin:10'><table width='95%' align='center' cellspacing='1' border='1' style='cursor:default'>"
	for (var i=0;i<6;i++)
	{
		html += "<tr>"
		for (var j=0;j<6;j++)
		{
			for (var k=0;k<6;k++)
			{
				r = hexa.charAt(i*51>>4)+hexa.charAt(i*51 & 15)
				g = hexa.charAt(j*51>>4)+hexa.charAt(j*51 & 15)
				b = hexa.charAt(k*51>>4)+hexa.charAt(k*51 & 15)
				html += "<td style='background-color:#"+r+g+b+"' onMouseover='document.all.test.style.color=this.style.backgroundColor' onclick='document.all.color_id.value=this.style.backgroundColor'>&nbsp;</td>"
			}
		}
		html += "</tr>"
	}
	html += "</table>"
	html += "<br><br><table width='150' align='center'><tr><td id='test' style='font:bold bold 10pt Verdana;text-align:center'>B?n th?y th? nào?</td></tr>"
	html += "<tr><td><input type='text' size='10' style='height:19px' id='color_id'>"
	html += " <input type='button' value='View' onclick='document.all.test.style.color=document.all.color_id.value'>"
	html += " <input type='button' value='OK' onclick='opener.bbfontstyle(\"[color=\"+document.all.color_id.value+\"]\", \"[/color]\");self.close()'></td></tr></table>"
	html += "<div class='gensmall' align='center'>"+J4Ulang.color_guide+"</div>"
	html += "</div></body></html>"
	w = popwin('', 'color')
	w.document.writeln(html)
}

var BUTTON_IMAGE_PREFIX = "buttonImage";
var BUTTON_DIV_PREFIX = "buttonDiv";
function addButton(id, name, toggle)
{
	var DOMdiv = document.createElement('div');
	DOMdiv.className = 'TB_Button_Off';
	DOMdiv.id = BUTTON_DIV_PREFIX+id;
	DOMdiv.txthelp = J4Ulang['help_'+name];
	DOMdiv.act = (toggle=='')? 'bbstyle('+id+')' : toggle;
	DOMdiv.onmouseover = function() {buttonOver(this);showHelp(this.txthelp)};
	DOMdiv.onmouseout = function() {buttonOut(this);}
	DOMdiv.onmousedown = function() {buttonDown(this);}
	DOMdiv.onmouseup = function() {buttonUp(this);eval(this.act);}

	var DOMimg = document.createElement('img');
	DOMimg.src = '/skin/toolbar/button.'+name+'.gif';
	DOMimg.id = BUTTON_IMAGE_PREFIX+id;
	DOMimg.unselectable = 'on';
	newCell = document.getElementById('TB_row').insertCell(-1);

	DOMdiv.appendChild(DOMimg);
	newCell.appendChild(DOMdiv);
}
function addBar(name)
{
	var newCell = document.getElementById('TB_row').insertCell(-1);
	var newImg = document.createElement('img');
	newImg.src = '/skin/toolbar/toolbar.'+name+'.gif';
	newCell.appendChild(newImg);
}

function editorInstantiate()
{
	var DOMa = document.createElement('A');
	DOMa.href = 'javascript:void(0)';
	DOMa.id = 'switchText';
	DOMa.onclick = function() {document.getElementById('tEditor').style.display='block';document.getElementById('switchText').style.display='none';}
	DOMa.className = 'gensmall';
	DOMa.appendChild(document.createTextNode(J4Ulang.show_editor));
	document.getElementById('editor_control').appendChild(DOMa);
}

function editorShow()
{
	html = "<table width='100%' cellspacing='0' cellpadding='0' id='tEditor' style='display:none'><tr><td><table width='100%'><tr><td>";
	html += "<select onChange=\"bbfontstyle('[font=' + this.options[this.selectedIndex].value + ']', '[/font]');this.selectedIndex=0\" onMouseOver='showHelp(J4Ulang.help_font)'>";
	html += "<option style='color:black;background-color: #CCCCCC' value=''>"+J4Ulang.font_+"</option>"
	html += "<option value='Arial'>"+J4Ulang.font_Arial+"</option>"
	html += "<option value='Courier New'>"+J4Ulang.font_Courier+"</option>"
	html += "<option value='Times New Roman'>"+J4Ulang.font_Times+"</option>"
	html += "<option value='Tahoma'>"+J4Ulang.font_Tahoma+"</option>"
	html += "<option value='Verdana'>"+J4Ulang.font_Verdana+"</option>"
	html += "<option value='Georgia'>"+J4Ulang.font_Georgia+"</option>"
	html += "</select>"
	html += "<select onChange=\"bbfontstyle('[size=' + this.options[this.selectedIndex].value + ']', '[/size]');this.selectedIndex=0\" onMouseOver='showHelp(J4Ulang.help_size)'>";
	html += "<option style='color:black;background-color: #CCCCCC' value=''>"+J4Ulang.size_+"</option>"
	html += "<option value='7'>"+J4Ulang.size_tiny+"</option>"
	html += "<option value='9'>"+J4Ulang.size_small+"</option>"
	html += "<option value='12'>"+J4Ulang.size_medium+"</option>"
	html += "<option value='18'>"+J4Ulang.size_big+"</option>"
	html += "<option value='24'>"+J4Ulang.size_large+"</option>"
	html += "</select>"
	html += "<select onChange=\"bbfontstyle('[F=' + this.options[this.selectedIndex].value + ']', '[/F]');this.selectedIndex=0\" onMouseOver='showHelp(J4Ulang.help_format)'>";
	html += "<option style='color:black;background-color: #CCCCCC' value=''>"+J4Ulang.format_+"</option>"
	html += "<option value='-'>"+J4Ulang.format_none+"</option>"
	html += "<option value='wingdings'>"+J4Ulang.format_wingdings+"</option>"
	html += "<option value='symbol'>"+J4Ulang.format_symbol+"</option>"
	html += "<option value='quote'>"+J4Ulang.format_quote+"</option>"
	html += "<option value='bold'>"+J4Ulang.format_bold+"</option>"
	html += "<option value='file'>"+J4Ulang.format_file+"</option>"
	html += "<option value='code'>"+J4Ulang.format_code+"</option>"
	html += "</select>"
	html += "<select onChange=\"bbfontstyle('[P=' + this.options[this.selectedIndex].value + ']'+nl, nl+'[/P]');this.selectedIndex=0\" onMouseOver='showHelp(J4Ulang.help_para)'>";
	html += "<option style='color:black;background-color: #CCCCCC' value=''>"+J4Ulang.para_+"</option>"
	html += "<option value='title'>"+J4Ulang.para_title+"</option>"
	html += "<option value='note'>"+J4Ulang.para_note+"</option>"
	html += "<option value='side'>"+J4Ulang.para_side+"</option>"
	html += "<option value='warn'>"+J4Ulang.para_warn+"</option>"
	html += "<option value='screen'>"+J4Ulang.para_screen+"</option>"
	html += "<option value='center'>"+J4Ulang.para_center+"</option>"
	html += "</select>"
	html += "<select onChange=\"bbfontstyle('[LIST' + this.options[this.selectedIndex].value + ']'+nl+'[*]'+nl+'[*]'+nl+'[*]', nl+'[/LIST]');this.selectedIndex=0\" onMouseOver='showHelp(J4Ulang.help_list)'>";
	html += "<option style='color:black;background-color: #CCCCCC' value=''>"+J4Ulang.list_+"</option>"
	html += "<option value=''>"+J4Ulang.list_normal+"</option>"
	html += "<option value='=1'>"+J4Ulang.list_num+"</option>"
	html += "<option value='=I'>"+J4Ulang.list_roman1+"</option>"
	html += "<option value='=i'>"+J4Ulang.list_roman2+"</option>"
	html += "<option value='=A'>"+J4Ulang.list_abc1+"</option>"
	html += "<option value='=a'>"+J4Ulang.list_abc2+"</option>"
	html += "</select></td></tr></table></td></tr>"

	html += "<tr><td><table class='TB_Toolbar' cellspacing='0' cellpadding='0'><tr id='TB_row'></tr></table></td></tr>"
	html += "<tr><td><table width='100%' cellspacing='0' cellpadding='0'><tr><td><div class='guide' id='helpbox' style='display:nonez;clear:left;height:20px'></div></td></tr></table></td></tr>";
	html += "</table>"

	document.getElementById('editor_control').innerHTML = html

	addBar('start');
	addButton(0, 'bold', '');
	addButton(1, 'italic', '');
	addButton(2, 'underline', '');
//	addButton(22, 'color', 'select_color()');
	addButton(11, 'subscript', '');
	addButton(12, 'superscript', '');
	addBar('separator');
	addButton(3, 'quote', '');
	addButton(4, 'code', '');
	addButton(5, 'html', '');
	addButton(6, 'sql', '');
	addButton(7, 'url', '');
	addBar('separator');
	addButton(13, 'tex', '');
	addButton(8, 'img', '');
	addButton(9, 'flash', '');
	addButton(10, 'media', '');
	addBar('separator');
	addButton(-1, 'closeall', '');
	addBar('end');
}

function Estartup()
{
	if (typeof(J4Ulang)=='undefined' || typeof(J4Ulang.test)=='undefined')
	{
		// lang.js hasn't been loaded
		setTimeout(Estartup, 200);
		return;
	}
	editorShow();
	editorInstantiate();
}

function Editor()
{
	this.instantiate = Estartup;
}

inEditor = 2
