$(function(){
	// всякие разные функции
	function str_replace(search, replace, subject) {
	    return subject.split(search).join(replace);
	}


	// Вешаем обработчики на поле поиска
	document.getElementById('siteSearchInput').onclick = function() {
		if (this.value == 'Поиск...')
			this.value = '';
	};

	document.getElementById('siteSearchInput').onblur = function() {
		if (this.value=='')
			this.value = 'Поиск...';
	}


	// Рейтинг поста
	$('.post_rating img, .pp_post_content .rating img').click(function(){
		var rateSection = $(this).parent();
		var postId = rateSection.attr('data-postid');
		var rateAction = false, rateChange;

		if ($(this).hasClass('post_rate_up')) {
			rateAction = 'up';
			rateChange = 1;
		} else if ($(this).hasClass('post_rate_down')) {
			rateAction = 'down';
			rateChange = -1;
		}

		if (rateAction !== false && !rateSection.hasClass('rated')) {
			$.post('/userajax/postrate/', {postId: postId, rateAction: rateAction}, null, 'json')
				.success(function(response){
					var rateSpan = rateSection.find('span.value'), rateVal;
					rateVal = parseInt(rateSpan.text());
					rateVal += rateChange;

					if (rateVal > 0) {
						rateSpan.addClass('positive').text('+' + rateVal);
					} else if (rateVal < 0) {
						rateSpan.addClass('negative').text(rateVal);
					} else {
						rateSpan.removeClass('negative positive').text(rateVal);
					}
					rateSection.addClass('rated');
				})
		}
	});


	// Отправка комментария
	$('#commentSend').click(function(){
		var commentText = '', commentAuthor = '', postId, parentCommentId;
		commentText = $('#commentText').val();
		commentAuthor = $('#commentAuthor').val();
		postId = $(this).attr('data-postid');
		parentCommentId = $(this).parents('.comment').attr('data-id') || '0';

		if (commentAuthor!='' && commentText!='') {
			$('#commentLoader').show();
			$.post('/userajax/addcomment/', {
				postId: postId,
				commentAuthor: commentAuthor,
				commentText: commentText,
				parentCommentId: parentCommentId
			}, null, 'json')
				.success(function(r){
					if (typeof r.error == 'undifned' || r.error === true) {
						alert('Что-то пошло не так :(');
					} else {
						var nc = '';

						if (parentCommentId == 0) nc = r.newComment;
						else
							nc = '<div class="cm_replys">' + r.newComment + '</div>';

						$('#commentReplyForm').before(nc).detach().appendTo('.comments_list');
						$('#commentText').val('');

						// Ставим на месяц куку с именем автора
						var d = new Date();
						d.setUTCMonth(d.getUTCMonth()+1);
						document.cookie = 'author_name='+encodeURIComponent(commentAuthor)+'; expires='+d.toUTCString()+'; path=/';
					}
				}).complete(function(){
					$('#commentLoader').hide();
				});
		} else {
			alert('Заполните все поля');
		}

		return false;
	});


	// Ответ на комментарий
	$('.cm_reply_link a').live('click', function(){
		var cf = $('.cm_reply_form').detach();
		$(this).parent().append(cf);
		return false;
	});

	// Заполняем имя посетителя из cookie
	if ($('#commentAuthor').length) {
		var docCookie = document.cookie;
		var cookieName = 'author_name=';
		if(docCookie.indexOf(cookieName) != -1) {
			var search = docCookie.substring(docCookie.indexOf(cookieName) + cookieName.length, docCookie.length).split(';')[0];
			search = decodeURIComponent(search);
			$('#commentAuthor').val(search);
		}
	}

	if($('.pp_socials').length) {
		$.ajax({
			url: 'http://userapi.com/js/api/openapi.js',
			dataType: 'script',
			cache: true,
			type: 'GET',
			success: function(){
				VK.init({
					apiId: 2239335,
					onlyWidgets: true
				  });
				VK.Widgets.Like("vk_like", {type: "mini"});
			}
		});

		$.ajax({
			url: 'http://cdn.connect.mail.ru/js/loader.js',
			dataType: 'script',
			cache: true,
			type: 'GET'
		});

		window.___gcfg = {lang: 'ru'};
		(function() {
		var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
		po.src = 'https://apis.google.com/js/plusone.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
		})();

		(function(d, s, id) {
			var js, fjs = d.getElementsByTagName(s)[0];
			if (d.getElementById(id)) return;
			js = d.createElement(s); js.id = id;
			js.src = "//connect.facebook.net/ru_RU/all.js#xfbml=1";
			fjs.parentNode.insertBefore(js, fjs);
		}(document, 'script', 'facebook-jssdk'));
	}

});
