$(document).ready(function () {
	$(".info-block").infoBlock();
	var $offerDescription = $("#offer_description");
	$offerDescription.textAreaMaxLength(200);
	$offerDescription.on("input", function () {
		updateCharsCount(this);
	});

	$("#change-to-prd-choose, #change-to-custom-prd").click(function () {
		$("#customDodji, #activeDodji, .send-request__block-title, .info-block__text-inner, .offer-tip").toggleClass("hidden");
		if ($("#customDodji").hasClass("hidden")) {
			$("#offer-submited-type").val("prd");
		} else {
			$("#offer-submited-type").val("custom");
		}

		validateOffer();
	});

	$("#offer_prd_form").on("submit", function (e) {
		e.preventDefault();
		btnDisableToggle("on");

		var params = window
			.location
			.search
			.replace("?", "")
			.split("&")
			.reduce(
				function (p, e) {
					var a = e.split("=");
					p[ decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
					return p;
				},
				{}
			);

		var formDataSerialized = $(this).serialize();

		var addedParams = ["a","c","page"];

		for(var i in addedParams){
			if(params[addedParams[i]]){
				formDataSerialized += "&"+ addedParams[i] +"=" + params[addedParams[i]];
			}
		}

		$.post("/api?method=create_offer", formDataSerialized, function (response) {
			if (response.success === true) {
				location.href = response.redirect;
			} else {
				$(".new-offer-form-control__error").text(response.error);
				$("#request-prd-name, #request-prd-id").change(); //Перевалидация и включение кнопки
			}
		}, "json");
	});
});

function updateCharsCount(el) {
	var used = $(el).val().length;
	$(".wishdescused").html(used);
}

$(window).load(function () {
	updateCharsCount($("#offer_description"));
});