// небольшая хитрость, чтобы увести пользователя со страницы запроса файла
// иначе при перезагрузке и при переходе по страницам файл будет запрашиваться снова и снова
if (location.href.indexOf('fileMailer.file') != -1) {
	location.href = location.href.replace(/fileMailer\.file=\d+&?/, '').replace(/\?$/, '');
}

var wtbCityId = 0;
var tagId;

$(document).ready(function(){
	$("img").ifixpng();

	$("a.subscribe").click(function(){
		$(this).hide();
		$("#subscrform").show();
		return(false);
	});
	
	$("#subscrform .subscribeAll input").change(function(){
		if(!$(this).hasClass("checked")){
			$(this).parent().parent().find("label[title='" + $(this).parent().find("label").text() + "']").parent().find("input").attr("checked", "checked");
			$(this).addClass("checked");
	        return;
		}
		$(this).parent().parent().find("label[title='" + $(this).parent().find("label").text() + "']").parent().find("input").removeAttr("checked");
		$(this).removeClass('checked');
	});
	
	$("#subscrform form").submit(function() {
		if (!$("#subscrform form input:checked").length) {
			$("#subscrform .buttons p").remove();
			$("#subscrform .buttons").append("<p><strong>Не выбраны разделы для подписки</strong></p>");
			return false;
		}
	});
	
	/*catOrder*/
	if($("#catOrderForm").length != 0) {
		$.ajax({
			url: "140?widget=create",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				$("#catOrderForm").append(data.trimmedcontent);
				$(".order-field-wrapper textarea").val($("h1").text());
				$("#catOrderForm .form-submit").val("Отправить сообщение");
				/* Валидация
				------------------------------------------------------------------------------------------------------------------- */
				$('form .required input').addClass('required');
				$('form .required textarea').addClass('required');
				$('form .email-wrapper .required input').addClass('email');
				$('.tab').not('.local').find('input').removeClass('required');
				$('form').each(function() { $(this).validate() });
				/* ---------------------------------------------------------------------------------------------------------------- */
				captchaCkeck("/140");
			}
		});
	}
	/*/catOrder*/
	
	/*managerFeedback*/
	if($("#maganerFeedbackForm").length != 0) {
		$("#maganerFeedbackForm .name-field-wrapper input").val($("h1").text());
		/*
		$.ajax({
			url: "340?widget=create",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				$("#maganerFeedbackForm").append(data.trimmedcontent);
				$("#form-create-managerFeedback-wrapper .name-field-wrapper input").val($("h1").text());
				$("#maganerFeedbackForm .form-submit").val("Отправить сообщение");

				$('form .required input').addClass('required');
				$('form .required textarea').addClass('required');
				$('form .email-wrapper .required input').addClass('email');
				$('.tab').not('.local').find('input').removeClass('required');
				$('form').each(function() { $(this).validate() });

				captchaCkeck("/340");
			}
		});
		*/
	}
	/*/managerFeedback*/
	
	/*where_to_buy*/
	if(wtbCityId != 0) {
		$(".wtbForm select.wtbCity option").removeAttr("selected");
		$(".wtbForm select.wtbCity option[value='" + wtbCityId + "']").attr("selected", "selected");
		$.ajax({
			url: "340?widget=wtbOffices&widget=wtbOffices&wtbOffices.filter[office.wtbCity]=" + wtbCityId + "&wtbOffices.sort[wtbCompany]=desc",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				$(".wtbForm select.wtbCompany").replaceWith($(data.trimmedcontent).find("select.wtbCompany"));
			}
		});
	}
	else $(".wtbForm select.wtbCompany").attr("disabled", "disabled");
	/*
	$.ajax({
		url: "340?widget=wtbOffices&wtbOffices.sort[wtbCity]=asc",
		dataType: "json",
		success: function (data) {
			data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
			$(".wtbForm select.wtbCity").replaceWith($(data.trimmedcontent).find("select.wtbCity"));
			wtbCitySelect();
			wtbCompanySelect();
		}
	});

	$.ajax({
		url: "340?widget=wtbOffices&wtbOffices.sort[wtbCompany]=desc",
		dataType: "json",
		success: function (data) {
			data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
			$(".wtbForm select.wtbCompany").replaceWith($(data.trimmedcontent).find("select.wtbCompany"));
			wtbCitySelect();
		}
	});
	*/

	$(".wtbForm select.wtbCity").change(function() {
		var parent = $(this).find("option:selected");
		$.ajax({
			url: "340?widget=wtbOffices&widget=wtbOffices&wtbOffices.filter[office.wtbCity]=" + parent.val() + "&wtbOffices.sort[wtbCompany]=desc",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				$(".wtbForm select.wtbCompany").replaceWith($(data.trimmedcontent).find("select.wtbCompany"));
			}
		});
	});
	
	/*
	function wtbCompanySelect() {
		$(".wtbForm select.wtbCompany").change(function() {
			var parent = $(this).find("option:selected");
			$.ajax({
				url: "340?widget=wtbOffices&wtbOffices.filter[office.wtbCompany]=" + parent.val(),
				dataType: "json",
				success: function (data) {
					data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
					$(".wtbForm select.wtbCity").replaceWith($(data.trimmedcontent).find("select.wtbCity"));
				}
			});
		});
	}
	*/
	/*/where_to_buy*/
	
	if ($("#nav ul li a[href='1639']").parent().parent().hasClass("selected")) {
		$.ajax({
			url: "1639?widget=offices&offices.limit=0",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				$("#content .contact").prepend("<div class='form-create-wrapper'><form action='1639' method='get' class='wtbForm'><div class='control'><label><select id='citySelect' name=offices.filter[name]><option value=''>Все города</option></select></label></div><div class='control'><input type='submit' value='Найти' /></div></form></div>");
				$(data.trimmedcontent).find("h3 a").each(function() {
					if ($(this).text() != $("#citySelect option:last").val()) $("#citySelect").append("<option>" + $(this).text() + "</option>");
				});
			}
		});
	}
	
	$(".formlink a").click(function(){
		$(".form_wrapper").toggle();
		$(".crn_btm").toggleClass("crn_btm_def");
		return(false);
	});

	$("input[name='position']").val($(".node-vacancy h1").text());
	
	$(".top_login .form_logout").click(function(){
		$(this).parent().find("form").submit();
		return(false);
	});
	
	$("#content .form_logout").click(function(){
		$(this).parents("form").submit();
		return(false);
	});
	
	if($("#content .profile_info").length) {
		$.ajax({
			url: tagId + "?widget=profile&profile.action=edit",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				$("#content .profile_info").append(data.trimmedcontent);
				$("#profile-edit-form").attr("action", $("#profile-edit-form").attr("action").replace("%3Fprofile.action%3Dedit%26profile.status%3Dok", "%3Fmessage%3DПароль успешно изменён"));
				$("#profile-edit-form .password-field-wrapper:first span").html($("#profile-edit-form .password-field-wrapper:first span").html().replace("Пароль","Новый пароль"));
				$("#content .profile_info a.dynamic").click(function() {
					$("#profile-edit-form").toggle();
					return false;
				});
			}
		});
	}
	
	/*gallery*/
	$(".galleryPhotosSmall li a").click(function(){
		$(".galleryPhotoBig .img_box a").attr("href", $(this).attr("href") + "/" + $(this).attr("rel")).attr("title", $(this).attr("title"));
		$(".galleryPhotoBig .img_box a img").attr("src", $(this).attr("href") + ",330,330,d/" + $(this).attr("rel")).attr("title", $(this).attr("title"));
		$(".galleryPhotoBig .text_box").html("<p>" + $(this).attr("title") + "</p>");
		return(false);
	});
	/*/gallery*/
	
	$(".form-create-wrapper form .attachment-control .remote").remove();
	
	/*captcha_ajax_check*/
	function captchaCkeck(goTo) {
		if ($(".captcha-wrapper").length != 0) var formId = $(".captcha-wrapper").parent().attr("id");
		if (formId == "form-create-dealerReg") var goTo = "/143";
		if (formId == "form-create-dealerRegDASO") var goTo = "/344";

		$("form#" + formId).submit(function() {
			$(this).ajaxSubmit({
				type: 'post',
				/*
				url: $(this).attr("action"),
				data: $("form#" + formId).formSerialize(),
				*/
				dataType: 'json',
				success: function (data) {
					data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
					if ($(data.trimmedcontent).find("h1").html() == "Ошибка 400") {
						$(".captchablock label.error").remove();
						$(".captchablock").append("<label class='error'>Вы ввели неверный код. Попробуйте ещё раз.</label>")
					}
					else {
						window.location.href = goTo + "&pending=1";
					}
				},
				error: function(data) {
					data.trimmedcontent = data.responseText.toString().replace(new RegExp('\\r\\n', 'g'), '');
					if ($(data.trimmedcontent).find("h1").html() == "Ошибка 400") {
						$(".captchablock label.error").remove();
						$(".captchablock").append("<label class='error'>Вы ввели неверный код. Попробуйте ещё раз.</label>")
					}
					else {
						window.location.href = goTo + "&pending=1";
					}
				}
			});
			return(false);
		});
	}
	
	captchaCkeck(window.location.href);
	/*/captcha_ajax_check*/
	
	/*password_confirm_check*/
/*	$(".profile_register form").submit(function() {
		$.ajax({
			type: 'post',
			url: $(this).attr("action"),
			data: $(this).serialize(),
			dataType: 'json',
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				if ($(data.trimmedcontent).find("h1").html() == "Ошибка 400") {
					$(".form-password2").parent().find("label.error").remove();
					$(".form-password2").parent().append("<label class='error'>Подтверждение пароля не совпадает с паролем.</label>")
				}
				else {
					window.location.href = window.location.href + "&profile.status=wait";
				}
			}
		});
		return(false);
	});*/
	/*/password_confirm_check*/
		
	$(".searchform a").click(function(){
		$(".searchform form").submit();
		return(false);
	});
	
	$(".anonscat .anonstxt a").each(function() {
		var parent = $(this);
		$.ajax({
			url: parent.attr("href") + "?widget=doc",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				parent.attr("href", $(data.trimmedcontent).find("span.tag_id").attr("id") + "/" + $(data.trimmedcontent).find("span.tag_id").attr("title"));
				parent.parent().parent().find("a.catImage").attr("href", $(data.trimmedcontent).find("span.tag_id").attr("id") + "/" + $(data.trimmedcontent).find("span.tag_id").attr("title"));
			}
		});
	});
	
	$(".indexcat .anonstxt a").each(function() {
		var parent = $(this);
		$.ajax({
			url: parent.attr("href") + "?widget=doc",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				parent.attr("href", $(data.trimmedcontent).find("span.tag_id").attr("id") + "/" + $(data.trimmedcontent).find("span.tag_id").attr("title"));
				parent.parent().parent().find("a.catImage").attr("href", $(data.trimmedcontent).find("span.tag_id").attr("id") + "/" + $(data.trimmedcontent).find("span.tag_id").attr("title"));
			}
		});
	});
	
	$(".menu_sitemap a[href='340']").click(function() {
		$("ul", $(this).parent()).toggle();
		return(false);
	});
	
	/*docsDealerTypical*/
	$("#content .table_dealerTypical a.to_email").click(function() {
		if (confirm("Отправить файл на e-mail?")) {
			alert("Файл отправлен");
		}
		else {
			alert("Запрос отменён");
			return false;
		}
	});
	/*/docsDealerTypical*/
	
	/*zebra stripping*/
	$("#content table tr:nth-child(odd)").addClass("even");
	/*/zebra stripping*/
	
	/*fancybox*/
	$("a.fancybox").fancybox(); 
	/*/fancybox*/
});

$(function(){
	/* Валидация
	------------------------------------------------------------------------------------------------------------------- */
	/* дефолтные сообщения */
	$.validator.messages.required = "Это поле является обязательным для заполнения";
	$.validator.messages.email = "Некорректный формат адреса электронной почты";
	
	$('form .required input').addClass('required');
	$('form .required textarea').addClass('required');
	$('form .email-wrapper .required input').addClass('email');
	$('.tab').not('.local').find('input').removeClass('required');
	$('form[class!="wtbForm"]').each(function() { $(this).validate() });
	/* ---------------------------------------------------------------------------------------------------------------- */
});



