//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// действия в окне "вход на сайт"
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// переключение с "входа на сайт" на "забыли пароль" и обратно
function popup_enter_to_site_change_tab()
{
	$('#popup div.error').html('');
	$('#enter_to_site').toggle();
	$('#reminder_pass').toggle();
	if ($('#change_tab').html() == 'Забыли пароль?')
	{
		$('#change_tab').html('Войти на сайт');
		$('#reminder_pass_email').focus();
	}
	else
	{
		$('#change_tab').html('Забыли пароль?');
		$('#enter_to_site_email').focus();
	}
}
//---------------------------------------------------------------------------------
// вход на сайт
function enter_to_site()
{
	var email =  $('#enter_to_site_email').val();
	var pass =  $('#enter_to_site_pass').val();
	var find_to_site =  $('#enter_to_site_find').is(':checked') ? 1 : 0;

	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { enter_to_site_email: email, enter_to_site_pass: pass, enter_to_site_find: find_to_site }, function(txt)
	{
		if (txt.substr(0, 8) == 'redirect')
		{
			window.location = txt.substr(8);
		}
		else if (txt.substr(0, 9) == 'user_menu')
		{
			if ($('#user_info').length || $('#forum')) // если вход на сайт со своей личной страницы
				window.location.reload();
			else
			{
				$('#main_right_text').remove();

				$('#user_menu').html(txt.substr(9));
				// если на странице есть форма для добавления комментариев
				$('#comments div.add_comment_2 div.textangles').html('<a href="javascript:window.location.reload();">Перезагрузите</a> страницу, чтобы оставить комментарий.');

				$('#popup').dialog('close');
			}
		}
		else
		{
			$('#popup').html(popup_html);
			$('#popup div.err').remove();
			$('#popup #enter_to_site').before(get_error(txt));
			$('#enter_to_site_email').focus();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// напоминание пароля
function reminder_pass()
{
	var email =  $('#reminder_pass_email').val();

	$('#popup').children('div.mes').remove();
	$('#popup').children('div.err').remove();
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { reminder_pass_email: email }, function(txt)
	{
		if (txt == '')
		{
			$('#popup').html(popup_html).prepend(get_message('На ваш e-mail отправлено письмо с новым паролем!'));
			popup_enter_to_site_change_tab();
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
			$('#reminder_pass_email').focus();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// обновление меню пользователя
function update_user_menu()
{
	$.post($('#popup').attr('path'), { update_user_menu: true }, function(txt)
	{
		if (txt.substr(0, 9) == 'user_menu' && $('#user_menu_head').length)
		{
			$('#user_menu').html(txt.substr(9));
			setTimeout('update_user_menu();', 240000);
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// открытие всплывающего окна для удаления
function open_popup_delete(del, text)
{
	if (text == undefined) text = '';
	$('#popup').html(get_delete(del, text)).dialog('option', 'width', 300).dialog('option', 'height', 'auto').dialog('option', 'title', 'Действительно удалить?').dialog('open');
}
//---------------------------------------------------------------------------------
// редактирование лозунга
function edit_signature()
{
	var signature =  $('#edit_signature').val();

	$('#user_signature').prev('div.err').remove();
	$('#signature_load').show().siblings('div').hide();

	$.post($('#popup').attr('path'), { edit_signature: signature }, function(txt)
	{
		if (txt == '')
		{
			$('#ui_signature').html(strip_tags(signature));
			if (signature == '')
				$('#signature_edit').show().siblings('div').hide();
			else
				$('#signature_view').show().siblings('div').hide();
		}
		else
		{
			$('#user_signature').before(get_error(txt));
			$('#signature_edit').show().siblings('div').hide();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя :: информация о себе
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// редактирование информации о себе
function edit_info()
{
	var nick =  $('#edit_nick').val();
	var birthdayday =  $('#edit_birthdayday').val();
	var birthdaymonth =  $('#edit_birthdaymonth').val();
	var birthdaymonth_title =  $('#edit_birthdaymonth option:selected').html();
	var birthdayyear =  $('#edit_birthdayyear').val();
	var sex =  $('#edit_sex').val();
	var country_id =  $('#countries_list').val();
	var country_title =  $('#countries_list option:selected').html();
	var city_id =  $('#cities_list').val();
	var city_title =  $('#cities_list option:selected').html();
	var city_other =  $('#cities_other').val();
	var grade_id =  $('#grades_list').val();
	var grade_title =  $('#grades_list option:selected').html();
	var about =  $('#edit_about').val();

	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { edit_nick: nick, edit_birthdayday: birthdayday, edit_birthdaymonth: birthdaymonth, edit_birthdayyear: birthdayyear, edit_sex: sex, edit_country_id: country_id, edit_city_id: city_id, edit_city_other: city_other, edit_grade_id: grade_id, edit_about: about }, function(txt)
	{
		if (txt == '')
		{
			if ($('#user_name_2').html() == '' && trim(nick) != '') // если ника не было, а теперь есть
			{
				$('#user_name_2').html('(' + $('#user_name_1').html() + ')');
				$('#user_name_1').html(trim(nick));
			}
			else if ($('#user_name_2').html() != '' && trim(nick) != '') // если ник был и остался (может быть измененный)
			{
				$('#user_name_1').html(trim(nick));
			}
			else if ($('#user_name_2').html() != '' && trim(nick) == '') // если ник был, а теперь нет
			{
				$('#user_name_1').html($('#user_name_2').html().replace('(', '').replace(')', ''));
				$('#user_name_2').html('');
			}
			$('#ui_birthday').html(birthdayday != 0 && birthdaymonth != 0 ? ('/ день рождения ' + birthdayday + ' ' + birthdaymonth_title + (birthdayyear != 0 ? (' ' + birthdayyear + ' г.') : '')) : '');
			$('#ui_town').html(city_other != '' ? city_other : (city_id != 'CityOther' && city_id != 0 ? city_title : ''));
			$('#ui_country').html(($('#ui_town').html() != '' ? ', ' : '') + country_title);
			$('#ui_grade').html(grade_title ? ('в беге: ' + grade_title) : '');
			$('#ui_about').html(nl2br(strip_tags(about)));

			$('#popup').dialog('close');

			$('#cities_list').attr('town_id', city_id);
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
			$('#edit_birthdayday').focus();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя :: смена пароля
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
function edit_password()
{
	var old_password =  $('#old_password').val();
	var new_password =  $('#new_password').val();
	var new_password2 =  $('#new_password2').val();

	$('#popup').children('div.err').remove();
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'),
	{
		old_password: old_password,
		new_password: new_password,
		new_password2: new_password2
	},
	function(txt)
	{
		if (txt == '')
		{
			$('#popup').dialog('close');
			$('#user_info_edit').prepend(get_message('Пароль успешно изменен'));
			setTimeout("$('#user_info_edit').children('div.mes').hide('highlight')", 3000);
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
			$('#old_password').focus();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя :: смена email
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
function edit_email()
{
	var old_email =  $('#old_email').val();
	var new_email =  $('#new_email').val();

	$('#popup').children('div.err').remove();
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'),
	{
		old_email: old_email,
		new_email: new_email
	},
	function(txt)
	{
		if (txt == '')
		{
			$('#popup').dialog('close');
			$('#user_info_edit').prepend(get_message('E-mail успешно изменен - теперь используйте именно его для захода на сайт.'));
			setTimeout("$('#user_info_edit').children('div.mes').hide('highlight')", 3000);
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
			$('#old_email').focus();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя :: забеги
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// открытие всплывающего окна для добавления/редактирования забегов
function open_popup_add_edit_heat(heat_id, path)
{
	if (path.indexOf('heat_type') != -1)
	{
		// перенос забега в прошлые
		$.post($('#popup').attr('path'), { change_heat_type: heat_id }, function(txt)
		{
			window.location = path;
			return;
		}, 'text');
		return;
	}

	$('#popup').dialog('option', 'width', 500).dialog('option', 'height', 'auto').html(get_loading()).dialog('option', 'title', heat_id == -1 ? 'Добавление забега' : 'Редактирование забега').dialog('open');

	var type = $('#user_heats div.head a.act').attr('type');

	if (type == 2 && path == '')
	{
		$('#popup').html('<center><input type="radio" name="temp" value="1" checked> добавить из календаря (рекомендуется)&nbsp;&nbsp;<input type="radio" name="temp" value="2"> добавить вручную<br><br><br><img src="/img/btn_cancel.gif" alt="Отмена" title="Отмена" onClick="$(\'#popup\').dialog(\'close\');">&nbsp;&nbsp;&nbsp;&nbsp;<img src="/img/btn_add.gif" alt="Добавить" title="Добавить" onClick="if ($(\'#popup input[value=1]\').is(\':checked\')) window.location=\'/calendar\'; else open_popup_add_edit_heat(' + heat_id + ', \'111\');"></center>');
		return;
	}

	// получение содержимого всплывающего окна
	$.post($('#popup').attr('path'), { get_popup_add_edit_heat: heat_id, heat_type: type }, function(txt)
	{
		$('#popup').html(txt);
		$('#popup_add_edit_heat').find('input:first').focus();
	}, 'text');
}
//---------------------------------------------------------------------------------
// добавление/редактирование забегов
function add_edit_heat(heat_id)
{
	var type = $('#user_heats div.head a.act').attr('type');

	$('#popup div.err').remove();
	$('#popup_add_edit_heat').hide();
	$('#popup').prepend(get_loading());

	$.post($('#popup').attr('path'),
	{
		add_edit_heat_id: heat_id,
		add_edit_heat_type: type,
		add_edit_heat_day: $('#add_edit_heat_day').val(),
		add_edit_heat_month: $('#add_edit_heat_month').val(),
		add_edit_heat_year: $('#add_edit_heat_year').val(),
		add_edit_heat_location: $('#add_edit_heat_location').val(),
		add_edit_heat_distance: $('#add_edit_heat_distance').val(),
		add_edit_heat_hours: type != 2 ? $('#add_edit_heat_hours').val() : '',
		add_edit_heat_minutes: type != 2 ? $('#add_edit_heat_minutes').val() : '',
		add_edit_heat_seconds: type != 2 ? $('#add_edit_heat_seconds').val() : '',
		add_edit_heat_comment: $('#add_edit_heat_comment').val() ,
		add_edit_heat_calendar_id: $('#add_edit_heat_calendar_id').val()
	}, function(txt)
	{
		if (txt.substr(0, 4) == 'heat')
		{
			if (heat_id == -1) // если доабвление забега
			{
				var obj = $('#user_heats_type_' + type + ' table tbody').length ? $('#user_heats_type_' + type + ' table tbody') : $('#user_heats_type_' + type + ' table');
				obj.append(txt.substr(4));
				$('#heats_count_type_' + type).html(parseInt($('#heats_count_type_' + type).html()) + 1);
			}
			else // если редактирование забега
			{
				$('#heat_' + heat_id).after(txt.substr(4)).remove();
			}
			$('#popup').dialog('close');
		}
		else
		{
			$('#popup').children('div.load').remove();
			$('#popup').prepend(get_error(txt));
			$('#popup_add_edit_heat').show().find('input:first').focus();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление забега
function del_heat(heat_id, heat_type)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { del_heat: heat_id }, function(txt)
	{
		if (txt == '')
		{
			$('#popup').dialog('close');
			$('#heat_' + heat_id).remove();
			$('#heats_count_type_' + heat_type).html(parseInt($('#heats_count_type_' + heat_type).html()) - 1);
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя :: дневник
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// открытие всплывающего окна для добавления/редактирования записи дневника
function open_popup_add_edit_journal(journal_id, type)
{
	$('#popup').dialog('option', 'width', 845).dialog('option', 'height', 550).dialog('option', 'position', 'center').html(get_loading()).dialog('option', 'title', journal_id == -1 ? 'Добавление записи в дневник' : 'Редактирование записи в дневнике').dialog('open');

	$('#popup').bind('dialogclose', function(event, ui) { $('#journal_' + journal_id + ' div.announce').css('visibility', 'visible'); });

	// получение содержимого всплывабщего окна
	$.post($('#popup').attr('path'), { get_popup_add_edit_journal: journal_id }, function(txt)
	{
		$('#journal_' + journal_id + ' div.announce').css('visibility', 'hidden');
		$('#popup').html(txt);
		$('#add_edit_journal_title').focus();
		if (type == 1)
		{
			$('#add_edit_journal_text').tinymce(
			{
				theme: "advanced",
				language: "ru",
				width: "672",
				height: "300",
				element_format : "html",

				plugins: "safari, emotions, inlinepopups, paste, media",

				setup : function(ed)
				{
					ed.addButton('texthide',
					{
						title : 'Скрыть выделенный текст за ссылкой',
						image : '/img/cut.gif',
						onclick : function()
						{
							ed.selection.setContent('<del>' + ed.selection.getContent({format : 'html'}) + '</del>');
						}
					});
					ed.addButton('texthide_cancel',
					{
						title : 'Отменить скрытие текста',
						image : '/img/cut_cancel.gif',
						onclick : function()
						{
							tinyMCE.activeEditor.setContent(tinyMCE.activeEditor.getContent().replace('<del>', '').replace('</del>', ''))
						}
					});
				},

				theme_advanced_buttons1 : "bold, italic, underline, strikethrough, |, forecolor, |, hr, link, unlink, image, media, emotions, |, texthide, texthide_cancel",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",

				theme_advanced_toolbar_location: "top",
				theme_advanced_toolbar_align: "left",

				oninit: "tiniLoadForJournal",

				content_css: "/css/tiny.css"
			});
		}
		else
		{
			$('#add_edit_journal_text').tinymce(
			{
				theme: "advanced",
				language: "ru",
				width: "672",
				height: "300",
				element_format : "html",

				plugins: "safari, table, emotions, inlinepopups, contextmenu, paste, media",

				setup : function(ed)
				{
					ed.addButton('texthide',
					{
						title : 'Скрыть выделенный текст за ссылкой',
						image : '/img/cut.gif',
						onclick : function()
						{
							ed.selection.setContent('<del>' + ed.selection.getContent({format : 'html'}) + '</del>');
						}
					});
					ed.addButton('texthide_cancel',
					{
						title : 'Отменить скрытие текста',
						image : '/img/cut_cancel.gif',
						onclick : function()
						{
							tinyMCE.activeEditor.setContent(tinyMCE.activeEditor.getContent().replace('<del>', '').replace('</del>', ''))
						}
					});
				},

				theme_advanced_buttons1 : "tablecontrols, |, hr, link, unlink, image, media, emotions, charmap, |, removeformat, cleanup, visualaid, |, code",
				theme_advanced_buttons2 : "formatselect, fontsizeselect, bold, italic, underline, strikethrough, |, justifyleft, justifycenter, justifyright, justifyfull, |, forecolor, backcolor, |, bullist, numlist, |, outdent, indent, |, texthide, texthide_cancel",
				theme_advanced_buttons3 : "",

				theme_advanced_toolbar_location: "top",
				theme_advanced_toolbar_align: "left",

				theme_advanced_font_sizes: "Обычный=100%, Большой=120%, Очень большой=140%",

				oninit: "tiniLoadForJournal",

				content_css: "/css/tiny.css"
			});
		}
	}, 'text');
}
function tiniLoadForJournal()
{
	$('#add_edit_journal_text').parent('div.hide').show().prev('div.field').remove();
}
//---------------------------------------------------------------------------------
// редактирование записи в дневнике
function add_edit_journal(journal_id)
{
	$('#popup div.err').remove();
	$('#popup_add_edit_journal').hide();
	$('#popup').prepend(get_loading());

	$.post($('#popup').attr('path'),
	{
		add_edit_journal_id: journal_id,
		add_edit_journal_title: $('#add_edit_journal_title').val(),
		add_edit_journal_text: $('#add_edit_journal_text').val(),
		add_edit_journal_tags: $('#add_edit_journal_tags').val()
	},
	function(txt)
	{
		if (txt.substr(0, 7) == 'journal')
		{
			if (journal_id == -1) // если доабвление зписи
			{
				$('#pre_journals').after(txt.substr(7));
				$('#user_links').before(get_message('Запись успешно добавлена.'));
				setTimeout("$('#user_links').prev('div.mes').hide('highlight')", 3000);

				$('#popup').dialog('close');
			}
			else // если редактирование зписи
			{
				if ($('#journal_' + journal_id).length) // если редактирование из списка записей
				{
					$('#journal_' + journal_id).after(txt.substr(7)).remove();
					$('#journal_' + journal_id).prepend(get_message('Запись успешно изменена.'));
					edit_journal = $('#journal_' + journal_id);
					setTimeout("edit_journal.children('div.mes').hide('highlight')", 3000);

					$('#popup').dialog('close');
				}
				else // если редактирование из одной записи
					window.location.reload();
			}
		}
		else
		{
			$('#popup').children('div.load').remove();
			$('#popup').prepend(get_error(txt));
			$('#popup_add_edit_journal').show().find('input:first').focus();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление записи в дневнике
function del_journal(journal_id)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { del_journal: journal_id }, function(txt)
	{
		if (txt == '')
		{
			$('#popup').dialog('close');
			$('#journal_' + journal_id).remove();
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя :: фотоальбомы
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//
function open_edit_title_photo(photo_id)
{
	$('#photo_' + photo_id).children('div.title').hide();
	$('#photo_' + photo_id).children('div.edit').show();
	if ($('#photo_' + photo_id).find('textarea').val() == 'нажмите здесь, чтобы изменить название')
		$('#photo_' + photo_id).find('textarea').val('');
	$('#photo_' + photo_id).find('textarea').focus();
}
//
function edit_title_photo(code, photo_id)
{
	title = $('#photo_' + photo_id).find('textarea').val();
	$('#photo_' + photo_id).children('div.edit').hide().before(get_loading('loading_hor2.gif'));

	$.post($('#popup').attr('path'),
	{
		code: code,
		photo_id: photo_id,
		edit_title_photo: title
	},
	function(txt)
	{
		$('#photo_' + photo_id).children('div.title').next('div.load').remove();
		$('#photo_' + photo_id).children('div.title').html(title).show();
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление фотоальбома
function del_photoalbum(photoalbum_id)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { del_photoalbum: photoalbum_id }, function(txt)
	{
		if (txt.substr(0, 6) == 'reload')
		{
			window.location = txt.substr(6);
			//$('#popup').dialog('close');
			//$('#journal_' + journal_id).remove();
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление фотографии
function del_photo(photo_id)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { del_photo: photo_id }, function(txt)
	{
		if (txt == '')
		{
			$('#popup').dialog('close');
			$('#photo_' + photo_id).remove();
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// "сделать обложкой"
function set_main_photo(photo_id)
{
	if ($('#photo_' + photo_id).children('img').attr('src').indexOf('icon_photo_main.gif') != -1)
		return;

	$.post($('#popup').attr('path'), { main_photo: photo_id }, function(txt)
	{
		if (txt == '')
		{
			$('div.photo img[src*=icon_photo_main.gif]').attr('src', '/img/icon_photo_main_no.gif');
			$('#photo_' + photo_id).children('img[src*=icon_photo_main_no.gif]').attr('src', '/img/icon_photo_main.gif');
		}
		else
		{
			$('#photo_' + photo_id).prepend(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя :: сообщения
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// открытие всплывающего окна для отправки сообщения
function open_popup_add_message(user_id, message_id, message_type)
{
	if (message_type == undefined) message_type = 'i';
	$('#popup').html(get_loading()).dialog('option', 'width', 500).dialog('option', 'height', 'auto').dialog('option', 'title', 'Отправка сообщения').dialog('open');

	// получение содержимого всплывабщего окна
	$.post($('#popup').attr('path'), { get_popup_add_message: user_id, message_type: message_type }, function(txt)
	{
		$('#message_' +  message_id).addClass('action_message');
		$('#user_' +  user_id).addClass('action_friend');
		$('#popup').html(txt);
		$('#add_message_text').tinymce(
		{
			theme: "advanced",
			language: "ru",
			width: "320",
			height: "200",
			element_format : "html",

			plugins: "safari, emotions, inlinepopups, paste",

			theme_advanced_buttons1 : "bold, italic, underline, strikethrough, |, forecolor, |, emotions",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",

			theme_advanced_toolbar_location: "top",
			theme_advanced_toolbar_align: "left",

			oninit: "tiniLoadForMessage",

			content_css: "/css/tiny.css"
		});
	}, 'text');
}
function tiniLoadForMessage()
{
	$('#add_message_text').parent('div.hide').show().prev('img').remove();
}
//---------------------------------------------------------------------------------
// доавбление сообщения (user_id - id пользователя, которому отправляется сообщение)
function add_message(user_id, message_type)
{
	var text = $('#add_message_text').val();

	//$('#popup').html(get_loading()).dialog('option', 'width', 500).dialog('option', 'title', 'Отправка сообщения').dialog('open');

	$('#popup div.err').remove();

	if (trim(text) == '')
	{
		$('#popup').prepend(get_error('Введите сообщение.'));
		return;
	}

	$('#popup_add_message').hide();
	$('#popup').prepend(get_loading());

	$.post($('#popup').attr('path'),
	{
		add_message_user_id: user_id,
		add_message_text: text,
		message_type: message_type
	},
	function(txt)
	{
		if (txt.substr(0, 7) == 'message')
		{
			if ($('#messages_i_writing_count').length)
				$('#messages_i_writing_count').html(parseInt($('#messages_i_writing_count').html()) + 1);

			if ($('#user_' + user_id).hasClass('action_friend')) // если отправка из списка пользователей
			{
				$('#user_' + user_id).prepend(get_message('Сообщение отправлено.'));
				obj = $('#user_' + user_id);
				setTimeout("obj.removeClass('action_friend').children('div.mes').hide('highlight')", 3000);
			}
			else if ($('table.action_message').length) // если отправка из списка сообщений
			{
				// если ответ на новое сообщение
				if ($('#messages_me_writing_count').length && $('table.action_message td.message > div').length)
				{
					update_user_menu();
					$('#messages_me_writing_count').html(parseInt($('#messages_me_writing_count').html()) - 1);
					$('table.action_message td.message div').remove();
				}

				$('#pre_messages').after(txt.substr(7));
				$('table.action_message').before(get_message('Сообщение отправлено.'));
				setTimeout("$('table.action_message').removeClass('action_message').prev('div.mes').hide('highlight')", 3000);
			}
			else if ($('tr.action_message').length) // если отправка из списка сообщений на форуме
			{
				$('tr.action_message td.text').append(get_message('Сообщение отправлено.'));
				setTimeout("$('tr.action_message').removeClass('action_message').children('td.text').children('div.mes').hide('highlight')", 3000);
			}
			else // если отправка с чужой страницы
			{
				$('#user_links').before(get_message('Сообщение отправлено.'));
				setTimeout("$('#user_links').prev('div.mes').hide('highlight')", 3000);
			}

			$('#popup').dialog('close');
		}
		else
		{
			$('#popup').children('div.load').remove();
			$('#popup').prepend(get_error(txt));
			$('#popup_add_message').show();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление сообщения
function del_message(message_id)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { del_message: message_id }, function(txt)
	{
		if (txt == '')
		{
			if ($('#messages_i_writing_count').length)
				$('#messages_i_writing_count').html(parseInt($('#messages_i_writing_count').html()) - 1);

			$('#popup').dialog('close');
			$('#message_' + message_id).remove();
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// страница пользователя :: друзья
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// доавбление друга
function add_friend(friend_id)
{
	temp_html = $('#user_links').html();
	$('#user_links').html(get_loading('loading_hor.gif'));

	$.post($('#popup').attr('path'), { add_friend_id: friend_id }, function(txt)
	{
		if (txt == '')
		{
			$('img.ic_friend_' + friend_id).show();
			if ($('#user_' + friend_id).length) // добавление идет из списка пользователей
			{
				$('#user_' + friend_id + ' a.add_friend').hide();
				$('#user_' + friend_id + ' a.del_friend').show();
			}
			else if ($('tr.user_' + friend_id).length) // добавление идет из списка сообщений на форуме
			{
				$('tr.user_' + friend_id + ' a.add_friend').hide();
				$('tr.user_' + friend_id + ' a.del_friend').show();
			}
			else // добавление идет с чужой главной страницы
			{
				$('#user_links').html(temp_html);
				$('#user_links td.add_friend').hide();
				$('#user_links td.del_friend').show();
			}
		}
		else
		{
			$('#user_links').before(get_error(txt));
			setTimeout("$('#user_links').prev('div.err').hide('highlight');", 3000);
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление друга
function del_friend(friend_id)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { del_friend_id: friend_id }, function(txt)
	{
		if (txt == '')
		{
			$('img.ic_friend_' + friend_id).hide();
			if ($('#friends_count_me').length && $('#countries_list').length) // удаление идет со своей страница списка друзей
			{
				$('#friends_count_me').html(parseInt($('#friends_count_me').html()) - 1);
				$('#user_' + friend_id).remove();
			}
			else if ($('#user_' + friend_id).length) // удаление идет из списка пользователей
			{
				$('#user_' + friend_id + ' a.del_friend').hide();
				$('#user_' + friend_id + ' a.add_friend').show();
			}
			else if ($('tr.user_' + friend_id).length) // удаление идет из списка сообщений на форуме
			{
				$('tr.user_' + friend_id + ' a.del_friend').hide();
				$('tr.user_' + friend_id + ' a.add_friend').show();
			}
			else // удаление идет с чужой главной страницы
			{
				$('#user_links td.del_friend').hide();
				$('#user_links td.add_friend').show();
			}
			$('#popup').dialog('close');
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// календарь забегов
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//
function get_popup_add_to_my_heats(heat_id)
{
	//alert($('#heat_plans_' + heat_id).length);
	if ($('#heat_plans_' + heat_id).length && $('#heat_plans_' + heat_id).hasClass('already_plans')) return;
	$('#popup').dialog('option', 'width', 400).dialog('option', 'height', 'auto').html(get_loading()).dialog('option', 'title', 'Добавление забега в свой календарь').dialog('open');

	// получение содержимого всплывающего окна
	$.post($('#popup').attr('path'), { get_popup_add_to_my_heats: heat_id }, function(txt)
	{
		$('#popup').html(txt);
	}, 'text');
}
// добавление забега из календаря в свои планы
function add_to_my_heats(heat_id)
{
	var distance_id = $('#popup_heat_distances').val();
	$('#popup').html(get_loading());
	$.post($('#popup').attr('path'),
	{
		add_to_my_heats: heat_id,
		distance_id: distance_id
	},
	function(txt)
	{
		if (txt.substr(0, 4) == 'link')
		{
			$('#popup').dialog('close');
			$('#add_to_my_heats').html('<br>&nbsp;Вы добавили этот забег в свои планы.<br>&nbsp;Список ваших планируемых забегов вы можете посмотреть <a href="' + txt.substr(4) + '">здесь</a>');
			$('#heat_plans_' + heat_id).removeClass('add_to_plans').addClass('already_plans').html('[в планах]');
		}
		else
		{
			alert(txt);
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//
function get_popup_add_new_heat()
{
	$('#popup').dialog('option', 'width', 500).dialog('option', 'height', 'auto').html(get_loading()).dialog('option', 'title', 'Добавление нового забега').dialog('open');

	// получение содержимого всплывающего окна
	$.post($('#popup').attr('path'), { get_popup_add_new_heat: true }, function(txt)
	{
		$('#popup').html(txt);
	}, 'text');
}
//---------------------------------------------------------------------------------
// добавление нового забега пользователем
function add_new_heat()
{
	var new_heat_title = $('#new_heat_title').val();
	var new_heat_date = $('#new_heat_date').val();
	var new_heat_location = $('#new_heat_location').val();
	var new_heat_url = $('#new_heat_url').val();
	var new_heat_desc = $('#new_heat_desc').val();

	$('#popup div.err').remove();

	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'),
	{
		new_heat_title: new_heat_title,
		new_heat_date: new_heat_date,
		new_heat_location: new_heat_location,
		new_heat_url: new_heat_url,
		new_heat_desc: new_heat_desc
	},
	function(txt)
	{
		if (txt == '')
		{
			$('#popup').html('Спасибо за отправленную информацию, она будет добавлена на сайт после проверки.');
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
			$('#new_heat_title').val(new_heat_title);
			$('#new_heat_date').val(new_heat_date);
			$('#new_heat_location').val(new_heat_location);
			$('#new_heat_url').val(new_heat_url);
			$('#new_heat_desc').val(new_heat_desc);
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//
function recountHeatFoto()
{
	var count = parseInt($('#table_order_foto td input:checked').length);
	$('#order_foto_button1').html(count ? ('выбрано фото: ' + count) : 'отметьте фото для покупки');
}
//---------------------------------------------------------------------------------
//
function recountHeatFoto2()
{
	cost = 0;
	$('#table_order_foto td select').each(function()
	{
		cost += parseInt($(this).val());
	});
	$('#all_cost_order_foto').html(cost);
}
//---------------------------------------------------------------------------------
//
function payHeatFoto(cnt)
{
	if (cnt == 'all')
	{
		$('#table_order_foto td input').attr('checked', true);
		recountHeatFoto();
	}
	if (parseInt($('#table_order_foto td input:checked').length) > 0)
		$('#form_order_foto').submit();
	else
		alert('Выберите фото для покупки');
}
//---------------------------------------------------------------------------------
//
function orderHeatFoto()
{
	if ($('#pay_chronopay').is(':checked'))
	{
		count = parseInt($('#table_order_foto td input:checked').length);
		product_id = '005734-0001-0003';
		product_name = 'Photo';
		product_price = parseInt($('#all_cost_order_foto').html());
		//product_price = 1;
		cs1 = $('#order_foto_email').val();

		cs2 = '';
		$('#table_order_foto td select').each(function()
		{
			cs2 += '!' + $(this).attr('name').replace('foto[', '').replace(']', '');
			cs2 += '|' + $(this).val();
		});
        $('#table_order_foto td input.foto').each(function()
		{
			cs2 += '!' + $(this).attr('name').replace('foto[', '').replace(']', '');
			cs2 += '|' + $(this).val();
		});

		$.post($('#popup').attr('root') + 'calendar/',
		{
			get_sign: product_price, email: cs1
		},
		function(txt)
		{
			if (txt.substr(0, 3) == 'err')
			{
				$('#error').html(txt.substr(3));
			}
			else
			{
				$('<form action="https://payments.chronopay.com/" method="POST" name="payment_form" id="form_order_foto_chronopay"><input type="hidden" name="product_id" value="' + product_id + '"><input type="hidden" name="product_name" value="' + product_name + '"><input type="hidden" name="product_price" value="' + product_price + '"><input type="hidden" name="sign" value="' + txt + '"><input type="hidden" name="decline_url" value="http://42km.ru/calendar/?order_foto_err"><input type="hidden" name="language" value="ru"><input type="hidden" name="cb_url" value="http://42km.ru/calendar/?order_foto_ok2"><input type="hidden" name="cb_type" value="P"><input type="hidden" name="cs1" value="' + cs1 + '"><input type="hidden" name="cs2" value="' + cs2.substr(1) + '"><input type="hidden" name="cs3" value="' + $('#heat_id').val() + '"></form>').insertAfter('#secondary_left');
				//alert($('#form_order_foto_chronopay').html())
				$('#form_order_foto_chronopay').submit();
			}

		}, 'text');
	}
	else
	{
		$('#form_order_foto').submit();
	}
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// комментарии
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// подписка на комментарии
function user_subscr_record(code, record_id)
{
	if ($('#user_subscr_record_outer a').html().indexOf('подписаться') != -1)
	{
		//alert($('#user_subscr_record_outer').css('background'));
		$('#user_subscr_record_outer a').html('[ прекратить подписку ]');
		$('#user_subscr_record_outer').html($('#user_subscr_record_outer').html().replace('Вы можете получать уведомления о новых комментариях на свой e-mail', 'Вы подписаны на уведомления о комментариях к этой странице')).addClass('textangles_grey');
		$.post($('#popup').attr('path'),
		{
			subscr_code: code,
			subscr_record_id: record_id,
			subscr: 1
		},
		function(txt)
		{
			if (txt)
			{
				alert(txt);
			}
		}, 'text');
	}
	else
	{
		//alert($('#user_subscr_record_outer').css('background'));
		$('#user_subscr_record_outer a').html('[ подписаться на комментарии ]');
		$('#user_subscr_record_outer').html($('#user_subscr_record_outer').html().replace('Вы подписаны на уведомления о комментариях к этой странице', 'Вы можете получать уведомления о новых комментариях на свой e-mail')).removeClass('textangles_grey');
		$.post($('#popup').attr('path'),
		{
			subscr_code: code,
			subscr_record_id: record_id,
			subscr: 0
		},
		function(txt)
		{
			if (txt)
			{
				alert(txt);
			}
		}, 'text');
	}
}
//---------------------------------------------------------------------------------
// открытие всплывающего окна для редактирование комментария
function open_popup_add_edit_comment(comment_id, code, record_id)
{
	$('#popup').html(get_loading()).dialog('option', 'width', 670).dialog('option', 'height', 'auto').dialog('option', 'title', 'Редактирование комментария').dialog('open');

	// получение содержимого всплывающего окна
	$.post($('#popup').attr('path'),
	{
		get_popup_add_edit_comment: comment_id,
		comment_code: code,
		comment_record_id: record_id
	},
	function(txt)
	{
		$('#popup').html(txt);
		$('#popup textarea.add_edit_comment').tinymce(
		{
			theme: "advanced",
			language: "ru",
			width: "640",
			height: "200",
			element_format: "html",

			plugins: "safari, emotions, iespell, inlinepopups, paste",

			plugin_preview_width : "650",
			plugin_preview_height : "500",

			theme_advanced_buttons1 : "bold, italic, underline, strikethrough, |, forecolor, backcolor, |, bullist, numlist, |, link, unlink, emotions, image, charmap, |, blockquote, |, removeformat, cleanup",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",

			theme_advanced_toolbar_location: "top",
			theme_advanced_toolbar_align: "left",

			oninit: "tiniLoadForComments2",

			content_css: "/css/tiny.css"
		});
	}, 'text');
}
function tiniLoadForComments2()
{
	$('#popup textarea.add_edit_comment').parent('div.hide').show().prev('img').remove();
}
// добавдение/редактирование комментария
function add_edit_comment(comment_id, code, record_id, redirect, i)
{
	if ($('#popup textarea.add_edit_comment').length) // если редактирование комментария во всплывающем окне
	{
		obj = $('#popup_add_edit_comment');
		var comment = $('#popup textarea.add_edit_comment').val();
	}
	else if ($('#comments div.add_comment_' + i + ' textarea.add_edit_comment_' + i).length) // если добавление комментария со страницы со списком
	{
		obj = $('#comments div.add_comment_' + i);
		var comment = $('#comments div.add_comment_' + i + ' textarea.add_edit_comment_' + i).val();
	}
	else
		return;

	obj.prev('div.err').remove();
	obj.prev('div.mes').remove();
	$('#comment_' + comment_id).children('div.mes').remove();
	if (trim(comment) == '')
	{
		obj.before(get_error('Введите текст комментария.'));
		return;
	}

	$(get_loading()).css('height', '240px').insertBefore(obj);
	obj.hide();

	$.post($('#popup').attr('path'),
	{
		comment_id: comment_id,
		comment_code: code,
		comment_text: comment,
		comment_record_id: record_id
	},
	function(txt)
	{

		if (txt.substr(0, 7) == 'comment')
		{
			if (redirect != '')
			{
				window.location = redirect;
				return;
			}

			if ($('#popup textarea.add_edit_comment').length) // если редактирование комментария во всплывающем окне
			{
				$('#comment_' + comment_id).after(txt.substr(7)).remove();
				$('#comment_' + comment_id).prepend(get_message('Комментарий изменен.'));
				com = $('#comment_' + comment_id);
				setTimeout("com.children('div.mes').hide('highlight')", 3000);
				$('#popup').html('').dialog('close');
			}
			else if ($('#comments div.add_comment_' + i + ' textarea.add_edit_comment_' + i).length) // если добавление комментария со страницы со списком
			{
				// скрытие статусов "новый"
				for (i = 0; i < $('#comments div.text div.pre').length; i++)
				{
					pre = $('#comments div.text div.pre').eq(i);
					if (pre.html() == 'новый') pre.html('');
				}

				$('#aft_comments').before(txt.substr(7));
				$('#count_comments').html(parseInt($('#count_comments').html()) + 1);
				obj.prev('div.load').remove();
				obj.show().before(get_message('Ваш комментарий добавлен.'));
				setTimeout("obj.prev('div.mes').hide('highlight')", 3000);

				$('#comments div.add_comment_1 textarea.add_edit_comment_1').val('');
				$('#comments div.add_comment_2 textarea.add_edit_comment_2').val('');

			}
			else
				return;
		}
		else
		{
			obj.prev('div.load').remove();
			obj.show().before(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// отправка заявки
function add_send_mail(subject)
{
	var send_mail_email = $('#add_send_mail_email').val();
	var send_mail_text = $('#add_send_mail').val();

    if (trim(send_mail_email) == '')
    {
        alert('Введите E-mail');
        return;
    }

	$('#add_send_mail').parent('div.add_send_mail').before(get_loading());
	$('#add_send_mail').parent('div.add_send_mail').hide();

	$('#add_send_mail').parent('div.add_send_mail').prev('div.mes').remove();
	$('#add_send_mail').parent('div.add_send_mail').prev('div.err').remove();

	$.post($('#popup').attr('path'),
	{
		send_mail_subject: subject,
		send_mail_email: send_mail_email,
		send_mail_text: send_mail_text
	},
	function(txt)
	{
		$('#add_send_mail').parent('div.add_send_mail').prev('div.load').remove();
		if (txt == '')
		{
			$('#add_send_mail').parent('div.add_send_mail').before(get_message('Ваша заявка отправлена.'));
			obj = $('#add_send_mail').parent('div.add_send_mail');
			setTimeout("obj.prev('div.mes').hide('highlight')", 3000);
			$('#add_send_mail').val('');
			$('#add_send_mail_email').val('');
		}
		else
		{
			$('#add_send_mail').parent('div.add_send_mail').before(get_error('Попробуйте еще раз.'));
		}
		$('#add_send_mail').parent('div.add_send_mail').show();
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление комментария
function del_comment(comment_id)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { del_comment: comment_id }, function(txt)
	{
		if (txt == 'hide')
		{
			$('#popup').dialog('close');
			//alert($('#comment_' + comment_id + ' div.title a').length);
			$('#comment_' + comment_id + ' div.title a').remove();
			$('#comment_' + comment_id + ' div.title img').remove();
			$('#comment_' + comment_id).children('div.text').html('<div class="pre">Комментарий удален</div>');
			$('#comment_' + comment_id).children('div.link_right').html('');
		}
		else if (txt == 'all')
		{
			$('#count_comments').html(parseInt($('#count_comments').html()) - 1);
			$('#popup').dialog('close');
			$('#comment_' + comment_id).remove();
		}
		else
		{
			$('#popup').html(popup_html).prepend(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// форум
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
function open_popup_add_f_topic(theme_id, redirect)
{
	$('#popup').dialog('option', 'width', 820).dialog('option', 'height', 450).dialog('option', 'position', 'center').html(get_loading()).dialog('option', 'title', 'Добавление новой темы').dialog('open');

	// получение содержимого всплывабщего окна
	$.post($('#popup').attr('path'), { get_popup_add_f_topic: theme_id, redirect: redirect }, function(txt)
	{
		if (txt.substr(0, 5) == 'error')
			$('#popup').html(get_error(txt.substr(5)));
		else
		{
			$('#popup').html(txt);
			$('#add_f_topic_title').focus();

			$('#add_f_topic_text').tinymce(
			{
				theme: "advanced",
				language: "ru",
				width: "647",
				height: "300",
				element_format : "html",

				plugins: "safari, emotions, inlinepopups, paste",

				plugin_preview_width : "650",
				plugin_preview_height : "400",

				theme_advanced_buttons1 : "bold, italic, underline, strikethrough, |, forecolor, |, hr, link, unlink, image, emotions",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",

				theme_advanced_toolbar_location: "top",
				theme_advanced_toolbar_align: "left",

				oninit: "tiniLoadForForumTopic",

				content_css: "/css/tiny.css"
			});
		}
	}, 'text');
}
function tiniLoadForForumTopic()
{
	$('#add_f_topic_text').parent('div.hide').show().prev('div.field').hide();
}
function add_f_topic(theme_id, redirect)
{
	var f_topic_title = $('#add_f_topic_title').val();
	var f_topic_text = $('#add_f_topic_text').val();

	$('#popup_add_f_topic').prev('div.err').remove();
	$('#popup_add_f_topic').hide();
	$('#popup').prepend(get_loading());


	$.post($('#popup').attr('path'),
	{
		f_topic_theme_id: theme_id,
		f_topic_title: f_topic_title,
		f_topic_text: f_topic_text
	},
	function(txt)
	{
		if (txt.substr(0, 5) == 'topic')
		{
			if (redirect)
			{
				window.location = redirect;
				exit;
			}
			if ($('#forum tr.message').length)
			{
				window.location = $('#popup').attr('root') + 'f&th' + theme_id;
				return;
			}
			//var obj = $('#forum tbody').length ? $('#forum tbody') : $('#forum');
			$('#forum tbody').prepend(txt.substr(5));
			$('#forum').before(get_message('Новая тема успешно создана.'));
			obj = $('#forum');
			setTimeout("obj.prev('div.mes').hide('highlight')", 3000);
			$('#popup').dialog('close');
		}
		else
		{
			$('#popup').children('div.load').remove();
			$('#popup').prepend(get_error(txt));
			$('#popup_add_f_topic').show().find('input:first').focus();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
//
function open_popup_add_edit_f_message(message_id, topic_id, redirect)
{
	$('#popup').dialog('option', 'width', 700).dialog('option', 'height', 460).dialog('option', 'position', 'center').html(get_loading()).dialog('option', 'title', 'Добавление нового сообщения').dialog('open');

	// получение содержимого всплывабщего окна
	$.post($('#popup').attr('path'), { get_popup_add_edit_f_message: message_id, topic_id: topic_id, redirect: redirect }, function(txt)
	{
		if (txt.substr(0, 5) == 'error')
			$('#popup').html(get_error(txt.substr(5)));
		else
		{
			$('#popup').html(txt);

			$('#add_edit_f_message_text').tinymce(
			{
				theme: "advanced",
				language: "ru",
				width: "647",
				height: "300",
				element_format : "html",

				plugins: "safari, emotions, inlinepopups, paste",

				plugin_preview_width : "650",
				plugin_preview_height : "350",

				theme_advanced_buttons1 : "bold, italic, underline, strikethrough, |, forecolor, |, hr, link, unlink, image, emotions",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",

				theme_advanced_toolbar_location: "top",
				theme_advanced_toolbar_align: "left",

				oninit: "tiniLoadForForumMessage",

				content_css: "/css/tiny.css"
			});
		}
	}, 'text');
}
function tiniLoadForForumMessage()
{
	$('#add_edit_f_message_text').parent('div.hide').show().prev('div.field').hide();
}
function add_edit_f_message(message_id, topic_id, redirect)
{
	var f_message_text = $('#add_edit_f_message_text').val();

	$('#popup_add_edit_f_message').prev('div.err').remove();
	$('#popup_add_edit_f_message').hide();
	$('#popup').prepend(get_loading());


	$.post($('#popup').attr('path'),
	{
		f_message_id: message_id,
		f_message_topic_id: topic_id,
		f_message_text: f_message_text
	},
	function(txt)
	{
		if (txt.substr(0, 7) == 'message')
		{
			if (redirect)
			{
				window.location = redirect;
				exit;
			}

			if (message_id == -1)
			{
				//var obj = $('#forum tbody').length ? $('#forum tbody') : $('#forum');
				$('#forum tbody').append(txt.substr(7));
				$('#forum').after(get_message('Новое сообщение успешно добавлено.'));
				obj = $('#forum');
				setTimeout("obj.next('div.mes').hide('highlight')", 3000);
			}
			else
			{
				$('#message_' + message_id).after(txt.substr(7)).remove();
				$('#message_' + message_id + ' td.text').append(get_message('Сообщение отредактировано.'));
				obj = $('#message_' + message_id + ' td.text').children('div.mes');
				setTimeout("obj.hide('highlight')", 3000);
			}
			$('#popup').dialog('close');
		}
		else
		{
			$('#popup').children('div.load').remove();
			$('#popup').prepend(get_error(txt));
			$('#popup_add_edit_f_message').show();
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление сообщения на форуме
function del_f_message(message_id)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());

	$.post($('#popup').attr('path'), { del_f_message: message_id }, function(txt)
	{
		$('#popup').dialog('close');
		if (txt == '')
		{
			$('#message_' + message_id + ' td.text div.text').html('<b class="del">сообщение удалено</b>');
			$('#message_' + message_id + ' td.text div.edit').remove();
		}
		else
		{
			$('#message_' + message_id + ' td.text').append(get_error(txt));
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// открытие/закрытие топика на форуме
function open_close_topic(topic_id)
{
	if ($('#secondary_left a.open_close_topic').html().indexOf('закрыть') != -1)
	{
		$('#secondary_left a.open_close_topic').html('[ открыть тему ]');
		$('#secondary_left a.open_popup_add_message').remove();
	}
	else
	{
		$('#secondary_left a.open_close_topic').html('[ закрыть тему ]');
	}
	$.post($('#popup').attr('path'), { open_close_topic: topic_id }, function(txt)
	{
		if (txt != '')
		{
			$('#secondary_left a.open_close_topic').html($('#secondary_left a.open_close_topic').html().indexOf('закрыть') != -1 ? '[ открыть тему ]' : '[ закрыть тему ]');
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// удаление топика на форуме
function delete_topic(topic_id)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());
	$.post($('#popup').attr('path'), { delete_topic: topic_id }, function(txt)
	{
		if (txt.substr(0, 8) == 'redirect')
		{
			window.location = txt.substr(8);
		}
		else
			alert(txt);
	}, 'text');
}
//---------------------------------------------------------------------------------
// вырезание топика для объединения с другим топиком на форуме
function cut_topic(topic_id)
{
	$('#secondary_left a.cut_topic').html($('#secondary_left a.cut_topic').html().indexOf('вырезать') != -1 ? '[ удалить из буффера ]' : '[ вырезать тему ]');
	$('#secondary_left a.merge_topics').remove();
	$.post($('#popup').attr('path'), { cut_topic: topic_id }, function(txt)
	{
		if (txt != '')
		{
			$('#secondary_left a.cut_topic').html($('#secondary_left a.cut_topic').html().indexOf('вырезать') != -1 ? '[ удалить из буффера ]' : '[ вырезать тему ]');
		}
	}, 'text');
}
//---------------------------------------------------------------------------------
// объединение двух топиков на форуме
function merge_topics(topic_1, topic_2)
{
	var popup_html = $('#popup').html();
	$('#popup').html(get_loading());
	$.post($('#popup').attr('path'), { merge_topic_1: topic_1, merge_topic_2: topic_2 }, function(txt)
	{
		if (txt == '')
		{
			window.location.reload();
		}
		else
			alert(txt);
	}, 'text');
}
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// вспомогательные функции
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
function get_error(txt, txt2)
{
	if (txt2 == undefined) txt2 = 'Ошибка!';
	return '<div class="err"><span></span><b>' + txt2 + '</b> ' + txt + '</div>';
}
//---------------------------------------------------------------------------------
function get_message(txt, txt2)
{
	if (txt2 == undefined) txt2 = 'Спасибо!';
	return '<div class="mes"><span></span><b>' + txt2 + '</b> ' + txt + '</div>';
}
//---------------------------------------------------------------------------------
function get_loading(src)
{
	if (src == undefined) src = 'loading.gif';
	return '<div class="load"><img src="/img/' + src + '" alt="" title=""></div>';
}
//---------------------------------------------------------------------------------
function get_delete(del, text)
{
	return '<div class="delete">' + text + '<br><br><img src="/img/btn_cancel.gif" alt="Отмена" title="Отмена" width="88" height="24" onClick="$(\'#popup\').dialog(\'close\');">&nbsp;&nbsp;<img src="/img/btn_del.gif" alt="Удалить" title="Удалить" width="88" height="24" onClick="' + del + '"></div>';
}
//---------------------------------------------------------------------------------
