/**
 * @author JamesDS
 * 
 * Lots of code for the text area functionality has been taken
 * from phpBB
 */
var textarea; // textarea object
var t; // timeout variable
var ival; // interval variable
var previous_content = ""; // stores content of text area
var auto_update; // checkbox, ticked for automatic ajax updates
var char_count; // label that displays character count

function bb_code_editor_init() {
	// assign form elements to variables for later use
	textarea = document.getElementById('BBCodeEditor');
	auto_update = document.getElementById('auto_update');
	char_count = document.getElementById('char_count');
	
	// watch textarea for changes when focused
	textarea.onfocus = function() {
		ival = setInterval("check_textarea_update()", 200);
	}
	
	// stop watching for changes when not focused
	textarea.onblur = function(){
		clearInterval(ival);
	}
	
	check_textarea_update();
	
	// Calls phpBB init code
	initInsertions();
}

// Called when the textarea is updated
function check_textarea_update() {
	var len = textarea.value.length;
	check_length_within_range();
	update_char_count();
	
	// sets timeout if content has changed
	if(previous_content != textarea.value && auto_update.checked)
		set_timeout_for_update();
}

// Updates label with character count
function update_char_count() {
	var len = textarea.value.length;
	var counter_text = "Characters left: " + (MAX_CHARS - len);
	
	char_count.innerHTML = counter_text;
}

// Truncates textarea content if maximum length is exceeded
function check_length_within_range() {
	if(textarea.value.length > MAX_CHARS)
		textarea.value = textarea.value.substring(0, MAX_CHARS);
}

// Sets a new timeout for the Ajax request 
function set_timeout_for_update() {
	clearTimeout(t);
	t = setTimeout("make_ajax_request()", 1500);
	previous_content = textarea.value;
}

// Sets up the XMLHTTP Object and sends the textarea text to the server, then
// processes the data once it is received
// The request is handled by the 'preview' action in the replies controller
// Most code taken from w3schools.com
function make_ajax_request() {
	// Double check length is within limits
	if(textarea.value.length > MAX_CHARS)
		return false;
	
    var xmlhttp;
	
	// Shows spinning status icon
	toggle_spinning_status_icon(true);
    
    // Fetches XMLHTTP Object
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        update_live_preview_with("<b>Sorry, your browser does not support this feature</b>");
    }

    // Sends Ajax request
    var param = "text=" + encodeURIComponent(textarea.value);
    
    xmlhttp.open("POST", "/ajax_convert_bbcode_to_html", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", param.length);
    xmlhttp.setRequestHeader("Connection", "close");
    
    xmlhttp.send(param);
    
    // Updates live preview with HTML code received from server
    xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState == 4) { // If received server response 
            update_live_preview_with(xmlhttp.responseText);
			toggle_spinning_status_icon(false);
        }
    }
}

// Shows or hides the spinning status indicator
function toggle_spinning_status_icon(show) {
	var icon_style = document.getElementById("ajax_status_indicator").style;
	
	if(show) {
		icon_style.display = "";
	} else {
		icon_style.display = "none";
	}
}

// Updates HTML code in live preview div
function update_live_preview_with(html) {
    document.getElementById("preview").innerHTML = html;
}

/***********************************************************
 * The following code was taken from phpBB (www.phpbb.com) *
 ***********************************************************/

// Define the bbCode tags
var bbcode = new Array();
var bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]','[flash=]', '[/flash]','[size=]','[/size]');

/**
* bbCode control by subBlue design [ www.subBlue.com ]
* Includes unixsafe colour palette selector by SHS`
*/

// Startup variables
var imageTag = false;
var theSelection = false;

// 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_win = ((clientPC.indexOf('win') != -1) || (clientPC.indexOf('16bit') != -1));

var baseHeight;

/**
* Shows the help messages in the helpline window
*/
function helpline(help)
{
	document.forms[form_name].helpbox.value = help_line[help];
}

/**
* Fix a bug involving the TextRange object. From
* http://www.frostjedi.com/terra/scripts/demo/caretBug.html
*/ 
function initInsertions() 
{
	if (is_ie && typeof(baseHeight) != 'number')
	{
		textarea.focus();
		baseHeight = doc.selection.createRange().duplicate().boundingHeight;
	}
}

// Shows/hides colour pallete when 'Font Colour' button is clicked
function change_palette()
{
	e = document.getElementById('colour_palette');
	
	if (e.style.display == 'block')
	{
		e.style.display = 'none';
		document.getElementById('bbpalette').value = 'Font colour';
	}
	else
	{
		e.style.display = 'block';
		document.getElementById('bbpalette').value = 'Hide font colour';
	}
}

/**
* bbstyle
*/
function bbstyle(bbnumber)
{	
	if (bbnumber != -1)
	{
		bbfontstyle(bbtags[bbnumber], bbtags[bbnumber+1]);
	} 
	else 
	{
		insert_text('[*]');
		textarea.focus();
	}
}

/**
* Apply bbcodes
*/
function bbfontstyle(bbopen, bbclose)
{
	theSelection = false;

	textarea.focus();

	if ((clientVer >= 4) && is_ie && is_win)
	{
		// Get text selection
		theSelection = document.selection.createRange().text;

		if (theSelection)
		{
			// Add tags around selection
			document.selection.createRange().text = bbopen + theSelection + bbclose;
			textarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (textarea.selectionEnd && (textarea.selectionEnd - textarea.selectionStart > 0))
	{
		mozWrap(textarea, bbopen, bbclose);
		textarea.focus();
		theSelection = '';
		return;
	}
	
	//The new position for the cursor after adding the bbcode
	var caret_pos = getCaretPosition(textarea).start;
	var new_pos = caret_pos + bbopen.length;		

	// Open tag
	insert_text(bbopen + bbclose);

	// Center the cursor when we don't have a selection
	// Gecko and proper browsers
	if (!isNaN(textarea.selectionStart))
	{
		textarea.selectionStart = new_pos;
		textarea.selectionEnd = new_pos;
	}	
	// IE
	else if (document.selection)
	{
		var range = textarea.createTextRange(); 
		range.move("character", new_pos); 
		range.select();
		storeCaret(textarea);
	}

	textarea.focus();
	
	return;
}

/**
* Insert text at position
*/
function insert_text(text, spaces, popup)
{
	if (spaces) 
	{
		text = ' ' + text + ' ';
	}
	
	if (!isNaN(textarea.selectionStart))
	{
		var sel_start = textarea.selectionStart;
		var sel_end = textarea.selectionEnd;

		mozWrap(textarea, text, '')
		textarea.selectionStart = sel_start + text.length;
		textarea.selectionEnd = sel_end + text.length;
	}
	else if (textarea.createTextRange && textarea.caretPos)
	{
		if (baseHeight != textarea.caretPos.boundingHeight) 
		{
			textarea.focus();
			storeCaret(textarea);
		}

		var caret_pos = textarea.caretPos;
		caret_pos.text = caret_pos.text.charAt(caret_pos.text.length - 1) == ' ' ? caret_pos.text + text + ' ' : caret_pos.text + text;
	}
	else
	{
		textarea.value = textarea.value + text;
	}
	if (!popup) 
	{
		textarea.focus();
	}
	
}

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

	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;
	txtarea.selectionStart = selEnd + open.length + close.length;
	txtarea.selectionEnd = txtarea.selectionStart;
	txtarea.focus();
	txtarea.scrollTop = scrollTop;

	return;
}

/**
* Insert at Caret 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();
	}
}

/**
* Color pallette
*/
function colorPalette(dir, width, height)
{
	var r = 0, g = 0, b = 0;
	var numberList = new Array(6);
	var color = '';

	numberList[0] = '00';
	numberList[1] = '40';
	numberList[2] = '80';
	numberList[3] = 'BF';
	numberList[4] = 'FF';

	document.writeln('<table class="font-colour-palette" cellspacing="1" cellpadding="0" border="0">');

	for (r = 0; r < 5; r++)
	{
		if (dir == 'h')
		{
			document.writeln('<tr>');
		}

		for (g = 0; g < 5; g++)
		{
			if (dir == 'v')
			{
				document.writeln('<tr>');
			}
			
			for (b = 0; b < 5; b++)
			{
				color = String(numberList[r]) + String(numberList[g]) + String(numberList[b]);
				document.write('<td style="width: ' + width + 'px; height: ' + height + 'px; background-color: #' + color + ';">');
				document.write('<a href="#" onclick="bbfontstyle(\'[color=#' + color + ']\', \'[/color]\'); return false;"><img src="/images/forum_bb_spacer.gif" width="' + width + '" height="' + height + '" alt="#' + color + '" title="#' + color + '" /></a>');
				document.writeln('</td>');
			}

			if (dir == 'v')
			{
				document.writeln('</tr>');
			}
		}

		if (dir == 'h')
		{
			document.writeln('</tr>');
		}
	}
	document.writeln('</table>');
}


/**
* Caret Position object
*/
function caretPosition()
{
	var start = null;
	var end = null;
}


/**
* Get the caret position in an textarea
*/
function getCaretPosition(txtarea)
{
	var caretPos = new caretPosition();
	
	// simple Gecko/Opera way
	if(txtarea.selectionStart || txtarea.selectionStart == 0)
	{
		caretPos.start = txtarea.selectionStart;
		caretPos.end = txtarea.selectionEnd;
	}
	// dirty and slow IE way
	else if(document.selection)
	{
	
		// get current selection
		var range = document.selection.createRange();

		// a new selection of the whole textarea
		var range_all = document.body.createTextRange();
		range_all.moveToElementText(txtarea);
		
		// calculate selection start point by moving beginning of range_all to beginning of range
		var sel_start;
		for (sel_start = 0; range_all.compareEndPoints('StartToStart', range) < 0; sel_start++)
		{		
			range_all.moveStart('character', 1);
		}
	
		txtarea.sel_start = sel_start;
	
		// we ignore the end value for IE, this is already dirty enough and we don't need it
		caretPos.start = txtarea.sel_start;
		caretPos.end = txtarea.sel_start;			
	}

	return caretPos;
}