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", "URL", "IMG", "QUOTE", "COLOR", "SIZE", "MEDIA", "CODE", "S", "THUMB"]; //names are just for ease of management
var nameArray = ["B", "I", "U", "URL", "IMG", "QUOTE", "COLOR", "SIZE", "MEDIA", "CODE", "S", "THUMB"]; //names are just for ease of management
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, textarea_id, x, y)
{

	var the_text = document.getElementById(textarea_id);
	var storedHeight = the_text.scrollHeight;
	var storedScrollTop = the_text.scrollTop;

	var _font_color = document.getElementById(textarea_id + "_font_color");
	var _font_size = document.getElementById(textarea_id + "_font_size");
	
	if( tagArray[ arrayPos ] == false )
	{
		if (openTag != "[URL REF=%]*" && openTag != "[IMG]*" && openTag != "[MEDIA]*")
		{		  
			document.getElementById( nameArray[ arrayPos ] + "_button_"+ textarea_id).style.backgroundPosition = x+" -23";
			
		}
		switch(openTag)
		{
			case "[COLOR COLOR=*]":
				insertAtCursor(the_text, openTag.replace("*", _font_color.value ) );
				break;
			
			case "[SIZE SIZE=*]":
				insertAtCursor(the_text, openTag.replace("*", _font_size.value ) );
				break;
			
					
			case "[URL REF=%]*":
				var ans = prompt("URL адрес", "");
				var txt = prompt("Имя ссылки (необязательно)", "");
				if (ans != null && ans != "")
				{
					var link=openTag;
					if (txt != null && txt != "")
					{
						link = link.replace("%", ans);
						link = link.replace("*", txt);
					}
					else {
						link = link.replace("*", ans);
						link = link.replace("REF=%", "");
					}
					insertAtCursor(the_text, link+closeTag );
					tagArray[ arrayPos ] = false;
				}
				break;

			case "[IMG]*":
				var ans = prompt("Адрес картинки", "");
				if (ans != null && ans != "")
				{
					insertAtCursor(the_text, openTag.replace("*", ans)+closeTag );
					tagArray[ arrayPos ] = false;
				}
				break;

			case "[THUMB]*":
					insertAtCursor(the_text, openTag.replace("*", picURL)+closeTag );
					tagArray[ arrayPos ] = false;
				break;			
			
			case "[MEDIA]*":
				var ans = prompt("Код видеоролика", "");
				if (ans != null && ans != "")
				{
					insertAtCursor(the_text, openTag.replace("*", ans)+closeTag );

					tagArray[ arrayPos ] = false;
				}
				break;

			
			case "[QUOTE]":
				insertAtCursor(the_text, openTag.replace("=*", "") );
				break;
			
			default:
				insertAtCursor(the_text, openTag);
		}
		if (openTag != "[URL REF=%]*" && openTag != "[IMG]*" && openTag != "[MEDIA]*")		
			tagArray[ arrayPos ] = true;
		
		
	}
	else
	{
		insertAtCursor(the_text, closeTag);
	//	document.getElementById( nameArray[ arrayPos ] + "_button" ).value = document.getElementById( nameArray[ arrayPos ] + "_button_"+textarea_id ).value.replace("*", "");
	y = y - 23;
		document.getElementById( nameArray[ arrayPos ] + "_button_"+ textarea_id).style.backgroundPosition = x+" 0";
		tagArray[ arrayPos ] = false;
	}
	
	
	if(document.selection) {
//		the_text.scrollHeight = storedHeight;
	}
	else if (the_text.selectionEnd) {
		the_text.scrollTop = storedScrollTop;
	}
	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();
		var storedHeight = myField.scrollTop
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		
		sel = document.selection.createRange();
		sel.text = myValue;
		
		myField.selectionStart = startPos;
		myField.selectionEnd = endPos;
		
//		myField.scrollHeight = storedHeight;
	
	}
	else if( myField.selectionStart || myField.selectionStart == '0' )
	{
		var storedScrollTop = myField.scrollTop;
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;

		myField.value = myField.value.substring(0, startPos) + myValue + " " + myField.value.substring(endPos, myField.value.length);
		myField.selectionStart = startPos + myValue.length;
		myField.selectionEnd = startPos + myValue.length+1;

		myField.scrollTop = storedScrollTop;

	}
	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);
		
	if (open =="[URL TITLE=")
	{
		s2 = s2.replace(/ /g, "_");
	
	}
	txtarea.value = s1 + open + s2 + close + s3;

	startt = s1 + open     ;
	endd   = s1 + open + s2;

	txtarea.selectionStart = startt.length;
	txtarea.selectionEnd   = endd.length;


	return;
}
function addTagSelection(openTag, closeTag, arrayPos, txtarea_id, x, y)
{  

	var txtarea = document.getElementById(txtarea_id);
	var storedHeight = txtarea.scrollHeight;
	var storedScrollTop = txtarea.scrollTop;
	var _font_color = document.getElementById(txtarea_id+"_font_color");
	var _font_size = document.getElementById(txtarea_id+"_font_size");
		
	if( (clientVer >= 4) && is_ie )
	{
	   ///txtarea.focus();
	
	   /*var sel = document.selection;	   
		  var rng = sel.createRange();*/		  
			//rng.colapse;						
      //var sel = document.selection.createRange();
			
			
    txtarea.focus();  
		theSelection = document.selection.createRange().text;    						
		if (theSelection != '')
		{

			switch(openTag)
			{
				
				
				
				
				
				case "[COLOR COLOR=*]":
					document.selection.createRange().text = openTag.replace("*", _font_color.value ) + theSelection + closeTag;
					txtarea.focus();
					
					break;
				
				case "[SIZE SIZE=*]":
					document.selection.createRange().text = openTag.replace("*", _font_size.value ) + theSelection + closeTag;
					txtarea.focus();
					
					break;
																
				
				case "[URL REF=%]*":
					var ans = prompt("URL адресс", "");
					//var txt = prompt("Имя ссылки (необязательно)", "");
					if (ans != null && ans != "")
					{
						var link = "";
						if (theSelection != null && theSelection != "") {
							link = openTag.replace("%", ans);
							link = link.replace("*", theSelection);
							document.selection.createRange().text = link + closeTag;
						}
						txtarea.focus();	
					}
					/*
					document.selection.createRange().text = openTag.replace("*", prompt("URL address", "") ) + theSelection + closeTag;
					txtarea.focus();		*/			
					break;

				case "[IMG]*":
					document.selection.createRange().text = openTag.replace("*", prompt("Адрес картинки", "") ) + theSelection + closeTag;
					txtarea.focus();					
					break;

				case "[MEDIA]*":
					document.selection.createRange().text = openTag.replace("*", prompt("Код видеоролика", "") ) + theSelection + closeTag;
					txtarea.focus();					
					break;

				
				case "[QUOTE]":
					document.selection.createRange().text = openTag + theSelection + closeTag;
					txtarea.focus();					
					break;				
				
				
				
				default:
				  //theSelection.text = openTag + theSelection.text + closeTag
					document.selection.createRange().text = openTag + theSelection + closeTag;
					//theSelection = openTag + theSelection + closeTag;
					txtarea.focus();
					
					break;
			}
			
			//txtarea.scrollTop = storedHeight;
			return;
		}
	}
	else if( txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0) )
	{
		switch(openTag)
		{	
					
			case "[COLOR COLOR=*]":
				mozWrap(txtarea, openTag.replace("*", _font_color.value ), closeTag);
				txtarea.focus();
				
				break;
			
			case "[SIZE SIZE=*]":
				mozWrap(txtarea, openTag.replace("*", _font_size.value), closeTag);
				txtarea.focus();
				
				break;
			
					
			case "[URL REF=%]*":

				var ans = prompt("URL адрес", "");				
				if (ans != null && ans != "")
				{
					var _open = "[URL REF=%]".replace("%", ans);
					var _close = "[/URL]"
				/*
					var link = openTag.replace("*", ans);
					if (txt != null && txt != "")
						link = link.replace("%", txt);
					else
						link = link.replace("TITLE=%", "");
						*/										
					mozWrap(txtarea, _open, _close);
					txtarea.focus();
				}				
				break;


			case "[IMG]*":
				mozWrap(txtarea, openTag.replace("*", prompt("Адрес картинки", "") ), closeTag);
				txtarea.focus();				
				break;

			case "[MEDIA]*":
				mozWrap(txtarea, openTag.replace("*", prompt("Код видеоролика", "") ), closeTag);
				txtarea.focus();				
				break;

			
			case "[QUOTE]":
				mozWrap(txtarea, openTag.replace("*", "" ), closeTag);
				txtarea.focus();
				
				break;

			
			default:
				mozWrap(txtarea, openTag, closeTag);
				txtarea.focus();
				
				break;
		}
		
		txtarea.scrollTop = storedScrollTop;
		return;
	}
	
	addTag(openTag, closeTag, arrayPos, txtarea_id, x, y);
}

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;
	
	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);
}

function moveBG(obj, x, y)
{
  if (obj.style.backgroundPosition != x+"px -23px")
    obj.style.backgroundPosition = x+" "+y;
} 


function printToolbar(textarea_id) {
	document.write ('<div class=editor_toolbar_line1>\n');
	
		
	
	document.write ('		<select class="editorDropDown" id="' + textarea_id + '_font_color" onChange="updateDropValues();">\n');
	document.write ('			<option style="color:black; background-color: #FAFAFA" value="" >По умолчанию</option>\n');
	document.write ('			<option style="color:darkred; background-color: #FAFAFA" value="darkred" >Темно-красный</option>\n');
	document.write ('			<option style="color:red; background-color: #FAFAFA" value="red" >Красный</option>\n');
	document.write ('			<option style="color:orange; background-color: #FAFAFA" value="orange" >Оранжевый</option>\n');
	document.write ('			<option style="color:brown; background-color: #FAFAFA" value="brown" >Коричневый</option>\n');
	document.write ('			<option style="color:yellow; background-color: #FAFAFA" value="yellow" >Желтый</option>\n');
	document.write ('			<option style="color:green; background-color: #FAFAFA" value="green" >Зеленый</option>\n');
	document.write ('			<option style="color:olive; background-color: #FAFAFA" value="olive" >Оливковый</option>\n');
	document.write ('			<option style="color:cyan; background-color: #FAFAFA" value="cyan" >Голубой</option>\n');
	document.write ('			<option style="color:blue; background-color: #FAFAFA" value="blue" >Синий</option>\n');
	document.write ('			<option style="color:darkblue; background-color: #FAFAFA" value="darkblue" >Темно-синий</option>\n');
	document.write ('			<option style="color:indigo; background-color: #FAFAFA" value="indigo" >Индиго</option>\n');
	document.write ('			<option style="color:violet; background-color: #FAFAFA" value="violet" >Фиолетовый</option>\n');
	document.write ('			<option style="color:white; background-color: #FAFAFA" value="white" >Белый</option>\n');
	document.write ('			<option style="color:black; background-color: #FAFAFA" value="black" >Черный</option>\n');
	document.write ('		</select>\n');
	document.write ('\n');
	
document.write ('	<input type="button" title="Цвет текста" class="editorBtn" onMouseOver="moveBG(this,0,-46)" onMouseOut="moveBG(this,0,0)" style="margin-left:5px;margin-right:5px;background-position: 0 0;\" onclick="addTagSelection(\'[COLOR COLOR=*]\', \'[/COLOR]\', 6, \'' + textarea_id + '\',0, -46);" id="COLOR_button_' + textarea_id + '" /> \n');
	
	
 
	
  	document.write ('		<select class="editorDropDown"  id="' + textarea_id + '_font_size" onChange="updateDropValues();">\n');
	document.write ('			<option class="SIZE_small" value="SMALL">Small</option>\n');
	document.write ('			<option class="SIZE_normal" selected="true" value="NORMAL">Normal</option>\n');
	document.write ('			<option class="SIZE_large" value="LARGE">Large</option>\n');
	document.write ('		</select>\n');
	
 
	document.write ('	<input type="button" title="Размер текста" class="editorBtn" style="margin-left:5px;margin-right:5px;background-position: -23 0px;" onMouseOver="moveBG(this,-23,-46)" onMouseOut="moveBG(this,-23,0)" onclick="addTagSelection(\'[SIZE SIZE=*]\', \'[/SIZE]\', 7, \'' + textarea_id + '\', -23, -46);" id="SIZE_button_' + textarea_id + '" /> \n');
	
	document.write ('	<input type="button" title="Жирный" class="editorBtn" onMouseOver="moveBG(this,-46,-46)" onMouseOut="moveBG(this,-46,0)" style="margin-left:5px;background-position: -46px 0px;" onclick="addTagSelection(\'[B]\', \'[/B]\', 0, \'' + textarea_id + '\', -46, -46);" id="B_button_' + textarea_id + '"> \n');
  	
	document.write ('	<input type="button" title="Курсив" class="editorBtn" onMouseOver="moveBG(this,-69,-46)" onMouseOut="moveBG(this,-69,0)" style="background-position: -69px 0px;" onclick="addTagSelection(\'[I]\', \'[/I]\', 1, \'' + textarea_id + '\', -69, -46);" id="I_button_' + textarea_id + '"/> \n');
	
	document.write ('	<input type="button" title="Подчеркнутый" class="editorBtn" onMouseOver="moveBG(this,-92,-46)" onMouseOut="moveBG(this,-92,0)" style="background-position: -92px 0px;" onclick="addTagSelection(\'[U]\', \'[/U]\', 2, \'' + textarea_id + '\', -92, -46);" id="U_button_' + textarea_id + '"/> \n');

	document.write ('	<input type="button" title="Перечеркнутый" class="editorBtn" onMouseOver="moveBG(this,-230,-46)" onMouseOut="moveBG(this,-230,0)" style="background-position: -230px 0px;" onclick="addTagSelection(\'[S]\', \'[/S]\', 10, \'' + textarea_id + '\', -230, -46);" id="S_button_' + textarea_id + '"/> \n');
  	
	document.write ('	<input type="button" title="Вставить ссылку" class="editorBtn" onMouseOver="moveBG(this,-115,-46)" onMouseOut="moveBG(this,-115,0)" style="background-position: -115px 0px;" onclick="addTagSelection(\'[URL REF=%]*\', \'[/URL]\', 3, \'' + textarea_id + '\', -115, -46);" id="URL_button_' + textarea_id + '"/> \n');  	

	document.write ('	<input type="button" title="Вставить удаленную картинку" class="editorBtn" onMouseOver="moveBG(this,-299,-46)" onMouseOut="moveBG(this,-299,0)" style="background-position: -299px 0px;" onclick="addTagSelection(\'[IMG]*\', \'[/IMG]\', 4, \'' + textarea_id + '\', -299, -46);" id="IMG_button_' + textarea_id + '"/> \n');  	

	document.write ('	<input type="button" title="Вставить закаченную с комьютера картинку" class="editorBtn" onMouseOver="moveBG(this,-138,-46)" onMouseOut="moveBG(this,-138,0)" style="background-position: -138px 0px;" onclick="insertUploadedPic(\'' + textarea_id + '\')" id="IMG_button_' + textarea_id + '" id="IMG_button_' + textarea_id + '"/> \n');  	

	document.write ('	<input type="button" title="Вставить уменьшенную картинку с линком на оригинальную (уменьшается автоматически)" class="editorBtn" onMouseOver="moveBG(this,-322,-46)" onMouseOut="moveBG(this,-322,0)" style="background-position: -322px 0px;" onclick="insertThumb(\'' + textarea_id + '\')" id="THUMB_button_' + textarea_id + '"/> \n');  	

	document.write ('	<input type="button" title="Вставить цитату" class="editorBtn" onMouseOver="moveBG(this,-161,-46)" onMouseOut="moveBG(this,-161,0)" style="background-position: -161px 0px;" onclick="addTagSelection(\'[QUOTE]\', \'[/QUOTE]\', 5, \'' + textarea_id + '\', -161, -46);" id="QUOTE_button_' + textarea_id + '"/> \n');

	document.write ('	<input type="button" title="Вставить Macromedia Flash видео" class="editorBtn" onMouseOver="moveBG(this,-184,-46)" onMouseOut="moveBG(this,-184,0)" style="background-position: -184px 0px;" onclick="addTagSelection(\'[MEDIA]*\', \'[/MEDIA]\', 8, \'' + textarea_id + '\', -184, -46);" id="MEDIA_button_' + textarea_id + '"/> \n');

	document.write ('	<input type="button" title="Вставить код" class="editorBtn" onMouseOver="moveBG(this,-207,-46)" onMouseOut="moveBG(this,-207,0)" style="background-position: -207px 0px;" onclick="addTagSelection(\'[CODE]\', \'[/CODE]\', 9, \'' + textarea_id + '\', -207, -46);" id="CODE_button_' + textarea_id + '"> \n');  		

	document.write ('\n');

	document.write ('	</div>\n<br>');
}


function insertThumb(textarea_id) {
	showUploadDialog("THUMB", textarea_id);
}

function insertUploadedPic(textarea_id) {
	showUploadDialog("IMG", textarea_id);
}

function showUploadDialog(tag, textarea_id) {
	document.getElementById('uploadIMGDiv'+textarea_id).style.display="block";

	document.getElementById('uploadIMGText' + textarea_id).src='fileUpload.php?id=' + textarea_id + '&div=uploadIMGDiv' + textarea_id + '&tag=' + tag;
}