/* *************************************************************************
*
*  File: common.js
*  Purpose: Commonly used functions
*
************************************************************************* */

function check_add_topic() {
	var pat_email=/^[a-zA-Z][a-zA-Z\_\.\-\d]*@[a-zA-Z\_\.\-\d]+.[a-zA-Z]{2,4}$/;
	var pat_text=/^\s*$/;
	var pat_num=/^\d*$/;
	var pat_phone_num=/^[\d\s\-\_]*$/;

	if (pat_text.test(document.addtopic.topic_title.value)) {alert ("Заполните поле \"Заголовок темы\"");	return false;}
	if (pat_text.test(document.addtopic.topic_message.value)) {alert ("Заполните поле \"Сообщение\"");	return false;}

	return true;
}

function check_add_mes() {
	var pat_email=/^[a-zA-Z][a-zA-Z\_\.\-\d]*@[a-zA-Z\_\.\-\d]+.[a-zA-Z]{2,4}$/;
	var pat_text=/^\s*$/;
	var pat_num=/^\d*$/;
	var pat_phone_num=/^[\d\s\-\_]*$/;

	if (pat_text.test(document.addmessage.forum_message.value)) {alert ("Заполните поле \"Сообщение\"");	return false;}

	return true;
}

function calcTop(x_ele){
//	if (!document.all) return (x_ele.offsetTop);
	var x_ret=0;
	var oParent = x_ele.offsetParent;
	if (oParent == null) return 0
		else x_ret=x_ele.offsetTop + calcTop(oParent);
	return x_ret;
}

function calcLeft(x_ele){
//	if (!document.all) return (x_ele.offsetLeft);
	var x_ret=0;
	var oParent = x_ele.offsetParent;
	if (oParent == null) return 0
		else x_ret=x_ele.offsetLeft + calcLeft(oParent);
	return x_ret;
}


function saveArticle(el,id){
	var saveObj = document.getElementById("popular_popup");
	saveObj.style.top = calcTop(el)+"px";
	saveObj.style.left = (calcLeft(el)-250)+"px";
	saveObj.innerHTML="Сохранение материала...";
	saveObj.style.display="block";
	document.getElementById("popular_popup_frame").src="/profile/folders/save/?id="+id+"&rand="+Math.random();
}

function deleteArticle(el,id,folder){
	var saveObj = document.getElementById("popular_popup");
	saveObj.style.top = calcTop(el)+"px";
	saveObj.style.left = (calcLeft(el)-170)+"px";
	saveObj.innerHTML="Удаление...";
	saveObj.style.display="block";
	document.getElementById("popular_popup_frame").src='/profile/folders/save/?action=delete&folder='+folder+'&id='+id+'&rand='+Math.random();
}

function clearFolder(el,folder){
	var saveObj = document.getElementById("popular_popup");
	saveObj.style.top = calcTop(el)+"px";
	saveObj.style.left = (calcLeft(el)-170)+"px";
	saveObj.innerHTML='<div style="margin-bottom: 5px">Действительно хотите очистить папку?</div><a href="" onclick="clearingFolder('+folder+'); return false">Да</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="hideSaveAction(); return false">Нет</a>';
	saveObj.style.display="block";
}


function clearingFolder(folder){
	var saveObj = document.getElementById("popular_popup");
	saveObj.innerHTML='Очистка...';
	saveObj.style.display="block";
	document.getElementById("popular_popup_frame").src='/profile/folders/save/?action=clear&folder='+folder+'&rand='+Math.random();
}

var foldersName= new Array(false, false, false);

function renameFolder(el,folder){
	var saveObj = document.getElementById("popular_popup");
	saveObj.style.top = calcTop(el)+"px";
	saveObj.style.left = (calcLeft(el)-145)+"px";
	saveObj.innerHTML='<div style="margin-bottom: 5px">Название папки:<br /><input type="text" style="border: solid 1px black; background: white; font-size: 11px; font-family: Arial; color: black; width: 155px; margin-top:3px" id="newFolderName" value="" /></div><a href="" onclick="renamingFolder('+folder+'); return false">Переименовать</a>&nbsp;&nbsp;&nbsp;<a href="#" onclick="hideSaveAction(); return false">Отменить</a>';
	saveObj.style.display="block";
}

function renamingFolder(folder){
	var saveObj = document.getElementById("popular_popup");
	foldersName[folder]=document.getElementById("newFolderName").value;
	document.getElementById("popular_popup_frame").src='/profile/folders/save/?action=rename&name='+base64_encode(utf8_encode(foldersName[folder]))+'&folder='+folder+'&rand='+Math.random();
	saveObj.innerHTML='Сохранение...';
	saveObj.style.display="block";
}

function checkSaveAction(action, folder, id){
	top.document.getElementById("popular_popup").innerHTML=document.body.innerHTML;
	if (action=='save') setTimeout("hideSaveAction()", 2000);
	if (action=='delete') {
		setTimeout("hideSaveAction()", 2000);
		if (id) top.document.getElementById("link_"+id).style.display="none";
		if (folder) {
			var oldCount=Number(top.document.getElementById("folderCount"+folder).innerHTML);
			top.document.getElementById("folderCount"+folder).innerHTML=oldCount-1;
		}
	}
	if (action=='clear') {
		setTimeout("hideSaveAction()", 2000);
		if (folder) {
			top.document.getElementById("folderGroup"+folder+"Content").style.display="none";
			top.document.getElementById("folderCount"+folder).innerHTML="0";
		}

	}
	if (action=='rename') {
		setTimeout("hideSaveAction()", 2000);
		if (folder) {
			if (top.foldersName[folder] && top.foldersName[folder]!='')
				top.document.getElementById("folderName"+folder).innerHTML=top.foldersName[folder];
			top.foldersName[folder]=false;
		}

	}
}

function hideSaveAction(){
	top.document.getElementById("popular_popup").style.display="none";
}

function sendLink(path){
openPopup ('/sendlink/?path='+path, 'sendLink', '', 438, 375);
return false;
}

function openVideo(ch,id){
	openPopup ('/videoplayer/?ch='+ch+'&id='+id, 'video', '', 358, 375);
	return false;
}

function openAudio(ch, id){
	openPopup ('/audioplayer/?ch='+ch+'&id='+id, 'audio', '', 358, 180);
	return false;
}


function openVoting(id){
openPopup ('/allvotings/result/?id='+id, 'voteResult', '', 438, 375);
return false;
}

var azWin = '     Ё               ё       АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя'
var azKoi = 'ё                Ё           юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ'
var AZ=azWin
var azURL = '0123456789ABCDEF'
var b64s  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
var b64a  = b64s.split('')
function enBASE64(str) {
  var a=Array(), i
  for( i=0; i<str.length; i++ ){
    var cch=str.charCodeAt(i)
    if( cch>127 ){  cch=AZ.indexOf(str.charAt(i))+163; if(cch<163) continue; }
    a.push(cch)
  };
  var s=Array(), lPos = a.length - a.length % 3
  for(i=0;i<lPos;i+=3){
    var t=(a[i]<<16)+(a[i+1]<<8)+a[i+2]
    s.push( b64a[(t>>18)&0x3f]+b64a[(t>>12)&0x3f]+b64a[(t>>6)&0x3f]+b64a[t&0x3f] )
  }
  switch ( a.length-lPos ) {
    case 1 : var t=a[lPos]<<4; s.push(b64a[(t>>6)&0x3f]+b64a[t&0x3f]+'=='); break
    case 2 : var t=(a[lPos]<<10)+(a[lPos+1]<<2); s.push(b64a[(t>>12)&0x3f]+b64a[(t>>6)&0x3f]+b64a[t&0x3f]+'='); break
  }
  return s.join('')
}

function openFolder(filePath,date,rubric,title,x,y){
	var playerPath="/explayer/photos.php";
	var name='photos';
	var width=Math.max(Number(x)+25, 360);
	var height=Math.max(455,Number(y)+120);
	var path=playerPath+"?path="+filePath+"&date="+date+"&rubric="+encodeURIComponent(enBASE64(rubric))+"&title="+encodeURIComponent(enBASE64(title))+"&x="+x+"&y="+y;
	var left=(window.screen.availWidth/2)-(width/2);
	var top=(window.screen.availHeight/2)-(height/2);
	var param = "scrollbars=nos,status=no,resizable=0,width=" + width + ",height=" + height + ",left=" + left + ",top=" + top;
	eval(name+'=window.open("'+path+'", "'+name+'", "'+param+'");');
	eval(name+'.focus();');
}

/* *************************************************************************
*
*  function setInit ()
*
************************************************************************* */

function setInit ()
{

}

/* *************************************************************************
*
*  function getObj (_idElement, _objParent)
*
************************************************************************* */

function getObj (_idElement, _objParent)
{
	var objElement = null;

	if (!_objParent)
	{
		_objParent = document;
	}

	if (document.getElementById)
	{
		objElement = _objParent.getElementById (_idElement);
	}

	return objElement;
}

/* *************************************************************************
*
*  function getX (_objElement)
*
************************************************************************* */

function getX (_objElement)
{
	var posX = 0;

	do
	{
		posX += _objElement.offsetLeft;
	}
	while ((_objElement = _objElement.offsetParent) != null);

	return posX;
}

/* *************************************************************************
*
*  function getY (_objElement)
*
************************************************************************* */

function getY (_objElement)
{
	var posY = 0;

	do
	{
		posY += _objElement.offsetTop;
	}
	while ((_objElement = _objElement.offsetParent) != null);

	return posY;
}

/* *************************************************************************
*
*  function getHeight (_objElement)
*
************************************************************************* */

function getHeight (_objElement)
{
	var posY = 0;

	if (typeof (_objElement) == 'object')
	{
		posY = _objElement.offsetHeight;
	}
	else
	{
		posY = document.getElementById (_objElement).clientHeight;
	}

	return posY;
}

/* *************************************************************************
*
*  function openPopup (_url, _name, _title, _width, _height, _posX, _posY)
*
************************************************************************* */

function openPopup (_url, _name, _title, _width, _height, _posX, _posY)
{
	var strParams = 0,
		idWindow = null;

	_posX = Math.round ((window.screen.availWidth / 2) - (_width / 2));

	if (window.screen.availHeight - 24 < _height)
	{
		_posY = 0;
		_width += 17;
		_height = window.screen.availHeight - 24;
	}
	else
	{
		_posY = Math.round ((window.screen.availHeight / 2) - (_height / 2 + 12));
	}

	strParams = "scrollbars=yes,status=yes,resizable=1,width=" + _width + ",height=" + _height + ",left=" + _posX + ",top=" + _posY;

	idWindow = window.open (_url, _name, strParams);

	return idWindow;
}

/* *************************************************************************
*
*  function clearInputDefault (_this, _default)
*
************************************************************************* */

function clearInputDefault (_this, _default)
{
	if (_this.value == _default)
	{
		_this.value = '';
	}
}

/* *************************************************************************
*
*  function restoreInputDefault (_this, _default)
*
************************************************************************* */

function restoreInputDefault (_this, _default)
{
	if (_this.value == '')
	{
		_this.value = _default;
	}
}

/* *************************************************************************
*
*  function expandFolder ()
*
************************************************************************* */

function expandFolder (_idGroup, _suffixTitle, _suffixContent)
{
	var objGroup = getObj (_idGroup),
		objGroupTitle = getObj (_idGroup + _suffixTitle),
		objGroupContent = getObj (_idGroup + _suffixContent);

	if (objGroup.className.indexOf ('Expanded') != -1)
	{
		objGroup.className = objGroup.className.replace (/Expanded/ig, 'Collapsed');
	}
	else
	{
		objGroup.className = objGroup.className.replace (/Collapsed/ig, 'Expanded');
	}
}

/* *************************************************************************
*
*  function switchOptionSearch (_this, _idContainer, _idSearchInput)
*
************************************************************************* */

function switchOptionSearch (_this, _idContainer, _idSearchInput, value)
{
	document.formSearch.type.value=value;
	var arrContainerChildren = _this.parentNode.parentNode.childNodes,
		posX = 35;
		objContainer = getObj (_idContainer),
		objSearchInput = getObj (_idSearchInput);

	for (var indexOptions = 0; indexOptions < arrContainerChildren.length; indexOptions++)
	{
		arrContainerChildren [indexOptions].className = 'item';
	}

	_this.parentNode.className = 'item this';

	posX = getX (_this) - getX (objContainer) + Math.round (_this.offsetWidth / 2) - 4;

	objContainer.style.backgroundPosition = posX + 'px 0px';

	objSearchInput.focus ();
}

/* *************************************************************************
*
*  function setAutoFocus (_idInput)
*
************************************************************************* */

function setAutoFocus (_idInput)
{
	var objInput = (_idInput != null ? getObj (_idInput) : null),
		objInputTemp = null;

/*	if (objInput == null)
	{
		for (var indexForms = 0; indexForms < document.forms.length; indexForms++)
		{
			for (var indexInput = 0; indexInput < document.forms[indexForms].elements.length; indexInput++)
			{
				objInputTemp = document.forms[indexForms].elements[indexInput];

				if (objInputTemp.type != 'checkbox' && objInputTemp.type != 'radio' && objInputTemp.type != 'select' && objInputTemp.type != 'hidden' && objInputTemp.type != 'button' && objInputTemp.type != 'image' && objInputTemp.type != 'submit')
				{
					objInput = objInputTemp;

					break;
				}
			}

			if (objInput != null)
			{
				break;
			}
		}
	}*/

	if (objInput != null)
	{
		objInput.focus ();
	}
}

/* *************************************************************************
*
*  function getElementCollectionByName(_name, _tags)
*
************************************************************************* */

function getElementCollectionByName (_name, _tags)
{
	var count = 0,
		objCollection = new Array (),
		tagsCollection = new Array (),
		namesCollection;

	if (_tags != null)
	{
		tagsCollection = _tags.split (',');
	}
	else
	{
		return null;
	}

	for (var indexTags = 0; indexTags < tagsCollection.length; indexTags++)
	{
		namesCollection = document.all.tags (tagsCollection[indexTags]);

		for (var indexNames = 0; indexNames < namesCollection.length; indexNames++)
		{
			if (namesCollection[indexNames].name == _name)
			{
				objCollection[count++] = namesCollection[indexNames];
			}
		}
	}

	if (count > 0)
	{
		return objCollection;
	}

	return null;
}

/* *************************************************************************
*
*  function getFormElementCollectionByName(_name, _tags)
*
************************************************************************* */

function getFormElementCollectionByName (_name)
{
	var count = 0,
		objCollection = new Array (),
		tagsCollection = new Array ('input', 'textarea'),
		namesCollection;

	for (var indexForms = 0; indexForms < document.forms.length; indexForms++)
	{
		for (var indexInput = 0; indexInput < document.forms[indexForms].elements.length; indexInput++)
		{
			if (document.forms[indexForms].elements[indexInput].name == _name)
			{
				objCollection[count++] = document.forms[indexForms].elements[indexInput];
			}
		}
	}

	if (count > 0)
	{
		return objCollection;
	}

	return null;
}

/* *************************************************************************
*
*  function setCheckboxes (_this, _nameGroup)
*
************************************************************************* */

function setCheckboxes (_this, _nameGroup)
{
	var elementsList = new Array ();

	elementsList = getFormElementCollectionByName (_nameGroup);

	for (var indexCheckboxes = 0; indexCheckboxes < elementsList.length; indexCheckboxes++)
	{
		elementsList[indexCheckboxes].checked = (_this.checked ? true : false);
	}
}


function checkMail(obj){
	var pat=/^[a-zA-Z][a-zA-Z_\.\-d]*@[a-zA-Z_\.\-d]+.[a-zA-Z]{2,4}$/;
	if(pat.test(obj.value)) return true;
		else return false;
}

var agt = navigator.userAgent.toLowerCase ();
var is_major = parseInt (navigator.appVersion);
var is_minor = parseFloat (navigator.appVersion);
var is_nav  = ((agt.indexOf ('mozilla') != -1) && (agt.indexOf ('spoofer') == -1) && (agt.indexOf ('compatible') == -1) && (agt.indexOf ('opera') == -1) && (agt.indexOf ('webtv') == -1) && (agt.indexOf ('hotjava') == -1) && (agt.indexOf ('safari') == -1));
var is_nav6 = (is_nav && (is_major == 5) && (agt.indexOf ("netscape") != -1) && (agt.indexOf ("netscape/7") == -1));
var is_nav6up = ((is_nav && (is_major >= 5)) || (is_nav && (agt.indexOf ('netscape/7') != -1)));
var is_ie      = ((agt.indexOf ("msie") != -1) && (agt.indexOf ("opera") == -1) && (agt.indexOf ("safari") == -1));
var is_ie3     = (is_ie && (is_major < 4));
var is_ie4     = (is_ie && (is_major == 4) && (agt.indexOf ("msie 4")!=-1));
var is_ie4up   = (is_ie && (is_major >= 4));
var is_ie5     = (is_ie && (is_major == 4) && (agt.indexOf ("msie 5.0") != -1));
var is_ie5_5   = (is_ie && (is_major == 4) && (agt.indexOf ("msie 5.5") != -1));
var is_ie5up   = (is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up = (is_ie && !is_ie3 && !is_ie4 && !is_ie5)
var is_firefox = ((agt.indexOf ("firefox") != -1) && (agt.indexOf ("opera") == -1) && (agt.indexOf ("safari") == -1));
var is_opera = (agt.indexOf ("opera") != -1);
var is_nn = ((is_nav6 || is_nav6up) ? true : false);

function base64_encode(a) {
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
    var i, n = a.length, tmp = 0, s = Array();
    i = j = 0;
    while (i < n) {
        tmp = (tmp << 8) | a[i];
        if (i % 3 == 2) {
            s[s.length] = chars[(tmp >> 18) & 0x3f];
            s[s.length] = chars[(tmp >> 12) & 0x3f];
            s[s.length] = chars[(tmp >> 6) & 0x3f];
            s[s.length] = chars[tmp & 0x3f];
            j += 4;
            if (j % 76 == 0) s[s.length] = '\r\n';
            tmp = 0;
        }
        i++;
    }
    switch (i % 3) {
    case 1 :
        s[s.length] = chars[(tmp >> 2) & 0x3f];
        s[s.length] = chars[(tmp << 4) & 0x3f];
        s[s.length] = '=';
        s[s.length] = '=';
        break;
    case 2 :
        s[s.length] = chars[(tmp >> 10) & 0x3f];
        s[s.length] = chars[(tmp >> 4) & 0x3f];
        s[s.length] = chars[(tmp << 2) & 0x3f];
        s[s.length] = '=';
        break;
    }
    return s.join('');
}

function base64_decode(s) {
    s = s.split('');
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
    var i, j, codes = Object(), a = Array(), n = s.length, tmp = 0;
    for (i = 0; i < 64; i++) codes[chars[i]] = i; //
    i = j = 0;
    while (i < n) {
        while (i < n && isNaN(codes[s[i]]) && s[i] != '=') i++; //
        if (i == n || s[i] == '=') break;
        tmp = (tmp << 6) | codes[s[i]];
        if (j % 4 == 3) {
            a[a.length] = (tmp >> 16) & 0xff;
            a[a.length] = (tmp >> 8) & 0xff;
            a[a.length] = tmp & 0xff;
            tmp = 0;
        }
        j++;
        i++;
    }
    switch (j % 4) {
    case 2 :
        a[a.length] = (tmp >> 4) & 0xff;
        break;
    case 3 :
        a[a.length] = (tmp >> 10) & 0xff;
        a[a.length] = (tmp >> 2) & 0xff;
        break;
    }
    return a;
}

function utf8_encode(s) {
    var n = s.length, i, a = Array(), ch;
    for (i = 0; i < n; i++) {
        ch = s.charCodeAt(i);
        if (!(ch >> 7)) a[a.length] = ch; //
        else if (!(ch >> 11)) {
            //
            a[a.length] = 0xc0 | (ch >> 6);
            a[a.length] = 0x80 | (ch & 0x3f);
        } else if (!(ch >> 16)) {
            //
            a[a.length] = 0xe0 | (ch >> 12);
            a[a.length] = 0x80 | ((ch >> 6) & 0x3f);
            a[a.length] = 0x80 | (ch & 0x3f);
        } else {
            //
            a[a.length] = 0xf0 | (ch >> 18);
            a[a.length] = 0x80 | ((ch >> 12) & 0x3f);
            a[a.length] = 0x80 | ((ch >> 6) & 0x3f);
            a[a.length] = 0x80 | (ch & 0x3f);
        }
    }
    return a;
}

function utf8_decode(a) {
    var n = a.length, i, s = '', ch;
    i = 0;
    while (i < n) {
        if (!(a[i] & 0x80)) ch = a[i]; //
        else if (i + 1 < n && !((a[i + 1] & 0xc0) ^ 0x80)) {
            if (!((a[i] & 0xe0) ^ 0xc0)) {
                ch = ((a[i] & 0x1f) << 6) | (a[i + 1] & 0x3f); //
                i++;
            }
            else if (i + 2 < n && !((a[i + 2] & 0xc0) ^ 0x80)) {
                if (!((a[i] & 0xf0) ^ 0xe0)) {
                    ch = ((a[i] & 0x0f) << 12) | ((a[i + 1] & 0x3f) << 6) | (a[i + 2] & 0x3f); //
                    i += 2;
                }
                else if (i + 3 < n && !((a[i + 3] & 0xc0) ^ 0x80)) {
                    if (!((a[i] & 0xf8) ^ 0xf0)) {
                        ch = ((a[i] & 0x07) << 18) | ((a[i + 1] & 0x3f) << 12) | ((a[i + 2] & 0x3f) << 6) | (a[i + 3] & 0x3f); //
                        i += 3;
                    }
                    else {
                        //                     i
                    }
                } else {
                    //                     i + 3
                }
            } else {
                //                     i + 2
            }
        } else {
            //                     i + 1
        }
        s += String.fromCharCode(ch);
        i++;
    }
    return s;
}



// bbCode control by
// subBlue design
// www.subBlue.com

// 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_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_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]');
imageTag = false;

// 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() {

	formErrors = false;

	if (document.addmessage.message.value.length < 2) {
		formErrors = l_empty_message;
	}

	if (formErrors) {
		alert(formErrors);
		return false;
	} else {
		bbstyle(-1);
		//formObj.preview.disabled = true;
		//formObj.submit.disabled = true;
		return true;
	}
}

function emoticon(text) {
	var txtarea = document.addmessage.message;
	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function emoticon_wospaces(text) {
	var txtarea = document.addmessage.message;
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function bbstyle(bbnumber) {
	var txtarea = document.addmessage.message;

	txtarea.focus();
	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += bbtags[butnumber + 1];
			buttext = eval('document.addmessage.addbbcode' + butnumber + '.value');
			eval('document.addmessage.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
		txtarea.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
			document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		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 & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				txtarea.value += bbtags[butnumber + 1];
				buttext = eval('document.addmessage.addbbcode' + butnumber + '.value');
				eval('document.addmessage.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags

		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			txtarea.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			document.addmessage.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}

		// Open tag
		txtarea.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('document.addmessage.addbbcode'+bbnumber+'.value += "*"');
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

// 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();
}

var selection = false; // Selection data

// Catching selection
function catchSelection()
{
	if (window.getSelection)
	{
		selection = window.getSelection().toString();
	}
	else if (document.getSelection)
	{
		selection = document.getSelection();
	}
	else if (document.selection)
	{
		selection = document.selection.createRange().text;
	}
}

// Putting username to the post box
function putName(name)
{
	emoticon_wospaces('[b]'+name+'[/b]\n');
	document.addmessage.message.focus();
	return;
}

// Putting selection to the post box
function quoteSelection(name)
{
	if (selection)
	{
		emoticon_wospaces('[quote="'+name+'"]' + selection + '[/quote]\n');
		selection = '';
		document.addmessage.message.focus();
		return;
	}
	else
	{
		alert("Выделите фрагмент для цитирования");
		return;
	}
}

// Check short subscribe form
function check_short_subs() {
	var pat_text=/^\s*$/;
	var pat_email=/^[a-zA-Z][a-zA-Z\_\.\-\d]*@[a-zA-Z\_\.\-\d]+.[a-zA-Z]{2,4}$/;
	if (pat_text.test(document.getElementById("formSubscriptionEmail").value)) {alert ("Укажите свой e-mail.");	return false;}
	if (!pat_email.test(document.getElementById("formSubscriptionEmail").value)) {alert ("укажите валидный email.");	return false;}
	return true
};
