var theSelection = false;

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 tagArray = ["B", "I", "U", "COLOR", "SIZE", "ALIGN", "FONT", "CENTER", "CODE", "PHP", "EMAIL", "URL", "IMG", "QUOTE", "LIST"]; //names are just for ease of management
var nameArray = ["B", "I", "U", "COLOR", "SIZE", "ALIGN", "FONT", "CENTER", "CODE", "PHP", "EMAIL", "URL", "IMG", "QUOTE", "LIST"]; 
var fontProps = ["#000000", "Arial, Helvetica, sans-serif", "14px", "left"];

for(var i=0; i < tagArray.length; i++)
{
	tagArray[i] = false;
}

var currentTimer = null;
var canGo = true;

function selectAll(field)
{
	  var field = document.getElementById(field);
	  field.focus();
	  field.select();
}

function addTag(openTag, closeTag, arrayPos)
{
	var the_text = document.getElementById("the_text");
	var storedHeight = the_text.scrollHeight;
	
	if( tagArray[ arrayPos ] == false )
	{
		document.getElementById( nameArray[ arrayPos ] + "_button" ).innerHTML += "*";
		
		switch(openTag)
		{
			case "[color=*]":
				insertAtCursor(the_text, openTag.replace("*", fontProps[0] ) );
				break;
			
			case "[size=*]":
				insertAtCursor(the_text, openTag.replace("*", fontProps[2] ) );
				break;
			
			case "[align=*]":
				insertAtCursor(the_text, openTag.replace("*", fontProps[3] ) );
				break;
			
			case "[font=*]":
				insertAtCursor(the_text, openTag.replace("*", fontProps[1] ) );
				break;
			
			case "[url=*]":
				var ans = prompt("URL address (Cancel if hyperlink text is the same as URL)", "");
				if( ans == null )
				{
					insertAtCursor(the_text, openTag.replace("=*", "") );
				}
				else
				{
					insertAtCursor(the_text, openTag.replace("*", ans) );
				}
				break;
			
			case "[quote=*]":
				var ans = prompt("Name of quoted (Cancel if none)", "");
				if( ans == null )
				{
					insertAtCursor(the_text, openTag.replace("=*", "") );
				}
				else
				{
					insertAtCursor(the_text, openTag.replace("*", '"' + ans + '"') );
				}
				break;
			
			default:
				insertAtCursor(the_text, openTag);
		}
		
		tagArray[ arrayPos ] = true;
	}
	else
	{
		insertAtCursor(the_text, closeTag);
		document.getElementById( nameArray[ arrayPos ] + "_button" ).innerHTML = document.getElementById( nameArray[ arrayPos ] + "_button" ).innerHTML.replace("*", "");
		tagArray[ arrayPos ] = false;
	}
	
	updateDiv();
	the_text.scrollTop = storedHeight;
	the_text.focus();
}



//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// function insertAtCursor written for PhpMyAdmin, which was released under the GPL v2.
// Therefore, this function is subject to the terms of the GPL v2.
// http://www.phpmyadmin.net/documentation/LICENSE
function insertAtCursor(myField, myValue)
{
	if( document.selection )
	{
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	else if( myField.selectionStart || myField.selectionStart == '0' )
	{
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
	}
	else
	{
		myField.value += myValue;
	}
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

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;
}

function addTagSelection(openTag, closeTag, arrayPos)
{
	var txtarea = document.getElementById("the_text");
	var storedHeight = txtarea.scrollHeight;
	
	if( (clientVer >= 4) && is_ie )
	{
		theSelection = document.selection.createRange().text;
		if (theSelection != '')
		{
			switch(openTag)
			{
				case "[color=*]":
					document.selection.createRange().text = openTag.replace("*", fontProps[0] ) + theSelection + closeTag;
					txtarea.focus();
					updateDiv();
					break;
				
				case "[size=*]":
					document.selection.createRange().text = openTag.replace("*", fontProps[2] ) + theSelection + closeTag;
					txtarea.focus();
					updateDiv();
					break;
				
				case "[align=*]":
					document.selection.createRange().text = openTag.replace("*", fontProps[3] ) + theSelection + closeTag;
					txtarea.focus();
					updateDiv();
					break;
				
				case "[font=*]":
					document.selection.createRange().text = openTag.replace("*", fontProps[1] ) + theSelection + closeTag;
					txtarea.focus();
					updateDiv();
					break;
				
				case "[url=*]":
					document.selection.createRange().text = openTag.replace("*", prompt("URL address (Cancel if hyperlink text is the same as URL)", "") ) + theSelection + closeTag;
					txtarea.focus();
					updateDiv();
					break;
				
				case "[quote=*]":
					document.selection.createRange().text = openTag.replace("*", prompt("Name of quoted (Cancel if none)", "") ) + theSelection + closeTag;
					txtarea.focus();
					updateDiv();
					break;
				
				default:
					document.selection.createRange().text = openTag + theSelection + closeTag;
					txtarea.focus();
					updateDiv();
					break;
			}
			
			txtarea.scrollTop = storedHeight;
			return;
		}
	}
	else if( txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0) )
	{
		switch(openTag)
		{
			case "[color=*]":
				mozWrap(txtarea, openTag.replace("*", fontProps[0] ), closeTag);
				txtarea.focus();
				updateDiv();
				break;
			
			case "[size=*]":
				mozWrap(txtarea, openTag.replace("*", fontProps[2] ), closeTag);
				txtarea.focus();
				updateDiv();
				break;
			
			case "[align=*]":
				mozWrap(txtarea, openTag.replace("*", fontProps[3] ), closeTag);
				txtarea.focus();
				updateDiv();
				break;
			
			case "[font=*]":
				mozWrap(txtarea, openTag.replace("*", fontProps[1] ), closeTag);
				txtarea.focus();
				updateDiv();
				break;
			
			case "[url=*]":
				mozWrap(txtarea, openTag.replace("*", prompt("URL address (Cancel if hyperlink text is the same as URL)", "") ), closeTag);
				txtarea.focus();
				updateDiv();
				break;
			
			case "[quote=*]":
				mozWrap(txtarea, openTag.replace("*", prompt("Name of quoted (Cancel if none)", "") ), closeTag);
				txtarea.focus();
				updateDiv();
				break;
			
			default:
				mozWrap(txtarea, openTag, closeTag);
				txtarea.focus();
				updateDiv();
				break;
		}
		
		txtarea.scrollTop = storedHeight;
		return;
	}
	
	addTag(openTag, closeTag, arrayPos);
}

function updateDiv()
{
	if( canGo == true )
	{
		var the_div = document.getElementById("the_div");
		var the_text = document.getElementById("the_text");
		var saveNow = document.getElementById("saveNow");
	
		saveNow.innerHTML = "<i>Saved</i>";
		saveNow.removeAttribute("href");
		
		try
		{
			var req = new XMLHttpRequest();
		}
		catch(e)
		{
			var req = new ActiveXObject("Microsoft.XMLHTTP"); //IE sucks, I dont know why i'm even adding anything ActiveX to my code, bleh...
		}
		
		text = the_text.value.replace(/&/g, "::S018_AMP::");
		
		req.open("POST", "bbEngine.php", false);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send("bbcode=" + escape(text) );
		the_div.innerHTML = req.responseText;
		
		canGo = false;
	}
	else
	{
		var saveNow = document.getElementById("saveNow");
		saveNow.innerHTML = "Save Now";
		saveNow.setAttribute("href", "javascript:saveNow();");
		
		
		currentTimer = setTimeout(setCanGo, 1500);
	}
}

function updateDropValues()
{
	var Fcolor = document.getElementById("font_color");
	var Fface = document.getElementById("font_face");
	var Fsize = document.getElementById("font_size");
	var Falign = document.getElementById("font_align");
	
	Fcolor.style.color = Fface.style.color = Fsize.style.color = Falign.style.color = Fcolor.value;
	Fcolor.style.fontFamily = Fface.style.fontFamily = Fsize.style.fontFamily = Falign.style.fontFamily = Fface.value;
	Fcolor.style.textAlign = Fface.style.textAlign = Fsize.style.textAlign = Falign.style.textAlign = Falign.value;
	
	fontProps = [Fcolor.value, Fface.value, Fsize.value, Falign.value];
}

function saveNow()
{
	var the_text = document.getElementById("the_text");
	var saveNow = document.getElementById("saveNow");
	
	saveNow.innerHTML = "<i>Saved</i>";
	saveNow.removeAttribute("href");
	
	setCanGo();
}

function setCanGo()
{
	canGo = true;
	updateDiv();
	currentTimer = null;
}

function AFR_button()
{
	selectAll('the_text');
	addTagSelection('[color=*]', '[/color]', 3);
	selectAll('the_text');
	addTagSelection('[size=*]', '[/size]', 4);
	selectAll('the_text');
	addTagSelection('[align=*]', '[/align]', 5);
	selectAll('the_text');
	addTagSelection('[font=*]', '[/font]', 6);
}