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

	slideBlocks('extraFieldsBtn', 'extraFields');
	slideBlocks('tagsHelp', 'tagsHelpBlock');
	
	// Voting
	votingControls();
	
	// Comment form submit
	if($('#newComment')) commentForm();
	
	// Comments deleting
	deleteComments();
	
	// Main Menu Drop Down List
	newMainMenu();
	
	// Highlight Code
	highlightCode();
	
	// New question form
	if($('#newQuestion')) newQuestion();
	
	// Questions staff
	toggleQuestions();
	questionsActions();
	qaCategoryToggler();
	
	slideBlocks('toggleAltSubs', 'alternateSubscriptions');
	
	// Review form
	bookReview(); 
	defaultPrices(); 
	rebuildPrices();
	
	// Search field
	$('#searchField').inputDefualts({
		cl: 'inactive',
		text: 'Поиск по сайту'
	});
	
	// Lazy load
	$('img.bordered, img.prevImg').lazyload({
		effect : 'fadeIn'
	});
});

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

(function($) {
	$.fn.inputDefualts = function(options) {
		// дефолтные значения
		var defaults = {
 			cl: 'inactive', // имя класса для неактивного состояния
 			text: this.val()   // значение берется из самого инпута
  		}, 	opts = $.extend(defaults, options);	
  		
  		this.addClass(opts['cl']); 	// добавляем класс к инпуту
  		this.val(opts['text']);			// ставим значение по умолчанию
  		
  		// обрабатываем события фокуса на поле
  		this.focus(function() {
  			if($(this).val() == opts['text']) $(this).val(''); // обнуляем его, если надо
  			$(this).removeClass(opts['cl']); // убираем класс
  		});
  		
  		// теперь очередь блюра
  		this.blur(function() {
  			if($(this).val() == '') {
  				$(this).val(opts['text']); 			// возвращаем значение
  				$(this).addClass(opts['cl']); 	// и класс, если надо
  			}
  		});
	};
	
})(jQuery);

function randomXToY(minVal,maxVal,floatVal) {
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

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($('#articleCommentsNum').text());
	deleteBtns.each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			if(confirm('Ты точно хочешь удалить этот коммент?')) {
				$('#articleCommentsNum').text((parseInt($('#articleCommentsNum').text()) - 1));
				$(this).parent().parent().parent().addClass('noDisplay');
				$.get($(this).attr('href'));
			}
		});
	});
}

function newMainMenu() {
	var menuItems = $('#newMainMenu .dropDownArrow');
	
	menuItems.each(function() {
		$(this).click(function(e) {
			menuItems.parent().css({
				'z-index': '1'
			});
			e.preventDefault();
			var drop = $('#' + $(e.target).parent().attr('href').split('#')[1] + 'List');
			drop.css({
				'left': $(e.target).parent().parent().offset().left + 'px'
			});
			$(e.target).parent().parent().css({
				'z-index': '1000',
				'position': 'relative'
			});
			$(e.target).parent().parent().find('div').css('visibility', 'hidden');
			
			drop.fadeIn();
			$(e.target).parent().focus();
			
			$(e.target).parent().blur(function() {
				$(this).delay(100, function() {
					$('.menuDropDown:visible').hide();
					$(e.target).parent().parent().find('div').css('visibility', 'visible');
				});
			});
		});
	});
}

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);	
		return;
	} else {
		flag = true;	
		$('#totalPriceInput').val(total);
		//alert('finish');
	}
}

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).change(function(e) {
				dir = $(e.target).attr('checked') ? true : false;
				finish = 0;
				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);
				}
				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;
		});
	}
}

function mainPageArticlesToggler(links) {
	var artCont = $('#latestArticles');
	var tmp;
	var clicked = false;
	
	links.each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			if(!clicked) {
			links.parent().parent().removeClass('current');
			$(e.target).parent().parent().addClass('current');
			tmp = $(e.target);
			
			$.ajax({
   				type: 		"GET",
   				url: 		$(e.target).attr('href'),
   				data: 		'intro=only',
   				beforeSend:	function() {
   					artCont.css({
   						'height': artCont.css('height'),
   						'overflow': 'hidden'
   					});
   					$(e.target).hide();
   					$(e.target).next().hide();
   					$(e.target).next().next().html('Загрузка...').show();
   					clicked = true;
   				},
   				success:	function(msg) {
   					artCont.html(msg);
   					artCont.animate({'height': $('#articlePreviewWrapper').css('height')});
   					tmp.show();
   					tmp.next().show();
   					tmp.next().next().hide();
   					clicked = false;
   					votingControls();
   				}
			});
			}
		});
	});
}

function latestEventsToggler(links) {
	var prev = links[0];
	links.each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			links.parent().removeClass('current');
			$(e.target).parent().addClass('current');
			$('.latestEventsWrapper:visible').slideUp();
			$('#latestEvents_' + $(e.target).attr('href').split('#')[1]).slideDown();
		});
	});
}