function commentReply(postId, commentId)
{
	if (!commentId)
	{
		commentId = 0;
		mark = postId;
	}
	else
	{
		mark = commentId;
	}

	var str = '';
	var divs = document.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++)
	{
		if (divs[i].id == 'quickReply_' + mark)
		{
			divs[i].innerHTML =	'<form method="post" action="addComment.php">';
			divs[i].innerHTML += '<textarea rows="5" name="text" style="width: 450px;"></textarea><br />';
			divs[i].innerHTML += '<input type="hidden" value="' + postId + '" name="post_id" />';
			divs[i].innerHTML += '<input type="hidden" value="' + commentId + '" name="comment_parent_id" />';
			divs[i].innerHTML += '<input type="submit" value="тык" />';
			divs[i].innerHTML += '</form>';

			divs[i].style.display = 'block';
		}
		else if (divs[i].id.indexOf('quickReply') != -1)
		{
			divs[i].innerHTML = '';
			divs[i].style.display = 'none';
		}
	}
}

function PressedButton(number) {
	for (var i = 1; i <= 3; i++)
	{
		if (i == number)
		{

			$('#oprosMenuButton_' + i).addClass('menuActive');
			$('#oprosMenuButton_' + i).removeClass('menuPassive');
			$('#menuArr_' + i).css("display", "inline");
		}
		else
		{
			$('#menuArr_' + i).css("display", "none");
			$('#oprosMenuButton_' + i).addClass('menuPassive');
			$('#oprosMenuButton_' + i).removeClass('menuActive');
		}
	}
}

function PressedPageButton(number) {
	for (var i = 1; i <= 2; i++)
	{
		if (i == number)
		{
			$('#pageMenuButton_' + i).addClass('pageMenuActive');
			$('#pageMenuButton_' + i).removeClass('pageMenuPassive');
		}
		else
		{
			$('#pageMenuButton_' + i).addClass('pageMenuPassive');
			$('#pageMenuButton_' + i).removeClass('pageMenuActive');
		}
	}
}

var varNum = new Array();
function addVariant(questionId, count)
{
	if (varNum[questionId])
	{
		varNum[questionId]++;
	}
	else if (count)
	{
		varNum[questionId] = count + 1;
	}
	else
	{
		varNum[questionId] = 3;
	}

	var div = document.getElementById('pollVariant_' + questionId);
	var newDiv = document.createElement("div");
	div.appendChild(newDiv);

	newDiv.id = 'poll_variant_' + questionId + '_' + varNum[questionId];

	newDiv.innerHTML = '';
	newDiv.innerHTML += varNum[questionId] + '.&nbsp;'
	newDiv.innerHTML += '<input type="text" name="poll_answer[' + questionId + '][' + varNum[questionId] + '][text]" value="" style="width: 60%;" maxlength="128" />';
	newDiv.innerHTML += '<br />';
	return false;
}

function dropVariant(questionId, count)
{
	if (count && !varNum[questionId])
	{
		varNum[questionId] = count;
	}
	
	var els = document.getElementsByTagName('div');
	for (var i = 0; i < els.length; i++)
	{
		if (els[i].id == 'poll_variant_' + questionId + '_' + varNum[questionId])
		{
			els[i].innerHTML = '';
			els[i].style.display = 'none';
			els[i].id = null;
		}
	}
	if (varNum[questionId] && varNum[questionId] > 2) { varNum[questionId]--; }
	return false;
}

var checkCount = 1;
function dropQuestion(questionNumberDrop)
{
	checkCount = 0;
	varNum[questionNumberDrop] = 2;
	var div = document.getElementById('question_' + questionNumberDrop);
	if (div)
	{
		div.id = null;
		div.innerHTML = '';
		div.style.display = 'none';
	}
	if (questionNumber > 1) { questionNumber--; }

	var drop = document.getElementById('dropQuestion_' + questionNumber);
	if (drop) { drop.style.display = 'block'; }

	return false;
}

var questionNumber = 1;
function addQuestion(count)
{
	if (count && questionNumber == 1 && checkCount)
	{
		checkCount = 0;
		questionNumber = count;
	}
	
	var drop = document.getElementById('dropQuestion_' + questionNumber);
	if (drop) {
		drop.style.display = 'none';
	}

	questionNumber++;
	var div = document.getElementById('questionsBlock');
	var newDiv = document.createElement("fieldset");
	div.appendChild(newDiv);

	newDiv.id = 'question_' + questionNumber;
	newDiv.title = 'Вопрос ' + questionNumber;

	newDiv.innerHTML = '';
	newDiv.innerHTML += '<div class="question_caption3" style="width: 50%; float: left;">Вопрос ' + questionNumber + '</div>';
	newDiv.innerHTML += '<div id="dropQuestion_' + questionNumber + '" style="width: 40%; float: right;"><a href="#question_' + (questionNumber - 1) + '" onclick="dropQuestion(' + questionNumber + '); return false;">удалить вопрос</a></div>';
	newDiv.innerHTML += '<a name="question_"' + questionNumber + ' class="anchor"></a>';
	newDiv.innerHTML += '<input type="text" name="poll_question[' + questionNumber + '][text]" value="Название вопроса ' + questionNumber + '" style="width: 60%;"/>';
	newDiv.innerHTML += '<fieldset title="Варианты ответа на вопрос ' + questionNumber + '" style="margin-left: 50px;">';
	newDiv.innerHTML += '<label>Варианты ответов:</label>';
	newDiv.innerHTML += '<input type="radio" name="poll_question[' + questionNumber + '][type]" id="poll_answer_q_' + questionNumber + '_c" checked onclick="this.form.poll_answer_q_' + questionNumber + '_r.checked=0" value="radio"/> - можно выбрать один ответ';
	newDiv.innerHTML += '<input type="checkbox" name="poll_question[' + questionNumber + '][type] id="poll_answer_q_' + questionNumber + '_r" onclick="if (this.form.poll_answer_q_' + questionNumber + '_c.checked == 0) this.form.poll_answer_q_' + questionNumber + '_c.checked=1; else this.form.poll_answer_q_' + questionNumber + '_c.checked = 0;"/ value="checkbox"> - несколько ответов';
	newDiv.innerHTML += '<br />';
	newDiv.innerHTML += '<div id="pollVariant_' + questionNumber + '">';
	newDiv.innerHTML += '<label>1.&nbsp;</label><input type="text" value="Вариант ответа 1" name="poll_answer[' + questionNumber + '][1][text]" style="width: 60%"/><br />';
	newDiv.innerHTML += '<label>2.&nbsp;</label><input type="text" value="Вариант ответа 2" name="poll_answer[' + questionNumber + '][2][text]" style="width: 60%" />';
	newDiv.innerHTML += '</div>';
	newDiv.innerHTML += '<p style="width: 40%; float: left;"><a href="#" onclick="addVariant(' + questionNumber + '); return false;">добавить ещё<a></p>';
	newDiv.innerHTML += '<p style="width: 50%; float: right;"><a href="#" onclick="dropVariant(' + questionNumber + '); return false;">удалить лишний</a></p>';
	newDiv.innerHTML += '</fieldset>';
	newDiv.innerHTML += '</fieldset>';

	var prevDiv = document.getElementById('question_' + (questionNumber - 1));
	prevDiv

	return false;
}

function setRating(pollId, plus, minus)
{
	$("div[title='rating" + pollId + "']").load('updateRating.php', {
		'pollId': pollId,
		'plus': plus,
		'minus' : minus
	},
	function (responseText, textStatus, XMLHttpRequest) {
		if (responseText >= 0 || responseText == ':(') {
			$(this).css('color', '#ff9832');
		} else {
			$(this).css('color', '#5c5e7b');
		}
	}
	);
	return false;
}

function setClickable() {
	$('#editInPlace').click(function() {
		var textarea = '<div><textarea class="editable" rows="10" cols="60">'+$(this).html()+'</textarea>';
		var button	 = '<div><input type="button" value="Сохранить" class="saveButton" />&nbsp;<input type="button" value="Отмена" class="cancelButton" /></div></div>';
		var revert = $(this).html();
		$(this).after(textarea + button).remove();
		$('.saveButton').click(function(){saveChanges(this, false);});
		$('.cancelButton').click(function(){saveChanges(this, revert);});
	})
	.mouseover(function() {
		$(this).addClass("editable");
	})
	.mouseout(function() {
		$(this).removeClass("editable");
	});
}

function saveChanges(obj, cancel) {
	if(!cancel) {
		var t = $(obj).parent().siblings(0).val();
		$.post("updateNews.php",{
			content: t
		});
	}
	else {
		var t = cancel;
	}
	if(t == '') t = '(click to add text)';
	$(obj).parent().parent().after('<div id="editInPlace">' + t + '</div>').remove();
	setClickable();
}

$(document).ready(function() {
	setClickable();

	$("a#registerCreate").fancybox({
		'frameWidth': 650,
		'frameHeight': 530,
		'hideOnContentClick': false
	});
	
	$("a#registerMain").fancybox({
		'frameWidth': 650,
		'frameHeight': 530,
		'hideOnContentClick': false
	});
	
	$("a#registerCreate2").fancybox({
		'frameWidth': 650,
		'frameHeight': 530,
		'hideOnContentClick': false
	});
	
	$("a#registerCreate3").fancybox({
		'frameWidth': 650,
		'frameHeight': 530,
		'hideOnContentClick': false
	});
	
	$("a#profile").fancybox({
		'frameWidth': 650,
		'frameHeight': 575,
		'hideOnContentClick': false
	});
	
	$("a#login").fancybox({
		'frameWidth': 650,
		'frameHeight': 380,
		'hideOnContentClick': false
	});
	
	$("a#login2").fancybox({
		'frameWidth': 650,
		'frameHeight': 380,
		'hideOnContentClick': false
	});
	
	$("input[name='poll_topic']").focus(function(){
		var text = $(this).attr('value');
		if (text == 'Название опроса')
		{
			$(this).attr('value', '');
		}
	}).blur(function(){
		var text = $(this).attr('value');
		if (text == '')
		{
			$(this).attr('value', 'Название опроса');
		}
	});
	
	$("input[name='poll_tags']").focus(function(){
		var text = $(this).attr('value');
		if (text == 'Перечислите тэги через запятую')
		{
			$(this).attr('value', '');
		}
	}).blur(function(){
		var text = $(this).attr('value');
		if (text == '')
		{
			$(this).attr('value', 'Перечислите тэги через запятую');
		}
	});
	
	$('.deleteComment').click(function(){
		var commentId = $(this).attr('rel');
		$.post("deleteComment.php", {
			commentId: commentId },
			function(data, textStatus){
				if (textStatus == 'success')
				{
					if (data == '1')
					{
						$("#commentDiv_" + commentId).css('display', 'none');
						$("#commentDiv_" + commentId).remove();
					}
				}
			});
	});
	
     $('.commentBox[rel="editable"]').editable('updateComment.php', { 
         type      : 'textarea',
         cancel    : 'Отмена',
         submit    : 'Отредактровать',
         indicator : '<img src="img/small_preloader.gif" alt="" />',
         tooltip   : 'Редактировать комментарий',
         name: 'commentText',
         id: 'commentId',
         style: 'background-color: #fff'
     });
	
	$("#search").focus(function(){
		var text = $(this).attr('value');
		if (text == 'поиск')
		{
			$(this).attr('value', '');
		}
	}).blur(function(){
		var text = $(this).attr('value');
		if (text == '')
		{
			$(this).attr('value', 'поиск');
		}
	});

	$("div.comments").click(function(){
		window.location = '/?p=poll&postId=' + $(this).attr("title");
		return false;
	});

	$("div.resultButton").click(function(){
		window.location = '/?p=poll&postId=' + $(this).attr("title") + '&focus=result';
		return false;
	});

	$('#pollProcessButton').click(function()
	{
		/*
		$.ajax({
		type: "POST",
		url: "processVote.php",
		data: $("#pollForm").formSerialize(),
		success: function(data){
			$('#first').html(data);
		}
		});
		*/
		
		$("#pollForm").submit();
	});

	if ($.cookie('pollBlockArrow') == 'closed')
	{
		$(".tabs").css('display', 'none');
		$("#pollBlockArrow img").attr('src', 'img/arrow_active.gif');
	}
	else
	{
		$(".tabs").css('display', 'block');
		$("#pollBlockArrow img").attr('src', 'img/arrow.gif');
	}
	
	$('#pollBlockArrow').click(function() {
		if ($(".tabs").is(":hidden")) {
			$(".tabs").slideDown();
			$.cookie('pollBlockArrow', 'opened');
			$("#pollBlockArrow img").attr('src', 'img/arrow.gif');
		} else {
			$(".tabs").slideUp();
			$("#pollBlockArrow img").attr('src', 'img/arrow_active.gif');
			$.cookie('pollBlockArrow', 'closed');
		}
	});

	if ($.cookie('newsBlockArrow') == 'closed')
	{
		$(".tabs2").css('display', 'none');
		$("#newsBlockArrow img").attr('src', 'img/arrow_active.gif');
	}
	else
	{
		$(".tabs2").css('display', 'block');
		$("#newsBlockArrow img").attr('src', 'img/arrow.gif');
	}
	
	$('#newsBlockArrow').click(function() {
		if ($(".tabs2").is(":hidden")) {
			$(".tabs2").slideDown();
			$.cookie('newsBlockArrow', 'opened');
			$("#newsBlockArrow img").attr('src', 'img/arrow.gif');
		} else {
			$(".tabs2").slideUp();
			$("#newsBlockArrow img").attr('src', 'img/arrow_active.gif');
			$.cookie('newsBlockArrow', 'closed');
		}
	});

	$("#emailForm").livequery(function() {
		$(this).validate({
			errorElement: "em",
			errorContainer: $("#warning"),
			success: function(label) {
				label.addClass("success");
			},
			rules: {
				eemail: {
					required: true,
					email: true
				}
			}
		})
	});

	// готовим объект
	var options = {
	  target: "#divToUpdate",
	  url: "form.php",
	  success: function() {
	        alert("Спасибо за комментарий!");
	  }
	}; 
	
	$("#registerForm").livequery(function() {
		$(this).ajaxForm({
			target: "#answerDiv",
			url: "register.php",
			beforeSubmit: function() {
				$("#answerDiv").html('<img src="img/small_preloader.gif" alt="" />');
			},
			success: function(responseText) {
				$("#answerDiv").css('visibility', 'visible');
				if (responseText == '1')
				{
					$("#answerDiv").css('visibility', 'hidden');
					window.location.reload();
				}
			}
		});
	});
	
	$("#loginForm").livequery(function() {
		$(this).ajaxForm({
			target: "#answerDiv",
			url: "login.php",
			beforeSubmit: function() {
				$("#answerDiv").html('<img src="img/small_preloader.gif" alt="" />');
			},
			success: function(responseText) {
				$("#answerDiv").css('visibility', 'visible');
				if (responseText == '1')
				{
					$("#answerDiv").css('visibility', 'hidden');
					window.location.reload();
				}
			}
		});
	});
	
	$("#profileForm").livequery(function() {
		$(this).ajaxForm({
			target: "#answerDiv",
			url: "updateProfile.php",
			beforeSubmit: function() {
				$("#answerDiv").html('<img src="img/small_preloader.gif" alt="" />');
			},
			success: function(responseText) {
				$("#answerDiv").css('visibility', 'visible');
				if (responseText == '1')
				{
					$("#answerDiv").css('visibility', 'hidden');
					window.location.reload();
				}
			}
		});
	});
	
	$("#profileForm").livequery(function() {
		$(this).ajaxForm({
			target: "#answerDiv",
			url: "updateProfile.php",
			beforeSubmit: function() {
				$("#answerDiv").html('<img src="img/small_preloader.gif" alt="" />');
			},
			success: function(responseText) {
				$("#answerDiv").css('visibility', 'visible');
				if (responseText == '1')
				{
					$("#answerDiv").css('visibility', 'hidden');
					window.location.reload();
				}
			}
		});
	});
	
	$("#chartForm").ajaxForm({
		target: "#answerDivChart",
		url: "addSong.php",
		beforeSubmit: function() {
			$("#answerDivChart").html('<img src="img/small_preloader.gif" alt="" />');
		}
	});
	
	$("#registerInLogin").livequery(function() {
		$(this).fancybox({
			'frameWidth': 650,
			'frameHeight': 520,
			'hideOnContentClick': false
		});
	});

	$("#pollForm").validate();

	$("input#button").click(function(){
		$("#button").slideToggle("slow");
		return false;
	});
	
	$("select#voblast").change(function(){
		$("select#vtown").attr('disabled', 'disabled');
		$.getJSON('/getCities.php', {oblastId: $(this).attr('value')}, function(data, textStatus) {
			if (textStatus == 'success')
			{
				var options = '';
				for (var i = 0; i < data.length; i++) {
					options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
				}
				$("select#vtown").attr('disabled', '');
				$("select#vtown").html(options);
				$('select#vtown option:first').attr('selected', 'selected');
			}
		})
	})
	
	$("select#roblast").livequery(function(){
		$(this).change(function(){
			$("select#rtown").attr('disabled', 'disabled');
			$.getJSON('/getCities.php', {oblastId: $(this).attr('value')}, function(data, textStatus) {
				if (textStatus == 'success')
				{
					var options = '';
					for (var i = 0; i < data.length; i++) {
						options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
					}
					$("select#rtown").attr('disabled', '');
					$("select#rtown").html(options);
					$('select#rtown option:first').attr('selected', 'selected');
				}
			})
		})
	})
	
	$("a.chartLink").click(function(){
		var chartNum = $(this).attr('rel');
		if ($("#chart_block_" + chartNum).is(":hidden")) {
			$('div.chart_block').slideUp();
			$("#chart_block_" + chartNum).slideDown();
		} else {
			$("#chart_block_" + chartNum).slideUp();
		}
	})
});