
var canReply = 1;
var useCaptcha = 0;
var commentsHeightOffset = 0;

function commentsInitCaptcha(is_destroy)
{
	var is_destroy = is_destroy || false;
	
	if(is_destroy) Recaptcha.destroy();
	
	Recaptcha.create(captchaKeyPublic, "recaptcha_div", {
	   theme: "clean", lang: "ru"
	});
}


function commentRate(el, comment_id, value)
{
		jQuery().loadWait({
			elem: el,
			url: '/ajaxnew/comments/vote',
			params: {comment_id: comment_id, value: (value == 'plus' ? 1 : -1)},
			onDone: function(data) {
                if (data.status == 'ok')
                {
                    if (data.current_rating <=-5 && data.current_rating >-10) bad_class = 'bad5';
                    else if (data.current_rating <=-10 && data.current_rating >-15) bad_class = 'bad10';
                    else bad_class = '';
                    $(el).parent().parent().next().attr('class', bad_class);
                    
                    
                    $('#a_comment_plus_'+comment_id).hide();
                    $('#a_comment_minus_'+comment_id).hide();
                    $('#comment_rate_value_'+comment_id).html((data.current_rating > 0 ? '+' : '')+data.current_rating);
                    if (data.current_rating > 0 ) $('#comment_rate_value_'+comment_id).addClass('ok');
                
                }
			}
		});	

}


function replyTo(comment_id, level, def, focs)
{
	if(!canReply) return;
	var def = def != undefined ? def : false;
	var focs = focs != undefined ? focs : true;
	if(jQuery("#pid").val() != comment_id || def) {
		jQuery("#pid").val(comment_id);
		if(level == 0 && comment_id > 0) {
			level = parseInt(parseInt(jQuery('#cmnt_'+comment_id).css('margin-left'))/30);
		}
		jQuery("#reply").insertAfter("#cmnt_"+comment_id);
		jQuery("#reply").width(448 - level*30);
		if(comment_id == 0) {
			jQuery("#reply").addClass('new');
			jQuery("#new-comments h2.reply span").show();
			jQuery("#new-comments h2.reply a").hide();
			jQuery("#new-comments h2.reply").addClass('bord');
		} else {
			jQuery("#reply").removeClass('new');
			jQuery("#new-comments h2.reply span").hide();
			jQuery("#new-comments h2.reply a").show();
			jQuery("#new-comments h2.reply").removeClass('bord');
		}
		jQuery("#reply").css({display:"block", 'margin-left': level*30+'px'});
		jQuery('#message').remove();
		if(def) {
			jQuery("#reply textarea").val('');
		}
	}
	if(focs) jQuery("#reply textarea").removeAttr('disabled').focus();
}

function commentsDelete(elem, cid, subids)
{
	var subids = subids == undefined ? '' : subids;
	if(confirm('Ты уверен что хочешь удалить этот комментарий'+(subids!=''?' и всего его под-комментарии':'')+'?')) {
		canReply = 0;
		jQuery().loadWait({
			elem: elem,
			url: '/lib/comments/delete/',
			params: {cid: cid, subs: subids},
			onDone: function(data) {
				canReply = 1;
				replyTo(0, 0, true, false);
				if(data.action == 'deleted') {
					jQuery('#cmnt_'+cid).remove();
				} else {
					var m = jQuery('#cmnt_'+cid).css('margin-left');
					jQuery('#cmnt_'+cid).replaceWith(data.comment);
					jQuery('#cmnt_'+cid).css({'margin-left' : m});
				}
			},
			onError: function(data) {
				canReply = 1;
				replyTo(0, 0, true, false);
				if(!data.message_text) data.message_text = 'Произошла ошибка при удалении комментария, попробуй немного позже.';
				alert(data.message_text);
			} 
		});	
	}
}



function commentsPost()
{

	if(!jQuery('#comment_form textarea').val()) {
		jQuery('#comment_form textarea').focus();
	} else {
		if(!jQuery('#comment_form textarea').is(':disabled')) {
			var formData = jQuery('#comment_form').serializeArray();
			jQuery('#comment_form textarea').attr('disabled', 'disabled');
			jQuery('#message').remove();
			canReply = 0;
			jQuery.loadWait({
				elem: jQuery('#comment_form a.send'),
				url: '/lib/comments/add/',
				params: formData,
				onDone: function(data) {
					canReply = 1;
					if(useCaptcha) commentsInitCaptcha(true);
					
					// clearing form
					replyTo(0, 0, true);
					
					$('#new-comments p.no-comments').remove();
					// adding received comment to html
					if(data.parent_id == 0) {
						$('#new-comments').prepend(data.comment);
					} else {
						jQuery('#cmnt_'+data.parent_id).after(data.comment);
						// creating margin left to correct sublevel
						var newLevel = parseInt(jQuery('#cmnt_'+data.parent_id).css('margin-left'))/30;
						if(newLevel < 8) newLevel += 1; 
						jQuery('#cmnt_'+data.comment_id).css({'margin-left' : newLevel*30+'px'});
					}
					$.scrollTo('#cmnt_'+data.comment_id, {onAfter: function() {
						//console.log(commentsHeightOffset);
						if(parseInt(commentsHeightOffset) > 0)
						{
							$.scrollTo('-='+parseInt(commentsHeightOffset)+'px');
						}
					}});
				},
				onError: function(data) {
					if(useCaptcha) commentsInitCaptcha(true);
					
					canReply = 1;
					// show message with error
					jQuery('#comment_form textarea').attr('disabled', '');
					if(!data.message) {
						alert('Произошла ошибка при добавлении комментария, попробуй немного позже.');
					} else {
						jQuery('#comment_form').prepend(data.message);
					}
					jQuery('#comment_form textarea').focus();
				} 
			});
		}
	}

	return false;		
	
}