Your IP : 3.145.139.84


Current Path : /home/bitrix/ext_www/teplo.home-comfort.in.ua/conv-mount_files/
Upload File :
Current File : /home/bitrix/ext_www/teplo.home-comfort.in.ua/conv-mount_files/script.js

function startPreventBodyScroll(){
	$('body').addClass('is-fixed');
	if($(window).width() < 768){
		$('body').css({'position': 'fixed', width: $('body').width() + 'px'});
	}

}
function endPreventBodyScroll(){
	$('body').removeClass('is-fixed');
	if($(window).width() < 768){
		$('body').css({'position': 'static', 'width': 'auto'});
	}
}

// Переносит картинки в бэкграунд родителя
function jsBgImage(){
	$('.js-bg-image').each(function(){
		$this = $(this);
		$src = $this.attr('src');
		if($this.data('at-2x') && window.devicePixelRatio > 1.5){
			$src = $(this).data('at-2x');
		}
		$this.parent().css({ 'background-image': 'url("' + $src + '")'});
		$this.hide();
	});
}

$(document).ready(function() {
	jsBgImage();
});

// Прижимаем футер
$(function () {
	if($('html').hasClass('is-footer-fixed')) {
		var body = $('body');
		var footer = $('.layout__footer');
		var footerHeight = footer.height() + parseInt(footer.css('margin-top'));
		//body.css('margin-bottom', footerHeight); /*fixing footer float*/
	}
});



$(function () {
	// Модальные окна
	$('body').on('click', 'a.pupop, .js-modal', function (e) {

		//console.log(e);
		var that = this;

		if ($(e.target).hasClass("element-item__order js-buy-button")) {
			//console.log("HERE");
			if (typeof basketHandlerBeforeBy !== "undefined") {
				// if (typeof aaaaa !== "undefined")
				if (true)
				{
					e.preventDefault();

					basketHandlerBeforeBy.beforeBasketAdd($(e.target), function() {
						var target = $(that).data('href') || $(that).attr('href');
						var additionalTitle = $(that).attr("data-additional-title");
						var wrapCSS = $(that).attr("data-wrap-css");

						if(!additionalTitle || typeof additionalTitle == 'undefined')
						{
							additionalTitle = '';
						}
						if(!wrapCSS || typeof wrapCSS == 'undefined')
						{
							wrapCSS = '';
						}

						if(target.substr(0,1) == '#'){
							var $target = $(target);
						} else {
							$.get(target, function(data){
								$target = $(data);
								open(additionalTitle);

							});
							return false;
						}

						if($.fancybox.isOpen) {
							$.fancybox.close(true);
							setTimeout(function() {open(additionalTitle);}, 250);
						} else {
							open(additionalTitle);
						}



						function open(additionalTitle) {
							$.fancybox.open(
								$target,
								{
									padding: 30,
									margin: 10,
									closeEffect: 'none',
									wrapCSS: 'is-default' + ' ' + wrapCSS,
									closeSpeed: 0,
									openSpeed: 0,
									openEffect: 'none',
									openOpacity: false,
									closeOpacity: false,
									fitToView: true,
									scrolling: 'visible',
									afterLoad: function(){
										$target.find('.cart-modal__shopping-link').on('click', function(){ $.fancybox.close(); return false; })
									},
									beforeShow: function () {
										$('html').addClass('fancybox-margin fancybox-lock');
										$('.fancybox-wrap').livequery(function(){
											var $context = $(this);
											var goodField = $context.find(".good-name");
											$context.find('select').select2();
											$context.find('[type=checkbox]').iCheck();
											$context.find('[type=radio]').iCheck();

											var checkVal = function ($input, regExp) {
												var result = regExp.test($input.val());
												if (result) {
													$input.closest('.form-standart__field').removeClass('is-error');
												} else {
													$input.closest('.form-standart__field').addClass('is-error');
												}

												return result;
											};
											$('[data-mask="phone"]', $context).each(function(){
												$(this).mask('+7 (999) 999-99-99', {clearIfNotMatch: true});
											});
											$('[data-mask="email"]', $context).change(function () {

												var regExp = /^([A-Za-z0-9_-]+\.)*[A-Za-z0-9\+_-]+@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.[a-z]{2,6}$/g;
												checkVal($(this), regExp);
												return true;
											});

											if(additionalTitle)
											{
												var formTitle = $(".form-standart__title", $context);
												formTitle.text(formTitle.text() + ' ' + additionalTitle);
											}

											if(goodField.length > 0 && additionalTitle)
											{
												goodField.val(additionalTitle);
											}
										});

										yaClickEvents();
										gaClickEvents();
									}
								}
							);
						}

						return false;
					});

					return;
				}
			}
		}

		var target = $(this).data('href') || $(this).attr('href');
		var additionalTitle = $(this).attr("data-additional-title");
		var wrapCSS = $(this).attr("data-wrap-css");

		if(!additionalTitle || typeof additionalTitle == 'undefined')
		{
			additionalTitle = '';
		}
		if(!wrapCSS || typeof wrapCSS == 'undefined')
		{
			wrapCSS = '';
		}

		console.log(target);

		if(target.substr(0,1) == '#'){
			var $target = $(target);
		} else {
			$.get(target, function(data){
				$target = $(data);
				open(additionalTitle);
			});

			return false;
		}

		if($.fancybox.isOpen) {
			$.fancybox.close(true);
			setTimeout(function() {open(additionalTitle);}, 250);
		} else {
			open(additionalTitle);
		}

		function open(additionalTitle) {
			$.fancybox.open(
				$target,
				{
					padding: 30,
					margin: 10,
					closeEffect: 'none',
					wrapCSS: 'is-default' + ' ' + wrapCSS,
					closeSpeed: 0,
					openSpeed: 0,
					openEffect: 'none',
					openOpacity: false,
					closeOpacity: false,
					fitToView: true,
					scrolling: 'visible',
					afterLoad: function(){
						$target.find('.cart-modal__shopping-link').on('click', function(){ $.fancybox.close(); return false; })
					},
					beforeShow: function () {
						$('html').addClass('fancybox-margin fancybox-lock');
						$('.fancybox-wrap').livequery(function(){
							var $context = $(this);
							var goodField = $context.find(".good-name");
							$context.find('select').select2();
							$context.find('[type=checkbox]').iCheck();
							$context.find('[type=radio]').iCheck();

							var checkVal = function ($input, regExp) {
								var result = regExp.test($input.val());
								if (result) {
									$input.closest('.form-standart__field').removeClass('is-error');
								} else {
									$input.closest('.form-standart__field').addClass('is-error');
								}

								return result;
							};
							$('[data-mask="phone"]', $context).each(function(){
								$(this).mask('+9 (999) 999-99-99', {clearIfNotMatch: true});
							});
							$('[data-mask="email"]', $context).change(function () {

								var regExp = /^([A-Za-z0-9_-]+\.)*[A-Za-z0-9\+_-]+@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*\.[a-z]{2,6}$/g;
								checkVal($(this), regExp);
								return true;
							});

							if(additionalTitle)
							{
								var formTitle = $(".form-standart__title", $context);
								formTitle.text(formTitle.text() + ' ' + additionalTitle);
							}

							if(goodField.length > 0 && additionalTitle)
							{
								goodField.val(additionalTitle);
							}
						});

						yaClickEvents();
						gaClickEvents();
					}
				}
			);
		}

		return false;
	});

	$('input[type="phone"]').mask('+9 (999) 999-99-99', {clearIfNotMatch: true});
	$('input[name="phone"]').mask('+9 (999) 999-99-99', {clearIfNotMatch: true});

	// Модальные окна ajax
	$('.js-modal-ajax').on('click',  function() {
		var href =  $(this).attr('href');
		// console.warn('.js-modal-ajax '+href);
		$.fancybox.open(
			{
				href: href
			},
			{
				wrapCSS: 'is-ajax',
				type: 'ajax',
				fitToView: true,
				autoResize: true,
				padding: 20,
				margin: 20,
				maxWidth: 1000,
				afterLoad: function (current, previous) {
					var $content = $(current.content);

					$content.addClass('_ajax-append');
					current.content = $('<div>').append($content.clone()).html();
					$.fancybox.showLoading()
				},
				afterShow: function () {
					$('.fancybox-wrap').livequery();
					setTimeout(function () {
						$('.fancybox-wrap .bem').trigger('resize.block');
						$.fancybox .hideLoading();
						$('.fancybox-wrap').removeClass('is-ajax');
					}, 600);
				}
			}
		);
		return false;
	});

});

// Плейсхолдеры
$(function () {
	$('input[placeholder], textarea[placeholder]').placeholder();
});

// Стилизация селектов
$(function () {
	$('select.select2').each(function () {
		var placeholder = $(this).attr('placeholder');
		var  templateSR = function (state) {
			var $thstate = $(state.element);

			var $state = $(
				'<span>' + state.text  + '</span>'
			);
			if($thstate.data('img')){
				$('<span class="is-img-point" style="background-image: url('+ $thstate.data('img') +')"></span>').prependTo($state);
			}
			if($thstate.data('format')) $state.addClass('is-format-'+ $(state.element).data('format'));
			return $state;
		}

		$(this).select2({
			minimumResultsForSearch: 8,
			placeholder: placeholder,
			templateResult: templateSR,
			templateSelection: templateSR
		});
	});
});


// Стилизация радиокнопок и чекбоксов
$(function () {
	$('input[type="checkbox"], input[type="radio"]').not('.unstyled').each(function(){
		$(this).iCheck();
		$(this).on('ifToggled', function(e){
			$(this).trigger('change').trigger('click'); // Trigger default event
		});
	});
});

// Скрипт для форм form.result.new
$.fn.initWebForm = function(block, options) {
	/*
	 WP_SUCCESS_MODE

	 S1 - Редирект на страницу "Спасибо"
	 S2 - Редирект на текущую страницу (перезагрузка страницы)
	 S3 - Редирект на текущую страницу с показом информационного попапа, после загрузки страницы
	 S4 - Замена содержимого формы на сообщение об успешной отправке без изменения размера формы
	 S5 - Замена содержимого формы на сообщение об успешной отправке с изменением размера формы
	 S6 - Замена содержимого формы на сообщение об успешной отправке с последующим полным скрытием формы после небольшой паузы (закрыванием попапа).
	 S7 - Показ сообщения об успешной отправке в попапе и очистка (сброс) формы.
	 S8 - Показ сообщения об успешной отправке в попапе БЕЗ очистки (сброса) формы.
	 */

	var default_options = {
		WP_SUCCESS_MODE: 'S5'
	}
	var options = $.extend({}, default_options, options);

	var $form = $(this);
	var blockName = $form.find('input[name=block_name]').val() || block || 'form-standart';
	var $context = $form.closest('.'+blockName);

	var $inputs = $form.find('[data-fieldname]');
	var $fields = $('.' + blockName + '__field', $context);
	var $successMessage = $('.success-message-modal',$context);
	var isAjax = $context.hasClass('js-ajax') || $form.hasClass('js-ajax');

	var formId = $form.attr('id');

	var $jsTitle = $('[data-form-title="' + formId + '"]');

	var MESS = {
		'browser': 'Браузер',
		'windowsize': 'Размер окна',
		'utm_source': 'UTM источник',
		'utm_campaign': 'UTM кампания',
		'utm_medium': 'UTM медиа',
		'utm_keyword': 'UTM ключевые слова',
		'location': 'Текущая страница',
		'message_sent': 'Сообщение отправлено'
	}

	if($form.data('form-initiated') !== undefined) return;
	$form.data('form-initiated', true);

	prepareFieldsValidation();
	initFormSubmit();

	function getFieldsData(){
		var data = {};
		$form.find('[data-fieldname]').each(function(){
			data[$(this).data('fieldname')] = $(this).val();
		});
		return data;
	}

	function getCookie(name) {
		var matches = document.cookie.match(new RegExp(
			"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
		));
		return matches ? decodeURIComponent(matches[1]) : undefined;
	}

	function getUtms() {
		var utm = getCookie('__utmz');
		utms = {};
		if(utm){
			eval(utm.replace(/.*?(utm.*?)=([^|]*)[|]?/g, "utms['$1'] = '$2';\n"));
		}
		return utms;
	}

	function getUserInfo(){
		var userinfo = {};
		userinfo['browser'] = navigator.userAgent;
		userinfo['windowsize'] = $(window).width() + "×" + $(window).height();
		userinfo['location'] = document.location.href;
		utms = getUtms();
		if(utms.utmcsr){
			userinfo['utm_source'] = utms.utmcsr;
		}
		if(utms.utmccn){
			userinfo['utm_campaign'] = utms.utmccn;
		}
		if(utms.utmcmd){
			userinfo['utm_medium'] = utms.utmcmd;
		}
		if(utms.utmcmd){
			userinfo['utm_keyword'] = utms.utmctr;
		}

		var stringresult = "";
		$.each(userinfo, function(key, value){
			stringresult += MESS[key] + ": " + value + "\n";
		});
		return stringresult;
	}

	function prepareFieldsValidation () {
		// Обеспечиваем совместимость с предыдущим решением
		$fields.filter('[data-necessary]').each(function () {
			var $field = $(this);
			var $inputs = $('input, textarea, select', $field);
			var $iChecks = $field.find('.icheckbox');
			$iChecks.hide();

			$inputs.each(function () {
				var $this = $(this);
				$this.removeAttr('required').data('required', true);

				$this.on('click keydown change', function() {
					$(this).closest('.'+blockName+'__field').removeClass('is-none');
				});
			});

			$inputs.on('ifChecked', function(event){
				$(this).closest('.'+blockName+'__field').removeClass('is-none');
			});
		});

		$('input[data-necessary], textarea[data-necessary], select[data-necessary]', $form).each(function () {
			var $this = $(this);

			$this.data('required', true);

			$this.on('click keydown change', function() {
				$(this).closest('.'+blockName+'__field').removeClass('is-none');
			});
		});

		// Меняем дефолтное поведение обязательных полей
		$('input[required], textarea[required], select[required]', $form).each(function () {
			var $this = $(this);

			$this.removeAttr('required').data('required', true);

			$this.on('click keydown change', function() {
				$(this).closest('.'+blockName+'__field').removeClass('is-none');
			});
		});
	}

	function initFormSubmit () {
		if(isAjax) {
			$form.ajaxForm({
				dataType: (Webprofy.isOldIe() ? 'text' : 'json'),
				beforeSerialize: function(){
					$form.find('input[name="confirm"]').remove();
					$form.find('input[data-fieldname="_utm"]').val(getUserInfo());
				},
				beforeSubmit: function(){
					var preValidation = checkFields();

					/* Очищаем все ошибки формы*/
					var $all_error = $('.'+blockName+'__common-error-placeholder', $context);
					if($all_error.length) $all_error.html('');
					if(preValidation) {
						$form
							.find('input[type="submit"]')
							.prop( "disabled", true)
							.addClass('is-disabled');
					}

					return preValidation;
				},
				success: ajaxSuccessHandler,
				error: ajaxErrorHandler
			});
		} else {
			$form.on('submit', checkFields);
		}
	}

	function setSuccessTitleIfPresent() {
		if($jsTitle.length && options.WP_SUCCESS_TITLE){
			$jsTitle.html(options.WP_SUCCESS_TITLE);
		}
	}

	function ajaxSuccessHandler (data) {
		//console.log(data);

		$form.find('input[type="submit"]').prop( "disabled", false).removeClass('is-disabled');
		$form.find('.error-text').remove();
		$form.find('.is-error').removeClass('is-error');

		if(Webprofy.isOldIe()) {
			eval('var data=' + data);
		}

		// console.log(data);

		if(data.status == 'error'){
			var errorCommonContainer = $('.'+blockName+'__common-error-placeholder', $context);
			$.each(data.errors, function(key, value){
				var $input = $form.find('[data-fieldname="' + key + '"]');
				var $container = $input.closest('.'+blockName+'__field');
				var $error;

				if($container.length > 0){
					$error = $container.find('.'+blockName+'__error');
					if($error.length==0)
						$error = $('<div class="'+blockName+'__error"></div>').appendTo($container);

					$error.text(value);
					$container.addClass('is-error');

					$input.on('change',function(){
						$container.removeClass('is-error');
					});

				} else {
					if(errorCommonContainer.length > 0){
						$container = errorCommonContainer;
					}else{
						$form.append('<div class="'+blockName+'__common-error-placeholder"></div>');
						errorCommonContainer = $('.'+blockName+'__common-error-placeholder', $context);
					}

					$(errorCommonContainer).append(
						'<div class="'+blockName+'__common-error"><div class="'+blockName+'__common-error-text">'  + value + '</div></div>'
					);
				}
			});
			$(document).trigger('webform.error', [$form.attr('name'), data, getFieldsData()]);
		}

		if(data.status == 'success'){
			$(document).trigger('webform.success', [$form.attr('name'), getFieldsData()]);
			//console.log(options.WP_SUCCESS_MODE);
			//console.log(options);

			if (data.message == undefined) {
				data.message = options.WP_DEFAULT_SUCCESS_MESSAGE;
			}

			switch (options.WP_SUCCESS_MODE) {
				case 'S1':
					if(data.redirect) {
						window.location = data.redirect
					} else {
						window.location.reload();
					}
					break;
				case 'S2':
					window.location.reload();
					break;
				case 'S3':
					var loc = window.location;
					if(window.location.href.indexOf('?') + 1) {
						var popup_get = '&' + options.WP_FORM_ID + '=Y';
					} else {
						var popup_get = '?' + options.WP_FORM_ID + '=Y';
					}
					window.location = window.location.href + popup_get;
					break;
				case 'S4':
					// доработать - Замена содержимого формы на сообщение об успешной отправке без изменения размера формы
					$form.parent().html('<div class="success-message">' + data.message + '</div>');
					setSuccessTitleIfPresent();
					break;
				case 'S5':
					$form.parent().html('<div class="success-message">' + data.message + '</div>');
					setSuccessTitleIfPresent();
					break;
				case 'S6':
					// доработать - Замена содержимого формы на сообщение об успешной отправке с последующим полным скрытием формы после небольшой паузы (закрыванием попапа)
					$form.parent().html('<div class="success-message">' + data.message + '</div>');
					setSuccessTitleIfPresent();
					break;
				case 'S8':
					/** Используется в Личном кабинете */
					$.fancybox.close();
					$.fancybox($successMessage , {
						afterClose: function(){
							if($successMessage.hasClass('js-reload-page')){
								window.location = window.location;
							}
						},
						wrapCSS: 'modal-theme',
						autoCenter: false,
						padding: 0,
						fitToView: false
					});
					break;
				case 'S7':
				default:
					$.fancybox.close();
					$.fancybox($successMessage , {
						afterClose: function(){
							if($successMessage.hasClass('js-reload-page')){
								window.location = window.location;
							}
							$context.find('form').trigger('reset'); // todo: доработать - сброс формы на дефолтное состояние
						},
						wrapCSS: 'modal-theme',
						autoCenter: false,
						padding: 0,
						fitToView: false
					});
					break;

			}

			/*
			 if(data.redirect){
			 document.location = data.redirect;
			 } else if(data.message) {
			 $form.parent().html('<div class="success-message">' + data.message + '</div>');
			 } else {
			 $.fancybox($successMessage , {
			 afterClose: function(){
			 if($successMessage.hasClass('js-reload-page')){
			 window.location = window.location;
			 }
			 },
			 wrapCSS: 'modal-theme',
			 autoCenter: false,
			 padding: 0,
			 fitToView: false
			 });
			 }
			 */
		}
	}

	function ajaxErrorHandler (data) {
		//	console.log(data);

		if(typeof window.isLocalBuild !== 'undefined') {
			data.status = 'success';
			ajaxSuccessHandler(data);
		} else {
			$form.find('input[type="submit"]').prop( "disabled", false).removeClass('disabled');
			$form.find('.is-captcha-field').addClass('is-error');
		}
	}

	function checkFields () {
		var result = true;

		$fields.each(function () {
			var $field = $(this);
			var $inputs = $('input, textarea, select', $field);
			if($field.hasClass('is-error') || $field.hasClass('is-none')) {
				result = false;
				return;
			}

			$inputs.each(function () {
				var $input = $(this);
				var checkResult = true;
				var isContinue = true;

				if($input.data('required') == undefined) return;

				switch($input.attr('type')) {
					case 'checkbox':
						if(!$input.data('required')) {
							checkResult = true && checkResult;
						} else if($inputs.filter(':checked').length == 0) {
							checkResult = false;
							$field.addClass('is-none');
						}
						result = checkResult && result;
						break;

					case 'radio':
						if(!$input.data('required')) {
							checkResult = true && checkResult;
						} else if($inputs.filter(':checked').length == 0) {
							checkResult = false;
							$field.addClass('is-none');
						}
						result = checkResult && result;
						break;

					default:
						if(!$input.data('required')) {
							checkResult = true && checkResult;
						} else if($input.val() == '') {
							checkResult = false;
							$field.addClass('is-none');
						}
						result = checkResult && result;
						break;
				}
			});
		});

		return result;
	}
};

//Обновляем последние просмотренные товары
function updateViewList(site_id, product_id, parent_id) {
	var href="/bitrix/components/bitrix/catalog.element/ajax.php";
	$.ajax({
		type: "POST",
		url: href,
		dataType: "text",
		data: {
			AJAX: "Y",
			SITE_ID: site_id,
			PRODUCT_ID: product_id,
			PARENT_ID: parent_id
		}
	}).done(function(resp) {
		//Thanx, bitrix
		eval('var response='+resp);
		if(response.STATUS == 'SUCCESS') {
			// console.log('updateViewList.ok');
		}else{
			console.warn('updateViewList.error');
		}
	});
}

// контент зависимый от чекбокса .show-on-condition
function initShowOnCondition(){
	$('[data-watch]').each(function(){
		var $this = $(this),
			watch = $this.attr('data-watch'),
			$that = $(watch);

		var change = $this.attr('data-change');
		if(change){
			$that.change(function(){
				try{
					eval(change);
				}
				catch(e){
					console.error('bad data-change');
				}
			}).eq(0).trigger('change');
			return;
		}

		var showSelectEquals = $this.attr('data-show-select-equals');
		if(showSelectEquals){
			$this.change(function(){
				$that.filter(':checked').val('')
			})
		}
	});

	var listeners = [];

	$('.show-on-condition').each(function(){
		var self = $(this);
		var condition = self.data('condition');

		// Complex parser :)
		var conditions = condition.split(" and ");

		$.each(conditions, function(key, value){
			var operands = value.split(" ");
			if(operands.length == 3){
				listeners.push({
					input: operands[0],
					conditions: conditions,
					object: self
				});
			}
		});
	});

	$(document).on('change', 'input, textarea, select', function(){
		var name = $(this).attr('name');
		updateConditions(name);
	});

	function updateConditions(name){
		$.each(listeners, function(key, value){

			if(typeof(name) === 'string' && value.input != name)
				return; // skip this one;

			var result = true;
			$.each(value.conditions, function(k, v){
				var operands = v.split(" ");
				if(operands.length == 3){
					var input = $('[name="' + operands[0] + '"]');
					if(input.length >= 1){
						var input_value;
						if(input.length == 1){
							input_value = input.val();
						} else {
							input_value = input.filter(':checked').val();
						}

						if(input_value == operands[2]){
							result = result & (operands[1] == "is");
						} else {
							result = result & (operands[1] == "not");
						}
					} else {
						result = false;
					}
				} else {
					result = false;
				}
			});
			if(result){
				value.object.show();
			} else {
				value.object.hide();
			}
		});
	}
	updateConditions();
}
$(function(){
	initShowOnCondition();
});

$(function(){
	// Content table wrapper
	$('.content-area table').each(function(){
		$(this).wrap('<div class="layout__content-table"></div>');
	});
});

function plural(n,f){n%=100;if(n>10&&n<20)return f[2];n%=10;return f[n>1&&n<5?1:n==1?0:2]}


//Цели Google Analytics
//при клике на кнопку, вызываем событие
//у блока должен быть атрибут data-ga-click="reachName"
function gaClickEvents() {
	var dataGaButtons = $('[data-ga-click]');
	$(dataGaButtons).on('click', function (event) {
		var action = $(event.target).data('ga-click');
		if(!action){
			//если кликнули на вложенный тег, например nobr
			action = $(event.target).parent().data('ga-click');
		}
		if(action){
			ga('send', 'event', action, 'click');
		}
	});
}

//Цели Яндекс-Метрики
//при клике на кнопку, вызываем событие
//у блока должен быть атрибут data-ya-click="reachName"
function yaClickEvents() {
	var dataYaButtons = $('[data-ya-click]');
	if(window['Ya'] && typeof Ya.Metrika === 'function'){
		var counters = Ya.Metrika.counters();
		var counter = counters[0].id;
	}
	if(counter){
		$(dataYaButtons).on('click', function (event) {
			//console.log('click');
			var action = $(event.target).data('ya-click');
			if(!action){
				//если кликнули на вложенный тег, например nobr
				action = $(event.target).parent().data('ya-click');
			}
			if(action){
				var counterYa = eval('yaCounter' + counter);
				try{
					counterYa.reachGoal(action);
				}catch (e) {
				}
			}
		});
	}
}

$(function () {
	yaClickEvents();
	gaClickEvents();
});


/*!
 * parallax.js v1.5.0 (http://pixelcog.github.io/parallax.js/)
 * @copyright 2016 PixelCog, Inc.
 * @license MIT (https://github.com/pixelcog/parallax.js/blob/master/LICENSE)
 */
!function(t,i,e,s){function o(i,e){var h=this;"object"==typeof e&&(delete e.refresh,delete e.render,t.extend(this,e)),this.$element=t(i),!this.imageSrc&&this.$element.is("img")&&(this.imageSrc=this.$element.attr("src"));var r=(this.position+"").toLowerCase().match(/\S+/g)||[];if(r.length<1&&r.push("center"),1==r.length&&r.push(r[0]),"top"!=r[0]&&"bottom"!=r[0]&&"left"!=r[1]&&"right"!=r[1]||(r=[r[1],r[0]]),this.positionX!==s&&(r[0]=this.positionX.toLowerCase()),this.positionY!==s&&(r[1]=this.positionY.toLowerCase()),h.positionX=r[0],h.positionY=r[1],"left"!=this.positionX&&"right"!=this.positionX&&(isNaN(parseInt(this.positionX))?this.positionX="center":this.positionX=parseInt(this.positionX)),"top"!=this.positionY&&"bottom"!=this.positionY&&(isNaN(parseInt(this.positionY))?this.positionY="center":this.positionY=parseInt(this.positionY)),this.position=this.positionX+(isNaN(this.positionX)?"":"px")+" "+this.positionY+(isNaN(this.positionY)?"":"px"),navigator.userAgent.match(/(iPod|iPhone|iPad)/))return this.imageSrc&&this.iosFix&&!this.$element.is("img")&&this.$element.css({backgroundImage:"url("+this.imageSrc+")",backgroundSize:"cover",backgroundPosition:this.position}),this;if(navigator.userAgent.match(/(Android)/))return this.imageSrc&&this.androidFix&&!this.$element.is("img")&&this.$element.css({backgroundImage:"url("+this.imageSrc+")",backgroundSize:"cover",backgroundPosition:this.position}),this;this.$mirror=t("<div />").prependTo(this.mirrorContainer);var a=this.$element.find(">.parallax-slider"),n=!1;0==a.length?this.$slider=t("<img />").prependTo(this.$mirror):(this.$slider=a.prependTo(this.$mirror),n=!0),this.$mirror.addClass("parallax-mirror").css({visibility:"hidden",zIndex:this.zIndex,position:"fixed",top:0,left:0,overflow:"hidden"}),this.$slider.addClass("parallax-slider").one("load",function(){h.naturalHeight&&h.naturalWidth||(h.naturalHeight=this.naturalHeight||this.height||1,h.naturalWidth=this.naturalWidth||this.width||1),h.aspectRatio=h.naturalWidth/h.naturalHeight,o.isSetup||o.setup(),o.sliders.push(h),o.isFresh=!1,o.requestRender()}),n||(this.$slider[0].src=this.imageSrc),(this.naturalHeight&&this.naturalWidth||this.$slider[0].complete||a.length>0)&&this.$slider.trigger("load")}!function(){for(var t=0,e=["ms","moz","webkit","o"],s=0;s<e.length&&!i.requestAnimationFrame;++s)i.requestAnimationFrame=i[e[s]+"RequestAnimationFrame"],i.cancelAnimationFrame=i[e[s]+"CancelAnimationFrame"]||i[e[s]+"CancelRequestAnimationFrame"];i.requestAnimationFrame||(i.requestAnimationFrame=function(e){var s=(new Date).getTime(),o=Math.max(0,16-(s-t)),h=i.setTimeout(function(){e(s+o)},o);return t=s+o,h}),i.cancelAnimationFrame||(i.cancelAnimationFrame=function(t){clearTimeout(t)})}(),t.extend(o.prototype,{speed:.3,bleed:0,zIndex:100,iosFix:!0,androidFix:!0,position:"center",overScrollFix:!1,mirrorContainer:"body",refresh:function(){this.boxWidth=this.$element.outerWidth(),this.boxHeight=this.$element.outerHeight()+2*this.bleed,this.boxOffsetTop=this.$element.offset().top-this.bleed,this.boxOffsetLeft=this.$element.offset().left,this.boxOffsetBottom=this.boxOffsetTop+this.boxHeight;var t,i=o.winHeight,e=o.docHeight,s=Math.min(this.boxOffsetTop,e-i),h=Math.max(this.boxOffsetTop+this.boxHeight-i,0),r=this.boxHeight+(s-h)*(1-this.speed)|0,a=(this.boxOffsetTop-s)*(1-this.speed)|0;r*this.aspectRatio>=this.boxWidth?(this.imageWidth=r*this.aspectRatio|0,this.imageHeight=r,this.offsetBaseTop=a,t=this.imageWidth-this.boxWidth,"left"==this.positionX?this.offsetLeft=0:"right"==this.positionX?this.offsetLeft=-t:isNaN(this.positionX)?this.offsetLeft=-t/2|0:this.offsetLeft=Math.max(this.positionX,-t)):(this.imageWidth=this.boxWidth,this.imageHeight=this.boxWidth/this.aspectRatio|0,this.offsetLeft=0,t=this.imageHeight-r,"top"==this.positionY?this.offsetBaseTop=a:"bottom"==this.positionY?this.offsetBaseTop=a-t:isNaN(this.positionY)?this.offsetBaseTop=a-t/2|0:this.offsetBaseTop=a+Math.max(this.positionY,-t))},render:function(){var t=o.scrollTop,i=o.scrollLeft,e=this.overScrollFix?o.overScroll:0,s=t+o.winHeight;this.boxOffsetBottom>t&&this.boxOffsetTop<=s?(this.visibility="visible",this.mirrorTop=this.boxOffsetTop-t,this.mirrorLeft=this.boxOffsetLeft-i,this.offsetTop=this.offsetBaseTop-this.mirrorTop*(1-this.speed)):this.visibility="hidden",this.$mirror.css({transform:"translate3d("+this.mirrorLeft+"px, "+(this.mirrorTop-e)+"px, 0px)",visibility:this.visibility,height:this.boxHeight,width:this.boxWidth}),this.$slider.css({transform:"translate3d("+this.offsetLeft+"px, "+this.offsetTop+"px, 0px)",position:"absolute",height:this.imageHeight,width:this.imageWidth,maxWidth:"none"})}}),t.extend(o,{scrollTop:0,scrollLeft:0,winHeight:0,winWidth:0,docHeight:1<<30,docWidth:1<<30,sliders:[],isReady:!1,isFresh:!1,isBusy:!1,setup:function(){function s(){if(p==i.pageYOffset)return i.requestAnimationFrame(s),!1;p=i.pageYOffset,h.render(),i.requestAnimationFrame(s)}if(!this.isReady){var h=this,r=t(e),a=t(i),n=function(){o.winHeight=a.height(),o.winWidth=a.width(),o.docHeight=r.height(),o.docWidth=r.width()},l=function(){var t=a.scrollTop(),i=o.docHeight-o.winHeight,e=o.docWidth-o.winWidth;o.scrollTop=Math.max(0,Math.min(i,t)),o.scrollLeft=Math.max(0,Math.min(e,a.scrollLeft())),o.overScroll=Math.max(t-i,Math.min(t,0))};a.on("resize.px.parallax load.px.parallax",function(){n(),h.refresh(),o.isFresh=!1,o.requestRender()}).on("scroll.px.parallax load.px.parallax",function(){l(),o.requestRender()}),n(),l(),this.isReady=!0;var p=-1;s()}},configure:function(i){"object"==typeof i&&(delete i.refresh,delete i.render,t.extend(this.prototype,i))},refresh:function(){t.each(this.sliders,function(){this.refresh()}),this.isFresh=!0},render:function(){this.isFresh||this.refresh(),t.each(this.sliders,function(){this.render()})},requestRender:function(){var t=this;t.render(),t.isBusy=!1},destroy:function(e){var s,h=t(e).data("px.parallax");for(h.$mirror.remove(),s=0;s<this.sliders.length;s+=1)this.sliders[s]==h&&this.sliders.splice(s,1);t(e).data("px.parallax",!1),0===this.sliders.length&&(t(i).off("scroll.px.parallax resize.px.parallax load.px.parallax"),this.isReady=!1,o.isSetup=!1)}});var h=t.fn.parallax;t.fn.parallax=function(s){return this.each(function(){var h=t(this),r="object"==typeof s&&s;this==i||this==e||h.is("body")?o.configure(r):h.data("px.parallax")?"object"==typeof s&&t.extend(h.data("px.parallax"),r):(r=t.extend({},h.data(),r),h.data("px.parallax",new o(this,r))),"string"==typeof s&&("destroy"==s?o.destroy(this):o[s]())})},t.fn.parallax.Constructor=o,t.fn.parallax.noConflict=function(){return t.fn.parallax=h,this},t(function(){t('[data-parallax="scroll"]').parallax()})}(jQuery,window,document);
//paralax
$(document).ready(function() {
	if($('.js-promo-paralax').length>0)
	{
		var bg = $('.js-promo-paralax').css('background-image');
		bg = bg.replace('url(','').replace(')','').replace(/\"/gi, "");
		$('.js-promo-paralax').css({
			height: '150vh'
		});;
		$('.js-promo-paralax').parallax({imageSrc: bg });
	}
});

// mobile menu
$(document).ready(function() {
	$('.header__hamburger').click(function(event) {
		$('.Burger-bar').toggleClass('active');
		$('.NavSite-menu-popup').slideToggle();
	});
	$('.NavSite-menu-close').click(function(event) {
		$('.Burger-bar').toggleClass('active');
		$('.NavSite-menu-popup').slideToggle();
	});
});
// втонрой уровень mobile menu
$(document).ready(function() {
	$('.menu-top__first-js').click(function() {
		$(this).parent('.MainCategory').children('.header-mobile__catalog-holder').toggleClass('active');
		$('body').css('position', 'fixed');

		return false;
	});
});


$(document).ready(function(){
	$('.NavSite-l2-container-backButton').click(function(){
		$(this).parents('.MainCategory').children('.header-mobile__catalog-holder').toggleClass('active');

		if ($('body')[0].hasAttribute('style')) {
			$('body').removeAttr('style');
		}

		return false;
	});
});
//первый уровень mobile menu

$(document).ready(function(){
	$('.js-top-menu-submenu-click').click(function(){
		$(this).parent ('.js-top-menu-submenu-click').children('.menu-aside__second-holder').slideToggle();
		// return false;
	});
});
// $(document).ready(function() {
// 	$('.js-top-menu-submenu-click').click(function(event) {
// 		$('.menu-aside__link-text').slideToggle();
// 	});
//третий уровень mobile menu

$(document).ready(function(){
	$('.js-top-menu-submenu-click .menu-aside__first-link').click(function(){
		$(this).parent ('.js-top-menu-submenu-click').children('.menu-aside__second-holder').slideToggle();
		return false;
	});
});

// fixed top menu
$(document).ready(function() {
	var scrollPos = 0;
	var $headerHeight = $('.layout__header').height();

	$(window).scroll(function() {
		var st = $(this).scrollTop();

		if (st > scrollPos) {
			if ($(window).height() < ($('.menu-top__second-holder').height() + $headerHeight)) {
				var scrollValue = $(window).height() - ($('.menu-top__second-holder').height() + $headerHeight);

				$('.is-fixed-header .layout__header').css('top', scrollValue + 'px');
			} else {
				$('.is-fixed-header .layout__header').css('top','-118px');
			}
		} else {
			$('.is-fixed-header .layout__header').css('top','0');
		}

		scrollPos = st;
	});

	$('.js-rp-call-us').click(function(event) {
		$('.right-panel').toggleClass('active');

		var txt = $(this).find('.right-panel__item-text').text() === "Связаться с нами" ? 'Закрыть' : 'Связаться с нами';
		$(this).find('.right-panel__item-text').text(txt);
	});
	$(window).scroll(function()
	{
		var st = $(this).scrollTop();
		if (st > scrollPos){
			// down

		}
		else
		{
			//up
			$('.right-panel').removeClass('active');
			$('.js-rp-call-us').find('.right-panel__item-text').text("Связаться с нами");
		}
		scrollPos = st;
	});

	if($(window).width()< 668) {

		var mainpageCategorySliderHeight = $('.logo-slider.main .logo-slider__slider').height();

		$('.logo-slider.main .logo-slider__slider').attr('data-height', mainpageCategorySliderHeight);
		$('.logo-slider.main .logo-slider__slider').css('height', '544px');

		$('.js-main-page-show-more').click(function(event) {
			$(this).hide();
			$('.logo-slider.main .logo-slider__slider').height(mainpageCategorySliderHeight);
		});

		var moreButton = '\
		<div class="more-items__button">\
			<svg viewBox="0 0 17 10" class="SvgIcon SvgIcon--chevron-down">\
				<path d="M8.529 9.216L.5 2.251 1.738.784l6.791 5.888L15.261.784 16.5 2.251 8.529 9.216z"></path>\
			</svg>\
		</div>';

		$('.CategoryProduct__content').append(moreButton);

		$(document).on('click', '.more-items__button', function(event) {
			$(this).parents('.CategoryProduct').find('.CategoryProduct__image-body').toggleClass('active');
		});


	}

});

// scroll top button
$(document).ready(function () {
	var btn = $('.js-scroll-top');

	btn.on('click', function () {
		$('.header-mobile__catalog-holder').scrollTo(0);
	});
});

// get параметры из урла
function getUrlVars()
{
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

$(document).ready(function () {
	var button = $('.website-feedback-js-animate');
	var flag = true;

	button.on('click', function () {
		var self = $(this);

		if (flag) {
			self.find('.feedback__text').hide(300);
			self.addClass('feedback_circle');
			self.find('.website-feedback__row-container').show(300);
			self
				.find('.SvgIcon--speech-bubble-with-question-mark:not(.website-feedback-SvgIcon--close)')
				.hide(300, function () {
					flag = false;
				})
				.next()
				.show(300);
		} else {
			self.find('.website-feedback__row-container').hide(300);
			self
				.find('.website-feedback-SvgIcon--close')
				.hide(300)
				.siblings()
				.show(300, function () {
					flag = true;
				});
		}
	});
});

$(document).ready(function($) {
	$('.js-ModalPopup-outer').click(function() {
		$('.ModalPopup-outer').fadeIn();
		return false;
	});

	$('.ModalPopup-close').click(function() {
		$(this).parents('.ModalPopup-outer').fadeOut();
		return false;
	});

	$(document).keydown(function(e) {
		if (e.keyCode === 27) {
			e.stopPropagation();
			$('.ModalPopup-outer').fadeOut();
		}
	});

	$('.ModalPopup-outer').click(function(e) {
		if ($(e.target).closest('.ModalPopup-inner').length == 0) {
			$(this).fadeOut();
		}
	});
});


$(document).ready(function() {
	$('.multiple-items_content_toggle').prev().addClass('hide');

	$('.multiple-items_content_toggle').on('click', function(e) {
		e.preventDefault();

		$(this).prev().toggleClass('hide');

		if ($(this).prev().hasClass('hide')) {
			$(this).text('Читать еще');
		} else {
			$(this).text('Показать меньше');
		}
	});
});

$(document).ready(function() {
	$('.more-items__button').click(function(event) {
		$('.more-items__button').toggleClass('active');
		$('.more-items__item-dedcription').toggleClass('active');
	});
});

$( document ).ready(function(){
	$( ".contact-us-topics__topic-btn" ).click(function() {
		$(".contact-us-topics").toggle();
		$( ".contact-us-form" ).toggle();
		$( ".layout__page-header, .contact-us__description-text" ).toggle();
	});
});

$( document ).ready(function(){
	$( ".contact-us__back-btn" ).click(function() {
		$( ".layout__page-header, .contact-us__description-text" ).toggle();
		$(".contact-us-topics").toggle();
		$( ".contact-us-form" ).toggle();
	});
});

$( document ).ready(function(){
	$(".contact-us-form-new").submit(function() {
		$.ajax({
			type: "POST",
			url: "/contact-us/sendrequest.php/",
			data: $(this).serialize()
		}).done(function() {
			window.location = "/contact-us/contact_thanks.php";
		});
		return false;
	});
});