var b_open = 0;
var i_open = 0;
var u_open = 0;
var s_open = 0;
var q_open = 0;
var code_open = 0;

var text_enter_url      = "Введите полный адрес (URL)";
var text_enter_url_name = "Введите название сайта";
var text_enter_image    = "Введите полный адрес (URL) изображения";
var	text_enter_image_alt = "Введите подпись к изображению";
var list_prompt         = "Введите пункт списка. Нажмите 'Отмена' завершения списка";
var error_no_url   = "Вы должны ввести адрес (URL)";
var error_no_title = "Вы должны ввести название";

var help_bold        = "Жирный текст [b]текст[/b] (alt + b)";
var help_italic      = "Наклонный текст [i]текст[/i] (alt + i)";
var help_under       = "Подчеркнутый текст [u]текст[/u] (alt + u)";
var help_strike      = "Зачеркнутый текст [s]текст[/s] (alt + s)";
var help_font        = "Выбор типа шрифта";
var help_color       = "Выбор цвета шрифта";
var help_close       = "Закрытие всех открытых тегов";
var help_url         = "Ввод гиперссылки [a http://url]Название сайта[/a] (alt + h)";
var help_img         = "Подключение изображения [img=\"http://image_url\" alt=\"картинка\"] (alt + g)";
var help_quote       = "Ввод цитаты [q]текст[/q] (alt + q)";
var help_list        = "Создать список (alt + l)";
var help_code        = "Ввод кода [code]код[/code] (alt + p)";
var help_click_close = "Нажмите на кнопку для закрытия";
var help_translit    = "Перекодировка транслита / латиницы (alt + t)";
var help_changelayout= "Исправление раскладки клавиатуры ghbdtn → привет (alt + r)";
var help_smile			 = "Смайлики, улыбочки, ;-)"

var bbtags = new Array();

var myAgent   = navigator.userAgent.toLowerCase();
var myVersion = parseInt(navigator.appVersion, 10);

var is_ie  = ((myAgent.indexOf("msie") != -1)  && (myAgent.indexOf("opera") == -1));
var is_nav = ((myAgent.indexOf('mozilla')!=-1) && (myAgent.indexOf('spoofer')==-1)
					&& (myAgent.indexOf('compatible') == -1) && (myAgent.indexOf('opera')==-1)
					&& (myAgent.indexOf('webtv') ==-1)       && (myAgent.indexOf('hotjava')==-1));

var is_win = ((myAgent.indexOf("win")!=-1) || (myAgent.indexOf("16bit")!=-1));
var is_opera = (myAgent.indexOf('opera') != -1);
var ua_vers = parseInt(navigator.appVersion);
var ie_range_cache = '';


var edtForm;
var edtContent;

var selectionGlobal;


jQuery(document).ready(function($) {
	$("#save_btn").removeAttr("disabled");
});


function quoteMessageEx(theAuthor, intID) {
	var selection;
	if (document.getSelection)
	{
		selection = String(document.getSelection());
		selection = selection.replace(/\r\n\r\n/gi, "_newstringhere_");
		selection = selection.replace(/\r\n/gi, " ");
		selection = selection.replace(/  /gi, "");
		selection = selection.replace(/_newstringhere_/gi, "\r\n\r\n");
	}
	else
	{
		selection = document.selection.createRange().text;
	}

	if (selection!="")
	{
		doInsert("[q="+theAuthor+"]"+selection+"[/q]\n", "", false);
	}
	else
	{
		if (intID!="")
		{
			var oComment = document.getElementById('comment-text-' + intID);
			if (oComment && oComment.innerText) selection = oComment.innerText;
//			edtContent.value += "[q="+theAuthor+"]"+selection+"[/q]\n";
			doInsert("[q=" + theAuthor + "]" + selection + "[/q]\n", "", false);
		}
	}
}

function quoteMessageEx2(theAuthor, content) {
	doInsert("[q=" + theAuthor + "]" + content + "[/q]\n", "", false);
}

function storeCaret(textEl)
{
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}


function show_hints(msg) {
	document.getElementById('helpbox').innerText =  eval( "help_" + msg );
}


// Insert simple tags: B, I, U, CODE, QUOTE
function simpletag(thetag)
{
	var tagOpen = eval(thetag + "_open");

	if (tagOpen == 0)
	{
		if (doInsert("[" + thetag + "]", "[/" + thetag + "]", true))
		{
			eval(thetag + "_open = 1");
			// Change the button status
			eval("edtForm." + thetag + ".value += '*'");

			pushstack(bbtags, thetag);
			cstat();
			show_hints('click_close');
		}
	}
	else
	{
		// Find the last occurance of the opened tag
		lastindex = 0;

		for (i = 0 ; i < bbtags.length; i++ )
		{
			if ( bbtags[i] == thetag )
			{
				lastindex = i;
			}
		}

		// Close all tags opened up to that tag was opened
		while (bbtags[lastindex])
		{
			tagRemove = popstack(bbtags);
			doInsert("[/" + tagRemove + "]", "", false);

			// Change the button status
			eval("edtForm." + tagRemove + ".value = ' " + tagRemove + " '");
			eval(tagRemove + "_open = 0");
		}

		cstat();
	}
}

// Insert font tag
function alterfont(theval, thetag)
{
	if (theval == 0)
		return;

	if (doInsert("[" + thetag + "=" + theval + "]", "[/" + thetag + "]", true))
		pushstack(bbtags, thetag);

	edtForm.ffont.selectedIndex  = 0;
	edtForm.fcolor.selectedIndex = 0;
}


// Insert url tag
function tag_url()
{
	if (isSelection()) {
		// Do we have ranged text? Yes, just ask for the URL and wrap

		//hs_prompt() function resets the selection positions in textarea html elements.
		//Therefore we need to remember the selection position of textarea html element
		selectionGlobal = get_selection('content');
		hs_prompt(url_tag_hs_prompt_cb1, "Введите ссылку", null, "http://");
		//Return from function immediately after calling the hs_prompt() function.
		//You will get the answer from hs_prompt() in callback function
	}
	else {
		selectionGlobal = get_selection('content');
		hs_prompt(url_tag_hs_prompt_cb2, "Введите ссылку и название", "URL:", "http://", "Название:", "");
	}
}

function url_tag_hs_prompt_cb1(result) {
	set_selection('content', selectionGlobal);
	if (result == null) {
		return;
	}
	var enterURL;
	enterURL = result.value1;

	if (!enterURL) {
		return;
	}
	doInsert("[url=" + enterURL + "]", "[/url]", false);
}

function url_tag_hs_prompt_cb2(result) {
	set_selection('content', selectionGlobal);
	if (result == null) {
		return;
	}
	var enterURL, enterTITLE;
	enterURL = result.value1;
	enterTITLE = result.value2;

	if (!enterURL) {
		return;
	}
	if (!enterTITLE) {
		return;
	}
	doInsert("[url=" + enterURL + "]" + enterTITLE + "[/url]", false);
}



// Insert image tag
function tag_image()
{
	selectionGlobal = get_selection('content');
	hs_prompt(image_tag_hs_prompt_cb, "Введите ссылку на картинку", null, "http://");
}

function image_tag_hs_prompt_cb(result) {
	set_selection('content', selectionGlobal);
	if (result == null) {
		return;
	}
	var enterURL;
	enterURL = result.value1;
	var enterALT = "Изображение";
	if (!enterURL) {
		return;
	}
	doInsert("[img=\"" + enterURL + "\" alt=\"" + enterALT + "\" vspace=\"3\" hspace=\"8\"]", "", false);
}




function tag_list() {
	selectionGlobal = get_selection('content');
	tag_list2({ value1: "[list]", value2: null }, "flag");
}

function tag_list2(result, flag) {
	set_selection('content', selectionGlobal);
	var listvalue;
	if (result == null) {
		listvalue = null;
	}
	else {
		listvalue = result.value1;
	}
	if ((listvalue != "") && (listvalue != null)) {
		if (flag != null) {
			if (is_opera) { doInsert("\r\n" + listvalue, ""); } else { doInsert("\n" + listvalue, ""); }
		}
		else //write list items right to the textarea so she can see what items she alreay entered to the list
		{
			if (is_opera) { doInsert("\r\n" + "[*]" + listvalue, ""); } else { doInsert("\n" + "[*]" + listvalue, ""); }
		}
		selectionGlobal = get_selection('content');
		hs_prompt(tag_list2, "Введите пункт списка. Для завершения списка, нажмите \"отмена\" или оставьте очередное поле пустым", null, null);
	}
	else {
		if (is_opera) { doInsert("\r\n" + "[/list]\r\n", ""); } else { doInsert("\n" + "[/list]\n", ""); }
	}
}





//--------------------------------------------
// GENERAL INSERT FUNCTION
//--------------------------------------------

//--------------------------------------------
// Проверят выделен ли текст
//--------------------------------------------
function isSelection()
{
	var has_range = false;
	var postfieldobj = document.getElementById('content');

	// It's IE!
	if ((myVersion >= 4) && is_ie && is_win)
	{
		var sel = document.selection;
		var rng = sel.createRange();
		rng.colapse;

		if ( (sel.type == "Text" || sel.type == "None") && rng != null )
		{
			if ( rng.text.length > 0)
			{
				has_range = true;
			}
		}
	}
	// It's MOZZY!
	else if (postfieldobj.selectionEnd != null)
	{
		var ss = postfieldobj.selectionStart;
		var st = postfieldobj.scrollTop;
		var es = postfieldobj.selectionEnd;

		if (es <= 2)
		{
			es = postfieldobj.textLength;
		}

		var start  = (postfieldobj.value).substring(0, ss);
		var middle = (postfieldobj.value).substring(ss, es);
		var end    = (postfieldobj.value).substring(es, postfieldobj.textLength);

		// text range?
		if (postfieldobj.selectionEnd - postfieldobj.selectionStart > 0)
		{
			has_range = true;
		}
	}
	return has_range;
}



//--------------------------------------------
// opentext: opening tag
// closetext: closing tag, used if we have selected text
// issingle: true if we do not close the tag right now
// return value: true if the tag needs to be closed later
function doInsert(opentext, closetext, issingle)
{
	var has_closed = false;

	if (!issingle ) issingle = false;

	postfieldobj = document.getElementById('content');

	// It's IE!
	if ( (ua_vers >= 4) && is_ie && is_win )
	{
		if ( postfieldobj.isTextEdit )
		{
			postfieldobj.focus();

			var sel = document.selection;

			var rng = ie_range_cache ? ie_range_cache : sel.createRange();

			var stored_range = rng.duplicate()
			stored_range.moveToElementText( postfieldobj );
			stored_range.setEndPoint( 'EndToEnd', rng );

			// Stores start position of text selection
			postfieldobj.selectionStart = stored_range.text.length - rng.text.length;
			// Stores end position of text selection
			postfieldobj.selectionEnd = postfieldobj.selectionStart + rng.text.length;

			rng.colapse;

			if ( (sel.type == "Text" || sel.type == "None") && rng != null)
			{
				if (closetext != "" && rng.text && rng.text.length > 0)
				{
					opentext += rng.text + closetext;
				}
				else if (issingle)
				{
					has_closed = true;
				}

				rng.text = rng.text.charAt(rng.text.length - 1) == ' ' ? opentext + ' ' : opentext;
			}
			else
			{
				postfieldobj.value += opentext;
				has_closed = true;
			}
		}
		else
		{
			postfieldobj.value += opentext;
			has_closed = true;
		}

		ie_range_cache = null;

		rng.select();
	}

	// It's MOZZY!
	else if (postfieldobj.selectionEnd != null)
	{
		var ss = postfieldobj.selectionStart;
		var st = postfieldobj.scrollTop;
		var es = postfieldobj.selectionEnd;

		if (es <= 0)
		{
			es = postfieldobj.textLength;
		}

		var start  = (postfieldobj.value).substring(0, ss);
		var middle = (postfieldobj.value).substring(ss, es);
		var end    = (postfieldobj.value).substring(es, postfieldobj.textLength);

		// text range?
		if ( postfieldobj.selectionEnd - postfieldobj.selectionStart > 0 )
		{
			middle = opentext + middle + closetext;
		}
		else
		{
			middle = opentext + middle;

			if ( issingle )
			{
				has_closed = true;
			}
		}

		postfieldobj.value = start + middle + end;

		var cpos = ss + (middle.length);

		postfieldobj.selectionStart = cpos;
		postfieldobj.selectionEnd   = cpos;
		postfieldobj.scrollTop      = st;
	}

	// It's CRAPPY!
	else
	{
		if ( issingle )
		{
			has_closed = false;
		}

		postfieldobj.value += opentext + ' ' + closetext;
	}

	postfieldobj.focus();

	return has_closed;
}










// Close all tags
function closeall()
{
	if (bbtags[0])
	{
		while (bbtags[0])
		{
			tagRemove = popstack(bbtags);
			edtContent.value += "[/" + tagRemove + "]";

			if ( (tagRemove != 'font') && (tagRemove != 'size') && (tagRemove != 'color') )
			{
				eval("edtForm." + tagRemove + ".value = ' " + tagRemove + " '");
				eval(tagRemove + "_open = 0");
			}
		}
	}

	edtForm.tagcount.value = 0;
	bbtags = new Array();
	edtContent.focus();
}

// Stack functions
function pushstack(thearray, newval)
{
	arraysize = stacksize(thearray);
	thearray[arraysize] = newval;
}

function popstack(thearray)
{
	arraysize = stacksize(thearray);
	theval = thearray[arraysize - 1];
	delete thearray[arraysize - 1];
	return theval;
}

function stacksize(thearray)
{
	for (i = 0 ; i < thearray.length; i++ )
	{
		if ( (thearray[i] == "") || (thearray[i] == null) || (thearray == 'undefined') )
		{
			return i;
		}
	}

	return thearray.length;
}

// Show statistic
function cstat()
{
	var c = stacksize(bbtags);

	if ( (c < 1) || (c == null) )
	{
		c = 0;
	}

	if ( ! bbtags[0] )
	{
		c = 0;
	}

	edtForm.tagcount.value = c;
}


function translit()
{
	var textar = edtContent.value;

	var smallEngLettersReg = new Array(/e'/g, /ch/g, /sh/g, /yo/g, /jo/g, /zh/g, /yu/g, /ju/g, /ya/g, /ja/g, /a/g, /b/g, /v/g, /g/g, /d/g, /e/g, /z/g, /i/g, /j/g, /k/g, /l/g, /m/g, /n/g, /o/g, /p/g, /r/g, /s/g, /t/g, /u/g, /f/g, /h/g, /c/g, /w/g, /~/g, /y/g, /'/g);
	var capitEngLettersReg = new Array( /E'/g, /CH/g, /SH/g, /YO/g, /JO/g, /ZH/g, /YU/g, /JU/g, /YA/g, /JA/g, /A/g, /B/g, /V/g, /G/g, /D/g, /E/g, /Z/g, /I/g, /J/g, /K/g, /L/g, /M/g, /N/g, /O/g, /P/g, /R/g, /S/g, /T/g, /U/g, /F/g, /H/g, /C/g, /W/g, /~/g, /Y/g, /'/g);
	var smallRusLetters = new Array("э", "ч", "ш", "ё", "ё","ж", "ю", "ю", "я", "я", "а", "б", "в", "г", "д", "е", "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "щ", "ъ", "ы", "ь" );
	var capitRusLetters = new Array( "Э", "Ч", "Ш", "Ё", "Ё", "Ж", "Ю", "Ю", "\Я", "\Я", "А", "Б", "В", "Г", "Д", "Е", "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Щ", "Ъ", "Ы", "Ь");

	if (textar)
	{
		for (var i=0; i<smallEngLettersReg.length; i++)
		{
			textar = textar.replace(smallEngLettersReg[i], smallRusLetters[i]);
		}
		for (var i=0; i<capitEngLettersReg.length; i++)
		{
			textar = textar.replace(capitEngLettersReg[i], capitRusLetters[i]);
		}
		edtContent.value = textar;
	}
}



// Fix incorect keyboard layout
function changelayout() {
	var s = edtContent.value;
	if (s) {
		var RUS = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЫЭЮЯабвгдеёжзийклмнопрстуфхцчшщъьыэюя\"№;:?/.,";
		var ENG = "F<DULT~:PBQRKVYJGHCNEA{WXIO}MS'>Zf,dult`;pbqrkvyjghcnea[wxio]ms'.z\@#$^&|/?";
		var FROM="", TO="";
		if (RUS.indexOf(s.charAt(1))==-1)
		{
			FROM=ENG;
			TO=RUS;
		} else {
			FROM=RUS;
			TO=ENG;
		}
		var c = "";

		for(var i=0; i<s.length; i++)	{
			var j = FROM.indexOf(s.charAt(i));
			if (j < 0)
				c += s.charAt(i)
			else
				c += TO.charAt(j);
		}

		edtContent.value = c;
		return c;
	}
}



function comment_ban(ip, src) {
	WindowOpen('/back/ban.asp?ip=' + ip + '&src=' + src,'ban',500, 500);
}



  function SelectAll(form, state, check) {
  	if (arguments.length == 2)
	{ var ch_name = 'check' } else
	{ var ch_name = check };
    for (i=0; i<form.elements.length; i++) {
      if (form.elements[i].name == ch_name) {
        var item = form.elements[i];
        item.checked = state;}}};


function CheckAction(form, check_name, text) {
	for (i=0; i<form.elements.length; i++) {
		if (form.elements[i].name == check_name) {
			var item = form.elements[i];
			if (item.checked) {
				if (confirm ( text )) { return true; } else { return false; }; }}
	};
	return false;
};


//Функция выделяет все элементы объекта select в заданной форме
function selectAllOptions(iForm, iSelect, iIndex)
{
  var obj = document.forms[iForm].elements[iSelect];
  for	(var i=iIndex; i<obj.options.length; i++) {obj.options[i].selected = true;}
}

//Функция возвращает [true/false] - есть ли выделенный элемент заданного списка
function checkOptionsAndSend( iForm, iSelect)
{
  var obj = document.forms[iForm];
  var vSelected = obj.elements[iSelect].selectedIndex;
  if (vSelected > -1)
  {
    obj.submit();
  }
  return false;
}

//Функция возвращает [true/false] - есть ли выделенный элемент заданного списка
function setIMP( iForm, iAction, iRec)
{
  var obj = document.forms[iForm];
  obj.elements['action'].value = iAction;
  obj.elements['check'][iRec].checked = 'on';
  obj.submit();
  return false;
}


function toggleOptions(option,titlebar) {
	drawer = document.getElementById(option);
	//bar = document.getElementById(titlebar);

	if (drawer.style.display == 'block') {
		drawer.style.display = 'none';
		//bar.className = 'closed';
	} else {
		drawer.style.display = 'block';
		//bar.className = 'open';
	}
}

