
function votingControls() {
	var voteBtns = $('a.voteFor, a.voteAgainst');
	
	voteBtns.each(function() {
		$(this).click(function(e) { 
			e.preventDefault();
			var artId = this.id.split('-')[3];
			
			if(!$('#voteblock-' + artId).hasClass('disabled')) {
			
				if($('#'+ this.id).hasClass('voteFor')) n = 1;
				else n = -1; 
			
				$('#total-votes-' + artId).text(parseInt($('#total-votes-' + artId).text()) + n);			
				$('#voteblock-' + artId).addClass('disabled');
				
				$.ajax({ type: "GET", url: this.href });
			}
		});
	});
}

function deleteComments() {
	var deleteBtns = $('#comments li .actions a.delete'); 
	var commentsNum = parseInt($('#article-comments-num').text());
	deleteBtns.each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			if(confirm('Ты точно хочешь удалить этот коммент?')) {
				$('#articleCommentsNum').text((commentsNum - 1));
				$(this).parent().parent().parent().addClass('noDisplay');
				$.get($(this).attr('href'));
			}
		});
	});
}

function rssDropDown() {
	if($('#rssFeed') && $('#rssDropDown')) {
		$('#rssFeed').click(function(e) {
			e.preventDefault();
			$('#rssDropDown').css({
				'top': $('#rssFeed').offset().top + 'px',
				'left': ($('#rssFeed').offset().left - 120) + 'px'
			});
			
			$('#rssDropDown').fadeIn(function() {
				$('#rssDropDown').toggleClass('noDisplay')
			});
		});
		
		$(document).click(function(e) {
			if(!$('#rssDropDown').hasClass('noDisplay') && e.target.tagName != 'span' && e.target.tagName != 'b') {
				$('#rssDropDown').fadeOut('fast', function() {
					$('#rssDropDown').toggleClass('noDisplay')
				});
			}
		});
	}
}

function slideBlocks(btn, block) {
	if($('#' + btn) && $('#' + block)) {
		$('#' + btn).click(function(e) {
			e.preventDefault();
			$('#' + block).slideToggle();
		});
	}
}

function commentForm() {

	var form = $('#newComment');
	var preview = 0;
	
	$('#submitComment').click(function() 	{ preview = 0; });
	$('#previewComment').click(function() 	{ preview = 1; });
	
	form.autoResize({
    	animateDuration : 300
	});
	
	form.submit(function(e) {
		e.preventDefault();
		var err = false;
		$('#newComment .mandatoryField').each(function() {
			if($(this).val() == '' && !err) {
				$(this).focus();
				$('#' + $(this).attr('id') + 'Error').fadeIn();
				$(this).keypress(function() {
					$('#' + $(this).attr('id') + 'Error').fadeOut();
				});
				err = true;
			}
		});
		
		if(!err) { 
			
			$.ajax({
   				type: "POST",
   				url: form.attr('action'),
   				data: form.serialize() + '&remote=yes&preview=' + preview,
   				success: function(msg){
     				$('#commentsListing').html(msg);
     				$('#submitComment').val('Оставить сообщение');
     				$('#articleCommentsNum').text((msg.split('<li').length - 1));
					$('#submitComment').removeClass('sending');
					if(!preview) $('#formMessage').val('');
					$('#submitComment').attr('disabled', '');
					$('#previewComment').attr('disabled', '');
					
					deleteComments();
   				}
 			});
 			
			$('#submitComment').val('Идет отправка комментария, ждемс...');
			$('#submitComment').addClass('sending');
			$('#submitComment').attr('disabled', 'disabled');
			$('#previewComment').attr('disabled', 'disabled');
		}
		
		return false;
	});
}

function newQuestion() {
	var form = $('#newQuestion');
	var err = false;
	var preview = 0;
	
	$('#submitComment').click(function() 	{ preview = 0; });
	$('#previewComment').click(function() 	{ preview = 1; });
	
	form.submit(function(e) {
		e.preventDefault();
		
		$('#newQuestion .mandatoryField').each(function() {
			if($(this).val() == '' && !err) {
				$(this).focus();
				$('#' + $(this).attr('id') + 'Error').fadeIn();
				$(this).keypress(function() {
					$('#' + $(this).attr('id') + 'Error').fadeOut();
					err = false;
				});
				$(this).change(function() {
					$('#' + $(this).attr('id') + 'Error').fadeOut();
					err = false;
				});
				err = true;
			}
		});
		
		if(!err) {
			$.ajax({
   				type: "POST",
   				url: form.attr('action'),
   				data: form.serialize() + '&remote=yes&preview=' + preview,
   				success: function(msg){
   					if(preview) {
   						$('#preview').html(msg);
   						$('#previewWrapper').slideDown();
   					} else {
   						$('#preview').html('<div class="messageOk"><h6>Все круто!</h6><p>Ваш вопрос ушел на модерацию. Как только он вернется, то сразу появится <a href="../">в списке вопросов</a>.</p><p>Спасибо.</p></div>');
   						$('#previewWrapper').show();
   						$('#newQuestion').hide();
   					}
   					  			
					$('#submitComment').val('Отправить вопрос');
					$('#submitComment').attr('disabled', '');
					$('#previewComment').attr('disabled', '');
   				}
 			});
 			
			$('#submitComment').val('Идет отправка вопроса, ждемс...');
			$('#submitComment').attr('disabled', 'disabled');
			$('#previewComment').attr('disabled', 'disabled');
		}
		
		return false;
	});
}

function highlightCode() {
	var codes = $('code');
	codes.each(function() {
		if($(this).parent().get(0).tagName != 'PRE') $(this).wrap('<pre></pre>');
	});
}

function toggleQuestions() {
	$('#questionList .description').each(function () {
			
		if(parseInt($(this).css('height')) >= parseInt($($(this).find('.fullDescription')[0]).css('height'))) {
			$(this).addClass('tooSmall');
		} else {				
	
			$(this).data('height', $(this).css('height'));
			$(this).attr('title', 'Показать суть вопроса');
			$(this).css('cursor', 'pointer');
		
			$(this).click(function() {
				var h;
				var obj = $($(this).find('.fullDescription')[0]);
				var obj1 = $($(this).find('.fadeOut')[0]);
				
				if(obj1.is(':visible')) { 
					h = obj.css('height');
					obj1.fadeOut();
					var title = 'Скрыть';
				} else {
					h = obj.parent().data('height');
					obj1.fadeIn();
					var title = 'Показать суть вопроса';
				}
				obj.parent().animate({ 
        			height: h
      			}, 300);	
				$(this).attr('title', title);		
			});
		}
	});
}

function questionsActions() {
	$('#questionList .actions .delete').each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			if(confirm('Точно-точно удалить?')) {
				$('#question' + e.target.href.split('=')[3]).slideUp('fast');
				$.get(e.target.href);
			}
		});
	});
	
	$('#questionList .actions .approve').each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			$(e.target).fadeOut();
			$.get(e.target.href);
		});
	});
}

function qaCategoryToggler() {
	//questionCategoryToggler
	var toggler = $('#dropDownCategoriesToggler');
	var list = $('#questionCategoryToggler');
	list.css({
		'top': (toggler.offset().top + toggler.height() + 14),
		'left': (toggler.offset().left - list.width() + toggler.width() + 2)
	});
	
	toggler.click(function(e) {
		list.fadeIn();
		e.stopPropagation();
		$(document).click(function() {
			list.fadeOut();
		});
	});
}

var dir, 
	finish, 
	total = parseInt($('#totalPrice').text()), 
	speed = 500, 
	flag = true, 
	multilier = $('#reviewForm select option:selected').val();

function slowRecount() {
	var start = parseInt($('#totalPrice').text());
	flag = false;
	
	if(start != finish && !flag) {
		if(dir) total += speed;
		else total -= speed;	
		$('#totalPrice').text(total);
		setTimeout('slowRecount()', 1);	
	} else {
		flag = true;	
		$('#totalPriceInput').val(total);
	}
}

function defaultPrices() {
	$('#reviewForm .formRadioElements.reviewThis span.price').each(function() {
		$(this).data('defPrice', parseInt($(this).text()));
	});
	
	$('#reviewForm select').change(function() {
		multilier = $(this).val();
		rebuildPrices();
		rebuildTotalPrices();
	});
}

function rebuildPrices() {
	$('#reviewForm .formRadioElements.reviewThis span.price').each(function() {
		$(this).text($(this).data('defPrice') * multilier + ' р.');
	});
}

function rebuildTotalPrices() {
	var t = 0;
	$('#reviewForm .formRadioElements.reviewThis input:checked').each(function() {
		t += parseInt($(this).parent().prevAll(':first').text());
	});
	finish = t;
	dir = finish > total ? true : false;
	slowRecount();
}

function bookReview() {
	var err = false;
	if($('#reviewForm')) {
		$('#reviewForm .formRadioElements.reviewThis input').each(function() {
			$(this).click(function(e) {
				dir = $(e.target).attr('checked') ? true : false, 
				finish;
				var thisPrice = $(e.target).parent().prevAll(':first');
					
				if(dir) {
					finish = total + parseInt(thisPrice.text());
					thisPrice.animate({backgroundColor: '#fdecc6'}, 250);
				} else {
					finish = total - parseInt(thisPrice.text());
					thisPrice.animate({backgroundColor: '#FFFFFF'}, 10);
				}
				
				if(flag) slowRecount();
			});
		});	
		
		$('#reviewForm').submit(function(e) {	
			e.preventDefault();
			
			$('#reviewForm .mandatoryField').each(function() {
				if(($(this).val() == '' || $(this).val() == 'http://') && !err) {
					$(this).focus();
					$('#' + $(this).attr('id') + 'Error').fadeIn();
					$(this).keypress(function() {
						$('#' + $(this).attr('id') + 'Error').fadeOut();
						err = false;
					});
					$(this).change(function() {
						$('#' + $(this).attr('id') + 'Error').fadeOut();
						err = false;
					});
					err = true;
				}
			});		
			
		
			if(!err) {
				$('#reviewForm fieldset:first').slideUp();
				$('#reviewSendConfirm').slideDown();
				
				$.ajax({
   					type: "POST",
   					url: '/send_review_form.php',
   					data: $('#reviewForm').serialize() + '&remote=yes'
				});
			}
		
			return false;
		});
	}
}


//////////////////////////////

//$(document).ready(function(e) {
	

	slideBlocks('extraFieldsBtn', 'extraFields');
	slideBlocks('tagsHelp', 'tagsHelpBlock');
	
	// Voting
	votingControls();
	
	// Comment form submit
	if($('#newComment')) commentForm();
	
	// Comments deleting
	deleteComments();
	
	// RSS Drop Down List
	rssDropDown();
	
	// Highlight Code
	highlightCode();
	
	// New question form
	if($('#newQuestion')) newQuestion();
	
	// Questions staff
	toggleQuestions();
	questionsActions();
	qaCategoryToggler();
	
	slideBlocks('toggleAltSubs', 'alternateSubscriptions');
	
	// Review form
	bookReview(); 
	defaultPrices(); 
	rebuildPrices();
	
//});
