	$(document).ready(function() {
		$("form:not(.no-ajax)").live("submit", function() {
			$(this).find(".hint:input").val("");
			$(this).ajaxSubmit({
				context: this,
				dataType: "json",
				beforeSubmit: request,
				success: response,
				error: error_response
			});
			return false;
		});
		action("remove", "Удалить?");
		action("clear", "Очистить?");
		action("resend", "Переслать письма активации?");
		$("a.submit").live("click", function() {
			if (!$(this).hasClass("disabled")) {
				$(this).closest("form").submit();
			}
			return false;
		});
		$(".now").change(function() {
			var date_end = $(this).closest("table").find(".period .date:eq(1)");
			if ($(this).attr("checked")) {
				date_end.hide();
			} else {
				date_end.show();
			}
		}).change();
		$("a.remove").live('click', function() {
			$(this).parent().remove();
			return false;
		});
		$("a.delete").live('click', function() {
			var id = $(this).attr("title");
			$(this).closest("form").append('<input type="hidden" name="' + $(this).attr("href").substr(1) + '[delete][' + id + ']" value="' + id + '" />');
			$(this).parent().remove();
			return false;
		});
		$("a.multiple").live('click', function() {
			var index = parseInt($(this).attr("title")) + 1;
			var item = $(this).parent().siblings("div.template").clone(true);
			item.find(":input").each(function() {
				$(this).attr("name", $(this).attr("name").replace("_template", "[" + index + "]"));
			});
			item.attr("title", index).removeClass("template").addClass("item");
			$(this).attr("title", index).parent().before(item);
			return false;
		});
		$(".date > select").change(function() {
			var date = {"day": 1};
			$(this).parent().find("select").each(function() {
				date[$(this).attr("title")] = $(this).val();
			});
			$(this).siblings("input").val(date["year"] + "-" + date["month"] + "-" + date["day"]);
		});
		$("div.captcha > a").live('click', function() {
			var img = $(this).find("img");
			img.attr("src", "/captcha.php?field=" + img.attr("alt") + "&rnd=" + Math.random());
			return false;
		});
		$("button.attach-image").click(function() {
			$(this).prev().appendTo($("form.image"));
			$("form.image").submit();
		});
		$(".vacancy-section").change(function() {
			var text = $(this).find("option:selected").text();
			$(".cv-section").val($(".cv-section option:contains(" + text + ")").val());
		});
		$(".sortable").sortable({
			"axis": "y",
			"cursor": "move",
			"scroll": false,
			"update": function (event, ui) {
				var form = $("." + $(this).attr("rel"));
				var p = $(this).sortable("toArray");
				for (var i in p) {
					var name = "position[" + p[i] + "]";
					var input = $("input[name='" + name + "']");
					if (input.length > 0) {
						input.val(i);
					} else {
						form.append('<input type="hidden" name="' + name + '" value="' + i + '" />');
					}
				}
			}
		});
	});

	// меняет обработчик формы
	function action(type, question) {
		$("button." + type).click(function() {
			if (confirm(question)) {
				var form = $(this).closest("form");
				var action = form.attr("action");
				form.attr("action", action.replace(/[a-z]+$/i, type));
				form.submit();
				form.attr("action", action);
			}
			return false;
		});
	}

	// включение и отключение кнопок формы
	function button(form, action) {
		if (action == "on") {
			form.find("button").removeAttr("disabled");
			form.find("a.stylish").removeClass("disabled");
		} else {
			form.find("button").attr("disabled", "disabled")
			form.find("a.stylish").addClass("disabled");
		}
	}

	// перед тем как отправить запрос на сервер
	function request(data, form, options) {
		button(form, "off");
		form.find(".submit-form").show();
		form.find(".response").html("").hide();
		return true;
	}

	// обрабатываем ответ сервера
	function response(data, status, xhr, form) {
		form.find(".submit-form").hide();
		form.find(".response").html("<div class=\"" + data.status + "\">" + data.message + "</div>").slideDown(500);
		if (data.status == "ok") {
			// скрываем форму
			form.find(".form").slideUp(500);
			// перенаправляем пользователя
			setTimeout(function() {
				if (data.redirect) {
					location.replace(data.redirect);
				} else {
					location.reload();
				}
			}, 1500);
		} else {
			button(form, "on");
		}
	}

	// обрабатываем ошибки
	function error_response(XMLHttpRequest, textStatus, errorThrown) {
		if (errorThrown == undefined) {
			errorThrown = "Сервис временно недоступен";
		}
		response({ "status": "error", "message": errorThrown }, textStatus, XMLHttpRequest, $(this));
	}

	function fieldset(item) {
		$(item).closest("fieldset").toggleClass("hidden");
		return false;
	}

	function generate_password(element) {
		var passwd = random_password(8);
		$(element).closest("table").find("[name='passwd'],[name='passwd_v']").val(passwd);
		$("#generated").text(passwd);
	}

	// генерирует случайный пароль
	function random_password(length) {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // допустимые символы
		var passwd = "";
		var index;
		for (var i = 1; i <= length; i++) {
			index = Math.floor(Math.random() * chars.length);
			passwd += chars.charAt(index);
		}
		return passwd;
	}

	function format_float(element) {
		$(element).val($(element).val().replace(",", "."));
	}
