$(document).ready(function() {
	$(".expand").click(function() {
		$(this).toggleClass("active");
		$(this).next(".pane").slideToggle();
		return false;
	});

  	$(".popup-open").click(function() {
		var form = $(this).attr("rel");
		$("."+form).show();
		$(".overlay").css("height", $(document).height()+"px");
		$(".overlay").fadeIn();
		return false;
	});

	$(".overlay").click(function() {
		$(this).fadeOut();
		$(".form-sent .success").hide();
		$(".form-sent .loader").show();
		$(".form-sent").hide();
		$(".popup-form").hide();
	});

	$(".popup-form").click(function(e) {
		e.stopPropagation();
	});

	$(".popup-form .send").click(function() {
		var form = $(this).closest(".popup-form");
		var fields = [];
		form.find("input, select, textarea").each(function() {
			var field = {};
			field.name = $(this).attr("class").split(" ")[0];
			if (field.name == "send-sms")
				field.value = $(this).attr("checked") ? "yes" : "no";
			else
				field.value = $(this).val();
			if ($(this).hasClass("required")) {
				field.required = true;
				var rel = $(this).attr("rel");
				if (rel)
					field.req_group = rel;
			}
			fields.push(field);
		});
		form.find(".error").hide();
		var errors = [];
		var groups = {};
		for (i in fields) {
			if (fields[i].required) {
				if (fields[i].req_group) {
					var g = fields[i].req_group;
					if (groups[g] === undefined)
						groups[g] = false;
					groups[g] |= (fields[i].value.length > 0);
				} else {
					if (fields[i].value.length == 0)
						errors.push("error-"+fields[i].name);
				}
			}
		}
		for (g in groups)
			if (!groups[g])
				errors.push("error-"+g);
		if (errors.length > 0) {
			for (i in errors)
				form.find("."+errors[i]).show();
		} else {
			var data = {};
			for (i in fields)
				data[fields[i].name] = fields[i].value;
			form.hide();
			form.find("input, textarea").val("");
			form.find("select option:selected").attr("selected", "");
			form.find(".error").hide();
			$(".form-sent").show();
			$(window).scrollTop(0);
			$(".form-sent").css("margin-top", "px");
			$.post("/sender.php", data, function() {
				$(".form-sent .loader").hide();
				$(".form-sent .success")
					.html(form.find(".success").html())
					.show();
				setTimeout(function() {
					$(".overlay").click();
				}, 5000);
			});
		}
		return false;
	});

	$(".reviews-page form").submit(function() {
		if (!($(this).find("[name=author_nick]").val().length > 0)) {
			alert("Пожалуйста, введите ваше имя.");
			return false;
		}
		if (!($(this).find("[name=author_email]").val().length > 0)) {
			alert("Пожалуйста, введите ваш e-mail.");
			return false;
		}
		if (!($(this).find("[name=comment]").val().length > 0)) {
			alert("Вы не ввели текст отзыва.");
			return false;
		}
		return true;
	});
});
