var auth_err_mess = 'Что-то мы вас не узнаем. <a href="/login/">Представьтесь</a>, пожалуйста. Eсли вы не зарегистрированы, <a href="/reg/">зарегистрируйтесь</a>!';
var $j = jQuery.noConflict();

if(typeof cfg == 'undefined')
{
	cfg = {};
}
// тест
cfg.sTest = cfg.bTest?'/test':'';
		
// объект swfupload
cfg.oSwfUpload = null;

// урлы
cfg.oUrls = {
	swfuploader:cfg.sTest + '/swf/swfupload.swf',
	upload:cfg.sTest + '/upload.php'
};

// сообщения
cfg.oMessages = {
	delete_confirm:'Вы уверены что хотите произвести удаление?',
	waiting:'Ожидание...',
	big_file:'Файл слишком большой',
	empty_file:'Невозможно загрузить пустой файл',
	invalid_file:'Неверный формат файла',
	undefined:'Неизвестная ошибка',
	query_limit:'Превышен лимит в {num} файлов',
	loading:'Загрузка&hellip;',
	canceled:'Отменено',
	error_loading:'Ошибка загрузки: ',
	error_falied:'Ошибка загрузки',
	error_io:'Ошибка ввода-вывода',
	error_security:'Ошибка безопасности',
	error_timeout:'Время ожидания закончилось',
	error_stopped:'Загрузка остановлена',
	error_undefined:'Неизвестная ошибка: '
};

// загрузка изображений
cfg.oImgLoading = {
	iCurFileNum:0,
	file_size_limit:'2MB',
	file_upload_limit: 150,
	file_queue_limit: 150,
	file_types_description : "Фото файлы",
	sPattern:''+
'<div class="img-area" id="{file_id}">'+
	'<div class="img">'+
		'<i>0%</i>'+
		'<b>Загрузка&hellip;</b>'+
		'<input type="button" value="Отмена"/>'+
	'</div>'+
	'<i></i>'+
'</div>',
	sFormPattern:''+
'<div class="img-area">'+
	'<div class="img">'+
		'<a class="left" href="#"><img src="{url_prefix}/i/arrow_back.gif"/></a>'+
		'<a class="right" href="#"><img src="{url_prefix}/i/arrow_next.gif"/></a>'+
		'<a class="delete" href="#"><img src="{url_prefix}/i/a_delete.gif"/></a>'+
		'<a href="#" class="lightbox" rel="div.imgs">'+
			'<img src="{thumb_src}"/>'+
			'<div class="hidden imgs">'+
				'<input type="hidden" name="img[{index}][id]" value="{id}"/>'+
				'<input type="hidden" name="img[{index}][ext]" value="{ext}"/>'+
				'<input type="hidden" name="img[{index}][width]" value="{width}"/>'+
				'<input type="hidden" name="img[{index}][height]" value="{height}"/>'+
				'<input type="hidden" name="img[{index}][name]" value="{name}"/>'+
			'</div>'+
		'</a>'+
	'</div>'+
'</div>',
	iTimeout:5000
};
cfg.oImgPatterns = {
	full:'/i/post/{pic_th}/{pic_id}_full.{ext}',
	normal:'/i/post/{pic_th}/{pic_id}.{ext}',
	small:'/i/thumb/88x66/post/{pic_th}/{pic_id}.{ext}'
};

cfg.bNoAutosave = false;

$j(document).ready(
	function() {
		// общие обработчики
		
		$j('.pl_item').each(
			function() {
				$j('#footer_links div:eq(0) .a-right').before($j(this));
			}
		)		
			
		// если тестовая версия, то проставляем префикс '/test' всем ссылкам
		if(jisset($j('input[type=hidden][name=test][value=1]'))) {
			$j('a').each(
				function() {
					var sUrl=$j(this).attr('href');
					if(isset(sUrl) && sUrl.substr(0,1)=='/') {
						$j(this).attr('href','/test'+sUrl);
					}
				}
			)
		}

		// переключение закладок рубрики / сообщества
		$j('#rubr_1 a.tab').click(
			function() {
				if(!$j(this).hasClass('active')) {
					$j('#rubr_1 a.tab.active').removeClass('active');
					$j(this).addClass('active');
					var oPanelLi = $j(this).parents('li:eq(0)');
					if(oPanelLi.hasClass('rubric')) {
						$j('#rubr_1 .categories').removeClass('hide');
						$j('#rubr_1 .comms').addClass('hide');
						setCookie('panel', 'categories');
					} else if (oPanelLi.hasClass('community')) {
						$j('#rubr_1 .categories').addClass('hide');
						$j('#rubr_1 .comms').removeClass('hide');
						setCookie('panel', 'comms');
					}
				}
				return false;
			}
		);		
		
		var sPanel = getCookieValue('panel');
		if(sPanel == 'comms') {
			$j('#rubr_1 li.community a.tab').click();
		} else {
			$j('#rubr_1 li.rubric a.tab').click();			
		}
		
		// Определяем тип страницы
		var oInputPage = $j('input[type=hidden][name=page]');
		if(jisset(oInputPage)) {
			var ePage = oInputPage.attr('value');
		}
		
		// В зависимости от типа страницы добавляем необходимые обработчики
		switch(ePage)
		{
			case 'write':
				cfg.iStartWriteDt = new Date();
				window.setInterval("autosave();", 150000);
				$j(window).unload(
					function(){
						if(!cfg.bNoAutosave) {
							autosave();
						}
					}
				);
				
				$j('#btnCancel').click(
					function()
					{
						return false;
					}
				);
    			$j('.imgs-area input[type=checkbox]')
    				.livequery(
    					'click',
    					checkboxEvent
    				);
    			$j('.upload .img-area input.name')
    				.livequery(
    					'change',
						function()
						{
							$j(this).parent('.img-area').find("input[name*='[name]']").val($(this).val());
						}
					);
				initFileUploading();
								
			break;
			// обработчики событий страницы поста
			case 'post':
				// Подтверждение на удаление опроса
				$j('a.delete.edit_button').click(
					function()
					{
						if(!confirm('Вы действительно хотите удалить опрос?'))
						{
							return false;
						}
					}
				);

				
				// Кнопка проголосовать
				$j('.voteSubmit').click(
					function()
					{
						var oButton = $j(this);
						var oForm = oButton.parents('form'),i,ii;
						var aAnswers=oForm.get(0).elements,oData={};
						var bFlag=true,aMatches;
						for(i=0;i<aAnswers.length;i++)
						{
							var oElement=aAnswers[i];
							switch(oElement.type)
							{
								case 'checkbox':
								case 'radio':
									if(aMatches = oElement.name.match(/^([a-z]+)\[(\d+)\]$/))
									{
										var sEnt=aMatches[1];
										var iQuestionId=aMatches[2];
										var value;
										if(oElement.checked)
										{
											if(typeof oData[sEnt] == 'undefined')
											{
												oData[sEnt]=[];
											}
											if(typeof oData[sEnt][iQuestionId] == 'undefined')
											{
												oData[sEnt][iQuestionId]=[];
											}
											if(oElement.value.substring(0,1) == 'f')
											{
												if(typeof oData['free_'+sEnt] == 'undefined')
												{
													oData['free_'+sEnt]=[];
												}
												if(typeof oData['free_'+sEnt][iQuestionId] == 'undefined')
												{
													oData['free_'+sEnt][iQuestionId]=[];
												}
												var oText=oForm.get(0).elements[oElement.value];
												if(oText.value!='')
												{
													oData['free_'+sEnt][iQuestionId][oData['free_'+sEnt][iQuestionId].length]=oText.value;
													var value=0;
												}
											}
											else
											{
												var value=parseInt(oElement.value);
											}
											if(typeof value!='undefined')
											{
												oData[sEnt][iQuestionId][oData[sEnt][iQuestionId].length] = value;
											}
										}
										else
										{
											if(!
												(
													oElement.parentNode.tagName.toLowerCase()=='div'
													&&
													$j(oElement.parentNode).hasClass('question')
													&&
													$j(oElement.parentNode).hasClass('notNeeded')
												)
											)
											{
												if(typeof oData[sEnt] == 'undefined')
												{
													oData[sEnt]=[];
												}
												if(typeof oData[sEnt][iQuestionId] == 'undefined')
												{
													oData[sEnt][iQuestionId]=[];
												}						
											}					
										}
									}
								break;
								case 'hidden':
									if(oElement.name == 'vote_id')
									{
										oData['vote_id'] = oElement.value;
									}
								break;
								
									if(aMatches = oElement.name.match(/^([a-z]+)\[(\d+)\]$/))
									{
										var sEnt=aMatches[1];
										var iQuestionId=aMatches[2];
										if(oElement.checked)
										{
											if(typeof oData[sEnt] == 'undefined')
											{
												oData[sEnt]=[];
											}
											if(typeof oData[sEnt][iQuestionId] == 'undefined')
											{
												oData[sEnt][iQuestionId]=[];
											}		
											oData[sEnt][iQuestionId][oData[sEnt][iQuestionId].length] = oElement.value;
										}
									}
								break;			
					
							}
						}
						
						for(i in oData)
						{
							for(ii in oData[i])
							{
								if(oData[i][ii].length == 0)
								{
									bFlag=false;
								}
							}
						}
						
						if(!bFlag)
						{
							alert('Выберите вариант ответа!');
							return false;
						}
					
						postAjax('/inc/site/ajax/add_vote.php',oData, oButton);
						return false;
					}
				);
				

				// Кнопка отображения всей истории поста "Показать всю историю"
				$j('.history_list a.dashed').click(
					function(a)
					{
						$j(this).hide();
						$j('.history_list li').show();
						return false;
					}
				);
			
				// барьер по оценке комментариев
				$j('select.comments_barrier').change(
					function()
					{
						setCookie('comment_barrier',this.value);
						document.location.hash = 'comment_list';
						document.location.reload(false);
					}
				);
			
				// оценка комментария
				$j('.buttons input[type=image]').click(
					function()
					{
						var oComment = getCommentByObj($j(this));
						if(!auth())
						{
							authPopUp(oComment.prev(),false);
						}
						else
						{
							if($j(this).hasClass('bad'))
							{
								var iType = 2;
							}
							else if($j(this).hasClass('good'))
							{
								var iType = 1;
							}
							var aData = {iCommentId:oComment.find('input[name=comment_id]').attr('value'),'m':iType};
							postAjax('/inc/site/ajax/write_comment_mark.php',aData,oComment);
						}
						return false;
					}
				);
				
				// отобразить скрытый комментарий
				
				$j('dl.comment_bad a.arrow.unhide').livequery(
					'click',
					unhideComment
				);
				
				// добавление ответного комментария
				$j('dl.comment_bad a.arrow.reply,dl.comment_good a.arrow.reply').click(
					function()
					{
						var oComment = getCommentByObj($j(this));
						var aData = {iCommentId:oComment.find('input[name=comment_id]').attr('value')};
						postAjax('/inc/site/ajax/show_comment_form_reply.php',aData,oComment);
						return false;
					}
				);		
				
			break;
			default:

				// дружить
				$j('.user-profile input.but-friend').click(
					function()
					{
						var oBut=$j(this);
						if(!auth())
						{
							authPopUp(oBut);
						}
						else
						{
							var aData={
								'id':$j('.user-profile input:hidden[name=id]').attr('value'),
								'in':$j('.user-profile input:hidden[name=friend]').attr('value')==0?1:0
							};
							postAjax("/inc/site/ajax/friend.php",aData,oBut);
						}
						return false;
					}
				);		
				
				// вступить в сообщество, выйти из сообщества
				$j('input.in-comm[type=button]').click(
					function()
					{
						if(!auth())
						{
							authPopUp($j(this).parents('.pblock'),false);
						}
						else
						{
							var oComm = $j(this).parents('.comm-profile,.comm-header');
							var aData = {iCommId:parseInt(oComm.find('input[name=id]').attr('value'))};
							postAjax('/inc/site/ajax/in_comm.php',aData,oComm);
						}
						return false;
					}
				);
				
				// проверка логина на доступность на странице регистрации
				$j('input[name=check_login]').click(
					function()
					{
						var sLogin = $j('#f_login').attr('value');
						if(!isset(sLogin))
						{
							$j('#note_f_login').text('Введите логин');
						}
						else
						{
							var aData={'sLogin':sLogin};
							postAjax('/inc/site/ajax/check_uniq_login.php',aData);
						}
					}
				);
				
			
				// ajax контроль формы создания сообщества
				$j('form.comm input[name=name],form.comm input[name=nick]').change(
					function()
					{
						$j('form.comm span.error').text('');
						if(!$j('form.comm input[name=name]').attr('value'))
						{
							$j('form.comm input[name=name] + span.error').text('Поле обязательно для заполнения');
						}
						if(!$j('form.comm input[name=nick]').attr('value'))
						{
							$j('form.comm input[name=nick] + span.error').text('Поле обязательно для заполнения');
						}				
						var aData={
							name:$j('form.comm input[name=name]').attr('value'),
							nick:$j('form.comm input[name=nick]').attr('value')
						};
						postAjax("/inc/site/ajax/comm_check.php",aData,$j(this));
					}
				)
				
				
				// кнопка показать всех пользователей на странице профайла сообщества
				$j('.comm-profile .users .all').click(
					function()
					{
						var aData={id:$j('.comm-profile input:hidden[name=id]').attr('value')};
						postAjax("/inc/site/ajax/all_comm_users.php",aData,$j(this));
						return false;
					}
				);
				
				// кнопка показать все описание на странице сообщества
				$j('.comm-header .more').click(
					function()
					{
						var oMore=$j(this).parents('span');
						var sText=oMore.find('.hide').html();
						oMore.replaceWith(sText);
						return false;
					}
				);
			break;
		}

		// закрыть хинт кнопка
		$j('#hint1 .toclose').click(
			function()
			{
				if(auth())
				{
					$j.post(
						"/inc/site/ajax/hide_hint.php",
						{},
						function(mData)
						{
							if(mData.bSuccess)
							{
								$j('#hint1').hide();
							}
					  	},
						'json'
					);	
				}
				else
				{				
					setCookie('hide_hint',1);
					$j('#hint1').hide();
					
				}
				return false;
			}
		)
		
		// кнопка обновить хинт
		$j('#hint1 .toreload, #hint1 .btw').click(
			function()
			{
				postAjax("/inc/site/ajax/hint.php",{},$j(this));
				return false;
			}
		);
		
		
		// кнопка создать сообщество
		$j('#rubr_1 .comms input').click(
			function()
			{
				location='/comm/create/';
			}
		);

		// отвязка от сообщества
		$j('.comms a.not').click(
			function()
			{
				var oLink=$j(this);
				if(!auth())
				{
					authPopUp(oLink.parents('.pblock'),false);
				}
				else
				{
					var aData={iPostId:getPostId(oLink),iCommId:oLink.children('input[name=comm_id]').attr('value')};
					postAjax('/inc/site/ajax/write_post_comm_action.php',aData,oLink);
				}
				return false;
			}
		);		
		
		// отвязка от рубрики
		$j('.categories a.not').click(
			function()
			{
				var oLink=$j(this);
				if(!auth())
				{
					authPopUp(oLink.parents('.pblock'),false);
				}
				else
				{
					var aData={iPostId:getPostId(oLink),iCategoryId:oLink.children('input[name=category_id]').attr('value')};
					postAjax('/inc/site/ajax/write_post_category_action.php',aData,oLink);
				}
				return false;
			}
		);

		// спасибы
		$j('.golos input[type=button],.thx_block input#bottom_golos').click(
			function()
			{
				var oInput=$j(this);
				if(!auth())
				{
					if(jisset($j(this).parents('.thx_block')))
					{
						authPopUp($j(this).parents('.thx_block'),false);
					}
					else
					{
						authPopUp($j(this).parents('.pblock'),false);
					}
				}
				else
				{
					var aData={iPostId:getPostId($j(this))};
					postAjax('/inc/site/ajax/write_post_mark.php',aData,oInput);
				}
			}
		);
		
		// жалобы на пост
		$j('select[name=karma_action]').change(
			function()
			{
				var oSelect=$j(this);
				if(!auth())
				{
					oSelect.attr('value',0);
					authPopUp(oSelect.parents('.pblock'),false);
				}
				else
				{
					if(confirm('Пожаловаться?'))
					{
						var aData={iPostId:getPostId(oSelect),iActionId:oSelect.attr('value')};
						postAjax("/inc/site/ajax/write_post_action.php",aData,oSelect);
					}
					else
					{
						$j(this).attr('value',0);
					}
				}
			}
		);
		
		// альбомы
		$j('.album').each(
			function()
			{
				var oAlbum = $j(this);
				oAlbum.find('a.next,a.prev').click(
					function()
					{
						var oNav = oAlbum.find('.nav'),
							oInner = oNav.find('.inner'),
							oSelect = oInner.find('a.select');
						if($j(this).hasClass('next'))
						{
							var oA = oSelect.next('a');
						}
						else
						{
							var oA = oSelect.prev('a');
						}
						if(oA.size())
						{
							var iIndex = oInner.find('a').index(oA.get(0));
							oNav.get(0).scrollLeft = iIndex*95;
							oA.trigger('click');
						}
						return false;
					}
				);
				$j('.main td.img a').livequery(
					'click',
					function()
					{
						var oThis = $j(this),
							sSrc = oThis.attr('href'),
							iId = oThis.find('[name=id]').val(),
							iWidth = oThis.find('[name=width]').val(),
							iHeight = oThis.find('[name=height]').val();
						open_post_imgage(sSrc, iId, iWidth, iHeight);
						return false;
					}
				);
				
				oAlbum.find('.nav .inner a').click(
					function()
					{
						var oThis = $j(this),
							oMain = oAlbum.find('.main td.img'),
							oDesc = oAlbum.find('.desc'),
							sSrc = oThis.attr('href'),
							sDesc = oThis.find('span').text(),
							oFullSrc = oThis.find('[name=full_src]'),
							sHtml = '<img src="'+sSrc+'"/>';
						oAlbum.find('.inner .select').removeClass('select');
						
						oThis.addClass('select');
						if(oFullSrc.size())
						{
							var sFullSrc = oFullSrc.val(),
								iFullWidth = oThis.find('[name=full_width]').val(),
								iFullHeight = oThis.find('[name=full_height]').val(),
								sHtml = '<a href="'+sFullSrc+'">'+sHtml+'<input type="hidden" name="full_width" value="'+iFullWidth+'"/><input type="hidden" name="full_height" value="'+iFullHeight+'"/></a>';
						}
						oMain.html(sHtml);
						if(isset(sDesc) && sDesc!='')
						{
							oDesc.text(sDesc);
							oDesc.show();
						}
						else
						{
							oDesc.hide();
						}
						return false;
					}
				);

				var iWidth = oAlbum.find('.nav img').size() * 95;
				
				oAlbum.find('.nav .inner').width(iWidth+2);
				oAlbum.show();
				oAlbum.find('.nav').get(0).scrollLeft=0;
				//oAlbum.find('.nav').height(oAlbum.find('.nav').height()+1);		
				
			}
		)
		
		$j('a.tt').hover(
			function()
			{
				$j(this).addClass('hover');
			},
			function()
			{
				$j(this).removeClass('hover');
			}
		);		
	}
);

// правка комментария
function editComment(oLink){
	var oComment = getCommentByObj($j(oLink));
	var aData = {iCommentId:oComment.find('input[name=comment_id]').attr('value')};
	postAjax('/inc/site/ajax/show_comment_form_edit.php',aData,oComment);
	return false;
}


// в/из избранное
function toFav(oObj)
{
	var oBlock = $j(oObj).parents('.thx_block');
	if(!auth())
	{
		authPopUp(oBlock, false);
	}
	else
	{
		var oData = {iPostId:getPostId($j(oObj)), eType:$j('input#fav_type').val()};
		postAjax('/inc/site/ajax/fav.php', oData, oBlock);
	}
	return false;
}

function unhideComment() {
	var oComment = getCommentByObj($j(this));
	$j(this).hide();
	oComment.find('.body').show();
	oComment.find('.buttons').addClass("show");
	return false;
}

function markSpamComment(oLink) {
	var oComment = getCommentByObj($j(oLink));
	if(!auth()) {
		authPopUp(oComment.prev(),false);
	} else {
		var aData = {iCommentId:oComment.find('input[name=comment_id]').attr('value'),iActionId:6};
		postAjax('/inc/site/ajax/write_comment_action.php',aData,oComment);
	}
	return false;
}



function unpopp(){
	poppDiv=document.getElementById('poppDiv');if(poppDiv){poppDiv.parentNode.removeChild(poppDiv);poppDiv=false;}

		var elements = document.getElementsByTagName('select');
		for(var i = 0; i < elements.length; i++) {
			if(elements[i].style.display=='none') elements[i].style.display='inline';
		}	

}
function popp(id, text, type, last){
	unpopp();
	
	if(type==0){
		document.getElementById('post_action'+id).style.display='none';
	}	
	if(last)
	{
		document.getElementById('enclosure_last'+id).innerHTML+='<div id="poppDiv" class="inline-warning"><div><p>'+text+'</p><a href="javascript:unpopp(1)"><img src="/i/close.gif" class="close" width="22" height="22" alt="Close" /></a></div></div>';
	}
	else
	{
		document.getElementById('enclosure'+id).innerHTML+='<div id="poppDiv" class="inline-warning"><div><p>'+text+'</p><a href="javascript:unpopp(1)"><img src="/i/close.gif" class="close" width="22" height="22" alt="Close" /></a></div></div>';
	}
	return(false);
}


//просмотр большой картинки в новом окне
function open_post_imgage(url, id, w, h) {
	window.open (''+url, 'post_image'+id, 'width=640, height=480, scrollbars = yes, status=yes, toolbar=no, menubar=no, resizable=1'); 
	return false;
} 


function getCommentByObj(oObj)
{
	return $j(oObj).parents('dl.comment_bad,dl.comment_good').filter('*:eq(0)');
}

function save_comment(comment_id, oObj)
{
	var oComment = getCommentByObj(oObj);
	var aData = {iCommentId:comment_id, sMessage:oComment.find('textarea.comment_text').attr('value')};
	postAjax('/inc/site/ajax/save_comment.php',aData,oComment);
}

function comment_edit_cancel(comment_id, oObj)
{
	var oComment = getCommentByObj(oObj);
	oComment.find('.for-edit .for-form').html('');
	oComment.find('a.arrow.reply').show();
	oComment.find('a.arrow.edit').show();
	if(oComment.find('.body').css('display') == 'none')
	{
		oComment.find('a.arrow.unhide').show();
	}
}

function comment_reply_cancel(comment_id, oObj)
{
	var oComment = getCommentByObj(oObj);
	oComment.find('.for-reply .for-form').html('');
	oComment.find('.for-reply .for-form').css('display', 'inline');
	oComment.find('a.arrow.reply').show();
	oComment.find('a.arrow.edit').show();
	if(oComment.find('.body').css('display') == 'none')
	{
		oComment.find('a.arrow.unhide').show();
	}
}

function form_validate(form_id) {
	var str_full = "";
	var elements = document.getElementById(form_id).getElementsByTagName('input');
	// цикл по всем элементам формы
	for(var i = 0; i < elements.length; i++) {
	// проверяем, имеется ли образец
		var str = "";     
		var pattern = elements.item(i).getAttribute('pattern');
		var value = elements.item(i).value;     
		var element_id=elements.item(i).getAttribute('id');
		var noteDiv=document.getElementById('note_'+element_id);
		if (pattern != null && pattern != "") {
			// валидация значения элемента, используя образец      
			var offendingChar = value.match(pattern);      
			// если встечен недопустимый символ или элемент оставлен пустым 
	    	if(offendingChar != null || value.length == 0) {
				// показываем сообщения об ошибках
				str += elements.item(i).getAttribute('errorMsg') + "\n" +        "Найдено недопустимое значение: '" + offendingChar + "' \n";
			}
		}
		//проверяем длинну строки
		var min_reqs = elements.item(i).getAttribute('min_reqs');  
		var max_reqs = elements.item(i).getAttribute('max_reqs');  
		if (min_reqs && max_reqs) {
			if (value.length < min_reqs || value.length > max_reqs) {
				str += elements.item(i).getAttribute('errorMsg') + '\n';
			}
		}		
		if (str != "")		{
			if(noteDiv != null) noteDiv.innerHTML=str;
			// подсказка пользователю путем смены цвета фона; здесь красный
			elements.item(i).style.background = "#ffccff";       
		}	
		str_full+=str;
	}
	if (str_full != "") {
		// не посылаем форму
		alert("Что-то пошло не так.\n" +str_full);
		return false;
	} 
	else {
		// значения формы правильны; посылаем    
		document.getElementById(form_id).submit();
		return true;  
	}
}

function input_validate(id) {
	var str = "";
	// проверяем, имеется ли образец
	var elem=document.getElementByID(id);
	var noteDiv=document.getElementByID('note_'+id);
	var pattern = elem.getAttribute('pattern');
	var value = elem.value;     
	if (pattern != null) {
		// валидация значения элемента, используя образец      
		var offendingChar = value.match(pattern);      
		// если встечен недопустимый символ или элемент оставлен пустым 
    	if(offendingChar != null || value.length == 0) {
			// показываем сообщения об ошибках
			str += elem.getAttribute('errorMsg') + "\n" +        "Найдено недопустимое значение: '" + offendingChar + "' \n";
			// подсказка пользователю путем смены цвета фона; здесь красный
			elem.style.background = "red";       
		}
	}
	//проверяем длинну строки
	var min_reqs = elem.getAttribute('min_reqs');  
	var max_reqs = elem.getAttribute('max_reqs');  
	if (min_reqs != null && max_reqs != null) {
		if (value < min_reqs || value > max_reqs) {
			str += elem.getAttribute('errorMsg') + '\n';
		}
	}		
	noteDiv.innerHtml="aaaa";	
	if (str != "") {
		// не посылаем форму
		noteDiv.innerText=str;
		return false;
	} 
	else {
		// значения формы правильны; посылаем    
		return true;  
	}
}

/* -------------  ПОЧТА ------------------ */
function email (login, serv)
{
	if(serv=="") serv="risk.ru";
	eml = login +  "@" + serv;
	return eml;
}


function mylo (login, serv)
{
 document.write (email(login, serv));
}

function namylo (login, serv, subj)
{
eml = "mailto:" + email(login, serv);
re= /\s/;
while(subj.search(re)>0)
subj=subj.replace(re, "%20");

if (subj != "") eml += "?subject=" + subj;
window.location.href = eml;
} 

function shlop(id)
{
	if(document.getElementById('s'+id).style.display=='none')
	{
		document.getElementById('s'+id).style.display="block";
		document.getElementById('r'+id).checked=1;
		document.getElementById('i'+id).value = document.getElementById('t'+id).innerHTML;
		disable_inputs(id);
	}
	else
	{
		document.getElementById('s'+id).style.display="none";
		var spans=document.getElementsByTagName('span'),i;
		for(i=0;i<spans.length;i++)	
		{
			if(spans[i].style.display=='block')
			{
				var text=spans[i].getElementsByTagName('input')[1],radio=spans[i].getElementsByTagName('input')[0];
				id=text.id;
				id=id.substr(1,id.length-1);
				radio.checked=1;
				text.disabled=0;
				disable_inputs(id);
				return;
			}
		}
		
	}
}

function disable_inputs(id)
{
	var inputs=document.getElementsByTagName('input'),i;
	for(i=0;i<inputs.length;i++)	
	{
		if(inputs[i].type=='text')
		{
			if((inputs[i].id!='i'+id)&&(inputs[i].id!="first_search"))
			{
				inputs[i].disabled=1;
			}
			else
			{
				inputs[i].disabled=0;
			}
		}
		if(inputs[i].type=='button')
		{
			if(inputs[i].id!='b'+id)
			{
				inputs[i].disabled=1;
			}
			else
			{
				inputs[i].disabled=0;
			}
		}
	}
}
function submit_shlop(id)
{
	var form=document.getElementById('shlop');
	var inputs=document.getElementsByTagName('input'),i,k=0,id;
	for(i=0;i<inputs.length;i++)	
	{
		if((inputs[i].type=='checkbox')&&(inputs[i].checked))
		{
			var input=document.getElementById('tag_ids');
			if(k++>0)
			{
				input.value+=",";
			}
			id=inputs[i].id;
			id=id.substr(1,id.length-1);
			input.value+=id;
		}
		if((inputs[i].type=='text')&&(!inputs[i].disabled))
		{
			document.getElementById('text').value=inputs[i].value;
		}
		if((inputs[i].type=='radio')&&(inputs[i].checked))
		{
			id=inputs[i].id;
			id=id.substr(1,id.length-1);
			document.getElementById('id').value=id;
		}
	}
	document.getElementById('search').value=document.getElementById('first_search').value;
	form.submit();	
}

function num_declension($n, $arr)
{
	
	$d=0; //десяток
	$e=0; //единицы
	
	if($n<10) $e=$n;
	else{
		$e=$n-Math.floor($n/10)*10;
		if($n>9){
			$d=Math.floor(($n-Math.floor($n/100)*100)/10);
		}
	}
	
	if($d==1)	$str=$arr[0];
	
	else if(n_array($e, [2,3,4]))
	{
		$str=$arr[2];
	}
	else if($e==1)
	{
		$str=$arr[1];
	}
	else	$str=$arr[0];
	return $str;
}
function n_array(i,arr)
{
	for(var k=0;k<arr.length;k++)
	{
		if(arr[k] == i)
		{
			return true;
		}
	}
	return false;
}
function scrollA()
{
	var ver = navigator.userAgent;
	if (ver.indexOf("Opera") == -1)
	{
		if (location.hash != "")
		{
			try
			{
				var hash_links = document.getElementsByTagName('A');
				for(var ind in hash_links)
				{
					if('#'+hash_links[ind].name == location.hash)
					{
						var element = hash_links[ind];
						var top=0;
						while(element)
						{
							top+=parseInt(element.offsetTop);
							element=element.offsetParent;
						}
						window.scrollTo(0,top);
					}
				}
			}
			catch(e){}
			
		}
	}
}

function addForm(oContext,sInputClassNamePostfix,sFormsClassName)
{
	if(document.getElementById)
	{
		var i,oTmp=oContext,oForms;
		for(i=0;i<5;i++)
		{
			if(oTmp.className==sFormsClassName)
			{
				oForms=oTmp;
				break;
			}
			else
			{
				oTmp=oTmp.parentNode;
			}	
		}
		if(typeof oForms=='undefined')
		{
			var oForm=document.getElementById('voteQuestions'),i;
			var oDivs=oForm.getElementsByTagName('div');
			for(i=0;i<oDivs.length;i++)
			{
				if(oDivs[i].className==sFormsClassName)
				{
					oForms=oDivs[i];
					break;
				}
			}
		}
		if(typeof oForms=='undefined')
		{
			return false;
		}		
		
		var tpl=oForms.firstChild,newNode=tpl.cloneNode(true);
		var iQuestionNum=0;
		var oDivs=oForms.getElementsByTagName('div');
		for(i=0;i<oDivs.length;i++)
		{
			if(oDivs[i].className=='vote-block')
			{
				iQuestionNum++;
			}
		}
		var oInputs=newNode.getElementsByTagName('input');
		var oSpans=newNode.getElementsByTagName('input');
		for(i=0;i<oSpans.length;i++)
		{
			if(oSpans[i].className=='delQuestion')
			{
				oSpans[i].style.visibility = 'visible';
			}
			if(
				(oSpans[i].className=='delAnswer')
				&&
				(sInputClassNamePostfix=='Answer')
			)
			{
				oSpans[i].style.visibility = 'visible';
			}
			if(
				(oSpans[i].className=='addAnswer')
				&&
				(sInputClassNamePostfix=='Answer')
			)
			{
				oSpans[i].style.visibility = 'visible';
			}						
		}
		var oLabels=newNode.getElementsByTagName('label');
		var html=newNode.outerHTML;
		for(i=0;i<oInputs.length;i++)
		{
			if(oInputs[i].type=='text')
			{
				oInputs[i].value='';
			}
			if(
				oInputs[i].name
				&&
				oInputs[i].name.match(/question\[\d+\]/)
				&&
				typeof html=='undefined'
				&&
				sInputClassNamePostfix=='Question'
			)
			{
				oInputs[i].name = oInputs[i].name.replace(/(question\[)(\d+)(\])/,'$1'+iQuestionNum+'$3');
			}
		}
		var html=newNode.outerHTML;
		if(
			typeof html=='undefined'
			||
			(navigator.userAgent.indexOf ("Opera") != -1)
		)
		{
			oForms.appendChild(newNode);
		}
		else
		{
			if(sInputClassNamePostfix=='Question')
			{
				html=html.replace(/(question\[)(\d+)(\])/gm,'$1'+iQuestionNum+'$3');
			}
			oForms.innerHTML+=html;
		}
		iQuestionNum++;
		checkEdge(oForms,sInputClassNamePostfix);
	}
}

function delForm(oContext,sInputClassNamePostfix,sFormClassName,sFormsClassName)
{
	if(document.getElementById)
	{
		var oTmp=oContext,oAnswer,oAnswers,i;
		for(i=0;i<7;i++)
		{
			if(oTmp.className==sFormClassName)
			{
				oAnswer=oTmp;
				oTmp=oTmp.parentNode;
			}
			else if(oTmp.className==sFormsClassName)
			{
				oAnswers=oTmp;
				break;
			}
			else
			{
				oTmp=oTmp.parentNode;
			}	
		}
		oAnswer.parentNode.removeChild(oAnswer);
		checkEdge(oAnswers,sInputClassNamePostfix);
	}
}

function addAnswer(oContext)
{
	addForm(oContext,'Answer','voteAnswersForm');
}
function delAnswer(oContext)
{
	delForm(oContext,'Answer','answer', 'voteAnswersForm');
}
function addQuestion(oContext)
{
	addForm(oContext,'Question','voteQuestionsForm');
	refreshNumsQuestions()
}
function delQuestion(oContext)
{
	delForm(oContext,'Question','vote-block', 'voteQuestionsForm');
	refreshNumsQuestions()
}

function checkEdge(oContext,sInputClassNamePostfix)
{
	var aInputs=oContext.getElementsByTagName("input"),disValue,i,j,aAddBtns=[],aDelBtns=[];
	var oForm=document.getElementById('voteQuestions');
	var oFormDivs=oForm.getElementsByTagName('div');
	var oQuestions=[];
	for(i=0;i<oFormDivs.length;i++)
	{
		if(
			oFormDivs[i]
			&&
			oFormDivs[i].className=='voteQuestionForm'
		)
		{
			oQuestions[oQuestions.length]=oFormDivs[i];
		}
	}
	for(i=0;i<oQuestions.length;i++)
	{
		var oQuestInputs=oQuestions[i].getElementsByTagName("input");
		for(j=0;j<oQuestInputs.length;j++)
		{
			if(
				oQuestInputs[j]
				&&
				oQuestInputs[j].name
			)
			{
				if(oQuestInputs[j].name.match(/question\[\d+\]/))
				{
					oQuestInputs[j].name = oQuestInputs[j].name.replace(/(question\[)\d+(\])/,'$1'+i+'$2');
				}
			}
		}
	}	
	
	for(i=0;i<aInputs.length;i++)
	{
		if(typeof aInputs[i]!='undefined')
		{
			if(aInputs[i].className=='add'+sInputClassNamePostfix)
			{
				aAddBtns[aAddBtns.length]=aInputs[i];
				continue;
			}
			if(aInputs[i].className=='del'+sInputClassNamePostfix)
			{
				aDelBtns[aDelBtns.length]=aInputs[i];
				continue;
			}
		}
	}
	
	if($j('div', oContext).size() == 16)
	{
		disValue=true;
	}
	else
	{
		disValue=false;
	}
	for(i=0;i<aAddBtns.length;i++)
	{
		aAddBtns[i].disabled=disValue;
	}
	
	if(oContext.childNodes.length == 1)
	{
		disValue=true;
	}
	else
	{
		disValue=false;
	}
	for(i=0;i<aDelBtns.length;i++)
	{
		aDelBtns[i].disabled=disValue;
	}
}

function checkAddVoteForm(oForm)
{
	var bEmptyInput=false;
	var oInputs=oForm.getElementsByTagName('input'),i;
	for(i=0;i<oInputs.length;i++)
	{
		if(
			typeof oInputs[i]!='undefined'
			&&
			typeof oInputs[i].type!='undefined'
			&&
			oInputs[i].type=='text'
			&&
			(
				(typeof oInputs[i].className=='undefined')
				||
				(
					typeof oInputs[i].className!='undefined'
					&&
					oInputs[i].className!='textAnswer'
				)
			)
		)
		{
			if(oInputs[i].value=='')
			{
				bEmptyInput=true;
			}
		}
	}
	var oDivs=oForm.getElementsByTagName('div'),i;
	for(i=0;i<oDivs.length;i++)
	{
		if(oDivs[i].className=='voteAnswersForm')
		{
			var oInputs=oDivs[i].getElementsByTagName('input'),j,iCntNotEmpty=0;
			for(j=0;j<oInputs.length;j++)
			{
				if(
					typeof oInputs[j]!='undefined'
					&&
					typeof oInputs[j].type!='undefined'
					&&
					oInputs[j].type=='text'
				)
				{
					if(oInputs[j].value!='')
					{
						iCntNotEmpty++;
					}
				}
			}
			if(iCntNotEmpty<2)
			{
				bEmptyInput=true;
			}
		}
	}
	
	if(bEmptyInput)
	{
		alert('Заполнены не все поля!');
		return false;
	}	
}
function refreshNumsQuestions()
{
	var oForm=document.getElementById("voteQuestions"),i,j;
	oDivs=oForm.getElementsByTagName('div');
	var iQuestionsCnt=0;
	for(i=0;i<oDivs.length;i++)
	{
		if(oDivs[i].className=='vote-block')
		{
			iQuestionsCnt++;
			var oLabels=oDivs[i].getElementsByTagName('label');
			for(j=0;j<oLabels.length;j++)
			{
				if(oLabels[j].className=="title")
				{
					oLabels[j].innerHTML="Вопрос "+iQuestionsCnt+':';
				}
			}
		}
	}
}
function showAnswers(oObj)
{
	var oOls=oObj.parentNode.getElementsByTagName('ol');
	for(i=0;i<oOls.length;i++)
	{
		if(oOls[i].className="user-answers")
		{
			show(oOls[i]);
		}
	}
}
function showTextarea(oObj,sId)
{
	var oObj=document.getElementById(sId);
	show(oObj)
}
function showResults()
{
	var oObj=document.getElementById('vote-results');
	show(oObj);
}
function show(oObj)
{
	if(oObj.style.display=='block')
	{
		oObj.style.display="none";
	}
	else if(oObj.style.display=='none')
	{
		oObj.style.display="block";
	}	
}
function confirmLink(sLink,sMsg)
{
	if(confirm(sMsg))
	{
    	window.location.href = sLink;
    	return true;
	}
	else
	{
    	return false;
	}
}

if ( window.Node )
Node.prototype.removeNode = function( removeChildren )
{
	var self = this;
	if ( Boolean( removeChildren ) )
	{
		return this.parentNode.removeChild( self );
	}
	else
	{
		var range = document.createRange();
		range.selectNodeContents( self );
		return this.parentNode.replaceChild( range.extractContents(), self );
	}
}
function execAjaxResult(mData, oForm)
{
	var i;
	if(
		isset(mData.bSuccess)
		&&
		isset(mData.aActions)
	)
	{
		for(i in mData.aActions)
		{
			var oAction=mData.aActions[i];
			if(isset(oAction.a))
			{
				var oObj;
				if(isset(oAction.f))
				{
					if(oAction.f)
					{
						oObj=oForm.find(oAction.s);
					}
					else
					{
						oObj=oForm;
					}
				}
				else
				{
					if(isset(oAction.s))
					{
						oObj=$j(oAction.s);
					}
				}
				switch(oAction.a)
				{
					case 'html':
						oObj.html(oAction.h);
					break;
					case 'class':
						oObj.addClass(oAction.h);
					break;
					case 'remove_class':
						oObj.removeClass(oAction.h);
					break;					
					case 'attr':
						oObj.attr(oAction.d, oAction.h);
					break;
					case 'text':
						oObj.text(oAction.h);
					break;					
					case 'append':
						oObj.append(oAction.h);
					break;
					case 'replace':
						oObj.replaceWith(oAction.h);
					break;					
					case 'show':
						oObj.show();
					break;
					case 'hide':
						oObj.hide();
					break;					
					case 'value':
						oObj.attr('value',oAction.h);
					break;
					case 'alert':
						alert(oAction.h);
					break;					
					case 'click':
						var fn = eval('function(){$j(this).each('+oAction.h+');return false;}');
						oObj.bind(oAction.a, fn);
					break;					
					case 'auth':
						if(jisset(oForm))
						{
							var oDiv=oForm.parents('.pblock:eq(0)');
							if(!jisset(oDiv))
							{
								oDiv=oForm.prev();
							}
							authPopUp(oDiv,false,isset(oAction.h)?oAction.h:undefined);
						}
					break;
				}
			}
		}
	}
}
function isset(oObj)
{
	return typeof oObj!='undefined'&&oObj!==null;;
}
function jisset(oObj)
{
	return oObj.size()!=0;
}
function auth()
{
	return !jisset($j('#login .reg'));
}
function setCookie(cookieName, cookieValue) {
	cookieValue=escape(cookieValue);
	document.cookie=cookieName+"="+cookieValue+"; path=/";
}
function getCookieValue(cookieName) {
	var cookieValue = document.cookie,u;
	var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
	if(cookieStartsAt == -1) {
		cookieStartsAt = cookieValue.indexOf(cookieName + "=");
	}
	if(cookieStartsAt == -1) {
		cookieValue = u;
	} else {
		cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
		var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
		if(cookieEndsAt == -1) {
			cookieEndsAt = cookieValue.length;
		}
		cookieValue = unescape(cookieValue.substring(cookieStartsAt, cookieEndsAt));
	}
	return cookieValue;
}

function authPopUp(oObj,bMakeWrap,sMessage, oSelects)
{
	if(!isset(sMessage))
	{
		sMessage=auth_err_mess;
	}	
	if(!isset(bMakeWrap))
	{
		bMakeWrap=true;
	}
	if(bMakeWrap)
	{
		var oDiv=oObj.parents('.auth');
		if(!jisset(oDiv))
		{
			oObj.wrap('<div class="auth"></div>');
			var oDiv=oObj.parents('.auth');
		}
	}
	else
	{
		oDiv=oObj;
	}
	oDiv.find('select').css('display','none');
	if(isset(oSelects)&&jisset(oSelects))
	{
		oSelects.hide();
	}
	oDiv.append('<div id="poppDiv" class="inline-warning"><div><p>'+sMessage+'</p><a href="#" class="close"><img src="/i/close.gif" width="22" height="22" alt="Close"/></a></div></div>');
	oDiv.find('a.close').click(
		function()
		{
			$j(this).parents('.inline-warning').remove();
			if(isset(oSelects)&&jisset(oSelects))
			{
				oSelects.each(
					function()
					{
						if($j(this).css('display')=='none')
						{
							$j(this).css('display','block');
						}
					}
				);
			}
			$j('select').each(
				function()
				{
					if($j(this).css('display')=='none')
					{
						$j(this).css('display','inline');
					}
				}
			);
			return false;
		}
	)
}
// возвращает идентификатор поста по контейнеру внутри блока поста
function getPostId(oObj)
{
	return oObj.parents('.pblock').children('input[name=post_id]').attr('value');
}
function postAjax(sUrl,aData,oObj)
{
	$j.post(
		sUrl,
		aData,
		function(mData)
		{
			execAjaxResult(mData, oObj);
	  	},
		'json'
	);	
}

function updateImgIndexes()
{
	iIndex = 0;
	oItems = $j("div.imgs");
	oItems.each(
		function()
		{
			var oSubItems = $j(this).find("input[name^='img']");
			oSubItems.each(
				function()
				{
					$j(this).attr('name', $j(this).attr('name').replace(/\[(\d+)?\]/, '['+iIndex+']'));
				}
			);
			iIndex++;
		}
	);
	// индекс и количество элементов
	cfg.oImgLoading.iCurFileNum = iIndex;
	cfg.oSwfUpload.customSettings.all_files = iIndex;
};

function getImgSrc(sType, iId, sExt)
{
	var sImgSrc = cfg.oImgPatterns[sType].replace(/(\{pic_id\})/,iId);
	sImgSrc = sImgSrc.replace(/(\{pic_th\})/, Math.floor(iId /1000));
	return sImgSrc.replace(/(\{ext\})/,sExt);
};

function autosave()
{
	var aImgIds=[];
	$j(".for-img input[name$='[id]']").each(
		function()
		{
			aImgIds.push($j(this).val());
		}
	);
	var aSectionIds=[];
	aSectionIds.push($j('#category_id_1').val());
	aSectionIds.push($j('#category_id_2').val());
	var aCommIds=[];
	aCommIds.push($j('#comm_id_1').val());
	aCommIds.push($j('#comm_id_2').val());	
	
	var oData = {
		sTitle:$j('#title').val(),
		sMessage:$j('#message_m').val(),
		sButName:$j('input[name=but_name]').val(),
		aImgIds:aImgIds,
		aSectionIds:aSectionIds,
		aCommIds:aCommIds,
		sViaUrl:$j('#via_url').val(),
		sHistoryUrl:$j('#history_url').val(),
		sTags:$j('#tags').val()
	};
	postAjax('/inc/site/ajax/write_autosave.php',oData);
	var iNow = new Date();
	var iDelta = (iNow - cfg.iStartWriteDt) / 1000 / 60;
	iDelta+=0.9;
	$j('.autosave .bx a').each(
		function()
		{
			if($j(this).hasClass('disabled'))
			{
				var iMin = $j(this).find('input').val();
				if(iMin < iDelta)
				{
					$j(this).removeClass('disabled').removeAttr('disabled');
				}
			}
		}
	);
}