$(function() {
detectIE6(); // Определение ie
$('#cloud_info_close').click(new_info_close); // Закрытие событий
$('#show_online').click(online_content_show); // ONLINE
$('#click_show_search').click(search_show); // Показываем поиск
$('#login_click').click(login_show);
$('#new_online_close').live('click',new_online_close);


// ---------------- Избранное  -----------------------
var mouseovertime;
var mouseclosetime;
$('.like').mouseover(function(){
	$this = $(this);
	var id =$this.attr('like');
	var type =$this.attr('type');
	var load =$this.attr('load');
	var like_count =$this.attr('like_count');
	clearTimeout(mouseclosetime);

	if(load==0)
	{
		if(like_count!=0)
		{
			mouseovertime = setTimeout(function(){
				$('#like_'+id).slideDown(400);
				$('#like_'+id).html('Идёт загрузка данных... <img src="images/icons/loader_2.gif">');
				$.post('like_func.php?type=show', {'show':$.toJSON({"id_record":id,"like_count":like_count,"type":type})},function(data) {
					if(data.status=="ok")
					{
						$('#like_'+id).html(data.html);
						$this.attr('load','1');
					}
				});
			}, 500 );
		}
		else
		{
			mouseovertime = setTimeout(function(){
				$('#like_'+id).slideDown(400);
				$('#like_'+id).html('Нажмите на ссылку чтобы добавить в избранное.');
			}, 500 );
		}
	}
	else
	{
		$('#like_'+id).slideDown(400);
	}
}).mouseout(function(){
	clearTimeout(mouseovertime);
	var id =$(this).attr('like');
	mouseclosetime = setTimeout(function(){$('#like_'+id).slideUp(400);clearTimeout(mouseclosetime);}, 500);
});


$('.like').click(function(){
	$this = $(this);
	var id = $this.attr('like');
	var type =$this.attr('type');
	var like_count =$this.attr('like_count');
	$.post('like_func.php?type=click', {'click':$.toJSON({"id_record":id,"type":type})},function(data) {
		if(data.status=="add")
		{
			$('#like_'+id).html(data.html);
			if(like_count==0){
				$('#text_like_'+id).text('В избранном у 1');
				$('#count_like_'+id).text(Number(like_count)+1);
			} else {
				$('#count_like_'+id).text(Number(like_count)+1);
			}
			$this.attr('like_count',Number(like_count)+1);
			$this.attr('load','0');
		}
		if(data.status=="kill")
		{
			$('#like_'+id).html(data.html);
			if(like_count==1){
				$('#text_like_'+id).text('Добавить в избранное');
				$('#count_like_'+id).text(Number(like_count)-1);
			} else {
				$('#count_like_'+id).text(Number(like_count)-1);
			}
			$this.attr('like_count',Number(like_count)-1);
			$this.attr('load','0');
		}
	});
});


// ------------------ Показ меню пользователя ------------------
var top_menu_user_time;
$('.top_menu_user').mouseenter(function(){
	clearTimeout(top_menu_user_time);
	$('#top_menu_user').show();
}).mouseleave(function(){
	clearTimeout(top_menu_user_time);
	top_menu_user_time = setTimeout(function(){ $('#top_menu_user').hide(); }, 500);
});

// ------------------ Показ меню Всё ------------------
var top_menu_all_time;
$('.top_menu_all').mouseenter(function(){
	clearTimeout(top_menu_all_time);
	$('#top_menu_all').show();
}).mouseleave(function(){
	clearTimeout(top_menu_all_time);
	top_menu_all_time = setTimeout(function(){ $('#top_menu_all').hide(); }, 500);
});


	var cache = {};
	if ($('#top_search_form').length > 0) {
		$( "#top_search" ).autocomplete({
			minLength: 3,
			source: function(request, response) {
	
				if ( request.term in cache ) {
					response( cache[ request.term ] );
					return;
				}
	
				var sql = $('#top_search_select option:selected').val();
				$.ajax({
					url: "find_func.php?type=top_search&sql="+ sql,
					dataType: "json",
					data: request,
					success: function( data ) {
						cache[ request.term ] = data;
						response( data );
					}
				});
			}
		})
		.data( "autocomplete" )._renderItem = function( ul, item ) {
	
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( '<a class="photo_search_img" onclick="document.location.href=\'' + item.href + '\'"><img src="' + item.photo + '" width="64px"><div>Название: ' + item.label + '<br>Пользователь: ' + item.value + '</div></a>' )
				.appendTo( ul );
		};
	}
	

	$("#chat_sends").button({ icons: {primary:'ui-icon-person'} });

	// ------------- Если экран меньше 490 px то показываем Наверх --------------------
	$(window).scroll(function () {
		if ($(this).scrollTop() > 490) {
			$('#menu_go_top').fadeIn();
		} else {
			$('#menu_go_top').fadeOut();
		}
	});

	// Плавно поднимаем наверх
	$('#menu_go_top').click(function () {
		$('body,html').animate({
			scrollTop: 0
		}, 100);
		return false;
	});


	// -------------------- ToolTip на фото --------------------
	$('.img').poshytip({
		className: 'tip-bs',
		showTimeout: 1,
		alignX: 'center',
		offsetY: 30,
		allowTipHover: false,
		followCursor: true,
		liveEvents: true,
		fade: false,
		slide: false,
		content: function(updateCallback) {
			var html = '<img src="'+this.src+'">';
			return html;
		}
	});



	// -------------------- Сообщения --------------------
	var Messages = {

		active : 0,
		timer_chat : 0,
		user : 0,
		talk : 0,
		fio : '',
		first_id : 0,
		last_id : 0,
		new_start : 0,
		mess_new : 0,
		count_messages : 0,
		timer_messages : 0,
		mass_user : [],

		start : function() // Стартуем
		{
			$('#show_messages').toggle();
			var new_notification = $('.top_new_messages').text();
			if(new_notification>0) {
				$('.top_new_messages').text('0').hide();
				$("title").stopTime('timer_messages_title');
				$("#click_show_message").stopTime('timer_messages_notification');
				$("title").text('Будь собой');
				$.post('plugin/messages/messages_func.php?type=clear_notification');
			}

			if(Messages.active==0) {
				Messages.load_messages_user();
				Messages.send_ctrl_enter();

				$(window).bind("resize", function(){ //при изменении размера окна вызываем функцию
				    Messages.block_resize(); 
				});
			}
			Messages.active = 1;

			if($('#messages_load').length > 0) {
				Messages.scroll_down();
			}

			return false;
		},

		start_messages : function() // Стартуем
		{
			var user = $(this).attr('user');
			var fio = $(this).attr('fio');
			var get_fio = '';
			Messages.user = user;

			if(typeof(fio)!="undefined") {
				Messages.fio = fio;
				get_fio = 0;
			} else {
				get_fio = 1;
			}

			$('#chat_view').hide();
			$('#show_messages').show();

			if(Messages.active==0) {
				Messages.send_ctrl_enter();
			} else {

			}
			Messages.active = 1;
			Messages.new_start = 1;

			$.post('plugin/messages/messages_func.php?type=load_messages_user', {"user":user,"get_fio":get_fio}, function(data) {

				$('#messages_user').html(data.html);
				Messages.mass_user = data.mass;
				if(data.get_fio){Messages.fio=data.get_fio;}
				if(typeof(data.mass[Messages.user])!="undefined")
				{
					$('#user_select').find('li').removeClass();
					$('#user_select li[talk="'+data.mass[Messages.user]+'"]').addClass('user_select_active');
					Messages.talk = data.mass[Messages.user];	
					Messages.load_messages();
				}
				else
				{
					Messages.talk = 0;
					Messages.load_messages();
				}
			});

			return false;
		},

		load_messages_user : function() // Загрузка пользователей
		{
			$('#messages_user').html('<div class="time">Загрузка...</div>');
			$.post('plugin/messages/messages_func.php?type=load_messages_user', {}, function(data) {
				$('#messages_user').animate({opacity:0},10,function () {
					$('#messages_user').html(data.html);
					Messages.mass_user = data.mass;
					$('#user_select').find('li').removeClass();
					$('#user_select li[talk="'+Messages.talk+'"]').addClass('user_select_active');
				}).animate({opacity:1},700);
			});
		},

		load_messages : function() // Загрузка сообщений
		{

			var user = $(this).attr('user');
			var talk = $(this).attr('talk');
			var fio = $(this).attr('fio');
			var mess_new = $(this).attr('mess_new');
			var count_messages = $(this).attr('count_messages');

			if(typeof(mess_new)!="undefined") {
				if(mess_new>0){$(this).parent().find('.messages_user_new').remove();}
				$('#user_select').find('li').removeClass();
				$(this).parent().addClass("user_select_active");
			} else {
				mess_new = 0;
			}

			if(typeof(fio)!="undefined") {
				Messages.fio = fio;	
			}
			if(typeof(user)!="undefined") {
				Messages.user = user;	
			}


			if(Messages.timer_messages==0) // Проверка на запущеность таймера
			{
				$('#messages_content').everyTime('10s','timer_messages', function() {
					Messages.timer_messages = 1;
					Messages.messages_reload();
				});
			}


			if(Messages.talk!=talk||Messages.new_start==1)
			{
				if(typeof(talk)!="undefined") {
					Messages.talk = talk;
				}
	
				$('#messages_content').html('<div class="time">Загрузка...</div>');
				$.post('plugin/messages/messages_func.php?type=load_messages', {"talk":Messages.talk,"mess_new":mess_new,"count_messages":count_messages}, function(data) {
					Messages.first_id = data.first_id;
					Messages.last_id = data.last_id;
					$('#messages_content').animate({opacity:0},10,function () {
						$('#messages_content').html(data.html);
						$('#messages_info').html(Messages.fio+'  <span id="message_hide">скрыть</span>');
						Messages.block_resize();
						Messages.scroll_down();
					}).animate({opacity:1},700);
				});
			}
		},

		messages_reload : function(type) // Загрузка текста
		{
			if(typeof(type)=="undefined"){type='new';}
			if($('#messages_load').length > 0) {
				$.post('plugin/messages/messages_func.php?type=messages_reload', {"talk":Messages.talk,"last_id":Messages.last_id}, function(data) {
					Messages.last_id = data.last_id;
					$('#messages_load').append(data.html);
					if(data.is_new==1) {
						Messages.scroll_down();
						Messages.sound(type);
						Messages.title(type);
					}
				});
			}
		},

		load_messages_prev : function() // Загрузка предыдущих сообщений
		{
			if($('#messages_load').length > 0) {
				$(this).replaceWith('<hr style="border-bottom:1px solid #dadada;margin:15px;">');
				$.post('plugin/messages/messages_func.php?type=load_messages_prev', {"talk":Messages.talk,"first_id":Messages.first_id}, function(data) {
					Messages.first_id = data.first_id;
					$('#messages_load').prepend(data.html).effect("highlight", {}, 5000);
				});
			}
		},

		scroll_down : function() // Прокручиваем окно сообщений вниз
		{
			divOffset = $('#messages_load').offset().top;
			pOffset = $('div:last', $('#messages_load')).offset().top;
			pScroll = pOffset - divOffset;
			$('#messages_load').animate({ // Плавно прокручиваем
				scrollTop: '+='+pScroll+'px'
			}, 900 );
		},

		send_ctrl_enter : function() // Отправка на CTRL + ENTER
		{
			$(window).keypress(function (e) {
				if(e.keyCode==10 || (e.ctrlKey && e.keyCode==13))
				{
					if($('#messages_load').length > 0) {
						Messages.messages_send();
					}
				}
			});
		},

		block_resize : function()  // Определяем высоту окна браузера и обрезаем под экран
		{
			var windowHeight = $(window).height();
			var blockHeight = windowHeight - 190;
			if(blockHeight>440) {
				blockHeight = 440;
			}
			$('#messages_load').css('height', blockHeight);
		},

		new_messages : function() // Новое сообщение
		{
			$('#messages_content').html('<div class="time">Загрузка...</div>');
			$.post('plugin/messages/messages_func.php?type=new_messages', {}, function(data) {
				$('#messages_content').animate({opacity:0},10,function () {
					$('#messages_content').html(data.html);
					$('#messages_info').html('Поиск собеседников');
				}).animate({opacity:1},700);
			});
		},

		user_search : function () // Поиск пользователей
		{
			var search_user = $('#user_search').val();
			if(search_user.length>3)
			{
				$.post('plugin/messages/messages_func.php?type=search_user', {"search_user":search_user}, function(data) {
					$('#messages_search').html(data.html);
				});
			}
		},

		messages_send : function () // Отправка сообщения
		{
			var text = $('#messages_text').val();

			if(text.length<2)
			{
				Messages.show_error('Текст должен быть от 2 символов');
			}
			else
			{
				$.post('plugin/messages/messages_func.php?type=messages_send', {"talk":Messages.talk,"user":Messages.user,"text": text}, function(data) {
					if(data.status=="1")
					{
						$('#messages_text').val('');
						Messages.talk = data.talk;
						Messages.messages_reload('send');
						if(data.first==1||Messages.new_start==1){
							Messages.load_messages_user();
							Messages.new_start = 0;
						}
					}
					if(data.status=="0")
					{
						Messages.show_error(data.html);
					}
				});
			}
		},

		messages_user_hide : function() // Скрываем пользователя
		{
			var $this = $(this);
			var id_talk = $(this).attr('talk');
			jConfirm('Вы действительно хотите скрыть этого пользователя?<br>Пользователь снова появится в списке при возобновлении переписки.','Скрытие пользователя', function(r) {if(r){
				$.post('plugin/messages/messages_func.php?type=user_hide', {"id_talk":id_talk}, function(data) {
					if(data.status=="1")
					{
						$this.parent().html('<p class="info_gray">Пользователь скрыт</p>');
						$('#user_select li[talk="'+id_talk+'"]').fadeTo(2500,0.9).fadeOut(500, function () {
							$('#user_select li[talk="'+id_talk+'"]').remove();
						}); 
					}
					if(data.status=="0")
					{
						Messages.show_error(data.html);
					}
				});

			}});
		},

		messages_delete : function() // Удаляем сообщение
		{
			var $this = $(this);
			var id = $(this).attr('del_id');
			jConfirm('Вы точно хотите удалить это сообщение?','Удаление сообщения', function(r) {if(r){

				$.post('plugin/messages/messages_func.php?type=messages_delete', {"id":id}, function(data) {
					if(data.status=="1")
					{
						$this.parent().parent().html('<p class="info_gray">Сообщение удалено</p>');
					}
					if(data.status=="0")
					{
						Messages.show_error(data.html);
					}
				});

			}});
		},

		messages_spam : function() // Отмечаем как спам
		{
			var id = $(this).attr('spam_id');
			jConfirm('Вы действительно хотите оставить жалобу?<br>Нехорошие люди будут наказаны администрацией сайта.','Жалоба', function(r) {if(r){

				$.post('plugin/messages/messages_func.php?type=messages_spam', {"id":id}, function(data) {
					if(data.status=="1")
					{
						alert('Сообщение отмечено как спам');
					}
					if(data.status=="0")
					{
						Messages.show_error(data.html);
					}
				});

			}});
		},

		messages_hide : function() // Скрываем сообщалку
		{
			$('#show_messages').hide();
		},

		show_error : function(text) // Показываем ошибки
		{
			$('#messages_errors').html(text).fadeIn(550, function () {
				$('#messages_errors').fadeTo(2500,0.9).fadeOut(500); 
			}); 
		},

		show_success : function(text) // Показываем что всё ок
		{
			$('#messages_success').html(text).fadeIn(550, function () {
				$('#messages_success').fadeTo(2500,0.9).fadeOut(500); 
			}); 
		},

		messages_toggle_avatar : function() // Показать - Скрыть аватар
		{
			$('.user_info_avatar').toggle();
		},

		messages_toggle_online : function() // Показать - Скрыть тех кто в сети
		{
			$('#user_select li[online="0"]').toggle();
		},

		smile_show : function() // Показать - Скрыть смайлики
		{
			$('#more_smile_messages').slideToggle();
		},

		smile_insert : function() // Добавить в поле ввода смайлик
		{
			var smile = $(this).attr('alt');
			var messages_val = $('#messages_text').val();
			$('#messages_text').val(messages_val+smile);
		},

		go_user : function() // Перейти на страницу пользователя
		{
			var user= $(this).attr('user');
			location.href = '/anketa/'+user;
		},

		sound : function(type) // Звуки
		{
			if(typeof(type)=="undefined")
			{
				$('#sound').html("<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#4,0,0,0' width='1px' height='1px'><param name='src' value='new.swf'><embed src='http://budsoboi.ru/plugin/messages/new.swf' pluginspage='http://www.macromedia.com/shockwave/download/' type='application/x-shockwave-flash' width='1px' height='1px'></embed></object>");
			}

			if(type=="new")
			{
				$('#sound').html("<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#4,0,0,0' width='1px' height='1px'><param name='src' value='new.swf'><embed src='http://budsoboi.ru/plugin/messages/new.swf' pluginspage='http://www.macromedia.com/shockwave/download/' type='application/x-shockwave-flash' width='1px' height='1px'></embed></object>");
			}

			if(type=="send")
			{
				$('#sound').html("<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#4,0,0,0' width='1px' height='1px'><param name='src' value='send.swf'><embed src='http://budsoboi.ru/plugin/messages/send.swf' pluginspage='http://www.macromedia.com/shockwave/download/' type='application/x-shockwave-flash' width='1px' height='1px'></embed></object>");
			}

		},

		title : function(type) // Заголовок
		{
			if(type=="new")
			{
				var title_start = $("title").text();
				$('title').everyTime('1.1s','timer_messages_title_new', function() {
					var title_text = $("title").text();
					if(title_text=="Новое сообщение!") {
						$("title").text(' * • * • * • * • * • * • * ');
					} else {
						$("title").text('Новое сообщение!');
					}
				},10);

				$('title').oneTime('13s', function() {$("title").text(title_start);});
			}
		}

	}

	$('#click_show_message').live('click',Messages.start);
	$('#user_select > li > a').live('click',Messages.load_messages);
	$('#button_messages_send').live('click', Messages.messages_send);
	$('#messages_prev').live('click', Messages.load_messages_prev);


	$('#button_smile_show').live('click', Messages.smile_show);
	$('.smile_block_messages').live('click',function() {$('#more_smile_messages').slideUp('slow', function() {$(this).hide();});});
	$('.smile_block_messages > img').live('click',Messages.smile_insert);
	$('#messages_toggle_avatar').live('click', Messages.messages_toggle_avatar);
	$('#messages_toggle_online').live('click', Messages.messages_toggle_online);
	$('#button_new_messages').live('click', Messages.new_messages);
	$('#user_search').live('keyup',Messages.user_search);
	$('.user_select_active > a > span > img').live('click', Messages.go_user);
	$('.start_messages').live('click',Messages.start_messages);
	$('.messages_user_hide').live('click',Messages.messages_user_hide);
	$('.messages_delete').live('click',Messages.messages_delete);
	$('.messages_spam').live('click',Messages.messages_spam);
	$('#message_hide').live('click',Messages.messages_hide);
	



	// -------------------- Поддержка --------------------
	var Support = {

		show : function ()
		{
			var html = '<div style="margin:30px;">';
				html += '<label for="supportTitle">Тема обращения:</label><br> <input type="text" maxlength="90" id="supportTitle" style="width:95%;"><br><br>';
				if(!options.logname) {
					html += '<label for="supportEmail">Адрес электронной почты:</label><br> <input type="text"  id="supportEmail" style="width:50%;"><br><br>';
				}
				html += '<label for="supportText">Сообщение:</label><br> <textarea id="supportText" style="width:95%;height:150px;"></textarea>';
			html += '</div>';

			$("#dialog_show").html(html).dialog({
				draggable: false,
				resizable: false,
				stack: true,
				show: 'fade',
				hide: 'fade',
				title: 'Обращение в службу поддержки',
				width:700,
				height:560,
				modal: true,
				buttons: {
					'Отправить': function() {Support.send();},
					'Закрыть': function() {$(this).dialog('close');}
				}
			});

			return false;
		},

		send : function ()
		{
			var supportTitle = $('#supportTitle').val();
			var supportText = $('#supportText').val();
			var supportEmail = $('#supportEmail').val();

			if(!options.logname) {
				if(supportEmail.length<5) {
					jAlert('Введите <b>адрес электронной почты</b>','Ошибка');
					return false;
				}
			}


			if(supportTitle.length>5) {
				if(supportText.length>10) {
					
					$.post('support_func.php', {"title":supportTitle,"text":supportText,"email":supportEmail}, function(data) {
						if(data.status=="1") {
							$("#dialog_show").dialog('close');
							jAlert('Ваше обращение успешно отправлено, скоро Вам обязательно ответят!','Успех');
						}
						if(data.status=="2") {
							jAlert('Интервал между обращениями составляет 2 минуты, попробуйте позже.','Ошибка');
						}
						if(data.status=="3") {
							jAlert('Данные переданы неверно!','Ошибка');
						}
					});

				} else {
					jAlert('Введите <b>сообщение</b>. Не менее 5 символов','Внимание');
					return false;
				}
			} else {
				jAlert('Введите <b>тему обращения</b>. Не менее 10 символов','Внимание');
				return false;
			}
		}
	}
	$('#callSupport').live('click',Support.show);





	// -------------------- Подарки --------------------
	var Gifts = {

		set_category : 1,
		set_gift : 0,
		set_user : 0,

		show_category : function ()
		{
			$("#gifts_show").html('<div class="time">Загрузка...</div>').dialog({
				draggable: false,
				resizable: false,
				stack: true,
				show: 'fade',
				hide: 'fade',
				title: 'Подарки',
				width:800,
				height:580,
				modal: true,
				open:function() {$(this).parents(".ui-dialog:first").find(".ui-widget-header").remove();},
				close: function(event, ui) {},
				buttons: {'Закрыть': function() {$(this).dialog('close');}
				}
			});

			var user = $(this).attr('user');
			Gifts.set_user = user;

			$.post('plugin/gifts/gifts_func.php?type=load_gifts_category', {}, function(data) {
				$('#gifts_show').html(data.html);
			});	
		},

		show_category_main : function ()
		{
			$.post('plugin/gifts/gifts_func.php?type=load_gifts_category', {}, function(data) {
				$('#gifts_show').html(data.html);
			});	
		},

		show_inner_category : function ()
		{
			var category = $(this).attr('category');
			Gifts.set_category = category;

			$.post('plugin/gifts/gifts_func.php?type=load_inner_category', {"category":Gifts.set_category}, function(data) {
				$('#gifts_show').html(data.html);
			});			
		},

		show_gift : function ()
		{

			var id_gift = $(this).attr('id_gift');
			Gifts.set_gift = id_gift;

			$.post('plugin/gifts/gifts_func.php?type=load_gift', {"id_user":Gifts.set_user,"id_gift":Gifts.set_gift}, function(data) {
				$('#gifts_show').html(data.html);
			});
		},

		send_gift : function ()
		{
			var gift_text = $('#gift_text').val();
			$.post('plugin/gifts/gifts_func.php?type=send_gift', {"id_user":Gifts.set_user,"id_gift":Gifts.set_gift,"gift_text":gift_text}, function(data) {
				if(data.status=="ok")
				{
					$('.gifts_ul').prepend(data.html);
					$("#gifts_show").dialog('close');
				}
				if(data.status=="error")
				{
					alert(data.html);
				}
			});
		},

		view_gift : function ()
		{
			$("#gifts_show").html('<div class="time">Загрузка...</div>').dialog({
				draggable: false,
				resizable: false,
				stack: true,
				show: 'fade',
				hide: 'fade',
				title: 'Подарки',
				width:800,
				height:580,
				modal: true,
				open:function() {$(this).parents(".ui-dialog:first").find(".ui-widget-header").remove();},
				close: function(event, ui) {},
				buttons: {'Закрыть': function() {$(this).dialog('close');}
				}
			});

			var id_gift = $(this).attr('id_gift');
			$.post('plugin/gifts/gifts_func.php?type=load_view_gift', {"id_gift":id_gift}, function(data) {
				if(data.status=="error"){$('#gifts_show').html(data.text);}
				$('#gifts_show').html(data.html);
			});	
		},

		view_all_gifts : function ()
		{
			$("#gifts_show").html('<div class="time">Загрузка...</div>').dialog({
				draggable: false,
				resizable: false,
				stack: true,
				show: 'fade',
				hide: 'fade',
				title: 'Подарки',
				width:800,
				height:580,
				modal: true,
				open:function() {$(this).parents(".ui-dialog:first").find(".ui-widget-header").remove();},
				close: function(event, ui) {},
				buttons: {'Закрыть': function() {$(this).dialog('close');}
				}
			});

			var id_user = $(this).attr('user');
			$.post('plugin/gifts/gifts_func.php?type=load_all_view_gifts', {"id_user":id_user}, function(data) {
				if(data.status=="error"){$('#gifts_show').html(data.text);}
				$('#gifts_show').html(data.html);
			});	
		}

	}

	$('#gifts_go_category').live('click',Gifts.show_inner_category);
	$('#gifts_go_main').live('click',Gifts.show_category_main);
	$('#button_gifts').live('click',Gifts.show_category);
	$('#gifts > li').live('click',Gifts.show_inner_category);
	$('#gifts_select > li').live('click',Gifts.show_gift);
	$('#gift_send').live('click',Gifts.send_gift);
	$('.gifts_ul > li').live('click',Gifts.view_gift);
	$('.view_gift').live('click',Gifts.view_gift);
	$('#view_all_gifts').live('click',Gifts.view_all_gifts);






	// -------------------- Чат --------------------
	var Chat =
	{
		page_top: 1,
		timer_chat : 0,
		last_id : 0,

		load_chat : function() // Загрузка чата
		{
			$('#chat_view').toggle();
			Chat.load_chat_user();

			if(Chat.timer_chat==0) // Проверка на запущеность таймера
			{
				Chat.load_chat_text();
				Chat.send_ctrl_enter();
				Chat.smile_chat_load();

				$('#chat_load').everyTime('7s','timer_chat', function() {
					Chat.timer_chat = 1;
					Chat.chat_reload();
				});	
			}
		},

		chat_reload : function() // Загрузка текста чата
		{
			if($('#chat_view').is(':visible')) {
				$.post('main_func.php?type=chat_reload', {"last_id":Chat.last_id}, function(data) {
					Chat.last_id = data.last_id;
					$('#chat_load').append(data.html);
					Chat.scroll_down();
				});
			}
		},

		send_ctrl_enter : function() // Отправка на CTRL + ENTER
		{
			if($('#chat_view').is(':visible')) {
				$(window).keypress(function (e) {
					if(e.keyCode==13)
					{
						if($('#chat_view').is(':visible')) {
							Chat.chat_send();
						}
					}
				});
			}
		},

		scroll_down : function() // Прокручиваем окно чата вниз
		{
			var chat_scroll;
			 if($('#chat_scroll').is(':checked')) {
				chat_scroll = 1;
			} else {
				chat_scroll = 0;
			}

			if(chat_scroll==1)
			{
				divOffset = $('#chat_load').offset().top;
				pOffset = $('div:last', $('#chat_load')).offset().top;
				pScroll = pOffset - divOffset;
				$('#chat_load').animate({ // Плавно прокручиваем
					scrollTop: '+='+pScroll+'px'
				}, 900 );
			}
		},

		load_chat_text : function() // Первая загрузка текста чата
		{
			$.post('main_func.php?type=load_chat_text', {}, function(data) {
				$('#chat_load').animate({opacity:0},10,function () {
					$('#chat_load').html(data.html);
					Chat.last_id = data.last_id;
					Chat.chat_reload();
				}).animate({opacity:1},700);
			});
		},

		load_chat_user : function() // Загрузка пользователей чата
		{
			$('#chat_user').html('<div class="time">Загрузка...</div>');
			$.post('main_func.php?type=load_chat_user', {}, function(data) {
				$('#chat_user').animate({opacity:0},10,function () {$('#chat_user').html(data.html);}).animate({opacity:1},700);
			});
		},

		insert_nick : function ()
		{
			var text =$(this).text();
			var chat_val = $('#chat_text').val();
			$('#chat_text').val(text+': ');
		},

		chat_send : function () // Отправка сообщения
		{
			var text = $('#chat_text').val();

			if(text.length<2)
			{
				jAlert('Текст должен быть от 2 символов','Внимание');
			}
			else
			{
				$('#chat_text').attr('disabled', 'disabled');
				$('#button_chat_send').attr('value','Идёт отправка данных..').attr('disabled', 'disabled');

				$.post('main_func.php?type=chat_send', {"text": text}, function(data) {
					if(data.status=="1")
					{
						$('#chat_text').attr('disabled', false);
						$('#button_chat_send').attr('value','Отправить').attr('disabled', false);
						$('#chat_text').val('');
						//Chat.chat_reload();
					}
					if(data.status=="0")
					{
						$('#chat_text').attr('disabled', false);
						$('#button_chat_send').attr('value','Отправить').attr('disabled', false);
						alert(data.html);
					}
				});
			}
		},

		smile_chat_load : function () // Загрузка смаилов
		{
			$('#load_smile').load('plugin/messages/smiles.htm', function() {});  
		},

		smile_chat_show : function () // Показ смаилов
		{
			$('#more_smile_chat').toggle();
		},

		smile_insert : function() // Добавить в поле ввода смайлик
		{
			var smile = $(this).attr('alt');
			var chat_val = $('#chat_text').val();
			$('#chat_text').val(chat_val+smile);
		}

	}
	$('#button_chat_send').live('click', Chat.chat_send);
	$('#show_chat').live('click', Chat.load_chat);
	$('.c_nick').live('click', Chat.insert_nick);
	$('#button_smile_chat_show').live('click', Chat.smile_chat_show);
	$('.smile_block_chat > img').live('click',Chat.smile_insert);
	$('.smile_block_chat').live('click',function() {$('#more_smile_chat').slideUp('slow', function() {$(this).hide();});});





});


	// ------------------- Замена адресной строки -------------------
	var reg=/#pid=(\d*)/;
	var arr_url;
	if(arr_url=reg.exec(location.hash)) { js_url(arr_url[1]);}
	function js_url(page){
		location.hash = "pid="+page;
	}


	function search_show() {
		$('#show_search').slideToggle(200);
		$.post('/main_func.php?type=get_visitors', {}, function(data) {
			if(data) {
				$('#load_last_visitors').html(data.html);
			}
		});
	return false;
	}


	function login_show() {
		$(this).toggleClass( "top_login_fon");
		$('#login_show').slideToggle(200);
	return false;
	}

	var intervalHideNewOnline;
	function new_online() {

		$.post('/main_func.php?type=get_new_online', {}, function(data) {
			if(data) {
				if(data.count!="0")
				{
					$('#new_online').html(data.html);
					clearInterval(intervalHideNewOnline);
					$('#new_online').slideDown(1500);
					intervalHideNewOnline = setInterval(function() {
						$('#new_online').hide('drop',1500);
						clearInterval(intervalHideNewOnline);
					}, 25000);
				}
			}
		});

	return false;
	}


	function new_online_close() {
		$('#new_online').hide('drop',1500);
	return false;
	}


	var state = 0;
	function new_info() {

		$.get("/main_func.php?type=new_info", {}, function(data) {
			if(data) {
	
				if(data.message>0) {

					if( $('#show_messages').is(':hidden') ) // Проверка на скрытость
					{
						if(state==0)
						{
							state = 1;
							$('title').everyTime('1.1s','timer_messages_title', function() {
								var title_text = $("title").text();
								if(title_text=="Новое сообщение!") {
									$("title").text(' * • * • * • * • * • * • * ');
								} else {
									$("title").text('Новое сообщение!');
								}
							});
		
							$(".top_new_messages").show();
							$(".top_new_messages").html(data.message);
							$("#click_show_message").css('opacity','1').css('color','#fff').css('text-decoration','none');
							var messages_info = $('.top_new_messages');
							messages_info.animate({top: "5px"}, 150).animate({top: 8}, 150);
							$('#click_show_message').everyTime('1.4s','timer_messages_notification', function() {
								messages_info.animate({top: "5px"}, 150).animate({top: 8}, 150);
							});
						}

					sound(); // Звук входящего сообщения
					}

					//$("#cloud_info_message").replaceWith('<li><a href="message"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_message"></span>Сообщения <strong>+'+data.message+'</strong></div></a></li>');
				}
	
				if(data.guest>0) {
				$(".cloud_info").show(500);	
				$("#cloud_info_guest").replaceWith('<li><a href="visitors"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_guest"></span>Гости <strong>+'+data.guest+'</strong></div></a></li>');
				}
	
				if(data.comments>0) {
				$(".cloud_info").show(500);	
				$("#cloud_info_comments").replaceWith('<li><a href="new-comments"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_comments"></span>Комментарии <strong>+'+data.comments+'</strong></div></a></li>');
				}

				if(data.haracteristic>0) {
				$(".cloud_info").show(500);	
				$("#cloud_info_haracteristic").replaceWith('<li><a href="new-haracteristic"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_comments"></span>Характеристики <strong>+'+data.haracteristic+'</strong></div></a></li>');
				}

				if(data.gifts>0) {
				$(".cloud_info").show(500);	
				$("#cloud_info_gifts").replaceWith('<li><a href="new-gifts"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_gift"></span>Подарки <strong>+'+data.gifts+'</strong></div></a></li>');
				}

				if(data.friends>0) {
				$(".cloud_info").show(500);	
				$("#cloud_info_friends").replaceWith('<li><a href="friends"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_friends"></span>Друзья <strong>+'+data.friends+'</strong></div></a></li>');
				}

				if(data.vote>0) {
				$(".cloud_info").show(500);	
				$("#cloud_info_vote").replaceWith('<li><a href="new-votes"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_vote"></span>Оценки <strong>+'+data.vote+'</strong></div></a></li>');
				}

				if(data.vote_avatar>0) {
				$(".cloud_info").show(500);	
				$("#cloud_info_vote_avatar").replaceWith('<li><a href="new-avatar"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_avatar_vote"></span>Оценки Аватара <strong>+'+data.vote_avatar+'</strong></div></a></li>');
				}

				if(data.hi>0) {
				$(".cloud_info").show(500);	
				$("#cloud_info_comments").replaceWith('<li><a href="new-comments"><div class="cloud_info_nav_icon"><span class="anketa_left_icon anketa_left_icon_comments"></span>Запись на стене <strong>+'+data.hi+'</strong></div></a></li>');
				}

				if(data.award_count>0) {
					$(".top_new_award_info").show();
					$(".top_new_award_info").html(data.award_count);
					$(".top_new_award_info_menu").html(data.award_count);

					var award_info = $('.top_new_award_info');
					award_info.animate({top: "-3px"}, 150).animate({top: 0}, 150);
					intervalAnimate = setInterval(function() {
						award_info.animate({top: "-3px"}, 150).animate({top: 0}, 150);
					}, 1400);
				}

				if(data.smile_news>0) {
					$(".top_new_smile_menu").show();
					$(".top_new_smile_menu").html(data.smile_news);
				}
	
			}
		}); 

	}



	// ----------------------Закрыть инфу о новых событиях--------------------
	function new_info_close() {

			$.post('/main_func.php?type=new_info_close', {"id": "1"},function(data) {
				if(data.status=="ok"){$(".cloud_info").hide(500);}
			});

	return false;
	};	


	// -----------------------------------Звук входящего сообщения----------------------------
	function sound(){
		$('#sound').html("<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#4,0,0,0' width='1px' height='1px'><param name='src' value='msg.swf'><embed src='http://budsoboi.ru/plugin/message/msg.swf' pluginspage='http://www.macromedia.com/shockwave/download/' type='application/x-shockwave-flash' width='1px' height='1px'></embed></object>");
	}



	// ----------------------ONLINE и всё что с ним связано--------------------
	var interval_oc;
	var interval_cu;

	function online_content_show() {

		clearInterval(interval_oc);
		clearInterval(interval_cu);

		interval_oc = setInterval("online_content()", 60000);
		interval_cu = setInterval("chat_content_update()", 15000);

		$("#online_view").slideToggle(500);

		$('#chat_send').unbind("click",chat_add);
		$('#chat_send').bind('click',chat_add);
		online_content();
		chat_content_once();


	return false;
	}


	function online_content() {
	
		if( $('#online_view').is(':hidden') ){ // Проверка на скрытость
		}else{

		$("#online_boy > ul").empty();
		$("#online_girl > ul").empty();

			$.get("/main_func.php?type=online", {}, function(data) {
				if(data) {
	
					if(data.status=="reg"){$("#online_content").html('<div class="warning" style="margin-top:70px;">Чтобы просматривать эту страницу вам нужно <a href="login">авторизоваться</a> или <a href="/reg">зарегистрироваться</a>!!</div>');}
	
					$.each(data, function(id, online){
						if(online.pol==0)
						$("#online_girl > ul").append('<li><a href="anketa/'+online.user+'" title="'+online.nick+'"><img src="photo/'+online.user+'/avatar/'+online.avatar+'" width="55px"></a></li>');
						if(online.pol==1)
						$("#online_boy > ul").append('<li><a href="anketa/'+online.user+'" title="'+online.nick+'"><img src="photo/'+online.user+'/avatar/'+online.avatar+'" width="55px"></a></li>');
					});
		
				}
			}); 

		}

	return false;
	};	



	// -------------Выводим последние 20 сообщений при запуске------------
	function chat_content_once() {
	
		if( $('#online_view').is(':hidden') ){ // Проверка на скрытость
		}else{

			$("#online_chat_ul").empty();

			$.get("/main_func.php?type=chat_once", {}, function(data) {
				if(data) {
					$("#online_chat_ul").html(data.sourceHtml);
				}
			}); 

		}

	return false;
	};	



	function chat_add() {

		if( $('#online_view').is(':hidden') ){ // Проверка на скрытость
		}else{

			var text =$('#chat_textarea').val();
			$('#chat_send').attr('value','Идёт отправка данных..').attr('disabled', 'disabled');
	
			$.post("/main_func.php?type=chat_add", {"text":text}, function(data) {
				if(data) {
					if(data.status=="ok") {
						$('#chat_textarea').val('');
						chat_content_update(); // Обновляем
					}
					else
					if(data.status=="time") {
						$('#chat_errors').html('Лимит между отправкой сообщений 5 секунд!').fadeIn(550, function () {
							$('#chat_errors').fadeTo(2500,0.9).fadeOut(500); 
						}); 
					}
					else
					if(data.status=="text") {
						$('#chat_errors').html('Сообщение должно быть от 1 до 250 символов!').fadeIn(550, function () {
							$('#chat_errors').fadeTo(2500,0.9).fadeOut(500); 
						});
					}
					$('#chat_send').attr('value','Отправить').attr('disabled', false);
				}
			});

		}

	return false;
	}



	// -------------Проверка на новые сообщения------------
	function chat_content_update() {

		if( $('#online_view').is(':hidden') ){ // Проверка на скрытость
		}else{

			var last_id = $("#online_chat").find('li').attr('id').substr(5);

			$.get("/main_func.php?type=chat_update", {id:last_id}, function(data) {
				if(data) {
					$("#online_chat_ul").html(data.sourceHtml);
				}
			}); 

		}

	return false;
	};	



	// -------------Если IE6 то дурак------------
	function detectIE6(){
	  var browser = navigator.appName;
	  if (browser == "Microsoft Internet Explorer"){
	    var b_version = navigator.appVersion;
	    var re = /\MSIE\s+(\d\.\d\b)/;
	    var res = b_version.match(re);
	    if (res[1] <= 6){
		$('.work_area').html('<br><div class="warning">У вас очень старая модель браузера, вам нужно обновить его чтобы пользоваться сайтом! <a href="http://ie.yandex.ru/">Обновить браузер</a></div><p align="center"><br><img src="images/bs_positiv.jpg"></p>');
	    }
	  }
	  return false;
	}


