var CommentsOn = false;

function liFormat (row, i, num) {
 var result = row[0];// + '<p class=qnt>' + row[1] + ' роликов</p>';
 return result;
}
function selectItem(li) {
	if( li == null ) var sValue = 'А ничего не выбрано!';
	if( !!li.extra ) var sValue = li.extra[2];
	else var sValue = li.selectValue;
	//document.getElementById('').value=sValue;
}

$(document).ready(function() {
	$('#user-name').attr('value','Логин');

	//if (!$('#search input').value)
	//	$('#search input').attr('value', 'Поиск');
	
	$('#user-name').blur(function(){if (this.value == '') this.value = 'Логин';});
	$('#user-name').focus(function(){if (this.value == 'Логин') this.value='';});
	
	$('#search input').blur(function(){if (this.value == '') this.value = 'Поиск';});
	$('#search input').focus(function(){if (this.value == 'Поиск') this.value='';});

	//r1 = document.getElementById('star-rating');
	//r1.style.width = 50;
	//r2 = document.getElementById('current-rating');

	$('.adult').after('<img class="censored" src="/vs/main/images/censored.gif" width="23" height="17" alt="Доступ только для лиц от 18 лет" />');

	$("#words").autocomplete("/Ajax.php", {
	 delay: 5,
	 minChars: 3,
	 matchSubset: 1,
	 autoFill: true,
	 matchContains: 1,
	 cacheLength: 10,
	 selectFirst:true,
	 formatItem:liFormat,
	 maxItemsToShow: 20,
	 onItemSelect:selectItem
	});
	try {
    	$('#user-passwd').attr('type','text');
    	$('#user-passwd').attr('value','Пароль');
    	$('#user-passwd').blur(function(){if (this.value == '') {this.type='text'; this.value = 'Пароль';}});
    	$('#user-passwd').focus(function(){if (this.value == 'Пароль') {this.value=''; this.type='password'; }});
    } 
    catch (exception) {}
});


function mycallbackform(v,m){
	var frm = document.forms['files-form'];
	frm.elements['new-playlist-title'].value=m.children('#alertName').val();
	frm.elements['action'].value = 'move';
	frm.elements['to'].value     = 'new_playlist';
	frm.submit();
}

function check_new_playlist(elm){
	var frm = document.forms['files-form'];
	var files = getSelectedFiles('videos[]');
	if(files){
		if(elm.value == 'new_playlist' && frm){
			$.prompt('Введите название плейлиста:<br /><input type="text" id="alertName" name="myname" value="Новый плейлист" />', {callback: mycallbackform, buttons: {OK: 'ok' }})
		}
	} else {
		alert('Вы должны выбрать файлы');
	}
}

function findPos(obj) {
	var curleft = obj.offsetLeft || 0;
	var curtop = obj.offsetTop || 0;
	while (obj = obj.offsetParent) {
		curleft += obj.offsetLeft
		curtop += obj.offsetTop
	}
return {x:curleft,y:curtop};
}

var HideTextDescriptionTimerID = null;
var HideTextDescriptionTimerRunning = false;
var HideTextDescriptionTimerDelay = 2;
var ShowTextDescription = false;

function viewExport() {
	elP  = $("#param");
	elLD = document.getElementById('paramlink');
	elL  = $("#paramlink");
	var pos = findPos(elLD);
	if (a) {
			elP.css({
				top: (pos.y + 27) + "px",
				left: (pos.x - 194) + "px",
				display: 'block'
			}).show();
	elLD.className = 'ExpBtnOn';
	a = 0;
	} else {
	elP.hide();
	elLD.className = 'ExpBtn';
	a = 1;
	}
return false;
}


function ToggleTextDescription(On){
	if(document.getElementById('TextDescription')){
		elD  = $("#TextDescription");
		elId = document.getElementById('ItemInfo');
		var pos = findPos(elId);
		if(On){
			elD.css({
				top: (pos.y + elId.offsetHeight) + "px",
				left: (pos.x - 7) + "px",
				display: 'block'
			}).show();
			if (HideTextDescriptionTimerID) clearTimeout(HideTextDescriptionTimerID);
			HideTextDescriptionTimerID = null;
			ShowTextDescription = true;
		}
		if(!On && ShowTextDescription){
			HideTextDescriptionTimerID = setTimeout("HideTextDescription()", HideTextDescriptionTimerDelay);
		}
	}
}

function HideTextDescription(){
	elD = $("#TextDescription");
	elD.hide();
	ShowTextDescription = false;
}


function ToggleComments(el){
	CommentsBlock = $('#comments');
	if(CommentsOn){
	el.className = 'Toggle';
	CommentsBlock.slideUp('slow');
	CommentsOn = false;
	} else {
	el.className = 'ToggleOff';
	CommentsBlock.slideDown('slow');
	CommentsOn = true;
	}
}

function addToFavouritesBtn(el, Id){
		$.ajax({
				url: '/ajax/?action=add_favourites&id='+Id,
				cache: false,
				success: function(responseXML){
if(responseXML && responseXML.firstChild){
CountF = responseXML.firstChild.getAttribute('cf');
CountH = responseXML.firstChild.getAttribute('ch');
CountP = responseXML.firstChild.getAttribute('cp');
Add    = responseXML.firstChild.getAttribute('add');
if(document.getElementById('f-count')) {
	if(CountF == 0){
document.getElementById('f-count').style.display = 'none';
	} else {
document.getElementById('f-count').innerHTML = '(' + CountF + ')';
document.getElementById('f-count').style.display = '';
	}
}
if(document.getElementById('h-count')){
	if(CountH == 0){
document.getElementById('h-count').innerHTML = '(' + CountH + ')';
	} else {
document.getElementById('h-count').innerHTML = '(' + CountH + ')';
document.getElementById('h-count').style.display = '';
	}
}
if(document.getElementById('p-count')) {
	if(CountP == 0){
document.getElementById('p-count').innerHTML = '(' + CountP + ')';
	} else {
document.getElementById('p-count').innerHTML = '(' + CountP + ')';
document.getElementById('p-count').style.display = '';
	}
}
					if (Add == 1) {
el.className = 'FavBtnOff';
					} else {
el.className = 'FavBtnOn';
					}
}
				}
		});
		$('#star-rating').css({width: 50});
		return false;
}

function addToFavourites(el, Id, Hide){
		$.ajax({
				url: '/ajax/?action=add_favourites&id='+Id,
				cache: false,
				success: function(responseXML){
if(responseXML && responseXML.firstChild){
CountF = responseXML.firstChild.getAttribute('cf');
CountH = responseXML.firstChild.getAttribute('ch');
CountP = responseXML.firstChild.getAttribute('cp');
Add    = responseXML.firstChild.getAttribute('add');
if(document.getElementById('f-count')) {
	if(CountF == 0){
document.getElementById('f-count').style.display = 'none';
	} else {
document.getElementById('f-count').innerHTML = '(' + CountF + ')';
document.getElementById('f-count').style.display = '';
	}
}
if(document.getElementById('h-count')){
	if(CountH == 0){
document.getElementById('h-count').innerHTML = '(' + CountH + ')';
	} else {
document.getElementById('h-count').innerHTML = '(' + CountH + ')';
document.getElementById('h-count').style.display = '';
	}
}
if(document.getElementById('p-count')) {
	if(CountP == 0){
document.getElementById('p-count').innerHTML = '(' + CountP + ')';
	} else {
document.getElementById('p-count').innerHTML = '(' + CountP + ')';
document.getElementById('p-count').style.display = '';
	}
}
					if (Add == 1) {
				el.className = 'StarOn';
						if(Hide == 0){
$('#Thumb'+Id).effect("pulsate", {times: -1}, 500);
						}
					} else {
				el.className = 'StarOff';
						if(Hide == 1){
Item = $('#Item'+Id);
Item.hide('slow');
						}
					}
}
				}
		});
		$('#star-rating').css({width: 50});
}

function isEmail(email_str) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=email_str.match(emailPat);
	if (matchArray==null) return false;
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++)	if (user.charCodeAt(i)>127) 	return false;
	for (i=0; i<domain.length; i++)	if (domain.charCodeAt(i)>127)	return false;
	if (user.match(userPat)==null) 	return false;
	var IPArray=domain.match(ipDomainPat);

	if (IPArray!=null) {
		for (var i=1;i<=4;i++)
			if (IPArray[i]>255) return false;
		return true;
	}

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;

	for (i=0;i<len;i++) if (domArr[i].search(atomPat)==-1) return false;
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) return false;
	if (len<2) return false;

	return true;
}

function resize_bc (a) {
	if (a) {
		document.getElementById('broadcast').style.display = "block";
		document.getElementById('default_bc').style.display = "none";
		document.getElementById('close_bc').style.display = "block";
		document.getElementById('open_bc').style.display = "none";
	} else { 
		document.getElementById('broadcast').style.display = "none";
		document.getElementById('default_bc').style.display = "block";

		if (document.upload.access[0].checked)		
			document.getElementById('default_bc').innerHTML = 'Открыт для всех';
		if (document.upload.access[1].checked)		
			document.getElementById('default_bc').innerHTML = 'Открыт для друзей';
		if (document.upload.access[2].checked)		
			document.getElementById('default_bc').innerHTML = 'Закрыт';
		
		document.getElementById('close_bc').style.display = "none";
		document.getElementById('open_bc').style.display = "block";
	}
}

function resize_coord (a) {
    var form = document.upload;
    var months = ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
    
    var defaultCoord = '';
    var date  = '';
    var place = '';

	if (a) { 
		document.getElementById('coord').style.display = "block";
		document.getElementById('default_coord').style.display = "none";
		document.getElementById('close_coord').style.display = "block";
		document.getElementById('open_coord').style.display = "none";
	} else { 
		document.getElementById('coord').style.display = "none";
		document.getElementById('default_coord').style.display = "block";
		
		place = form.place.value; 
		date  = (form.day.value!='0' && form.month.value!='0' && form.year.value!='0') ? 
		    form.day.value + ' ' + months[form.month.value-1] + ' ' + form.year.value : '';
		    
		if (place && date)
		    defaultCoord = date + ', ' + place;
		else if (place || date)
		    defaultCoord = date + place;
		else
		    defaultCoord = 'Не задано';
		    
		document.getElementById('default_coord').innerHTML = defaultCoord;
		   
		document.getElementById('close_coord').style.display = "none";
		document.getElementById('open_coord').style.display = "block";
	}
}

function resize_options(a) {
	var form = document.upload;
	if (a) { 
		document.getElementById('options').style.display = "block";
		document.getElementById('default_options').style.display = "none";
		document.getElementById('close_options').style.display = "block";
		document.getElementById('open_options').style.display = "none";
	} else { 
		document.getElementById('options').style.display = "none";
		document.getElementById('default_options').style.display = "block";
		document.getElementById('default_options').innerHTML = (document.getElementById('comments').checked && document.getElementById('rating').checked && document.getElementById('export').checked) ? 'По умолчанию' : 'Изменены';
		document.getElementById('close_options').style.display = "none";
		document.getElementById('open_options').style.display = "block";
	}
}
function delComment(id) {
	if(confirm('Вы действительно хотите удалить свой комментарий?')){
		$.ajax({
			url: "/ajax/?action=ajax_comment_del&id=" + id,
			cache: false,
			success: function(html){
				if (html == 'del') {
				document.getElementById('CommentCon' + id).style.display = 'none';
				alert('Ваш комментарий был удален');
				} else {
				alert('При удалении комментария произошла ошибка!');
				}
			}
		});
	}
	return false;
}

var PostCommentId = 0;
function PostComment(){
	if(PostCommentId != 0){
	var elP = document.getElementById('CommentP' + PostCommentId);
	var elT = document.getElementById('CommentT' + PostCommentId);
		$.ajax({
			url: "/ajax/?action=ajax_comment_upd",
			type: 'POST',
			data: {id: PostCommentId,text: escape(elT.value)},
			cache: false,
			success: function(html){
				elP.innerHTML = html;
				elP.style.display = '';
				elT.parentNode.style.display = 'none';
			}
		});
	}
}
function checkUploadForm(form) {
    if (form.file.value == '') {
        alert('Выберите файл для загрузки!');
        form.file.focus();
        return false;
    }

    if (form.category_id.value == '') {
        alert('Выберите категорию!');
        form.category_id.focus();
        return false;
    }
    
    if (form.title.value == '') {
        alert('Введите заголовок для файла!');
        form.title.focus();
        return false;
    }
    
    return true;
}

function checkCommentForm(form) {
	if (form.text.value == '') {
		alert('Введите комментарий!');
		form.text.focus();
		return false;
	} else if(form.text.value.length > 600) {
		alert('Слишком длинный комментарий!');
		form.text.focus();
		return false;
	} else {
		return true;
	}
}
var CheckSpam = 0;
var IsSpam = 0;

function CheckTextareaLength(elTxt) {
	f = document.forms['CommentForm'];
	b = document.getElementById('TextareaStatus');
	/*
	if(TextWidth == 0){
	TextWidth = elTxt.style.offsetWidth;
	} else {
	elTxt.style.width = TextWidth;
	}
	*/
	max_length = 600;
	if(elTxt.value == '' || elTxt.value.length == 0 || elTxt.value.length > max_length){
		b.innerHTML = (elTxt.value == '' || elTxt.value.length == 0)?'Введите текст комментария!':'Слишком длинный комментарий!';
		b.className = b.className + ' RedAlert';
		f.submit.disabled = true;
	}else{
		/*
		$.ajax({
				url: '/ajax/?action=check_spam',
				type: 'POST',
				data: {text: escape(elTxt.value)},
				cache: false,
				success: function(html){
				CheckSpam = 0;
					if (html == 'SPAM') {
				IsSpam = 1;
				b.innerHTML = 'Ваш текст очень похож на спам';
				b.className = b.className + ' RedAlert';
				f.submit.disabled = true;
					} else {
				IsSpam = 0;
				f.submit.disabled = false;
					}
				}
		});
		*/
		if(IsSpam == 0){
		b.className = 'TextareaStatus';
		b.innerHTML = 'Осталось символов: ' + (max_length - elTxt.value.length);
		f.submit.disabled = false;
		}
	}
}

var BroadcastId = 0;
var ChatTimerID = null;
var ChatTimerRunning = false;
var ChatTimerDelay = 5000;

function chatFocus(){
	updMessages(BroadcastId);
}
function updMessages() {
	if(BroadcastId != 0){
		$.ajax({
				url: '/ajax/?action=chat_messages&bid=' + BroadcastId,
				cache: false,
				success: function(html){
				blockEl = document.getElementById('chat_block');
				blockEl.scrollTop = blockEl.scrollHeight-blockEl.clientHeight;
				blockEl.innerHTML = html;
				}
		});
	ChatTimerID = self.setTimeout("updMessages()", ChatTimerDelay);
	}
}
function chatMessage(frmEl, BroadcastId) {
	if(BroadcastId != 0 && frmEl.elements['ChatMessage'].value != ''){
		frmEl.submit.disabled = true;
		$.ajax({
				url: '/ajax/?action=chat_message&bid=' + BroadcastId,
				type: 'POST',
				data: {text: escape(frmEl.elements['ChatMessage'].value)},
				cache: false,
				success: function(html){
					if (html == 'OK') {
				frmEl.elements['ChatMessage'].value = '';
				frmEl.submit.disabled = false;
				updMessages();
					}
				}
		});
	}
	return false;
}


function checkRecoverForm(form) {
	if (form.email.value == '') {
		alert('Введите Ваш адрес электронной почты, который Вы указали при регистрации.\nНа него будет выслан новый пароль.');
		form.email.focus();
		return false;
	}

	if (!isEmail(form.email.value)) {
		alert('Введите правильный адрес электронной почты!\nНа него будет выслан новый пароль.');
		form.email.focus();
		return false;
	}

	if (form.code.value == '') {
		alert('Введите код для защиты от спама!');
		form.code.focus();
		return false;
	}

	return true;
}

var AllSelected = false;
function selectAll(inputName){
	var inputs = document.getElementsByTagName('INPUT');
    for(var i=0; i<inputs.length; i++) {
        var input = inputs[i];
        if (input.name == inputName) {
            input.checked = !AllSelected;
        }
    }
    AllSelected = !AllSelected;
}

function getSelectedFilesId(inputName) {
    var inputs = document.getElementsByTagName('INPUT');
    var ids = Array();
    
    for(var i=0; i<inputs.length; i++) {
        var input = inputs[i];
        if (input.name == inputName && input.checked) {
            ids.push(input.value);
        }
    }
    
    return ids;
}

function getSelectedFiles(inputName) {
    var inputs = document.getElementsByTagName('INPUT');
    var title = '';
    
    for(var i=0; i<inputs.length; i++) {
        var input = inputs[i];
        if (input.name == inputName && input.checked) {
            title += ' - ' + document.getElementById('title_'+input.value).innerHTML + '\n';
        }
    }
    
    return title;
}

function confirmDeleteSelected() {
    var files = getSelectedFiles('videos[]');

    if (files)
        return confirm('Вы действительно хотите удалить выбранные файлы:\n'+files);
    else {
        alert('Выберите хотя бы один файл, который Вы хотите удалить!');
        return false;
    }
}

function confirmReCreateSelected() {
    var files = getSelectedFiles('videos[]');

    if (files) {
    	if (confirm('Вы действительно хотите восстановить выбранные файлы:\n'+files)) {
    		document.getElementById('files-form-action').value = 'ReCreate-selected';
    		return true;
    	} else {
    		return false;
    	}
    } else {
        alert('Выберите хотя бы один файл, который Вы хотите удалить!');
        return false;
    }
}

function confirmDeleteSelectedContacts() {
    var contacts = getSelectedFiles('contacts[]');

    if (contacts)
        return confirm('Вы действительно хотите выбранных пользователей:\n'+contacts);
    else {
        alert('Выберите хотя бы одного пользователя, которого Вы хотите удалить!');
        return false;
    }
}
function implode( glue, pieces ) {
    return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}
function confirmCopyTo(btn) {
    var select = null;
    var s = '';
    for (var i in btn.parentNode.childNodes) {
        select = btn.parentNode.childNodes[i];
        if (select.tagName && select.tagName == 'SELECT')
            break;
    }

    if (select.value) {
        var files = getSelectedFilesId('videos[]');
        
        if (files) {
            if(document.getElementById('selected-files')){
            	document.getElementById('selected-files').value = files.join(',');
            }
            document.getElementById('files-form-action').value = 'move';
            document.getElementById('files-form-to').value = select.value;
            if(document.getElementById('selected-files').value != ''){
            	document.getElementById('files-form').submit();
            }
            return false;
        }
        else {
            alert('Выберите хотя бы один файл, который Вы хотите скопировать!');
        }
    }
    else {
        alert('Выберите место, куда Вы собираетесь скопировать файлы!');
    }
}

function confirmMoveTo(btn) {
    var select = null;
    var s = '';
    for (var i in btn.parentNode.childNodes) {
        select = btn.parentNode.childNodes[i];
        if (select.tagName && select.tagName == 'SELECT')
            break;
    }

    if (select.value) {
        var contacts = getSelectedFiles('contacts[]');
        
        if (contacts) {
            document.getElementById('contacts-form-action').value = 'move';
            document.getElementById('contacts-form-to').value = select.value;
            document.getElementById('contacts-form').submit();
        }
        else {
            alert('Выберите хотя бы одного пользователя, которого Вы хотите переместить!');
        }
    }
    else {
        alert('Выберите группу, куда Вы собираетесь переместить пользователей!');
    }
    
    return false;
}

function changePlaylist(select) {
    location.href = document.getElementById('playlists-url').value + '?list_id=' + select.value;
}

function openDialog(userId) {
    var width  = 500;
    var height = 550;

	_left = screen.width/2  - width/2;
	_top  = screen.height/2 - height/2;
	window.open('/user/my-messages/dialog/?user_id='+userId,'','status=yes,menubar=no,toolbar=no,resizable=no,scrollbars=no,width='+width+',height='+height+', left='+_left+',top='+_top);
	
	return false;
}

function openWindow(url, width, height) {
	_left = screen.width/2  - width/2;
	_top  = screen.height/2 - height/2;
	window.open(url,'','status=yes,menubar=no,toolbar=no,resizable=no,scrollbars=yes,width='+width+',height='+height+', left='+_left+',top='+_top);

	return false;
}

function updatePopularFiles(interval) {
	$.ajax({
		url: "/popular-files/?interval=" + interval,
		cache: false,
		success: function(html){
			$("#popular-month").removeClass('active-month');
			$("#popular-week").removeClass('active-week');
			$("#popular-day").removeClass('active-day');

			$("#popular-" + interval).addClass('active-' + interval);

			$("#container-video").html(html);
		}
	});

	return false;
}

function addToQuickList(url, id) {
	$.ajax({
		url: url + "?update=&action=ajax_add&id=" + id,
		cache: false,
		success: function(html){
			if (html == 'exists') {
				alert('Этот ролик уже присутствует в Вашем списке быстрого доступа.');
			}
			else if (html == 'not found') {
				alert('Информация о ролике не найдена!');
			}
			else {
				alert('Ролик `'+ html +'` добавлен в Ваш список быстрого доступа.');
			}
		}
	});

	return false;
}

function rateFile(url, id, r) {
	$.ajax({
		url: "/ajax/?action=ajax_rate&id=" + id + "&r="+ r,
		cache: false,
		success: function(responseXML){
if(responseXML && responseXML.firstChild){
r = responseXML.firstChild.getAttribute('r');
c = responseXML.firstChild.getAttribute('c');
m = responseXML.firstChild.getAttribute('m');
n  = c % 100;
n1 = c % 10;
			document.getElementById('current-rating').style.width = r + '%';
			}
		}
	});
	return false;
}
function DeleteMyAccount(){
		$.ajax({
			url: "/ajax/?action=delete_my_profile",
			method: 'GET',
			cache: false,
			success: function(html){
				html = html.replace(/[\n\r\t]+/gi, '');
				if(html == 'OK'){
					alert('Очень жаль :(\nМы отправили на ваш электронный ящик письмо с дальнейшими инструкциями.');
					document.location.href = '/user/login/1-logout/';
				} else {
					alert('В данный момент сервер не может выполнить удаление');
				}
			}
		});
}
function editComment(id) {
	PostCommentId = id;
	var elP = document.getElementById('CommentP' + id);
	var elT = document.getElementById('CommentT' + id);
	if(elP){
		if(elP.style.display == 'none'){
			elP.style.display = '';
			divEl = elT.parentNode;
			divEl.style.display = 'none';
		}else{
			elP.style.display = 'none';
			if(elP.parentNode && !elT){
					var divEl = document.createElement('div');
					divEl.setAttribute('id', 'edit-comment');
					var textEl = document.createElement('textarea');
					textEl.setAttribute('name', 'text');
					textEl.setAttribute('id', 'CommentT' + id);
					var CommentCode = elP.innerHTML;
					CommentCode = CommentCode.replace(/<br>\n/gi, '\n').replace(/<br\/>/gi, '\n');
					CommentCode = CommentCode.replace(/<b>/gi, '[b]').replace(/<\/b>/gi, '[/b]');
					CommentCode = CommentCode.replace(/<span class="quote"><span class="author">([^<]+)<\/span>/gi, '[quote author="$1"]');
					CommentCode = CommentCode.replace(/<span class="quote">/gi, '[quote]').replace(/<\/span>/gi, '[/quote]');
					CommentCode = CommentCode.replace(/<a href="">/gi, '[a href=""]').replace(/<a href="(.[^"]+)">/gi, '[a href="$1"]').replace(/<\/a>/gi, '[/a]').replace(/<a href="([^"]+)" target="(.[^"]+)">/gi, '[a href="$1" target="$2"]').replace(/<\/a>/gi, '[/a]');
					textEl.innerHTML = CommentCode;
					var btnEl  = document.createElement('input');
					btnEl.setAttribute('type', 'button');
					btnEl.setAttribute('value', 'Редактировать');
					btnEl.onclick = PostComment;
					divEl.appendChild(textEl);
					divEl.appendChild(btnEl);
					elP.parentNode.appendChild(divEl);
			}else{
					divEl = elT.parentNode;
					divEl.style.display = '';
			}
		}
	}
	return false;
}

function quoteComment(id){
	var CommentCode = (document.selection)?document.selection.createRange().text:window.getSelection();
	var UserName = document.getElementById('CommentA' + id).innerHTML;
	if(!CommentCode || CommentCode == ''){
		elP    = document.getElementById('CommentP' + id);
		CommentCode = elP.innerHTML;
	}
	CommentCode = CommentCode.replace(/<br>\n/gi, '\n').replace(/<br\/>/gi, '\n');
	CommentCode = CommentCode.replace(/<b>/gi, '[b]').replace(/<\/b>/gi, '[/b]');
	CommentCode = CommentCode.replace(/<span class="quote"><span class="author">([^<]+)<\/span>/gi, '[quote author="$1"]');
	CommentCode = CommentCode.replace(/<span class="quote">/gi, '[quote]').replace(/<\/span>/gi, '[/quote]');
	CommentCode = CommentCode.replace(/<a href="">/gi, '[a href=""]').replace(/<a href="(.[^"]+)">/gi, '[a href="$1"]').replace(/<\/a>/gi, '[/a]').replace(/<a href="([^"]+)" target="([^"]+)">/gi, '[a href="$1" target="$2"]').replace(/<\/a>/gi, '[/a]');
	document.forms['CommentForm'].elements['text'].value += '[quote author="'+UserName+'"]'+CommentCode+'[/quote]';
	document.forms['CommentForm'].elements['text'].focus();
	return false;
}