$(function(){
	$("#search > input").Watermark("поиск");
});

(function($)
{
	$.fn.favorites=function(params)
	{
		$(".favorites > a").click(function()
		{
			$.ajax({
				url: "/action/favorites/",
				data: {
					tpl_id: params.tpl_id,
					rec_id: params.rec_id
				},
				dataType : "json",
				type: "POST",
				beforeSend: function(XMLHttpRequest) {
					$(".favorites span.action_loader").show();
				},
				complete: function(XMLHttpRequest, textStatus) {
					$(".favorites span.action_loader").hide();
				},
				success: function (data, textStatus) {
					if(data.status=='ok')
					{
						$("div.favorites > a > span").html(data.text);
						$("div.favorites").removeClass().addClass("favorites").addClass(data.newclass);
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
				}
			});
		});
	}
})(jQuery);


function linkback()
{
	$("h1").text("Добавить ролик");
	$("div.upload").show();
	$("#status").hide();
	return false;
}

$cn = 0;

function viewform (id,obj)
{	
	if ($("#comment").css("display")=='none' || obj!=$("#post_id").attr("value"))
	{
		$("#post_id").attr("value",obj);
		$("#text").attr("value", '');
		$("#comment").appendTo(id);
		$("#comment").show();
		if ($cn++ > 0)
			$("#comment #text").focus();
	}else{
		if (obj==$("#post_id").attr("value")){
			$("#comment").hide();
		}
	}
}
		
var Alert = {
	show: function(title, text, class_name) {
		if (!$('#ajax_alert').attr('id')) {
			$('<div id="ajax_alert"></div>').appendTo(document.body);
		}
		$('<div class="item ' + class_name + '"><h2>' + title + '</h2>' + text + '</div>')
			.prependTo($('#ajax_alert'))
			.fadeIn('slow')
			.animate({opacity: 1.0}, 3000)
			.fadeOut('slow', function() {$(this).remove();});
	}
}


function addComment(url)
{
	if ($("#text").attr("value") == '')
	{
		Alert.show('Ошибка', 'Нужно ввести текст комментария', 'error');
		return false;
	}
	$("div.button").addClass("loader");
	$("div.log-in-show").hide();
	$("#addcomment").attr("disabled",'disabled');
	$("#cancelform").attr("disabled",'disabled');
	var $username = '';
	var $usermail = '';
	var $usermailsubscribe = '';
	
	if ($("input").is("#username"))
		$username = $("#username").attr("value");

	if ($("input").is("#usermail")){		
		$("#usermail").valid();
		$usermail = $("#usermail").attr("value");
	}
	if ($("input").is("#usermailsubscribe"))				
		$usermailsubscribe = $("#usermailsubscribe").attr("checked");
	
	$.ajax({
		url: url,
		data: {
			   comment: $("#text").attr("value"),
			   tpl_id: $("#tpl_id").attr("value"),
			   rec_id: $("#rec_id").attr("value"),
			   post_id: $("#post_id").attr("value"),
			   username: $username,
			   usermail: $usermail,
			   usermailsubscribe: $usermailsubscribe
		},
		dataType : "json",
		type: "POST",
		success: Success,
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
			$("#addcomment").attr("disabled",'');
			$("#cancelform").attr("disabled",'');
			$("div.button").removeClass("loader");		
			$("div.log-in-show").show();			
		}
	});

	function Success (data, textStatus)
	{
		if (data.status=='ok')
		{
			$("#addcomment").attr("disabled",'');
			$("#cancelform").attr("disabled",'');
			$("div.button").removeClass("loader");
			$("div.log-in-show").show();
			$("#comment").hide();

			$(data.comment).appendTo($("#post_id").attr("value"));
			$("#count_c").text($("#count_c").text()*1+1);
			window.location.hash = data.post;
			Alert.show('Спасибо', 'Комментарий успешно добавлен', 'message');
					
			$(".editcomment").editable("/action/editpost/",
			{			
				type      : 'textarea',
				cancel    : 'Отмена',
				submit    : 'Редактировать',
				height    : '100px',
				cssclass  : 'editface',
				indicator : '<img src="/template/images/loader.gif">',
				tooltip   : "Щелкните чтоб отредактировать этот комментарий",
			});
		}else{
			if (data.status=='error'){
				Alert.show('Ошибка', data.comment, 'error');
			}else
				Alert.show('Ошибка', 'Неизвестная ошибка, комментарий не добавлен', 'error');
					
			$("#addcomment").attr("disabled",'');
			$("#cancelform").attr("disabled",'');
			$("div.button").removeClass("loader");		
			$("div.log-in-show").show();
		}
	}
}

function parseQuery(s)
{
	s=s.substring(s.indexOf('?')+1);
	var q=s.split('&');
	var r={};
	for(var i=0;i<q.length;i++)
	{
		var t=q[i].split('=');
		r[t[0]]=t[1];
	}
	return r;
}

(function(a){
	a.fn.stars=function(e){
		function b(){
			a(this).parent().addClass("b-rating-stars-"+this.className.substring(1))
		}
		function d(){
			a(this).parent().removeClass().addClass("b-rating-stars")
		}
		function c(f){
			$.ajax({
				url: "/action/vote/",
				data: {
					tpl_id: e.tpl_id,
					rec_id: e.rec_id,
					vote: this.rel				
				},
				dataType : "json",
				type: "POST",
				success: function (data, textStatus) {
					if(data.status=='ok')
					{
						var r=$("div.rating");
						$("div.vote").hide();
						r.find("i").removeClass().addClass('b-rating-stars').addClass('b-rating-stars-'+data.votes);
						r.find("span").text(data.count);
						r.show();
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					Alert.show('Ошибка', 'Не удалось выполнить запрос: ', 'error');
				}
			});
			return false;
		}
	
		a("div.vote .b-rating-stars a").live("mouseover",b).live("mouseout",d).live("click",c)
	}
})(jQuery);

(function($)
{

	$.fn.tags=function(params)
	{
		var g=$(this);
		
		var element='';

		$(this).find("img.tag-delete").click(function(event)
		{
			var r=$(".popup-tags-delete");
			r.find("span").text($(this).parent().find("a").html());
			if(navigator.appName == "Microsoft Internet Explorer")
			{
				r.css('left',event.offsetX);
			}else{
				r.css('left',event.clientX - 240);
			}
			r.animate({ opacity: "show" }, "slow");
			element=$(this).parents("li");
		});

		$(".popup-tags-delete .cancel").click(function()
		{
			$(".popup-tags-delete").animate({ opacity: "hide" }, "slow");
		});

		$(".popup-tags-delete .remove").click(function()
		{
			$.ajax({
				url: "/action/deltags/",
				data: {
					tpl_id: params.tpl_id,
					rec_id: params.rec_id,
					tag: $(this).parents(".popup-tags-delete").find("span").html()
				},
				dataType : "json",
				type: "POST",
				success: function (data, textStatus) {
					if(data.status=='ok')
					{
						$(".popup-tags-delete").hide();
						element.hide();
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
				}
			});
		});

		$(".tags-add a").click(function(event)
		{
			if(navigator.appName == "Microsoft Internet Explorer")
			{
				$(".popup-tags-add").css('left',event.offsetX);
			}else{
				$(".popup-tags-add").css('left',event.clientX - 240);
			}
			$(".popup-tags-add").find(".input").attr("value",'');
			$(".popup-tags-add").animate({ opacity: "show" }, "slow");
		});

		$(".popup-tags-add .cancel").click(function()
		{
			$(".popup-tags-add").animate({ opacity: "hide" }, "slow");
		});


		$(".popup-tags-add .ok").click(function()
		{
			$.ajax({
				url: "/action/addtags/",
				data: {
					tpl_id: params.tpl_id,
					rec_id: params.rec_id,
					tag: $(".popup-tags-add").find(".input").attr("value")
				},
				dataType : "json",
				type: "POST",
				success: function (data, textStatus) {
					if(data.status=='ok')
					{
						$(".popup-tags-add").animate({ opacity: "hide" }, "slow");
						$("div.tags > ul").empty().append(data.tags);
						$("div.tags").tags({tpl_id: params.tpl_id, rec_id: params.rec_id});
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
				}
			});
		});
	}
	
})(jQuery);

(function($){
	$.fn.sorter=function(e){
		$("ul.sorter li").click(function()
		{
			if ($(this).hasClass("current")) return false;
			$.cookie(e.cookie, $(this).find("a").attr('rel'),{expires: 7, path: "/", domain: window.location.hostname, secure: false});
			$("ul.sorter li").each(function()
			{
				$(this).removeClass();
			});
			$(this).addClass("current");

			$.ajax({
				url: "/action/sorter/",
				data: {
					sortertype: $(this).find("a").attr('rel'),
					t_id: e.t_id,
					s_id: e.s_id
				},
				dataType : "html",
				type: "POST",
				beforeSend: function(XMLHttpRequest) {
					$("div.sub-nav span").show();
				},
				complete: function(XMLHttpRequest, textStatus) {
					$("div.sub-nav span").hide();
				},
				success: function (data, textStatus) {
					$("div.sorterlist").html(data);
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
				}
			});
			return false;
		});		
	}
})(jQuery);

$(document).ready(function(){

	$("#usermail").keyup(function(){
		if ($(this).attr('value') == '')
		{
			if ($("div.b-checkbox__comment label").is(":visible"))
				$("div.b-checkbox__comment label").hide().find("#usermailsubscribe").attr('checked','false');
		}else{
			if ($("div.b-checkbox__comment label").is(":hidden"))
				$("div.b-checkbox__comment label").show().find("#usermailsubscribe").attr('checked','true');
		}
	});

	$("#username").keyup(function(){
		if ($(this).attr('value') == '')
			$("div.log-in-show > b").text('анонимный пользователь');
		else
			$("div.log-in-show > b").text($(this).attr('value'));
		
		if ($(this).attr('value').length >= 30)
			$(this).attr('value',$(this).attr('value').substring(0, 30));
			
	
	});

	$(function(){
		$("div.b-input-hint > input, div.b-input-hint > textarea")
		.focus(function()
		{
			$(this).parent().find('label').hide();
		})
		.blur(function()
		{
			if ($(this).attr('value') == "")
				$(this).parent().find('label').show();
		})
		.mouseover(function()
		{
			if ($(this).attr('value') != "")
				$(this).parent().find('label').hide();
		}).bind('change',function()
		{
			if ($(this).attr('value') != "")
				$(this).parent().find('label').hide();
		}).trigger('change');
	});


	$("div.rightblock > a").click(function()
	{										   
		if (window.opera && window.print) // opera
			obj = 'html';
		else
			obj = 'html, body';
		
		$(obj).animate({ scrollTop: 0 }, 1000, 'easeInOutExpo');
		
		event.stopPropagation();
		event.preventDefault();

		return false;
	});


	$(".deletepost").click(function()
	{
		if (!confirm('Вы действительно хотите удалить этот пост?')) return false;

		$.ajax({
			url: "/action/deletepost/",
			data: {
				tpl_id: $(this).attr("tpl_id"),
				rec_id: $(this).attr("rec_id")
			},
			dataType : "json",
			type: "POST",
			success: function (data, textStatus) {
				if(data.status=='ok')
				{
					Alert.show('Спасибо', data.info, 'message');
				}else if(data.status=='error')
				{
					Alert.show('Ошибка', data.info, 'error');
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
			}
		});
	});

	$(".recent-tags a").click(function()
	{	
		$("#tag").focus();
		var s=$("#tag").attr("value");
		if (s != "") s=s+", ";
		$("#tag").attr("value",s+$(this).html());
	});
	
	$("blockquote").corner("10px");
//	$("#comment").corner("10px");
	$("div.popup-form").corner("10px");
				
	$("#cancelform").click(function()
	{
		$("#comment").hide();
	});
		
	$("a.option").click(function()
	{
		if ($("div.options").css("display")=='none')
		{
			$("div.options").show();
			$("a.option > arr").html("&uarr;");
			$("a.option > span").text("Дополнительно (скрыть)");
		}else{
			$("div.options").hide();
			$("a.option > arr").html("&darr;");
			$("a.option > span").text("Дополнительно (показать)");
		}
	});


	$("#search > input").focus(function()
	{
		$("#navi > div").css('width', '182px');
		$("ul.topnav").hide();
	});

	$("#search > input").blur(function()
	{
		$("#navi > div").css('width',' 633px');
		$("ul.topnav").show();
	});

	$(".editcomment").editable("/action/editpost/",
	{
		type      : 'textarea',
        cancel    : 'Отмена',
		submit    : 'Редактировать',
        height    : '100px',
		cssclass  : 'editface',
		indicator : '<img src="/template/images/loader.gif">',
		tooltip   : "Щелкните чтоб отредактировать этот комментарий",
	});

	$(".editforum").editable("/action/editforum/",
	{
		type      : 'textarea',
        cancel    : 'Отмена',
		submit    : 'Редактировать',
        height    : '100px',
		width     : '100%',
		cssclass  : 'editface',
		indicator : '<img src="/template/images/loader.gif">',
		tooltip   : "Щелкните чтоб отредактировать этот текст",
	});

	$(".editforumname").editable("/action/editforumname/",
	{
		type      : 'textarea',
        cancel    : 'Отмена',
		submit    : 'Редактировать',
		width     : '100%',
		cssclass  : 'editface editfacetitle',
		indicator : '<img src="/template/images/loader.gif">',
		tooltip   : "Щелкните чтоб отредактировать этот текст",
	});

	$("input.btn_cancel").click(function()
	{
		window.location.href = $(this).attr('rel');
	});

	$("#newalbum input.btn").click(function()
	{
		var tfocus = this;
		$.ajax({
			url: "/action/newphotoalbum/",
			data: {
				title: $('#newalbum input.title').attr('value'),
				description: $('#newalbum textarea.desc').attr('value'),
				theme: $('#newalbum select.theme').attr('value'),
				tag: $('#newalbum input.tag').attr('value')				
			},
			dataType : "json",
			type: "POST",
			beforeSend: function(XMLHttpRequest) {
				$(tfocus).attr('disabled', 'disabled');
				$('span.loader').show();
			},
			complete: function(XMLHttpRequest, textStatus) {
				$(tfocus).attr('disabled', '');
				$('span.loader').hide();
			},
			success: function (data, textStatus) {
				if(data.status=='ok')
				{
					window.location.href = data.uri;
				}else
					Alert.show(data.msg, data.text, 'error');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
			}
		});
		return false;
	});
	
	$("#editphotoalbum input.btn").click(function()
	{
		$.ajax({
			url: "/action/user_photo/",
			data: {
				action: "edit",
				name: $("#editphotoalbum input.name").attr('value'),
				f_desc: $("#editphotoalbum textarea.desc").attr('value'),
				albumid: $(this).attr('rel')
			},
			dataType : "json",
			type: "POST",
			beforeSend: function(XMLHttpRequest) {

				$("#editphotoalbum input.btn").attr('disabled', 'disabled');
			},
			complete: function(XMLHttpRequest, textStatus) {
				$("#editphotoalbum input.btn").attr("disabled",'');

			},
			success: function (data, textStatus) {
				if(data.status=='ok')
					Alert.show(data.title, data.msg, 'message');
				else
					Alert.show(data.title, data.msg, 'error');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
			}
		});
		return false;	
	});
	
	$("#editphotos a").click(function()
	{

		var tfocus = this;

		function result(type)
		{
			if (type == 'delphotos')
			{
				$(tfocus).parents('div.descr_f').animate({ opacity: "hide" }, "slow");
			}else if (type == 'rotate_right' || type == 'rotate_left')
			{
				var i = $(tfocus).parents('div.descr_f').find('div.album img');
				$(i).attr('src',$(i).attr('src') + "?" + Math.random());
			}
		}

		if (parseQuery(tfocus.href)['action'] == 'delphotos')
		{
			if (!confirm('Вы действительно хотите удалить эту фотографию?')) return false;
		}
		
		$.ajax({
			url: "/action/user_photo/",
			data: {
				action: parseQuery(tfocus.href)['action'],
				albumid: parseQuery(tfocus.href)['albumid'],
				photoid: parseQuery(tfocus.href)['photoid']
			},
			dataType : "json",
			type: "POST",
			beforeSend: function(XMLHttpRequest) {
				$(tfocus).attr('disabled', 'disabled');
				$(tfocus).parent().find("span").show();
			},
			complete: function(XMLHttpRequest, textStatus) {
				$(tfocus).attr('disabled', '');
				$(tfocus).parent().find("span").hide();
			},
			success: function (data, textStatus) {
				if(data.status=='ok')
				{
					result(parseQuery(tfocus.href)['action']);
					Alert.show(data.title, data.msg, 'message');
				}else
					Alert.show(data.title, data.msg, 'error');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
			}
		});
		return false;
	});
	
	$("#editphotos input.btn").click(function()
	{
		var tfocus = this;
		$.ajax({
			url: "/action/user_photo/",
			data: $("#editphotos").serializeArray(),
			dataType : "json",
			type: "POST",
			beforeSend: function(XMLHttpRequest) {
				$(tfocus).attr('disabled', 'disabled');
				$('span.loader').show();
			},
			complete: function(XMLHttpRequest, textStatus) {
				$(tfocus).attr('disabled', '');
				$('span.loader').hide();
			},
			success: function (data, textStatus) {
				if(data.status=='ok')
				{
					Alert.show(data.title, data.msg, 'message');
				}else
					Alert.show(data.title, data.msg, 'error');
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				Alert.show('Ошибка', 'Не удалось выполнить запрос', 'error');
			}
		});
		return false;
	});
	
});


(function($) {	
	var map=new Array();
	$.Watermark = {
		ShowAll:function(){
			for (var i=0;i<map.length;i++){
				if(map[i].obj.val()==""){
					map[i].obj.val(map[i].text);					
					map[i].obj.css("color",map[i].WatermarkColor);
				}else{
				    map[i].obj.css("color",map[i].DefaultColor);
				}
			}
		},
		HideAll:function(){
			for (var i=0;i<map.length;i++){
				if(map[i].obj.val()==map[i].text)
					map[i].obj.val("");					
			}
		}
	};
	
	$.fn.Watermark = function(text,color) {
		if(!color)
			color="#666666";
		return this.each(
			function(){		
				var input=$(this);
				var defaultColor=input.css("color");
				map[map.length]={text:text,obj:input,DefaultColor:defaultColor,WatermarkColor:color};
				function clearMessage(){
					if(input.val()==text)
						input.val("");
					input.css("color",defaultColor);
				}

				function insertMessage(){
					if(input.val().length==0 || input.val()==text){
						input.val(text);
						input.css("color",color);	
					}else
						input.css("color",defaultColor);	
				}

				input.focus(clearMessage);
				input.blur(insertMessage);								
				input.change(insertMessage);
				
				insertMessage();
			}
		);
	};
})(jQuery);


