$(function() {

$("a[href=visitors]", ".visitors_top").button({ icons: {primary:'ui-icon-person'} });
$("button", ".anketa_head").button({ icons: {primary:'ui-icon-person'} });


	// -------------------------Отображение меню-----------------------
	$('.click').click(show); 

	function show() {
	var id = $(this).attr('id').substr(5);
		$('.show_info').hide();
		$('#'+id).show("drop", {}, 400);
	return false;
	}


	// -------------------До даты прогрессбар-----------------------
	$(".event_bar").progressbar({
		value: 55
	});

	// ----------------------------Статус-----------------------
	$('.edit_status').editable('plugin/anketa/anketa_func.php?type=status', {
	      indicator : '<img src=images/icons/loader_3.gif>',
	      name : 'status',
	      type      : 'charcounter',
	      submit    : 'OK',
	      cancel    : 'Отмена',
	      tooltip   : 'Жми чтобы изменить...',
	      onblur    : 'ignore',
	      height   : '100px',
	      style  : 'inherit',
	      charcounter : {
	         characters : 250
	      }
	});


	// -------------------Смена Аватара--------------------
	$('.avatar_href').live('mouseover',function(){
		var src = $(this).attr('view');
		$('.avatar_img').attr('src',src);
		$('.cloud-zoom').attr('href',src);
		$('.cloud-zoom').CloudZoom();
	});

	// -------------------Показ блока с фото--------------------
	$('#more_photo').click(more_photo); 
	function more_photo() {
		$('#more_photo').hide(100);
		var user = $(this).attr('user');
		$.get("plugin/anketa/anketa_func.php?type=more_photo", {"user":user}, function(data) {
			if(data) {
				$('#more_photo_block').html(data.sourceHtml);
			}
			if(data.status == 'error') {
				$('#error').html(data.text).fadeIn(550, function () {
				$('#error').fadeTo(4500,0.9).fadeOut(500); 
				}); 
			}
		}, 'json');

	return false;
	}


	// ----------------------Отправка голоса за аватар--------------------
	$('.avatar_vote').click(avatar_vote); 
	var avatar_vote_result = $('.avatar_vote_result').attr('id').substr(19);

	function avatar_vote() {

	if(avatar_vote_result==0)
	{
		$("#confirm_avartar_vote").dialog({
			resizable: false,
			stack: true,
			show: 'puff',
			hide: 'puff',
			title: 'Оценка пользователя',
			width:780,
			height:540,
			modal: true,
			close: function(event, ui) {},
			buttons: {'Оценить аватар': function() {
	
				$("#confirm_avartar_vote").dialog({ buttons: { "Подождите идёт отправка данных": function() { alert('Идёт отправка') } } });
				var touser = $('.anketa_message').attr('id').substr(15);
				var voteCount1 = $lis.eq(0).data('avatar_votes_active');
				var voteCount2 = $lis.eq(1).data('avatar_votes_active');
				var voteCount3 = $lis.eq(2).data('avatar_votes_active');
				var voteCount4 = $lis.eq(3).data('avatar_votes_active');
				var voteCount5 = $lis.eq(4).data('avatar_votes_active');
				var voteCount6 = $lis.eq(5).data('avatar_votes_active');
				var voteCount7 = $lis.eq(6).data('avatar_votes_active');
				var voteCount8 = $lis.eq(7).data('avatar_votes_active');
				var voteCount9 = $lis.eq(8).data('avatar_votes_active');
				var voteCount10 = $lis.eq(9).data('avatar_votes_active');
		
				$.post('plugin/anketa/anketa_func.php?type=avatar_vote', 
				{'avatar_vote':$.toJSON({"touser" : touser,"vote1" : voteCount1,"vote2" : voteCount2,"vote3" : voteCount3,"vote4" : voteCount4,"vote5" : voteCount5,"vote6" : voteCount6,"vote7" : voteCount7,"vote8" : voteCount8,"vote9" : voteCount9,"vote10" : voteCount10})},
	
		
				function(data) {
					if(data.status == 'ok') {
						$("#confirm_avartar_vote").dialog({ buttons: { "Закрыть": function() { $(this).dialog("close"); } } });
						$('#avatar_votes').html(data.text);
						avatar_vote_result = 1;
						$('#avatar_vote_success').html('Выполнено успешно!').fadeIn(550, function () {
						$('#avatar_vote_success').fadeTo(2500,0.9).fadeOut(500); 
						}); 
					}
					if(data.status == 'error') {
						$('#avatar_vote_error').html(data.text).fadeIn(550, function () {
						$('#avatar_vote_error').fadeTo(2500,0.9).fadeOut(500); 
						}); 
					}
				});
	
			},'Отмена': function() {$(this).dialog('close');} }
	
		});
	}
	else
	{
		$("#confirm_avartar_vote").dialog({
			resizable: false,
			stack: true,
			show: 'puff',
			hide: 'puff',
			title: 'Оценка пользователя',
			width:780,
			height:600,
			modal: true,
			close: function(event, ui) {},
			buttons: {'Закрыть': function() {$(this).dialog('close');} }
		});
	}

	return false;
	}

	// ------------------------------- Звёздочки в голосовалке за аватар------------------------------
	var limit = 20;
	var $lis = $('#avatar_votes li:gt(0)'); // Строки выбора (без 1-ой т.к. там информационный div)
	$lis.data('avatar_votes_active', 0); // Ставим метку каждой строке - ничего не выбрано 
	$lis.find('a').click(function(){

		$this = $(this);
		$li = $this.parent('li');
		var vote = $li.children().index($this)-1; // текущий выбор
		var have = 0; // проверяем сколько имеется в других вариантах

		$lis.each(function(){
			if($(this)[0] != $li[0]) have += $(this).data('avatar_votes_active');
		});

		var sum = have + vote;
		if (sum > limit) {
			$('.avatar_touser').text('Вы привысили лимит доступных балов').show().fadeTo(1100).fadeOut("slow");
			//alert('привысили лимит в ' + limit);
		} else {
			$li.data('avatar_votes_active', vote);
			$li.find('a').removeClass('avatar_votes_active');
			$this.addClass('avatar_votes_active');
			$('#votesInfoCount').text(20-sum+' баллов осталось');
		}

	return false;
	});




	// ----------------------Отправка комплимента--------------------
	$('.anketa_kompliment').click(kompliment); 

	function kompliment() {

	var kompliment_user = $(this).attr('id').substr(18);
	$('.cloud-zoom').hide();

	$("#confirm_kompliment").dialog({
		resizable: false,
		stack: true,
		show: 'puff',
		hide: 'puff',
		title: 'Отправить комплимент',
		width:450,
		height:320,
		modal: true,
		close: function(event, ui) {$('.cloud-zoom').show();},
		buttons: {'Отправить комплимент': function() {

			$.post('plugin/anketa/anketa_func.php?type=kompliment', 
			{'kompliment':$.toJSON({"touser": kompliment_user})},
	
			function(data) {
	
				var response = eval('('+data+')');
				if(response.status == 'ok') {

					$('.cloud-zoom').show();
					$('#success').html(response.text).fadeIn(550, function () {
					$('#success').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
		
				if(response.status == 'error') {
	
					$('.cloud-zoom').show();
					$('#error').html(response.text).fadeIn(550, function () {
					$('#error').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
	
			});
			$(this).dialog('close');

		},'Отмена': function() {$('.cloud-zoom').show();$(this).dialog('close');} }

	});

	return false;
	}







	// ----------------------Отправка сообщения--------------------
	$('.anketa_message').click(send); 

	function send() {

	var id = 1;
	var message_user = $(this).attr('id').substr(15);
	$('.cloud-zoom').hide();

	$("#confirm_send").dialog({
		resizable: false,
		stack: true,
		show: 'puff',
		hide: 'puff',
		title: 'Новое сообщение',
		width:500,
		height:290,
		modal: true,
		close: function(event, ui) {$('.cloud-zoom').show();},
		buttons: {'Отправить сообщение': function() {

		var message_text  = $('#message_send_text').val();

			$.post('plugin/message/message_func.php?type=add', 
			{'message':$.toJSON({"id": id,  "touser": message_user, "text": message_text})},
	
			function(data) {
	
				var response = eval('('+data+')');
				if(response.status == 'ok') {

					$('.cloud-zoom').show();
					$('#message_send_text').val(""); // Чистим коммент в поле отправки
					$('#success').html(response.text).fadeIn(550, function () {
					$('#success').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
		
				if(response.status == 'error') {
	
					$('.cloud-zoom').show();
					$('#error').html(response.text).fadeIn(550, function () {
					$('#error').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
	
			});
			$(this).dialog('close');

		},'Отмена': function() {$('.cloud-zoom').show();$(this).dialog('close');} }

	});

	return false;
	}





	// ----------------------Отметка спамера-------------------
	$('.anketa_spam').click(spam); 

	function spam() {

	var spam_user = $(this).attr('id').substr(12);
	$('.cloud-zoom').hide();

	$("#confirm_spam").dialog({
		resizable: false,
		stack: true,
		show: 'puff',
		hide: 'puff',
		title: 'Отметка спамера или просто не хорошего человека..',
		width:500,
		height:290,
		modal: true,
		close: function(event, ui) {$('.cloud-zoom').show();},
		buttons: {'Пожаловаться': function() {

		var spam_text  = $('#spam_send_text').val();

			$.post('plugin/message/message_func.php?type=spam', 
			{'spam':$.toJSON({"user": spam_user, "text": spam_text, "type": "anketa"})},
	
			function(data) {
	
				var response = eval('('+data+')');
				if(response.status == 'ok') {

					$('.cloud-zoom').show();
					$('#spam_send_text').val(""); // Чистим коммент в поле отправки
					$('#success').html(response.text).fadeIn(550, function () {
					$('#success').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
		
				if(response.status == 'error') {
	
					$('.cloud-zoom').show();
					$('#error').html(response.text).fadeIn(550, function () {
					$('#error').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
	
			});
			$(this).dialog('close');

		},'Отмена': function() {$('.cloud-zoom').show();$(this).dialog('close');} }

	});

	return false;
	}





	// ----------------------Удаление друга--------------------
	$(".friends_del").click(del); 

	function del() {
	var id = $(this).attr('id').substr(11);
	$('.cloud-zoom').hide();

	$("#confirm_delete").dialog({
		resizable: false,
		stack: true,
		show: 'puff',
		hide: 'puff',
		title: 'Вы точно не хотите дружить с данным пользователем?',
		width:400,
		height:250,
		modal: true,
		close: function(event, ui) {$('.cloud-zoom').show();},
		buttons: {'Убрать из друзей': function() {
	

			$.post('plugin/friends/friends_func.php?type=del', 
			{'friends_del':$.toJSON({"id": id})},
	
			function(data) {
	
				var response = eval('('+data+')');
				if(response.status == 'ok') {
					$('.friends_del').hide();
					$('.cloud-zoom').show().html('<img src="images/icons/trash.png">');
					$('#success').html(response.text).fadeIn(550, function () {
					$('#success').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
		
				if(response.status == 'error') {
					$('.cloud-zoom').show();
					$('#error').html(response.text).fadeIn(550, function () {
					$('#error').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
	
			});
			$(this).dialog('close');

		},'Отмена': function() {$('.cloud-zoom').show();$(this).dialog('close');} }
	});

	return false;
	}







	// ----------------------Добавление друга--------------------
	$('.friends_new').click(add); 

	function add() {
	var user = $(this).attr('id').substr(11);
	$('.cloud-zoom').hide();


	$("#confirm_add").dialog({
		resizable: false,
		stack: true,
		show: 'puff',
		hide: 'puff',
		title: 'Предложение дружбы',
		width:400,
		height:250,
		modal: true,
		close: function(event, ui) {$('.cloud-zoom').show();},
		buttons: {'Добавить в друзья': function() {

		var text = $('#friends_new_text').val();

			$.post('plugin/friends/friends_func.php?type=add_new', 
			{'friends_new':$.toJSON({"user": user,"text": text})},
	
			function(data) {
	
				var response = eval('('+data+')');
				if(response.status == 'ok') { 

					$('.friends_new').hide(); // Скрываем ссылку на добавление
					$('.cloud-zoom').show(); // Показываем аватар
					$('#success').html(response.text).fadeIn(550, function () {
					$('#success').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
		
				if(response.status == 'error') {
					$('.cloud-zoom').show();
					$('#error').html(response.text).fadeIn(550, function () {
					$('#error').fadeTo(2500,0.9).fadeOut(500); 
					}); 
				}
	
			});
			$(this).dialog('close');

		},'Отмена': function() {$('.cloud-zoom').show();$(this).dialog('close');} }
	});
	return false;
	}





	// ---------------------Характеристики-------------------
	$('.haracteristik_add').click(haracteristik); 

	function haracteristik() {

	var id = $(this).attr('id').substr(4,1);
	var user = $(this).attr('id').substr(6);

			$.post('plugin/anketa/anketa_func.php?type=haracteristik', 
			{'haracteristik':$.toJSON({"user": user, "vote": id})},
	
			function(data) {
	
				if(data.status == 'ok') {
					$('#success_har').html(data.text).fadeIn(550, function () {$('#success_har').fadeTo(2500,0.9).fadeOut(500);}); 
					$('.haracteristik_add').hide();
					$('#har_count_'+id).text(Number($('#har_count_'+id).text())+1);
				}
				if(data.status == 'error') {
					$('#error_har').html(data.text).fadeIn(550, function () {$('#error_har').fadeTo(2500,0.9).fadeOut(500);}); 
				}
	
			});

	return false;
	}


	// ---------------------Настроение-------------------.
	nastroenie();

	function nastroenie() {
	
		var id = $('#anketa_age');
		var percent = id.attr('class').substr(11);

		if(percent==10) {
			$('#text_nastroenie').text('Сплошной позитив');
			id.find('a').css('background','url(/images/icons/nastroenie/10.png) no-repeat scroll center center');
		} else if(percent==9) {
			$('#text_nastroenie').text('Влюблённое настроение');
			id.find('a').css('background','url(/images/icons/nastroenie/9.png) no-repeat scroll center center');
		} else if(percent==8) {
			$('#text_nastroenie').text('Настроение отличное');
			id.find('a').css('background','url(/images/icons/nastroenie/8.png) no-repeat scroll center center');
		} else if(percent==7) {
			$('#text_nastroenie').text('Настроение хорошее');
			id.find('a').css('background','url(/images/icons/nastroenie/7.png) no-repeat scroll center center');
		} else if(percent==6) {
			$('#text_nastroenie').text('Настроение пойдёт');
			id.find('a').css('background','url(/images/icons/nastroenie/6.png) no-repeat scroll center center');
		} else if(percent==5) {
			$('#text_nastroenie').text('Настроение так себе');
			id.find('a').css('background','url(/images/icons/nastroenie/5.png) no-repeat scroll center center');
		} else if(percent==4) {
			$('#text_nastroenie').text('Настроение средней паршивости');
			id.find('a').css('background','url(/images/icons/nastroenie/4.png) no-repeat scroll center center');
		} else if(percent==3) {
			$('#text_nastroenie').text('Плохое настроение');
			id.find('a').css('background','url(/images/icons/nastroenie/3.png) no-repeat scroll center center');
		} else if(percent==2) {
			$('#text_nastroenie').text('Ужасное настроение');
			id.find('a').css('background','url(/images/icons/nastroenie/2.png) no-repeat scroll center center');
		} else if(percent==1) {
			$('#text_nastroenie').text('Вообще нет настроения');
			id.find('a').css('background','url(/images/icons/nastroenie/1.png) no-repeat scroll center center');
		}

	}


	var nastroenie_edit_active = 0;
	$('#nastroenie_button').click(nastroenie_edit);
	$('#nastroenie_button_2').click(nastroenie_edit);

	function nastroenie_edit() {
		
		$('#nastroenie_conteiner').dialog({
			draggable: false,
			resizable: false,
			stack: true,
			show: 'fade',
			hide: 'fade',
			title: 'Укажите ваше настроение',
			width:490,
			height:300,
			open:function() {$(this).parents(".ui-dialog:first").find(".ui-widget-header").remove();$('.ui-dialog').css('overflow','visible');$(this).parents(".ui-dialog:first").append('<div class="get_nastroenie_smile"></div>');},
			close: function(event, ui) {$('.get_nastroenie_smile').remove();},
			buttons: {'Сохранить': function() {nastroenie_save();$(this).dialog('close');},'Закрыть': function() {$(this).dialog('close');}
			}
		});

			if(nastroenie_edit_active==0) 
			{
	
			var select = $("#minbeds");
			var slider = $('<div id="slider" style="margin-top:10px;"></div>').insertAfter(select).slider({
				min: 1,
				max: 10,
				range: "min",
				animate: true,
				value: select[0].selectedIndex + 1,
				slide: function(event, ui) {
					select[0].selectedIndex = ui.value - 1;
				},
				change: function(event, ui) {
					var dataNastroenie = ui.value;
					$('#anketa_age').find('a').css('background','url("/images/icons/nastroenie/' + ui.value + '.png") no-repeat scroll center center');
		
					if(dataNastroenie==10) {
						$('#text_nastroenie').text('Сплошной позитив');
					} else if(dataNastroenie==9) {
						$('#text_nastroenie').text('Влюблённое настроение');
					} else if(dataNastroenie==8) {
						$('#text_nastroenie').text('Настроение отличное');
					} else if(dataNastroenie==7) {
						$('#text_nastroenie').text('Настроение хорошее');
					} else if(dataNastroenie==6) {
						$('#text_nastroenie').text('Настроение пойдёт');
					} else if(dataNastroenie==5) {
						$('#text_nastroenie').text('Настроение так себе');
					} else if(dataNastroenie==4) {
						$('#text_nastroenie').text('Настроение средней паршивости');
					} else if(dataNastroenie==3) {
						$('#text_nastroenie').text('Плохое настроение');
					} else if(dataNastroenie==2) {
						$('#text_nastroenie').text('Ужасное настроение');
					} else if(dataNastroenie==1) {
						$('#text_nastroenie').text('Вообще нет настроения');
						
					}
		
				}
			});
			$("#minbeds").click(function() {
				slider.slider("value", this.selectedIndex + 1);
			});
	
		nastroenie_edit_active = 1;
		}

	return false;
	}



	$('#nastroenie_save').click(nastroenie_save);

	function nastroenie_save() {

		var value = $( "#slider" ).slider( "option", "value" );
	
				$.post('plugin/anketa/anketa_func.php?type=nastroenie', 
				{'nastroenie':$.toJSON({"num": value})},
		
				function(data) {
		
					if(data.status == 'ok') {
						$('#success').html(data.text).fadeIn(550, function () {$('#success').fadeTo(2500,0.9).fadeOut(500);}); 
						$('#nastroenie_conteiner').hide();
					}

					if(data.status == 'error') {
						$('#error').html(data.text).fadeIn(550, function () {$('#error').fadeTo(2500,0.9).fadeOut(500);}); 
					}

				});

	return false;
	}





	// ---------------------Изменение дизайна-------------------.
	$('#change_page_style').click(change_page_style);
	function change_page_style() {
		
		$('#dialog_show').dialog({			closeOnEscape: false,
			draggable: false,
			resizable: false,
			stack: true,
			show: 'fade',
			hide: 'fade',
			modal: true,
			title: 'Изменение дизайна страницы',
			width:680,
			height:460,
			open:function() {$(this).parents(".ui-dialog:first").find(".ui-widget-header").remove();$('.ui-dialog').css('overflow','visible');},
			close: function(event, ui) {},
			buttons: {'Сохранить изменения': function() {$("#change_page_style_form").submit();$("#dialog_show").dialog({ buttons: { "Подождите идёт отправка данных": function() { alert('Идёт отправка') } } });},'Закрыть': function() {$(this).dialog('close');}
			}
		});

		var html = '<div class="conteiner">';
	 		html += '<div class="top_block" style="padding:13px 5px;margin-bottom:10px;"><h1>Изменение дизайна страницы</h1></div>';
	 		html += '<div style="margin:15px 0px;text-align:center;"><img src="images/icons/change_style_1.jpg"></div>';
	 		html += 'Загрузить фоновое изображение:';
	 		html += '<form enctype="multipart/form-data" method="post" action="plugin/anketa/anketa_func.php?type=change_page_style" id="change_page_style_form">';
	 			html += '<input type="file" value="" name="image_field" class="input-text">';
	 			html += '<p class="info_gray">Максимум 3 мегабайта, JPEG, PNG, GIF.</p>';
	 		html += '</form>';
 		html += '</div>';

		$('#dialog_show').html(html);

	return false;
	}





	// ---------------------Видео аватар-------------------.
	$('#video_button').click(video_show);
	function video_show() {
		
		$('#video_conteiner').dialog({
			draggable: false,
			resizable: false,
			stack: true,
			show: 'fade',
			hide: 'fade',
			modal: true,
			title: 'Видео аватар',
			width:500,
			height:440,
			open:function() {$(this).parents(".ui-dialog:first").find(".ui-widget-header").remove();$('.ui-dialog').css('overflow','visible');$(this).parents(".ui-dialog:first").append('<div class="get_video_avatar"></div>');},
			close: function(event, ui) {$('.get_video_avatar').remove();},
			buttons: {'Закрыть': function() {$(this).dialog('close');}
			}
		});

			var user = $('#video_conteiner').attr('user');
			var sig = $('#video_conteiner').attr('sig');
			var flashvars = {};
			var params = {};
			params.quality = "best";
			params.wmode = "transparent";
			flashvars.logname = user+"&sig="+sig;
			var attributes = {};
			attributes.align = "middle";
			swfobject.embedSWF("plugin/anketa/video_avatar.swf", "videoprivet", "320", "300", "9.0.0", false, flashvars, params, attributes);

	return false;
	}



	$('#video_avatar_show').click(video_play);
	function video_play() {

		$('#show_video_avatar').dialog({
			draggable: false,
			resizable: false,
			stack: true,
			show: 'fade',
			hide: 'fade',
			modal: true,
			title: 'Видео аватар',
			width:440,
			height:430,
			open:function() {$(this).parents(".ui-dialog:first").find(".ui-widget-header").remove();$('.ui-dialog').css('overflow','visible');$(this).parents(".ui-dialog:first").append('<div class="get_video_avatar"></div>');},
			close: function(event, ui) {$('.get_video_avatar').remove();},
			buttons: {'Закрыть': function() {$(this).dialog('close');}
			}
		});

		var user = $('#video_conteiner').attr('view_user');
		var flashvars = {"comment":"Будь собой","st":"http://budsoboi.ru/plugin/anketa/player/styles/video_anketa.txt","file":"http://budsoboi.ru/plugin/anketa/video/"+user+"/videoprivet.flv"};
		var params = {wmode:"transparent", allowFullScreen:"false", allowScriptAccess:"always",id:"video_avatar"}; 
		new swfobject.embedSWF("http://budsoboi.ru/plugin/anketa/player/play_video.swf", "video_avatar", "320", "275", "9.0.115.0", false, flashvars, params);

	return false;
	}

});

function save_button_show()
{
	$('#video_conteiner').dialog("option", "buttons",  [{text: "Сохранить",click: function() { video_save();$(this).dialog('close'); } },{text: "Закрыть",click: function() { if(confirm('Вы точно хотите закрыть, у вас осталось не сохранёное видео')){$(this).dialog('close');} }}] );
}

function save_button_hide()
{
	$('#video_conteiner').dialog("option", "buttons",  [{text: "Закрыть",click: function() { $(this).dialog('close');} }] );
}

function video_save() {
	$.post("plugin/anketa/anketa_func.php?type=save_video", {}, function(data) {
		if(data.status=="ok")
		{
			location.href = data.text;
		}
		if(data.status=="error")
		{
			alert(data.text);
		}
	});
return false;
}
