var translates = [];
var preloader_timeout_ajax;
String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};
var Utils = (function(){
	var isActiveWindow = false;

	return {
		// Проверка на пустоту
		empty: function(mixed_var) {
			var undef, key, i, len;
			var emptyValues = [undef, null, false, 0, '', '0'];
			for (i = 0, len = emptyValues.length; i < len; i++) {
				if (mixed_var === emptyValues[i]) {
					return true;
				}
			}
			if (typeof mixed_var === 'object') {
				for (key in mixed_var) {
					return false;
				}
				return true;
			}
			return false;
		},
		// Оставить только уникальные элементы массива
		uniqueArray: function(A) {
			if (this.empty(A)) return [];
			var n = A.length,
				k = 0,
				B = [];
			for (var i = 0; i < n; i++) {
				var j = 0;
				while (j < k && B[j] !== A[i]) j++;
				if (j == k) B[k++] = A[i];
			}
			return B;
		},
		declOfNum: function(number, titles) {
			var cases = [2, 0, 1, 1, 1, 2];
			return titles[ (number%100>4 && number%100<20)? 2 : cases[(number%10<5)?number%10:5] ];
		},
		declOfNumEn: function(number, titles) {
			return titles[ number == 1 ? 0 : 1 ];
		},
        numberFormat: function( number, decimals, dec_point, thousands_sep ) {
            var i, j, kw, kd, km;

            if( isNaN(decimals = Math.abs(decimals)) ){
                decimals = 2;
            }
            if( dec_point == undefined ){
                dec_point = ",";
            }
            if( thousands_sep == undefined ){
                thousands_sep = ".";
            }

            i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

            if( (j = i.length) > 3 ){
                j = j % 3;
            } else{
                j = 0;
            }

            km = (j ? i.substr(0, j) + thousands_sep : "");
            kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
            kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");

            return km + kw + kd;
        },
        getScrollBarWidth: function () {
            var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
                widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
            $outer.remove();
            return 100 - widthWithScroll;
        },
        getWindowOffset: function () {
            return ($(window).height() ^ 0) + ($(window).scrollTop() ^ 0);
        },
        replaceQueryParam: function(param, newVal, search) {
            var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
            var query = search.replace(regex, "$1").replace(/&$/, '');
            return (query.length > 2 ? query + "&" : "?") + (newVal ? param + "=" + newVal : '');
        },
        debounce: function (func, wait, immediate) {
            var timeout;
            return function () {
                var context = this, args = arguments;
                var later = function () {
                    timeout = null;
                    if (!immediate) func.apply(context, args);
                };
                var callNow = immediate && !timeout;
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
                if (callNow) func.apply(context, args);
            }
        },
        throttle: function (fn, threshold, scope, firstDelay) {
            threshold || (threshold = 250);
            var last = 0,
                deferTimer;
            return function () {

                if (firstDelay && !last) {
                    last = +new Date;
                }

                var context = scope || this;

                var now = +new Date,
                    args = arguments;

                if ((firstDelay || last) && now < last + threshold) {
                    clearTimeout(deferTimer);
                    deferTimer = setTimeout(function () {
                        if (firstDelay) {
                            last = 0;
                        } else {
                            last = now;
                        }
                        fn.apply(context, args);
                    }, threshold);
                } else {
                    last = now;
                    fn.apply(context, args);
                }
            };
        },
        initActiveWindowListener: function() {
	        if(document.hidden !== undefined && !document.hidden){
		        isActiveWindow = true;
            }
            $(window).blur(function(){
                isActiveWindow = false;
            });
            $(window).focus(function(){
                isActiveWindow = true;
            });
        },
        isActiveWindow: function() {
            return isActiveWindow;
        },
			isSafariBrowser: function(){
				return navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1 &&  navigator.userAgent.indexOf('Android') == -1;
			},
			isEmptyObject: function (obj) {
				for (var i in obj) {
					if (obj.hasOwnProperty(i)) {
						return false;
					}
				}
				return true;
			},
        updateQueryString: function(key, value, url) {
            if (!url) url = window.location.href;
            var regExp = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
                hash;

            if (regExp.test(url)) {
                if (typeof value !== 'undefined' && value !== null) {
                    return url.replace(regExp, '$1' + key + "=" + value + '$2$3');
                } else {
                    hash = url.split('#');
                    url = hash[0].replace(regExp, '$1$3').replace(/(&|\?)$/, '');
                    if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                        url += '#' + hash[1];
                    }
                    return url;
                }
            } else {
                if (typeof value !== 'undefined' && value !== null) {
                    var separator = url.indexOf('?') !== -1 ? '&' : '?';
                    hash = url.split('#');
                    url = hash[0] + separator + key + '=' + value;
                    if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                        url += '#' + hash[1];
                    }
                }

                return url;
            }
        },
        priceFormat: function (price, priceItemLang, thousandsDelimiter) {
            if (!priceItemLang) {
                priceItemLang = lang;
            }
            if (thousandsDelimiter === undefined) {
                thousandsDelimiter = " ";
            }
            if (priceItemLang === "ru") {
                return Utils.numberFormat(price, 0, ",", thousandsDelimiter);
            } else {
                if ((price ^ 0) === price) {
                    return Utils.numberFormat(price, 0, ".", thousandsDelimiter);
                } else {
                    return Utils.numberFormat(price, 2, ".", thousandsDelimiter);
                }
            }
        },
        addCurrencySign: function (formattedPrice, priceItemLang, ruSign) {
            if (!priceItemLang) {
                priceItemLang = lang;
            }

            if (ruSign === undefined) {
                ruSign = "руб.";
            }
            if (priceItemLang === "ru") {
                return formattedPrice + " " + ruSign;
            } else {
                return "$" + formattedPrice;
            }
        },
        priceFormatWithSign: function (price, priceItemLang, thousandsDelimiter, ruSign) {
		    var formattedPrice = Utils.priceFormat(price, priceItemLang, thousandsDelimiter);
            return Utils.addCurrencySign(formattedPrice, priceItemLang,  ruSign);
        }
}
})();

Utils.initActiveWindowListener();

var CartModule = (function() {

	var isVisible = false;
	var showCartTimeout;
	var _data = [];
	var preventNextShow = false;

	var _cartUpdate = function(data) {
		if (!Utils.isActiveWindow() || (Utils.isActiveWindow() && data['action'] !== 'item_delete') || !isVisible) {
			$('.cart-popup').replaceWith(data['cart_html']);
			_reInitJsp();
			refreshCartScroll();
		}

		if (preventNextShow) {
			preventNextShow = false;
			return;
		}

		if (Utils.isActiveWindow()) {
			if (data['action'] === 'item_add' || data['action'] === 'no_purse_add') {
				if (isMobile()) {
					var showAlert = typeof data["show_alert"] === undefined;
					if (showAlert) {
						alert(cot_sitename['phrases']['addedincard_fcharup']);
					}
				}
				if (isVisible) {
					_show();
				} else {
					setTimeout(_show, 150);
					showCartTimeout = setTimeout(_hide, 5000);
				}
			}
		}
	};

	var _setEvents = function() {
		$(document).on('mouseenter', '.cart-popup', function() {
			clearTimeout(showCartTimeout);
			_show();
		}).on('mouseleave', '.cart-popup', function() {
			showCartTimeout = setTimeout(_hide, 100);
		});
		if (PULL_MODULE_ENABLE) {
			PullModule.on(PULL_EVENT_UPDATE_CART, _cartUpdate);
		}
		_reInitJsp();
	};

	var _reInitJsp = function() {
		$('.cart-popup .block-popup_body').jScrollPane({
			autoReinitialise: true
		});
	};

	var _show = function() {
		$('.dropdownbox').hide();
		$('.cart-popup').find('.block-popup:not(.not_to_hide)').fadeIn(200, 'swing');
		$('.cart-popup .block-popup_body').jScrollPane();
		update_cart();
		refreshCartScroll();
		$('.cart-popup .cart-popup_icon').addClass('active');
		$('.massage .block-popup:not(.not_to_hide)').hide();
		isVisible = true;
	};

	var _hide = function() {
		$('.cart-popup').find('.block-popup:not(.not_to_hide)').hide();
		$('.cart-popup .cart-popup_icon').removeClass('active');
		isVisible = false;
	};

	var _addItem = function() {
		var form = $('#newextformside');
		$('.abandoned-basket').slideUp(300);
		$.ajax({
			type: "POST",
			url: '/api?method=cart_add',
			data: form.serialize(),
			success: function(data, textStatus, xrf) {
        if(data) {
          data = JSON.parse(data);
          if(data.success) {
            $('#header_cart_morder_ispay').hide(); $('#header_cart_morder').show();
            if(data.item.ciexists == 1) {
              $('.cart-popup .block-popup .block-popup_body_conteiner .cart-popup_row[data-id="' + data.id + '"]').remove();
            }

            var newitem = '<div class="cart-popup_row" data-id="' + data.id + '">' +
                            '<div class="cart-popup__col cart-popup__image"><a role="button"><img src="' + data.item.photo_first + '" width="90" height="60" alt=""></a></div>' +
                            '<div class="cart-popup__col cart-popup__name"><a role="button" class="cart-popup_text">' + data.item.title + '</a></div>' +
                            '<div class="cart-popup__col cart-popup__count">' + data.item.cnt_item + '</div><div class="cart-popup__col cart-popup__extras">' + data.item.cnt_extras + '</div>' +
                            '<div class="cart-popup__col cart-popup__sum"><span class="cart-popup_price_prd-js" data-price="' + data.item.cost + '">' + data.item.cost_format + '</span>&nbsp;<span class="rouble">Р</span></div>' +
                            '<div class="cart-popup__col cart-popup__delete-block">' +
                              '<div class="cart-popup_delete" onclick="CartModule.deleteItem(this, ' + data.id + ');"></div>' +
                            '</div>' +
                          '</div>';

            $('.cart-popup').addClass('active').find('.block-popup .cart-popup_empty_block').hide();
            $('.cart-popup .block-popup .block-popup_body_conteiner').prepend(newitem);
            _show();
          }
        }
      }
		});
	};

	var _deleteItem = function(obj, orderHash) {
		$('.page-basket .cart-popup_row:not(.cart-popup_head)').eq($(obj).closest('.cart-popup_row').index()).remove();
		$('.header .cart-popup_row:not(.cart-popup_head)').eq($(obj).closest('.cart-popup_row').index()).remove();

		if ($('.page-basket .cart-popup_row:not(.cart-popup_head)').length === 0) {
			$('.empty-basket-text-js').show();
			$('.page-basket .cart-popup').remove();
		}
		if ($('.cart-popup .block-popup .cart-popup_row:not(.cart-popup_head)').length === 0) {
			$('.cart-popup').removeClass('active');
		}
		var delData = "orderHash=" + orderHash;
		$.ajax({
			type: "POST",
			url: '/api?method=cart_delete',
			data: delData,
			success: function(data, textStatus, xrf) {
        $('#header_cart_morder_ispay').hide(); $('#header_cart_morder').show();
      }
		});
		refreshCartScroll();
		update_cart();
		$('.abandoned-basket').slideUp(300);
	};

	var _makeOrder = function() {
		$('#cart-form').find('.block-popup:not(.not_to_hide)').hide();
		$.ajax({
			type: "POST",
			url: '/api?method=cart_make',
			success: function(data) {
        $('#header_cart_morder_ispay').hide(); $('#header_cart_morder').show();
				var result = JSON.parse(data);
				if (result.success) {
					$('#cart-form').submit();
				} else if (result.reason === 'purse') {
					show_balance_popup(result.price, 'cart', result.cartid);
				}
			}
		});
	};

	var _preventNextShow = function() {
		preventNextShow = true;
	};

	return {
		init: function() {
			_setEvents();
		},
		addItem: function() {
			_addItem();
		},
		deleteItem: function(obj, orderHash) {
			_deleteItem(obj, orderHash);
		},
		makeOrder: function() {
			_makeOrder();
		},
		hide: function() {
			_hide();
		},
		setShowCartTimeout: function(timeout) {
			showCartTimeout = timeout;
		},
		getShowCartTimeout: function() {
			return showCartTimeout;
		},
		setData: function(field, value) {
			_data[field] = value;
		},
		getData: function(field) {
			return _data[field];
		},
		preventNextShow: function() {
			return _preventNextShow();
		}
	}
})();

$(document).ready(function() {
	CartModule.init();
	anchorInit();
});
/**
 * @module
 */
var Api = (function() {
	var SEND_URL = '/api';

	/**
	 *
	 * @param {String} method
	 * @param {Object} params
	 * @param {Object} callback
	 * @private
	 */
	var _request = function(method, params, callback) {
		$.post(SEND_URL + '?method=' + method, params, function(response) {
			if (response.success !== true) {
				console.error('method ' + method + ' has error', response);
			}

			callback.call(this, response.data);
		}, 'json');
	};

	return {
		request: _request
	}
})();

(function($) {
	$.fn.hasScrollBar = function() {
		return this.get(0) ? this.get(0).scrollHeight > this.innerHeight() : false;
	};
})(jQuery);

(function($) {

	var _measure = function(fn) {
		var $el = $(this).clone(false);
		$el.css({
			visibility: 'hidden',
			position: 'absolute'
		});
		$el.appendTo('body');
		var result = fn.apply($el);
		$el.remove();

		return result;
	};

	var _measure = function(fn) {
		var $el = $(this).clone(false);
		$el.css({
			visibility: 'hidden',
			position: 'absolute'
		});
		$el.appendTo('body');
		//copyComputedStyle(this, $el[0]);
		var result = fn.apply($el);
		$el.remove();

		return result;
	};

	var _setTooltipDimensions = function(tooltip) {
		var $that = $(this);
		if ($that.data('proportion')) {
			_setByProportion($(tooltip), $that.data('proportion'));
		}

		var $tooltip = $(tooltip),
			hPos = $tooltip.data('position'),
			tooltipWidth = _measure.call(tooltip, function() {
				if ($that.data('proportion')) {
					_setByProportion(this, $that.data('proportion'));
				}

				return this.outerWidth();
			}),
			tooltipHeight = _measure.call(tooltip, function() {
				if ($that.data('proportion')) {
					_setByProportion(this, $that.data('proportion'));
				}

				return this.outerHeight();
			}),
			parentCenter = $(this).offset().left + parseInt($(this).css('margin-left')) + $(this).outerWidth() / 2,
			parentRight = $(this).offset().left + parseInt($(this).css('margin-left')) + $(this).outerWidth();

		_setVertical.call(this, $tooltip);
		_setHorizontal.call(this, $tooltip);

		var maxRightPosition = 0,
			tooltipPosition = 0;
		switch (hPos) {
			case 'center':
				maxRightPosition = parentCenter + tooltipWidth / 2 + 50;
				tooltipPosition = parentCenter - tooltipWidth / 2;
				break;
			case 'right':
				maxRightPosition = parentCenter - tooltipWidth + 50;
				tooltipPosition = parentCenter - tooltipWidth + 30;
				break;
			case 'right-fill':
				maxRightPosition = parentRight - tooltipWidth;
				tooltipPosition = parentRight - tooltipWidth;
				break;
			case 'left-fill':
				maxRightPosition = parentCenter + tooltipWidth + 50 + 25;
				tooltipPosition = parentCenter - 25;
				break;
			case 'left':
			default:
				maxRightPosition = parentCenter + tooltipWidth + 50;
				tooltipPosition = parentCenter - 30;

		}

		if (maxRightPosition > $(window).width()) {
			tooltipPosition = $(document).width() - tooltipWidth - 10;
		}

		if (tooltipPosition < 0) {
			tooltipPosition = 0;
		}
		var tooltipLeft = tooltipPosition;
		if ($tooltip.data('aroundPosition') == 'right') {

			if (!$that.data('proportion')) {
				$tooltip.css('width', maxRightPosition - tooltipPosition + 'px');
			}
			var cornerTop = (-tooltipHeight / 2) + 10;
			$tooltip.find('.js-tooltip-block-corner__inner').css({
				'top': cornerTop + 'px'
			});

			tooltipLeft = $tooltip.offset().left;

		} else if ($tooltip.data('aroundPosition') == 'top') {
			var shift = 0;
			$tooltip.parents("*").each(function(i) {
				if ($(this).css('position') == 'relative') {
					shift = $(this).offset().left - 2;
					return false;
				}
			});
			$tooltip.css({
				'left': (tooltipPosition - shift) + 'px'
			});

			var left = parentCenter - tooltipPosition;
			var cornerLeft = left - 30;
			$tooltip.find('.js-tooltip-block-corner__inner').css({
				'left': cornerLeft + 'px'
			});

		} else if ($tooltip.data('aroundPosition') === 'left') {
			if (!$that.data('proportion')) {
				$tooltip.css('width', maxRightPosition - tooltipPosition + 'px');
			}
			var cornerTop = (-tooltipHeight / 2) + 10;
			$tooltip.find('.js-tooltip-block-corner__inner').css({
				'top': cornerTop + 'px'
			});

			tooltipLeft = $tooltip.offset().left;
		} else {
			$tooltip.css({
				'left': (tooltipPosition) + 'px'
			});
			var left = parentCenter - tooltipPosition;
			var cornerLeft = left - 30;
			$tooltip.find('.js-tooltip-block-corner__inner').css({
				'left': cornerLeft + 'px'
			});
		}

		var width = tooltipWidth;
		if (tooltipLeft + tooltipWidth > $(window).width()) {
			width = $(document).width() - tooltipLeft - 10;
		}
		if ($that.data('proportion')) {
			$tooltip.outerWidth(width);
		} else {
			$tooltip.css('width', width + 'px');
		}
	};

	var _setByProportion = function(tooltip, proportion) {
		var baseWidth = tooltip.width();
		var needleProportion;

		if (proportion === true) {
			needleProportion = (4 / 2); //default proportion
		} else {
			proportion = proportion.split(':');
			needleProportion = (proportion[0] / proportion[1]);
		}

		var wTry = baseWidth;
		var step = 10;
		var currentProportion = tooltip.width() / tooltip.height();
		while (currentProportion > needleProportion) {
			wTry -= step;
			tooltip.width(wTry);
			currentProportion = tooltip.width() / tooltip.height();
		}

		var i = 0;
		while (!_canSqueeze(tooltip) && i < 50) {
			wTry += step;
			tooltip.width(wTry);
			i++;
		}

		if (!_canSqueeze(tooltip)) {
			tooltip.find('.js-tooltip-block__text').css({
				'word-break': 'break-all',
				'overflow-x': 'inherit'
			});
		}
	};

	var _canSqueeze = function(tooltip) {
		var $text = tooltip.find('.js-tooltip-block__text');
		$text.css('overflow-x', 'auto');
		return $text[0].scrollWidth <= $text.width();
	};

	var _setVertical = function($tooltip) {
		var $that = $(this);
		var outerHeight = _measure.call($tooltip[0], function() {
				if ($that.data('proportion')) {
					_setByProportion(this, $that.data('proportion'));
				}
				return this.outerHeight();
			}),
			parentOffsetTop = $(this).offset().top,
			scrollTop = $('body').scrollTop();

		var position = {};
		if ($tooltip.data('aroundPosition') == 'right' || $tooltip.data('aroundPosition') == 'left') {
			position.vertical = 'right';
		} else {
			position.vertical = 'top';
		}

		var tooltipTop;
		if (position.vertical == 'top') {
			if (parentOffsetTop - outerHeight < scrollTop) {
				tooltipTop = $(this).position().top + $(this).outerHeight() + 10;
				$tooltip.removeClass('tooltip-block--top').addClass('tooltip-block--bottom');
			} else {
				tooltipTop = $(this).position().top + parseInt($(this).css('margin-top')) - outerHeight - 10;
				$tooltip.css({
					'top': tooltipTop + 'px'
				});
				$tooltip.removeClass('tooltip-block--bottom').addClass('tooltip-block--top');
			}
			$tooltip.css({
				'top': tooltipTop + 'px'
			});
		} else if (position.vertical == 'right') {
			tooltipTop = $(this).position().top + $(this).outerHeight() / 2 - outerHeight / 2;
			$tooltip.css({
				'top': tooltipTop + 'px'
			});
		}
	};

	var _setHorizontal = function($tooltip) {
		var tooltipLeft;
		var remove;
		var add;

		if ($tooltip.data('aroundPosition') == 'top') {} else if ($tooltip.data('aroundPosition') == 'right') {
			tooltipLeft = $(this).position().left + $(this).outerWidth() + 10;
			remove = 'tooltip-block--bottom tooltip-block--top';
			add = 'tooltip-block--right';
		} else if ($tooltip.data('aroundPosition') == 'left') {
			tooltipLeft = $(this).position().left - 10 - $tooltip.outerWidth();
			remove = 'tooltip-block--bottom tooltip-block--top';
			add = 'tooltip-block--left';
		}

		$tooltip.css({
			'left': tooltipLeft + 'px'
		});
		$tooltip.removeClass(remove).addClass(add);
	};

	var _needHide = function(e, block) {
		if (typeof $(block).data('tooltip') !== 'undefined') {
			var $tooltip = $(block).data('tooltip').tooltip;
			return !$(e.relatedTarget).closest('.js-tooltip-block').filter($tooltip).length;
		}

		return $(e.relatedTarget).filter(block).length == 0;
	};

	var methods = {
		init: function(options) {
			return this.each(function() {

				var $this = $(this),
					text = $(this).find('.js-tooltip-text').length ? $(this).find('.js-tooltip-text').html() : $this.data('tooltipText'),
					tooltipClass = $this.data('tooltipClass') ? $this.data('tooltipClass') : '',
					tooltipBlockClass = $this.data('tooltipBlockClass') ? $this.data('tooltipBlockClass') : '',
					tooltipTheme = $this.data('tooltipTheme') ? $this.data('tooltipTheme') : 'light',
					data = $this.data('tooltip'),
					$tooltip = $('<div />', {
						html: '<div class="js-tooltip-block__text ' + tooltipClass + '">' + text + '</div>'
					}).addClass('js-tooltip-block tooltip-block').addClass('tooltip-block_theme_' + tooltipTheme).addClass(tooltipBlockClass);
				var $corner = $('<div>').addClass('tooltip-block__corner')
					.html('<div class="tooltip-block-corner__inner js-tooltip-block-corner__inner">');
				$tooltip.append($corner);

				if ($this.data('tooltipHidden')) return this;

				if (!data) {
					$(this).data('tooltip', {
						target: $this,
						tooltip: $tooltip
					});

					$(this).bind({
						'mouseenter.tooltip': methods.show,
						'mouseleave.tooltip': methods.hide
					});
				}
			});
		},
		destroy: function() {

			return this.each(function() {

				var $this = $(this),
					data = $this.data('tooltip');

				$(window).unbind('.tooltip');
				data.tooltip.remove();
				$this.removeData('tooltip');

			})

		},
		show: function() {
			if ($('.js-tooltip-block').length) return;

			$(this).trigger('beforeshow.tooltip');

			var $tooltip = $(this).data('tooltip').tooltip;
			if ($(this).data('tooltipBlockClass')) {
				$('.' + $(this).data('tooltipBlockClass')).remove();
			}

			$tooltip.show();
			$(this).before($tooltip);
			$tooltip.bind({
				'mouseleave.tooltip': methods.hide
			});
			$tooltip.data('position', typeof $(this).data('tooltipPosition') != 'undefined' ? $(this).data('tooltipPosition') : 'left');
			$tooltip.data('aroundPosition', typeof $(this).data('tooltipAroundPosition') != 'undefined' ? $(this).data('tooltipAroundPosition') : 'top');
			$tooltip.data('animation', typeof $(this).data('tooltipAnimation') != 'undefined' ? $(this).data('tooltipAnimation') : false);
			$tooltip.data('delay', typeof $(this).data('tooltipDelay') != 'undefined' ? $(this).data('tooltipDelay') : false);
			$(this).data('currentTooltip', $tooltip);
			$(this).trigger('show.tooltip');
			_setTooltipDimensions.apply(this, $tooltip);
			$(this).trigger('aftershow.tooltip');

			if ($tooltip.data('animation')) {
				$tooltip.css('opacity', 0);
				$tooltip.animate({
					opacity: 1
				}, 200);
			}
			if ($tooltip.data('delay')) {
				$tooltip.css('opacity', 0);
				$tooltip.delay(parseFloat($tooltip.data('delay')) * 1000).animate({
					opacity: 1
				}, 0);
			}
		},
		get: function() {
			return $(this).data('tooltip').tooltip;
		},
		hide: function(e) {
			if (!_needHide(e, this)) {
				return;
			}

			var $tooltip;
			if ($(this).data('currentTooltip')) {
				$(this).trigger('hide.tooltip');
				$tooltip = $(this).data('currentTooltip');
			} else {
				$(this).next().trigger('hide.tooltip');
				$tooltip = $(this).next().data('currentTooltip');
			}
			$tooltip.data('delayHide', typeof $(this).data('tooltipDelayHide') != 'undefined' ? $(this).data('tooltipDelayHide') : false);
			if ($tooltip.data('animation')) {
				$tooltip.animate({
					opacity: 0
				}, 200, function() {
					$tooltip.removeAttr('style');
					$tooltip.remove();
				});
			} else {
				$tooltip = $tooltip.data('delayHide') ? $tooltip.delay(parseFloat($tooltip.data('delayHide')) * 1000) : $tooltip;
				$tooltip.animate({
					opacity: 0
				}, 10, function() {
					$tooltip.removeAttr('style');
					$tooltip.remove();
				});
			}
		},
		update: function(content) {
			var $tooltip = $($(this).data('currentTooltip'));
			$tooltip.find('.js-tooltip-block__text').html(content);
			_setTooltipDimensions.apply(this, $tooltip);
		},
		setContent: function(content) {
			var $tooltip = $(this).data('tooltip').tooltip;
			$tooltip.find('.js-tooltip-block__text').html(content);
			_setTooltipDimensions.apply(this, $tooltip);
		}
	};

	$.fn.tooltip = function(method) {

		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error(t('Метод с именем {{0}} не существует для jQuery.tooltip', [method]));
		}

	};

})(jQuery);

(function($) {

	var _setPosition = function($preloader) {
		var parentOffsetTop = $(this).offset().top,
			parentOffsetLeft = $(this).offset().left,
			scrollTop = $('body').scrollTop();
		var top, left;

		left = parentOffsetLeft + $(this).outerWidth() / 2;

		if (parentOffsetTop + $(this).height() > scrollTop + $(window).height()) {
			top = scrollTop + $(window).height() - parentOffsetTop;
		} else {
			top = $(this).height();
		}

		top = parentOffsetTop + top / 2;
		$preloader.offset({
			top: top,
			left: left
		});
		$(this).prepend($preloader);
	};

	var _setWhiteBlock = function() {
		var $block = $('<div style="background-color: white; opacity: 0.5;position:absolute">');
		$block.width($(this).width()).height($(this).height());

		$(this).prepend($block);
	};

	var methods = {
		init: function(options) {
			return this.each(function() {});
		},
		show: function() {
			var $this = $(this),
				preloaderClass = $this.data('preloaderClass') ? $this.data('preloaderClass') : '',
				$preloader = $('<div class="preloader__ico" />').addClass(preloaderClass);

			if ($(this).data('preloaderOpacity') == true) {
				_setWhiteBlock.call(this);
			}

			_setPosition.call(this, $preloader);
		}
	};

	$.fn.preloader = function(method) {

		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error(t('Метод с именем {{0}} не существует для jQuery.tooltip', [method]));
		}

	};

})(jQuery);

function DataLayer() {
	this.dataLayer = [];

	this.add = function(item) {
		this.dataLayer.push(item);
	};

	this.get = function() {
		return this.dataLayer;
	};
};
var dL = new DataLayer();

function addRefParam() {
	var params = getGetParams();

	return params['ref'] ? '&ref=' + params['ref'] : '';
}

$(document).ready(function() {
	$('.js-tooltip').tooltip();

	$('.prd_birthday_badge.js-tooltip')
		.mouseover(function() {
			$(this).addClass('prd_birthday_badge_hover');
		})
		.mouseout(function() {
			$(this).removeClass('prd_birthday_badge_hover');
		});

	// Выпадающий список
	$(".droparrow").on('mouseenter', function() {
		var $this = $(this);
		$this.find('.dropdownbox').fadeIn(200, 'swing');
	}).on('mouseleave', function() {
		if ($('.tooltipster-base:hover').length != 0) {
			('.tooltipster-base').addClass('dropdownbox-tooltip');
			return false
		} else {
			var $this = $(this);
			// For tablet view user menu
			if (isMobile() && $this.hasClass('usernamebox')) {
				$this.find('>a').data('clicked', false);
			}
			$this.find('.dropdownbox').hide();
		}
	});

	$(".dropdownbox-tooltip").on('mouseleave', function() {
		if ($('.droparrow:hover').length != 0) {
			return false
		} else {
			var $this = $(".droparrow");
			// For tablet view user menu
			if (isMobile() && $this.hasClass('usernamebox')) {
				$this.find('>a').data('clicked', false);
			}
			$this.find('.dropdownbox').hide();
		}
	});

	// For tablet view user menu
	$(".droparrow.usernamebox > a").click(function(e) {
		var el = $(this);
		if (isMobile() && !el.data('clicked')) {
			el.data('clicked', true);
			e.preventDefault();
		}
	});

	$(".dropdown dt a").click(function() {
		$(this).parent().parent().find("dd ul").toggle();
		return false;
	});
	$(".dropdown dd ul li a").click(function(e) {
		var text = $(this).html();
		$(this).parent().parent().parent().parent().find("dt a span").html(text);
		$(this).parent().parent().parent().parent().find("dd ul").hide();
		//e.preventDefault();
	});

	function getSelectedValue(id) {
		return $("#" + id).find("dt a span.value").html();
	}
	$(document).bind('click', function(e) {
		var $clicked = $(e.target);
		if (!$clicked.parents().hasClass("dropdown"))
			$(".dropdown dd ul").hide();
	});
	var time_show_extras;
	var time_hide_extras;
	$('.order-extras').hide();
	$(".hoverMe").on('mouseenter', function() {
		$('.need-gray').addClass('gray');
		$('.order-extras').addClass('open');
		$('.order-extras').removeClass('close');
	});
	$(".hoverMe").on('mouseleave', function() {
		$('.need-gray').removeClass('gray');
		$('.order-extras').removeClass('open');
		$('.order-extras').addClass('close');
		$('.chosen-container.chosen-container-single.chosen-container-single-nosearch.chosen-container-active').removeClass('chosen-with-drop').removeClass('chosen-container-active');
	});
	$(".order-more-block-btn").on('mouseenter', function() {
		clearTimeout(time_hide_extras);
		time_hide_extras = setTimeout(function() {
			clearTimeout(time_show_extras);
			$('.need-gray').addClass('gray');
			$('.order-extras').addClass('open');
			$('.order-extras').removeClass('close');
		}, 100);
	});
	$(".order-extras-list").on(
		"webkitAnimationEnd oanimationend msAnimationEnd animationend",
		function() {
			if ($(this).height() > 0) {
				$(this).addClass("no-overflow");
			}
		}
	);
	$(".order-more-block-btn").on('mouseleave', function() {
		var that = this;
		time_show_extras = setTimeout(function() {
			clearTimeout(time_hide_extras);
			$('.need-gray').removeClass('gray');
			$('.order-extras').removeClass('open');
			$('.order-extras').addClass('close');
			$(that).find('.order-extras .order-extras-list').removeClass('no-overflow');
			$('.chosen-container.chosen-container-single.chosen-container-single-nosearch.chosen-container-active').removeClass('chosen-with-drop').removeClass('chosen-container-active');
		}, 0);
	});
	$('.contactUser').hide();
	$(".contactPopup").on('click', function() {
		$('.contactUser').fadeIn();
		$('html, body').animate({
			scrollTop: $(".contactUser").offset().top
		}, 800);
		return false;
	});
	$(".reviews-more .show-all-text").on('click', function() {
		$(this).toggleClass('active');
		$(this).parents('.reviews-more_block').find('p').toggleClass('show-all');
	});

  /*
  $('.balance-refill-btn-js').click(function(){
	    $(this).parent().hide();
	    $('.balance-refill-form-js').show();
	});
	$('.withdraw-money-btn-js').click(function() {
		$(this).parent().hide();
		$("#can-withdraw-tooltip").removeClass('hidden');
		$('.withdraw-money-form-js').show();

	});
	$('.hide-form-btn-js').click(function() {
		$("#can-withdraw-tooltip").addClass('hidden');
		$('.balance-refill-form-js').hide();
		$('.withdraw-money-form-js').hide();
		$('.btn-group-js').show();
	});
  */

	$(document).on('keydown paste', '.maxLength-js', function() {
		$(this).val($(this).val().slice(0, $(this).attr('data-max') - 1))
	});


	if ($(".only-number").length > 0) {
		$(".only-number").ForceNumericOnly();
	}
	if ($('.main-slider').length > 0) {
		$('.main-slider').on('init', function() {
			$('.main-block-slider .centerwrap ').fadeIn();
		});
		$('.main-slider').slick({
			centerMode: true,
			variableWidth: true,
			slidesToShow: 1,
			infinite: true
		})
	}

	$('.block-select-options_search-form_close').bind('click', function() {
		$('.block-select-options_search-form').hide();
		$('.block-select-options_btn').show();
	});
	$('.block-select-options_btn_search-active').bind('click', function() {
		$('.block-select-options_search-form').show();
		$('.block-select-options_btn').hide();
	});

	$(document).on('click', '.promo-header-js', function() {
		$('.b-promo-top').toggleClass('active');
		var date = new Date();
		var days = 360;
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		setCookie('show_promo_header', 1, {
			expires: date,
			path: '/'
		});
	});
	$(document).on('click', '.hide-btn-promo-js', function() {
		var date = new Date();
		var days = 360;
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		setCookie('show_promo_header', 0, {
			expires: date,
			path: '/'
		});
	});

	$(document).on('hover', '.select-user-type-js', function() {
		if ($(this).hasClass('select-user-type_customer')) {
			$('.user-menu-payer').show();
			$('.user-menu-worker').hide();
		} else {
			$('.user-menu-payer').hide();
			$('.user-menu-worker').show();
		}
	});
	var userType = ($('[name=userType]#1').prop('checked')) ? 1 : 2;
	var changeUserTypeTimeout = false;
	var selectedUserType = false;
	$(document).on('mouseenter', '.select-user-type-js', function() {
		if ($(this).hasClass('select-user-type_customer')) {
			changeUserTypeTimeout = setTimeout(function() {
				$('.user-menu-payer').show();
				$('.user-menu-worker').hide();
				$('[name=userType]#1').prop('checked', true);
				selectedUserType = 1;
				changeUserTypeTimeout = false;
			}, 200);
		} else {
			changeUserTypeTimeout = setTimeout(function() {
				$('.user-menu-payer').hide();
				$('.user-menu-worker').show();
				$('[name=userType]#2').prop('checked', true);
				selectedUserType = 2;
				changeUserTypeTimeout = false;
			}, 200);
		}
	});
	$('.select-user-type-js').on('mouseleave', function() {
		clearTimeout(changeUserTypeTimeout);
		changeUserTypeTimeout = false;
	});
	$('.dropdownbox-profile li').on('click', function() {
		if (selectedUserType) {
			changeUserType(selectedUserType, false);
		}
	});
	$('.dropdownbox-profile').hover(function() {}, function() {
		if (selectedUserType && userType == 2) {
			$('.user-menu-payer').hide();
			$('.user-menu-worker').show();
			$('[name=userType]#2').prop('checked', true);
		} else {
			if (selectedUserType && userType == 1) {
				$('.user-menu-payer').show();
				$('.user-menu-worker').hide();
				$('[name=userType]#1').prop('checked', true);
			}
		}
		selectedUserType = userType;
	});
	// блокировка формы после сабмита
	$(document).on('submit', 'form:not(.ajax-disabling)', function() {
		$(this).find(':submit').attr('disabled', 'disabled').addClass('sleep1000');
		setTimeout(function() {
			$('.sleep1000').removeAttr('disabled').removeClass('sleep1000');
		}, 1000);
	});

	if ($('textarea[data-autoresize]').length > 0) {
		$.each($('textarea[data-autoresize]'), function() {
			var offset = this.offsetHeight - this.clientHeight;

			var resizeTextarea = function(el) {
				$(el).css('height', 'auto').css('height', el.scrollHeight + offset);
			};
			$(this).on('keyup input', function() {
				resizeTextarea(this);
			}).removeAttr('data-autoresize');
		});
	}

	$(window).scroll(function() {
		$('.header').css("margin-left", -$(window).scrollLeft())
		if ($(this).scrollTop() > 100) {
			$('.scrollup').fadeIn();
		} else {
			$('.scrollup').fadeOut();
		}
	});

	$('.scrollup').click(function() {
		$("html, body").animate({
			scrollTop: 0
		}, 400);
		return false;
	});
});

function toggleBalanceRefillPopup() {
	$('.dropdownbox-balance').toggle();
}


(function($) {
	var _options = {
		textLinkShow: 'подсказку'
	};
	var methods = {
		init: function(options) {
			if (options) {
				_options = options;
			}
			return this.each(function() {
				var $infoBlock = $(this);
				var infoType = $infoBlock.data('type');

				$(this).find('.js-info-block__link').bind('click.infoBlock', function() {
					if ($infoBlock.data('hiddenBlock') != true) {
						$infoBlock.infoBlock('hide');
					} else {
						$infoBlock.infoBlock('show');
					}
				});

				$infoBlock.find('.info-block__text:not(".disable-height")').css('height', $infoBlock.find('.info-block__text').height());
				if (localStorage.getItem(infoType + ':info-block--hidden') == 1) {
					$infoBlock.infoBlock('hide');
				}

				$infoBlock.css('opacity', '1');

				setTimeout(function() {
					$infoBlock.addClass('info-block_animation');
          $infoBlock.show();
				}, 400);
			});
		},
		destroy: function() {
			return this.each(function() {
				$(window).unbind('.infoBlock');
			})

		},
		show: function() {
      var typeTitle = (($(this).data('typetitle') != undefined) ? $(this).data('typetitle') : _options.textLinkShow);
			$(this).data('hiddenBlock', false);
			$(this).find('.js-info-block__link').text('Скрыть ' + typeTitle);
			$(this).removeClass('info-block_rolled');
			localStorage.setItem($(this).data('type') + ':info-block--hidden', 0);
			$(this).trigger('show.infoBlock');
		},

		hide: function() {
      var typeTitle = (($(this).data('typetitle') != undefined) ? $(this).data('typetitle') : _options.textLinkShow);
			$(this).data('hiddenBlock', true);
			$(this).find('.js-info-block__link').text('Показать '+ typeTitle);
			$(this).find('.info-block__ico-image');
			$(this).addClass('info-block_rolled');
			localStorage.setItem($(this).data('type') + ':info-block--hidden', 1);
			$(this).trigger('hide.infoBlock');
		}
	};

	$.fn.infoBlock = function(method, options) {

		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, [options]);
		} else {
			$.error(t('Метод с именем {{0}} не существует для jQuery.infoBlock', [method]));
		}

	};

})(jQuery);

$(document).on('touchstart', '.nav-fox', function(e) {
	if (e.target != this) return;
	mobile_menu_hide();
});

function mobile_menu_toggle() {
	var $nav = $('#foxmobilenav');

	$('html').addClass('show-mobile-menu');
	$('.foxmenubutton').css({
		visibility: 'hidden'
	});
	$('body').css({
		overflow: 'hidden'
	});
	$nav.show();
	// $('.all_page').css({position:'relative'})
	setTimeout(function() {
		$('.mobile-menu-hide').css({
			left: '82%'
		}).fadeIn();

	}, 100);
	$('.fox-dotcom-mobile-dropdown').animate({
		left: '0px'
	}, 300);
}

function mobile_menu_hide() {
	$('html').removeClass('show-mobile-menu')
	$('.foxmenubutton').removeAttr('style');
	$('.mobile-menu-hide').hide();
	$('.fox-dotcom-mobile-dropdown').animate({
		left: '-220px'
	}, 300)
	$('.mobile-menu-hide').animate({
		left: '0'
	}, 300);
	$('.header').animate({
		left: '0px'
	}, 300, function() {
		$('.all_page').css({
			position: 'static'
		})
		$('#foxmobilenav').hide();
		$('body').css({
			overflow: 'visible'
		});
	})
}

$.fn.ForceNumericOnly =
	function() {
		return this.each(function() {
			$(this).keydown(function(e) {
				var key = e.charCode || e.keyCode || 0;
				return (
					key == 8 ||
					key == 9 ||
					key == 13 ||
					key == 46 ||
					(key >= 37 && key <= 40) ||
					(key >= 48 && key <= 57) ||
					(key >= 96 && key <= 105));
			});
		});
	};

function setCookie(name, value, options) {
	options = options || {};

	var expires = options.expires;

	if (typeof expires == "number" && expires) {
		var d = new Date();
		d.setTime(d.getTime() + expires * 1000);
		expires = options.expires = d;
	}
	if (expires && expires.toUTCString) {
		options.expires = expires.toUTCString();
	}

	value = encodeURIComponent(value);

	var updatedCookie = name + "=" + value;

	for (var propName in options) {
		updatedCookie += "; " + propName;
		var propValue = options[propName];
		if (propValue !== true) {
			updatedCookie += "=" + propValue;
		}
	}

	document.cookie = updatedCookie;
}


var deleteCookie = function(name) {
	document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};


// возвращает cookie с именем name, если есть, если нет, то undefined
function getCookie(name) {
	var matches = document.cookie.match(new RegExp(
		"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
	));
	return matches ? decodeURIComponent(matches[1]) : undefined;
}

function show_balance_popup(amount, from, payment_id) {
	/*Показываем попап пополнения баланса*/
	var amountBlock = '';
	if (typeof(amount) !== 'undefined') {
		amountBlock = 'value="' + amount + '"';
	}
	var fromBlock = '';
	if (typeof(from) !== 'undefined') {
		fromBlock = '<input name="from_type" value="' + from + '" type="hidden" />';
	}
	var paymentIdBlock = '';
	var balanceSwitchToCheck = '';
	if (typeof(payment_id) !== 'undefined') {
		paymentIdBlock = '<input id="payment_id" name="payment_id" value="' + payment_id + '" type="hidden" />';
		balanceSwitchToCheck = 'return balance_popup_switch_to_check(this);';
	}
	var bankLabel = 'Банковские карты';
	var billOption = '';
	var paymentHeader = "<i class=\"icon ico-mastercardVisa\"></i>";
	if (actor_lang == 'ru') {
		paymentHeader = "<div class=\"balance-popup__table-title\">Способ</div>";
	}
	var methods = "Credit & Debit Cards <input type=\"hidden\" value=\"card\" name=\"pay_type\"/>";

		methods = '<select name="pay_type" class="js-balance-popup-select balance-popup__input text styled-input font-OpenSans f14 w240">';

    for(bi = 0; bi < BILL_ARRAY.length; bi++) {
       if(BILL_ARRAY[bi].extra.length > 0) {
         for(bie = 0; bie < BILL_ARRAY[bi].extra.length; bie++) {
           methods += '<optgroup label="' + BILL_ARRAY[bi].extra[bie].title + '">';

           for(biet = 0; biet < BILL_ARRAY[bi].extra[bie].variants.length; biet++) {
              if(BILL_ARRAY[bi].extra[bie].variants[biet].active) methods += '<option value="' + BILL_ARRAY[bi].code + '_' + BILL_ARRAY[bi].extra[bie].variants[biet].code + '">' + BILL_ARRAY[bi].extra[bie].variants[biet].title + '</option>';
           }
         }
         methods += '</optgroup>'
       } else {
         methods += '<option value="' + BILL_ARRAY[bi].code + '">' + BILL_ARRAY[bi].title + '</option>';
       }
    }
		methods += '</select>';

	var content = '' +
		'<h1 class="popup__title">Пополнение баланса</h1>' +
		'<hr class="gray mt20 balance-popup__line">' +
		'<div class="balance-popup__description">' +
		'Пополняйте с запасом, чтобы<br>всегда заказывать в один клик' +
		'</div>' +
		'<div class="balance-refill-form-js" id="foxForm">' +
		'<form id="popup_balance_refill_form" class="js-popup-balance__form m-text-center" method="get" action="/billing">' +
		'<div id="balance_popup_content">' +
		'<table>' +
		'<tr style="height: 40px;">' +
		'<td class="w19p">' +
		paymentHeader +
		'</td>' +
		'<td width="310">' +
		methods +
		'</td>' +
		'</tr>' +
		'<tr style="height: 40px;">' +
		'<td class="w19p"><div class="balance-popup__table-title">Сумма</div></td>' +
		'<td>' +
		'<input name="action_type" value="refill" type="hidden" />' +
		fromBlock +
		paymentIdBlock +
		'<input name="sum" class="balance-popup__input text styled-input only-number js-balance-popup_input" ' + amountBlock + ' placeholder="Введите сумму" required>' +
		'</td>' +
		'</tr>' +
		'<tr class="bill_result_popup_block hidden" style="height: 40px;">' +
		'<td class="w19p"><div class="balance-popup__table-title">Итого</div></td>' +
		'<td class="bill_result_popup_amount"></td>' +
		'</tr>' +
		'</table>' +
		'<div class="js-popup-balance__notice hidden color-gray f12 mt10 mb10">' + t('Пополнение по безналичному переводу возможно на сумму не менее 10 000 руб. Комиссия при пополнении счета через банк составляет {{0}}%.', [BILL_COMISSION]) + '</div>' +
		'<div class="balance_refill_wait_block" style="display: none;">' +
		'<div>Ожидание подтверждения платежной системы...</div>' +
		'<div style="height: 50px;position:relative;"><div class="preloader__ico preloader__ico_small" style="top: 5px; left: 189px;"></div></div>' +
		'</div>' +
		'</div>' +
		"<input type=\"submit\" class=\"js-popup-balance__submit popup-balance__submit hugeGreenBtn GreenBtnStyle h50 pull-reset wMax v-align-m\" value=\"Пополнить баланс\">" +
		'</form>' +
		'</div>';
	show_popup(content, 'balance-popup');
	$(".only-number").ForceNumericOnly();
  /*
	$('.js-balance-popup-select').on('change', function() {
		if ($(this).val() == 'bank') {
			$('.js-popup-balance__submit').val('Выписать счет').data('block-check', 1);
			$('.js-popup-balance__form').attr('action', '/bill_get');
			$('.js-popup-balance__notice').removeClass('hidden');
			$('.balance-popup__input').addClass('js-min').data('min-value', 10000);
			$('.bill_result_popup_amount').text(t('{{0}} руб.', [getBillAmount($(".js-popup-balance__form input[name='sum']").val())]));
			$('.bill_result_popup_block').removeClass('hidden');
		} else {
			$('.js-popup-balance__submit').val('Пополнить баланс').data('block-check', 0);
			$('.js-popup-balance__form').attr('action', '/balance');
			$('.js-popup-balance__notice').addClass('hidden');
			$('.balance-popup__input').removeClass('js-min');
			$('.bill_result_popup_block').addClass('hidden');
		}
	});
  */
}

function show_balance_dodji_popup(amount, from, payment_id) {
	/*Показываем попап пополнения баланса*/

	var content = '' +
		'<h1 class="popup__title">Недостаточно средств</h1>' +
		'<hr class="gray mt20 balance-popup__line">' +
		'<div class="balance-popup__description">' +
		  'Для оплаты нехватает ' + amount + '&nbsp;<span class="rouble rouble-dodji"></span>'
		'</div>';
	show_popup(content, 'balance-dodji-popup');
}

function showBillFormPopup(sum) {
	$('.popup').remove();
	$.ajax({
		url: '/api?method=Bill.api_getForm',
		type: 'post',
		data: {
			'sum': sum
		},
		dataType: 'json',
		success: function(response) {
			if (response.result === 'success') {
				show_popup(response.html, 'bill-form-popup', '', '', true);
				billFormSetEvents();
			}
		}
	});
}

$(document).on('keyup paste blur', '.js-balance-popup_input', function() {
	$('.bill_result_popup_amount').text(t('{{0}} руб.', [getBillAmount($(this).val())]));
});

$(document).on('submit', 'form', function(e) {
	var proceed = true;
	if ($(this).find('input.js-min').length > 0) {
		$(this).find('input.js-min').each(function() {
			if ($(this).val() < $(this).data('min-value')) {
				$(this).addClass('min-value-error');
				e.preventDefault();
				proceed = false;
				return false;
			} else {
				$(this).removeClass('min-value-error');
			}
		});
	}
	if (!proceed) {
		return false;
	}
	if ($(this).attr('id') === 'popup_balance_refill_form') {
		if ($(this).find('.js-balance-popup-select').val() === 'bank') {
			if (isNotMobile()) {
				showBillFormPopup($(this).find("input[name='sum']").val());
				e.preventDefault();
				return false;
			}
		}
	}
});

var recentFormToSubmit = false;
var balancePopupInterval = false;
var balanceRefillWindow = false;

function balance_popup_switch_to_check(submitButton) {
	if ($(submitButton).data('block-check') == 1) {
		return true;
	}
	var formData = $("#popup_balance_refill_form").clone();
	var selectedType = $("#popup_balance_refill_form").find('.js-balance-popup-select').val();
	$(formData).hide();
	$("#balance_popup_content table").hide();
	$(submitButton).hide();
	$("#balance_popup_content .balance_refill_wait_block").show();

	clearInterval(balancePopupInterval);
	balancePopupInterval = setInterval(function() {
		var paymentId = $("#balance_popup_content table #payment_id").val();
		if (paymentId) {
			check_balance_payment_payed(paymentId);
		} else {
			clearInterval(balancePopupInterval);
		}
	}, 10000);

	balanceRefillWindow = window.open();
	$(balanceRefillWindow.document.body).append('<div>Перенаправление на страницу платежной системы...</div>');
	$(formData).find('.js-balance-popup-select').val(selectedType);
	$(balanceRefillWindow.document.body).append(formData);
	$(balanceRefillWindow.document.body).find("#popup_balance_refill_form").submit();
	return false;
}

function check_balance_payment_payed(paymentId) {
	$.ajax({
		url: '/api?method=User.api_isPaymentPayed',
		type: 'post',
		data: {
			'payment_id': paymentId
		},
		dataType: 'json',
		success: function(response) {
			if (response.result == 'success') {
				balanceRefillWindow.close();
				$(recentFormToSubmit).submit();
				clearInterval(balancePopupInterval);
			}
		}
	});
}

$(document).on('click', '.login-js', function(e) {
	e.preventDefault();
	if ($(this).parents('form').attr('data-submit-post') === 'true') {
		show_login(true);
	} else {
		show_login();
	}

})

function get_login_html(actionAfter, defaultEmail, isIndexPage) {
	var actionAfterBlock = '';
	if (typeof(actionAfter) !== 'undefined' && actionAfter != '') {
		actionAfterBlock = '<input type="hidden" name="action_after" value="' + actionAfter + ' ">';
		onclickBlock = 'onclick="show_signup(\'' + actionAfter + '\'); return false;"';
	} else {
		onclickBlock = 'onclick="show_signup(); return false;"';
	}
	if (isIndexPage == 1) {
		onclickBlock = 'onclick="showSignUpForm(); return false;"';
	}
	var actionUrlBlock = '';
	if (IS_MIRROR) {
		if (CANONICAL_ORIGIN_URL != ORIGIN_URL && CANONICAL_ORIGIN_URL != (ORIGIN_URL + '/login') && CANONICAL_ORIGIN_URL != (ORIGIN_URL + '/signup')) {
			actionUrlBlock = 'action="' + CANONICAL_ORIGIN_URL + '"';
		} else {
			actionUrlBlock = 'action="' + ORIGIN_URL + '"';
		}
	}
	var socialLogin = "<a href=\"" + ORIGIN_URL + "/hybridauth?a=login&provider=Facebook\" class=\"fb  pull-right\" title=\"Войти через Facebook\"><span>Facebook</span></a>" +
			"<a href=\"" + ORIGIN_URL + "/hybridauth?a=login&provider=Vkontakte\" class=\"vk\" title=\"Войти через Вконтакте\"><span>ВКонтакте</span></a>";
	var captchaBlock = '';
	var html = '<h1 class="popup__title">Вход</h1>' +
		'<hr class="gray mt15 mb15"">' +
		'<div id="foxForm">' +
		'<form id="form-login" ' + actionUrlBlock + '>' +
		actionAfterBlock +
		'<div class="popup-form-container-step1">' +
		'<div>' +
		'<div class="form-entry">' +
		'<input ' + (typeof defaultEmail == 'string' ? ' value="' + defaultEmail + '" ' : '') + 'class="text styled-input wMax h40 lh40 f15 noInvalidOutline" placeholder="Электронная почта или логин" id="l_username" name="l_username" tabindex="1" type="email" >' +
		'</div>' +
		'<div class="form-entry">' +
		'<input class="text styled-input wMax f15 h40 lh40" id="l_password" placeholder="Пароль" name="l_password" size="30" tabindex="2" type="password" />' +
		'</div>' +
		captchaBlock +
		'<div class="recaptcha_holder"></div>' +
		'<div class="form-entry">' +
		'<button class="green-btn mt0 h45 popup__button" formnovalidate>Войти</button><br>' +
		'<div class=" color-orange font-OpenSans f14 form-entry-error mt10"></div>' +
		'</div>' +
		'</div>' +
		'<div class="clearfix">' +
		'<a href="/passrecover" class="dib f14 font-OpenSans color-text underline pull-right" style="line-height:24px;">Забыли пароль?</a>' +
		'<div class="pull-left options">' +
		'<input class="checkbox dib" id="l_remember_me" name="l_remember_me" type="checkbox" value="1" checked />' +
		'<label class="f14 font-OpenSans mb0" for="l_remember_me">Запомнить меня</label>' +
		'</div>' +
		'</div>' +
		'<div class="form-entry-middle-popup font-OpenSans t-align-c mb5"><span>или</span></div>' +
		'<div class="t-align-c s-btn clearfix">' +
		socialLogin +
		'</div>' +
		'</div>' +
		'<div class="popup-footer">' +
		'<span class=" color-gray">Не зарегистрированы? </span>' +
		'<a class="color-text underline f14" style="cursor:pointer;" ' + onclickBlock + '>Зарегистрироваться</a>' +
		'</div>' +
		'<div class="clear"></div>' +
		'</form>' +
		'</div>';
	return html;
}

function show_login(actionAfter, successCallback, defaultEmail) {
	var html = get_login_html(actionAfter, defaultEmail);
	show_popup(html, 'popup-login_content', '', 'popup-login');

	$('#l_username').trigger('focus');
	if (typeof successCallback == 'function') {
		$('#form-login').data('successCallback', successCallback);
	}
}

function get_signup_html(actionAfter, isWorker, isIndexPage) {
	var actionAfterBlock = '';
	if (typeof(actionAfter) !== 'undefined' && actionAfter != '') {
		actionAfterBlock = '<input type="hidden" name="action_after" value="' + actionAfter + '">';
		onclickBlock = 'onclick="show_login(\'' + actionAfter + '\'); return false;"';
	} else {
		onclickBlock = 'onclick="show_login(); return false;"';
	}
	if (isIndexPage == 1) {
		onclickBlock = 'onclick="showAuthForm(); return false;"';
	}
	var actionUrlBlock = '';
	if (IS_MIRROR) {
		if (CANONICAL_ORIGIN_URL != ORIGIN_URL) {
			actionUrlBlock = 'action="' + CANONICAL_ORIGIN_URL + '"';
		} else {
			actionUrlBlock = 'action="' + ORIGIN_URL + '"';
		}
	}

	var captchaBlock = '';
	var socialLogin = "<a href='" + ORIGIN_URL + "/hybridauth?a=login&provider=Facebook&usertype=" + (isWorker ? '2' : '1') + "' data-sochref=\"" + ORIGIN_URL + "/hybridauth?a=login&provider=Facebook&usertype=\" class='fb pull-right' title=\'Войти через Facebook\'><span>Facebook</span></a>" +
			"<a href='" + ORIGIN_URL + "/hybridauth?a=login&provider=Vkontakte&usertype=" + (isWorker ? '2' : '1') + "' data-sochref=\"" + ORIGIN_URL + "/hybridauth?a=login&provider=Vkontakte&usertype=\" class='vk' title=\'Войти через Вконтакте\'><span>ВКонтакте</span></a>";

	var html = '<div class=" m-center-block m-text-center">' +
		'<h1 class="popup__title">Регистрация</h1>' +
		'<hr class="gray mt15 mb15"">' +
		'</div>' +
		'<form method="post" id="form-signup" ' + actionUrlBlock + '>' +
		actionAfterBlock +
		'<div class="popup-form-container-step1">' +
		'<div class=" select-user-type mb20 clearfix signup-step-1-js mt17">' +
		'<div class="dib pull-right"><input name="userType" type="radio" onclick="$(\'[data-sochref]\').each(function(){$(this).attr(\'href\', $(this).attr(\'data-sochref\') + \'2\')});" id="2" value="2" class="worker" ' + (isWorker ? 'checked' : '') + '/><label for="2">Исполнитель</label></div>' +
		'<div class="dib"><input name="userType" type="radio" onclick="$(\'[data-sochref]\').each(function(){$(this).attr(\'href\', $(this).attr(\'data-sochref\') + \'1\')});" id="1" value="1" class="payer" ' + (isWorker ? '' : 'checked') + ' /><label for="1">Заказчик</label></div>' +
		'</div>' +
		'<div>' +
		'<div id="foxForm">' +
		'<div class="form-entry signup-step-1-js" >' +
		'<input class="text styled-input wMax f15 h40 lh40" id="user_email" placeholder="Электронная почта" name="user_email" size="30" type="email" required />' +
		'</div>' +
		'<div class="form-entry signup-step-2-js" style="display:none;">' +
		'<input class="text h40 lh40 styled-input wMax f15" placeholder="Ваш логин (будет виден всем)" maxlength="20" name="user_username" size="15" type="text" required />' +
		'</div>' +
		'<div class="form-entry signup-step-2-js" style="display:none;">' +
		'<input class="text h40 lh40 styled-input wMax f15" placeholder="Пароль" id="user_password" name="user_password" size="30" type="password" autocomplete="off" required/>' +
		'</div>' +
		'<div class="form-entry signup-promo-field" style="display:none;">' +
		'<input class="text h40 lh40 styled-input wMax f15" placeholder="Введите промокод" id="user_promo" name="user_promo" size="30" type="text" autocomplete="off"/>' +
		'</div>' +
		captchaBlock +
		'<div class="form-entry mb0">' +
		'<button type="button" class="mt0 green-btn popup__button h45 next-signup-js signup-step-1-js">Далее</button>' +
		'<a class="mt10 mb15 signup-step-2-js signup-promo-placeholder signup-promo-placeholder-js" style="display:none;">У меня есть промокод</a>' +
		'<input type="submit" value="Зарегистрироваться" class="green-btn popup__button_reg h45 signup-step-2-js"  style="display:none;"/>' +
		'<br class="m-visible">' +
		'<div class="color-orange font-OpenSans f14 form-entry-error mt10"></div>' +
		'<input type="hidden" name="jsub" id="jsub" value="1" />' +
		'</div>' +
		'</div>' +
		'<div class="form-entry-middle-popup font-OpenSans t-align-c signup-step-1-js mt35 mb5"><span>или</span></div>' +
		'<div class="t-align-c s-btn clearfix signup-step-1-js">' +
		socialLogin +
		'</div>' +
		'</div>' +
		'</div>' +
		'<div class="popup-footer signup-step-1-js">' +
		'<span class=" color-gray">Уже зарегистрированы? </span>' +
		'<a class="color-text underline" ' + onclickBlock + ' style="cursor:pointer;">Войти</a>' +
		'</div>' +
		'<div class="popup-footer signup-step-2-js"  style="display:none;">' +
		'Регистрируясь, вы принимаете <a href="/rules" target="_blank" class="color-text underline">Правила сайта</a> и <a href="/system/16" target="_blank" class="color-text underline">Договор-оферту</a>' +
		'</div>' +
		'<div class="clear"></div>' +
		'</form>';
	return html;
}

function show_signup(actionAfter, isWorker) {
	var html = get_signup_html(actionAfter, isWorker);

	show_popup(html, 'popup-signup_content', '', 'popup-signup');
}

var genInputId = new IDGenerator('_id');
var formData = new FormData;

function showNameFilesPopup(obj) {
	haveFiles = true;
	if (obj.files && obj.files[0]) {
		var counter = $(".file-item", "#list-files_popup").size();
		var cnt = Object.keys(obj.files).length;
		// В safari Object.keys(obj.files) добавляет в конец массива 'length'
		{
			if (Object.keys(obj.files)[cnt - 1] == 'length') {
				cnt--;
			}
		}
		for (var i = 0; i < cnt; i++) {
			if (!(counter + i + 1 <= 10)) {
				alert('Превышено максимальное количество файлов.');
				obj.value = '';
				return false;
			}
			if (obj.files[i].size > 4194304) {
				alert('Размер файла не должен превышать 4Mb');
				obj.value = '';
				return false;
			}
		}
		for (var i = 0; i < cnt; i++) {
			var fileName = obj.files[i].name;
			var size = obj.files[i].size;
			var len = fileName.length;
			var symb3 = fileName.substr(len - 3, len).toLowerCase();
			var symb4 = fileName.substr(len - 4, len).toLowerCase();
			var ico = '';
			var allow = true;
			if ($.inArray(symb3, ['doc', 'xls', 'rtf', 'txt']) != -1 || $.inArray(symb4, ['docx', 'xlsx']) != -1) {
				ico = 'doc';
			} else if ($.inArray(symb3, ['zip', 'rar']) != -1) {
				ico = 'zip';
			} else if ($.inArray(symb3, ['png', 'jpg', 'gif', 'psd']) != -1 || $.inArray(symb4, ['jpeg']) != -1) {
				ico = 'image';
			} else if ($.inArray(symb3, ['mp3', 'wav', 'avi']) != -1) {
				ico = 'audio';
			} else if ($.inArray(symb3, ["exe", "com", "dll", "sys", "drv", "bin", "ovl", "ovy", "dot"]) != -1) {
				ico = 'zip';
				allow = false;
			} else {
				ico = 'zip';
			}
			var id = genInputId.getID();
			obj.id = 'fileInputPopup' + id;
			obj.className = 'fileInputs';
			var rightText = "";
			if (allow) {
				rightText = "<a class='remove-file-link' onclick=\"delNameFilesPopup('" + id + "')\"></a>";
			} else {
				rightText = "<a class='ml10 cur color-red' style='display:block;float:right;' onclick=\"delNameFiles('" + id + "')\">Тип файла не поддерживается</a>";
			}
			html = "<div class='mb5 file-item' id='fileNamePopup" + id + "'><i class='ico-file-" + ico + " dib v-align-m'></i><span class='dib v-align-m ml10 " + (allow ? "" : " color-red") + "'>" + fileName + "</span>" + rightText + "</div>";
			$("#list-files_popup").append(html);
			html = "<input id='fileInputPopup" + id + "' type='hidden' name='inputName_" + id + "' value ='sizeFile" + fileName + size + "'>";
			$("#list-files_popup").append(html);
			formData.append('fileInputPopup[]', obj.files[i]);
		}
		$(obj).after('<input onchange="showNameFilesPopup(this)" name="fileInputPopup[]" type="file" multiple/>');
		$(obj).hide();
	}
}

function delNameFilesPopup(id) {
	$('#fileNamePopup' + id).remove();
	$('#fileInputPopup' + id).remove();
}

$(document).on('click', '.short-login-js', function(e) {
	e.preventDefault();
	show_login();
});

$(document).on('click', '.signup-js', function(e) {
	e.preventDefault();
	var isWorker = $(this).is('.worker');
	show_signup('', isWorker);
});
$(document).on('click', '.next-signup-js', function() {
	var email = $(this).parents('form').find('#user_email').val();
	var target = $(this);
	if (email.length > 0 && validateEmail(email)) {
		$.ajax({
			type: "POST",
			url: '/api?method=register',
      data: 'user_email=' + email,
			dataType: 'json',
			success: function(data, textStatus, xrf) {
				if (data.success) {
					target.parents('form').find('.form-entry-error').text('');
					target.parents('form')
						.find('.popup-form-container-step1')
						.removeClass('popup-form-container-step1')
						.addClass('popup-form-container-step2');
					$('.signup-step-1-js').hide();
					$('.signup-step-2-js').show();
				} else {
					if (data.in_stop_list) {
						console.log(1);
						target.parents('form').find('.form-entry-error').text('Извините, данный адрес почты занесен в стоп-список. Регистрация с ним невозможна.');
						return false;
					} else if (data.user_exists) {
						show_login();
						$('#l_username').val(email);
						$('#l_password').focus();
					} else if (data.error != '') {
						target.parents('form').find('.form-entry-error').text(data.error);
						return false;
					} else {
						target.parents('form').find('.form-entry-error').text('Введите email');
						return false;
					}
				}
			}
		});
	} else {
		$(this).parents('form').find('.form-entry-error').text('Введите email');
		return false;
	}
});

$(document).on('submit', '#form-login', function(e) {
	e.preventDefault();
	var form = $(this);
	$.ajax({
		type: "POST",
		url: '/api?method=login',
		data: form.serialize(),
		success: function(data) {
			if (JSON.parse(data).success) {

				if (typeof form.data('successCallback') == 'function') {
					form.data('successCallback').call(this, data);
				} else {
					var result = JSON.parse(data);
					if (result.redirect != '') {
						window.location.href = result.redirect;
					} else {
						window.location.reload();
					}
				}
			} else {
				form.find('.form-entry-error').text(JSON.parse(data).error);
			}
		}
	});
});

var semaforUserSignup = false;
var resetSemaforUserSignup = false;

function doUserSignup(form) {
	semaforUserSignup = true;
	resetSemaforUserSignup = setTimeout(function() {
		semaforUserSignup = false;
	}, 10000);

	$.ajax({
		type: "POST",
		url: '/api?method=register&a=step2',
		data: form.serialize(),
		success: function(data, textStatus, xrf) {
			semaforUserSignup = false;
			clearTimeout(resetSemaforUserSignup);
			var result = JSON.parse(data);
			console.log(result);
			if (result.success) {
				if (result.redirect != '') {
					window.location.href = result.redirect;
				} else {
					window.location.reload();
				}
			} else {
				form.find('.form-entry-error').text(JSON.parse(data).error);
			}
		}
	});
}

$(document).on('submit', '#form-signup', function(e) {
	var form = $(this);
	e.preventDefault();
	if (semaforUserSignup === false) {
		doUserSignup(form);
	}
});
$(document).on('submit', '#newextformside', function(e) {
	var form = $(this);
	e.preventDefault();
	$.ajax({
		type: "POST",
		url: '/api?method=cart_order',
		data: form.serialize(),
		success: function(data, textStatus, xrf) {
      $('#header_cart_morder_ispay').hide(); $('#header_cart_morder').show();
			var result = JSON.parse(data);
			if (result.success) {
				window.location.replace(result.redirect);
				return true;
			} else {
				if (result.error == 'purse') {
					location.replace(result.redirect);
					return true;
				} else if (result.error == 'paused_prd') {
					show_message('notice', t(cot_sitename['phrases']['paused_fcharup'] + ', поскольку очередь к нему достигла {{0}} заказов. ' + cot_sitename['phrases']['hasbeenunpaused_fcharup'] + ', когда очередь снизится до {{1}} заказов.', [$("#newextformside").attr('data-pause-on'), $("#newextformside").attr('data-pause-off')]));
				} else {
          if(result.purse_amount > 0) {
            show_balance_popup(result.purse_amount, 'prd', result.id);
          } else {
					  show_message('error', 'Произошла ошибка. Пожалуйста, попробуйте еще раз.');
          }
        }
			}
			isMakeOrder = false;
			$('.make-order-disable').removeAttr('disabled').removeClass('make-order-disable');
		}
	});
});

$(document).on('click touchstart', '.popup .overlay, .popup-close-js', function() {
	if ($(this).hasClass('overlay-disabled')) {
		return false;
	}
	if ($(this).parents('.popup').hasClass('popup-signup') || $(this).parents('.popup').hasClass('popup-login')) {
		if ($(this).hasClass('overlay') && $('body').hasClass('is_mobile')) {
			return false;
		}
		$(this).parents('.popup').fadeOut(200);
	} else {
		$(this).parents('.popup').remove();
	}

});

function show_popup(content, popupContentClass, responsive, popupClass, overlayDisabled, showX) {
	var is_show_login = false;

	if ($('.popup').hasClass("popup-signup") || $('.popup').hasClass("popup-login")) {
		is_show_login = true;
	}
	$('.popup').remove();
	if (typeof popupContentClass == 'undefined') {
		popupContentClass = '';
	}
	if (typeof popupClass == 'undefined') {
		popupClass = '';
	}
	if (typeof showX == 'undefined') {
		showX = true;
	}
	var html = '';
	var responsiveClass = '';
	if (typeof responsive != 'undefined' && responsive == true) {
		responsiveClass = 'js-popup--responsive';
	}

	var overlayDisabledHtml = "";
	if (typeof overlayDisabled !== 'undefined' && overlayDisabled) {
		overlayDisabledHtml = " overlay-disabled";
	}
	html += '<div class="popup ' + popupClass + ' ' + responsiveClass + '">' +
		'<div class="overlay' + overlayDisabledHtml + '"></div>' +
		'<div class="popup_content ' + popupContentClass + '">';

	if (showX === true) {
		html += '<div class="pull-right popup-close-js popup-close cur" style="width:30px; height:20px; text-align:center; padding:10px 10px 10px;">X</div>';
	}


	html += content;

	html += '</div>' +
		'</div>';
	var $popup = $(html);
	$('body').append($popup);
	if (responsive) {
		setPopupWidth($popup);
	}
  popup_scroll_update();
	if (popupClass == 'popup-signup' || popupClass == 'popup-login') {
		if (is_show_login) {
			$('.popup').show();
		} else {
			$('.popup').fadeIn(200);
		}

	}
}

function popup_scroll_update() {
	var height_popup = $('.popup .popup_content').height() + parseInt($('.popup .popup_content').css('padding-top')) + parseInt($('.popup .popup_content').css('padding-bottom')) + parseInt($('.popup .popup_content').css('margin-top'));
	/*скалдываем высоту+отступы*/
	if ($(document).width() < 768 || isMobile()) {
		/*На мобильных окно у нас скролится вместе со страницей, поэтому показываем на уровне видимости*/

		if ((height_popup + $(document).scrollTop()) > $(document).height()) {
			/*Если больше высоту страницы*/
			$('.popup').css({
				top: ($(document).height() - height_popup) + 'px'
			});
		} else {
			$('.popup').css({
				top: $(document).scrollTop() + 'px'
			});
		}
	}
	if ($(window).height() < height_popup) {
		$('.popup .popup_content').css({
			'max-height': height_popup - (height_popup - $(window).height()) - parseInt($('.popup .popup_content').css('margin-top')),
			'width': parseInt($('.popup .popup_content').css('width')) + 15,
			'overflow-y': 'auto'
		})
	}
}

function popup_error(msg) {
	var html = '<h1 class="popup__title">Ошибка</h1>';
	html += '<hr class="gray mt15 mb15">';
	html += '<p>' + msg + '</p>';
	show_popup(html);
}

function remove_popup() {
	$('.popup').remove();
}

function setPopupWidth($popup) {
	var width = $popup.find('.js-popup__inner-content').width();
	if ($popup.find('.js-popup__inner-content').hasScrollBar()) {
		width += Utils.getScrollBarWidth();
	}

	$popup.find('.popup_content').width(width);
	$popup.find('.js-popup__inner-content').width(width);
	$popup.find('.popup_content').css('max-width', 'inherit');
}

function show_message(type, text) {
	close_message();
  if($("#fox_notification_block").length == 0) $(".all_page").prepend('<div id="fox_notification_block"></div>');
	var html = "<div class='fox_" + type + "'>" +
		"<p>" + text + "</p>" +
		"</div>";
	$("#fox_notification_block").prepend(html);
}

function close_message() {
	$(".fox_success, .fox_notice, .fox_error").remove();
}

/**
 * Review Module
 * @type {{init, load}}
 */
var ReviewsModule = (function(currentUserId) {
	var _params = {
		id: 0,
		type: 'positive',
		onPage: 0,
		onPageStart: 0,
		total: {
			positive: 0,
			negative: 0
		},
		offset: {
			positive: 0,
			negative: 0
		},
		entity: 'user',
		counter: 0
	};
	var _reviewCache = {
		positive: '',
		negative: ''
	};

	var $moreBtn;

	var _getType = function() {
		return _params.type;
	};

	var _fillReviews = function(response) {

		_params.offset[_getType()] += _params.onPage;
		$('.gig-reviews-list').append(response.html);
		$moreBtn.hide();
		_showNextButton();
		clearTimeout(preloader_timeout_ajax);
		$('.more-btn-reviews #more-text').removeClass('disabled');
		$('.reviews_order_preloader-js').addClass('hidden');
	};

	var _showNextButton = function() {
		var showCount = _params.offset[_getType()];
		if (_params.total[_getType()] > showCount) {
			$moreBtn.show();
		}
	};

	var _loadMoreReviews = function(offset, type) {
		var data = {
			method: 'reviews_load',
			offset: offset,
			type: type,
			id: _params.id,
			entity: _params.entity
		};
		$.get(_params.baseUrl + '/api', data, _fillReviews, 'json');
	};

	var _setCache = function() {
		if (_getType() == 'positive') {
			_reviewCache['negative'] = $('.gig-reviews-list').html();
		} else {
			_reviewCache['positive'] = $('.gig-reviews-list').html();
		}
	};
	var _changeTab = function() {
		var type = $(this).data('type');
		if ($('.reviews-tab__item.active').data('type') == type) {
			return false;
		}
		if (_params.total[type] == 0) {
			return false;
		}
		if (type == 'negative' && !parseInt(currentUserId) > 0) {
			show_signup();
			return false;
		}
		$moreBtn.hide();
		$('.reviews-tab__item').removeClass('active');
		$(this).addClass('active');
		_params.type = type;

		_setCache();

		$('.gig-reviews-list').html('');
		if (_reviewCache[type].length) {
			$('.gig-reviews-list').append(_reviewCache[type]);
			var showCount = _params.offset[type] + _params.onPage;
			if (_params.total[type] <= showCount) {
				$moreBtn.hide();
			} else {
				$moreBtn.show();
			}

			return false;
		}
		preloader_timeout_ajax = setTimeout(function() {
			$('.reviews_order_type .reviews_order_preloader-js').removeClass('hidden')
		}, 250)
		_loadMoreReviews(0, type);
	};

	return {
		init: function(params) {
			$moreBtn = $('.more-btn-reviews');

			for (var i in params) {
				_params[i] = params[i];
			}

			_params.total.positive = $('#pos').data('count') ^ 0;
			_params.total.negative = $('#neg').data('count') ^ 0;
			_params.type = $('.reviews-tab__item.active').data('type');
			if (!_params.offset[_getType()]) {
				_params.offset[_getType()] = _params.onPageStart;
			} else {
				_params.offset[_getType()] = _params.onPage;
			}

			$('.more-btn-reviews #more-text').on('click', function() {

				if (!parseInt(currentUserId) > 0 && _params.counter > 0) {
					show_signup();
					return false;
				}
				if (!parseInt(currentUserId) > 0 && _params.counter === 0) {
					_params.counter = 1;
				}

				if ($(this).hasClass('disabled')) {
					return false;
				}
				$(this).addClass('disabled');
				preloader_timeout_ajax = setTimeout(function() {
					$('.more-btn-reviews .reviews_order_preloader-js').css({
						"visibility": "visible"
					})
				}, 250)
				var offset = _params.offset[_getType()];
				_loadMoreReviews(offset, _getType());
			});

			$('.reviews-tab__item').on('click', _changeTab);

			_showNextButton();
		},

		load: function(offset, type) {
			_loadMoreReviews(offset, type);
		}
	}
})(USER_ID);

$(document).ready(function() {
	$('.cart-popup .block-popup_body').jScrollPane({
		autoReinitialise: true
	});
	$('body').on('mousewheel', function(e) {
		if ($(e.target).closest('.cart-popup .block-popup_body, .message .block-popup').length) return false;
	});
});

$(document).on('click', '.cart-popup_count_plus', function() {
	event.preventDefault();
	var current = parseInt($(this).parents('.cart-popup_count').find('input').val(), 10);
	if (current == 10) {
		return false;
	}
	current = current + 1;
	$(this).parents('.cart-popup_count').find('input').val(current);
	update_cart(true);
});

$(document).on('click', '.cart-popup_count_minus', function() {
	event.preventDefault();
	var current = parseInt($(this).parents('.cart-popup_count').find('input').val(), 10);
	if (current == 1) {
		return false;
	}
	current = current - 1;
	$(this).parents('.cart-popup_count').find('input').val(current);

	update_cart(true);
});

function update_cart() {
	var total_price = 0;
	$('.header .cart-popup .cart-popup_row:not(.cart-popup_head)').each(function() {
		var priceStr = $(this).find('.cart-popup_price_prd-js').attr('data-price');
		priceStr = priceStr.replace(/\s+/g, '');
		if (actor_lang === 'en') {
			var price = Math.round(parseFloat(priceStr) * 100) / 100;
		} else {
			var price = parseInt(priceStr, 10);
		}
		total_price = total_price + price;
	});
	$('.cart-popup_total-js').text(digit_view(total_price));

	setCartCountNotify();

	var extraCnt = $('.block-popup .block-popup_body .jspPane .block-popup_body_conteiner .cart-popup__extras').not('.hidden').length;
	if (extraCnt > 0) {
		$('.block-popup .cart-popup__extras').removeClass('hidden');
		$('.block-popup.noextra').removeClass('noextra');
	}
}

function setCartCountNotify() {
	var countStr = $('.header .cart-popup .cart-popup_row:not(.cart-popup_head)').length;
	var count = parseInt(countStr);
	if (count == 0) {
		$('.cart-popup_notify').text(countStr);
		$('.cart-popup_notify').css('opacity', '0');
		return false;
	}

	var oldCountStr = $('.cart-popup_notify').text();
	var oldCount = parseInt(oldCountStr);
	if (oldCount == count || (oldCountStr == '+' && count > 9)) {
		return false;
	}

	$('.cart-popup_notify').css('opacity', '0');
	if (count > 9) {
		countStr = '+';
		$('.cart-popup_notify').css('font-size', '10px');
	} else {
		$('.cart-popup_notify').css('font-size', '8px');
	}
	setTimeout(function() {
		$('.cart-popup_notify').text(countStr);
		$('.cart-popup_notify').css('opacity', '1');
	}, 100);

}

function refreshCartScroll() {
	if ($('.cart-popup .block-popup .cart-popup_row:not(.cart-popup_head)').length === 0) {
		$('.cart-popup').addClass('cart-popup_empty');
		$('.cart-popup_head').addClass('hidden');
	} else {
		$('.cart-popup_head').removeClass('hidden');
		$('.cart-popup').removeClass('cart-popup_empty');
		var height = 0;
		$.each($('.cart-popup .block-popup .cart-popup_row:not(.cart-popup_head)'), function(key, value) {
			if (key <= 2) { //количество показываемых блоков - 1
        //console.log($(this).outerHeight());
				height += 100;
			}
		});
		if ($('.cart-popup .block-popup .cart-popup_row:not(.cart-popup_head)').length > 4) {
			height = height - 1;
		}
		$('.cart-popup .block-popup_body').css({
			height: height + 'px'
		})
	}

	var pane = $('.cart-popup .block-popup_body');
	var api = pane.data('jsp');
	api.reinitialise();
}


function notActorCreateNewCartItem(obj, isPackage) //Добавление в корзину элементов, для не залогиненого пользователя
{
	show_login(); //Открываем форму логина
	CartModule.setData('IsCartItem', true);
	if (isPackage) {
		CartModule.setData('package', obj);
	}
}

$(document).on('mouseenter', '.massage', function() {
	$('.dropdownbox').hide();

	var this_element = $(this);
	var $popup = this_element.find('.block-popup:not(.not_to_hide)');
	$popup.fadeIn(200, 'swing');
	if (this_element.hasClass('js-notice-other') && $popup.hasClass('wating')) {
		loadNotify($popup);
	}
}).on('mouseleave', '.massage', function() {
	$(this).find('.block-popup:not(.not_to_hide)').hide();
});

function delete_confirm(url) {
	var count = $('.checkbox:checked').size();
	if (count == 0)
		return false;
	var hasOffers = $('.checkbox.has-offers:checked').size();
	var html = '' +
		'<div>' +
		'<h1 class="popup__title f26">Подтверждение удаления</h1>' +
		'<hr class="gray" style="margin-bottom:32px;">' +
		'<div style="display:inline-block;width:100%;">' +
		'<p class="f15 pb10 ml10">Удалить ' + cot_sitename['padeg']['v'] + '?</p>';
	if (hasOffers > 0) {
		html += '<p class="f15 pb50 ml10">Внимание! Ваши ранее отправленные предложения ' + cot_sitename['phrases']['etoi'] + ' по запросам будут удалены.</p>';
	}
	html += '<button class="popup__button red-btn" onclick="location.href=\'' + url + '\';">Удалить</button>';
	html += '' +
		'<button class="popup__button white-btn popup-close-js pull-right">Отменить</button>' +
		'</div>' +
		'</div>';
	show_popup(html);
}

function suspend_prd_offer_confirm() {
	//todo del
}

function suspend_prd_offer_confirm_2() {
	//todo del
}

function activate_prd_confirm() {
	//todo del
}

function change_prd_offer_confirm(goto) {
	//todo del
}

function delete_request_confirm(id) {
	var html = '' +
		'<div>' +
		'<form action="/projects/edit/' + id + '" method="get">' +
		'<input type="hidden" name="action" value="delete" />' +
		'<h1 class="popup__title f26">Подтверждение удаления</h1>' +
		'<hr class="gray" style="margin-bottom:32px;">' +
		'<div style="display:inline-block;width:100%;">' +
		'<p class="f15 pb50 ml10">Удалить запрос?</p>' +
		'<button class="popup__button red-btn" onclick="$(this).parent().parent().submit();">Удалить</button>' +
		'<button class="popup__button white-btn pull-right popup-close-js" onclick="return false;">Отменить</button></div>' +
		'</div>' +
		'</form>' +
		'</div>';
	show_popup(html);
}

function stop_request_confirm(id) {
	var html = '' +
		'<div class="js-popup__inner-content" style="width:400px">' +
		'<form action="/projects/edit/' + id + '" method="get">' +
		'<input type="hidden" name="action" value="stop" />' +
		'<h1 class="popup__title">Подтверждение остановки</h1>' +
		'<hr class="gray" style="margin-bottom:32px;">' +
		'<div style="display:inline-block;width:100%;">' +
		'<p class="f15 pb50 ml10">Вы подтверждаете остановку запроса? Продавцы не смогут больше добавлять в него свои предложения.</p>' +
		'<button class="popup__button red-btn" onclick="$(this).parent().parent().submit();">Остановить</button>' +
		'<button class="popup__button white-btn pull-right popup-close-js" onclick="return false;">Отменить</button></div>' +
		'</div>' +
		'</form>' +
		'</div>';
	show_popup(html, '', true);
}

function can_not_order_popup(catName, catLink) {
	var html = '' +
		'<div class="js-popup__inner-content" style="width:400px">' +
		'<div class="clear" style="margin-bottom:32px;"></div>' +
		'<div style="display:inline-block;width:100%;">' +
		'<p class="f15 pb20 ml10">' + t('Продавец временно не продает продает ' + cot_sitename['phrases']['danyi'] + '. Посмотрите другие ' + cot_sitename['padeg']['_i'] + ' из раздела “<a itemprop="item" href="{{0}}"><span itemprop="name">{{1}}</span></a><meta itemprop="position" content="2" />”. Вы также можете воспользоваться поиском вверху страницы.', [catLink, catName]) + '</p>' +
		'</div>' +
		'</div>';
	show_popup(html, '', true);
}

function declension(count, form1, form2, form5) {
	var count = count ? count : 0;
	var number = Math.abs(count) % 100;
	if (number > 10 && number < 20)
		return form5;

	number = number % 10;
	if (number > 1 && number < 5)
		return form2;

	if (number == 1)
		return form1;

	return form5;
}

function digit_view(str) {
	str = str.toString();
	return str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
}

function upstring(string) {
	var first = string[0].toUpperCase();
	return first + string.substr(1);
}

function toggleRisksAttention() {
	if ($('.risks-block .menulist:hidden')) {
		$('body').prepend('<div class="risks-overlay"></div>');
		$(document).on('click', '.risks-block .popup-close, .risks-overlay', function() {
			$('.risks-overlay').remove();
			$('.risks-block .menulist, .risks-block .menubox').hide();
		});
		$('.risks-block .menulist, .risks-block .menubox').show();
		checkRevertRisk();
	} else {
		$('.risks-overlay').remove();
		$('.risks-block .menulist, .risks-block .menubox').hide();
	}
}
$(function() {
	$(document).on('scroll', checkRevertRisk);
	$(document).on('scroll', checkRevertRequiredInfo);
});

function checkRevertRisk() {
	if (!$('.risks-block').length) {
		return;
	}

	var windowHeight = $(window).height(),
		scrollTop = $(document).scrollTop(),
		hintHeight = $('.risks-block .menulist').outerHeight(),
		hintTop = $('.risks-block').offset().top + $('.risks-block').height();
	if (hintTop + hintHeight + 20 > scrollTop + windowHeight) {
		$('.risks-block .menulist, .risks-block .menubox').addClass('revert');
		$('.risks-block .menulist').css({
			'top': '-' + hintHeight + 'px'
		});
	} else {
		$('.risks-block .menulist, .risks-block .menubox').removeClass('revert');
		$('.risks-block .menulist').css({
			'top': '10px'
		});
	}
}

function toggleInfoRequired() {
	if ($('.requiredInfo-block .menulist:hidden')) {
		$('body').prepend('<div class="requiredInfo-overlay"></div>');
		$(document).on('click', '.requiredInfo-block .popup-close, .requiredInfo-overlay', function() {
			$('.requiredInfo-overlay').remove();
			$('.requiredInfo-block .menulist, .requiredInfo-block .menubox').hide();
		});
		$('.requiredInfo-block .menulist, .requiredInfo-block .menubox').show();
		checkRevertRequiredInfo();
	} else {
		$('.requiredInfo-overlay').remove();
		$('.requiredInfo-block .menulist, .requiredInfo-block .menubox').hide();
	}
}

function checkRevertRequiredInfo() {
	if (!$('.requiredInfo-block').length) {
		return;
	}

	var windowHeight = $(window).height();
	var scrollTop = $(document).scrollTop();
	var hintHeight = $('.requiredInfo-block .menulist').outerHeight();
	if (hintHeight > windowHeight) {
		$('.requiredInfo-block .menulist').height(windowHeight * 0.6);
		$('.requiredInfo-block .menulist').css({
			'overflow-y': 'auto'
		});
		hintHeight = windowHeight * 0.6;
	}
	var hintTop = $('.requiredInfo-block').offset().top + $('.requiredInfo-block').height();
	if (hintTop + hintHeight + 20 > scrollTop + windowHeight) {
		$('.requiredInfo-block .menulist, .requiredInfo-block .menubox').addClass('revert');
		$('.requiredInfo-block .menulist').css({
			'top': '-' + hintHeight + 'px'
		});
	} else {
		$('.requiredInfo-block .menulist, .requiredInfo-block .menubox').removeClass('revert');
		$('.requiredInfo-block .menulist').css({
			'top': '10px'
		});
	}
}

function getGetParams() {
	var url = window.location.href;
	if (url.indexOf('?') == -1)
		return [];
	var uriArr = url.split('?')[1].split('&');
	var results = [];
	uriArr.forEach(function(item, i, arr) {
		var uriItem = item.split('=');
		results[uriItem[0]] = uriItem[1];
	});
	return results;
}

function implodeURI(params) {
	var result = "";
	var splitedUrl = window.location.href.split('?');
	if (splitedUrl.length == 1)
		var url = window.location.href;
	else
		var url = splitedUrl[0];
	for (var key in params) {
		result += '&' + key + '=' + params[key];
	}
	result = url + '?' + result.substr(1);
	return result;
}

function loadDodjis() {
	var url = window.location.href;
	if (typeof CatFilterModule == 'undefined') {
		var params = getGetParams();
	} else {
		var params = CatFilterModule.getParams();
	}
	params['page'] = parseInt(params['page']);
	if (!params['page'] || params['page'] < 1)
		params['page'] = 1;
	params['page']++;
	if (typeof weightMinute == 'undefined') {
		weightMinute = '';
	}
	var shownIds = $('.js-prd-card').map(function() {
		return $(this).data('id')
	}).get();
	$('.loadDodjis').addClass('onload');
	$.ajax({
		url: url,
		type: 'get',
		data: {
			'page': params['page'],
			'weightMinute': weightMinute,
			'excludeIds': shownIds
		},
		dataType: 'json',
		success: function(response) {
			$('.loadDodjis').removeClass('onload');
			var newUrl = implodeURI(params);
			window.history.pushState({
				urlPath: newUrl
			}, "", newUrl);
			if (response.paging.page * response.paging.items_per_page >= response.paging.total) {
				$('.loadDodjis').hide();
				if (typeof weightMinute !== 'undefined' && weightMinute !== '') {
					showMoreButtonPopup();
				}
				if ($('.request_block-js')) {
					$('.request_block-js').removeClass('hidden');
				}
			}
			if (sdisplay == "list")
				$(".newfox").last().after(response.html);
			else
				$(".cusongsblock").last().after(response.html);

			$('.js-tooltip').tooltip();
		}
	});
}

/*функционал для открытия подменю на тачскриновых устройствах*/
$(document).on('click', '.category-menu__list_item', function(e) {
	var $el = $(this);
	var isClick = $el.attr('data-click');
	var enableMobileFirstClick = $el.hasClass('mobile-enable-first-click');
	if (isMobile() && !isClick && !enableMobileFirstClick) {
		e.preventDefault();
		$el.attr('data-click', 'true');
	}
});
/*конец функционал для открытия подменю на тачскриновых устройствах*/

$(document).on('click', '.faq_sub-cat h2,.faq_page-block .faq_cat', function() {
	var faqParentEl = $(this).parent();
	faqParentEl.toggleClass('active');
});

// Событие выпадающего списка в меню
$(document).on('touchstart', '*', function(e) {
	var $listElements = $('.category-menu__list, .cart-popup, .js-notice-other, .droparrow, .lang-selector');
	if (isMobile() && (!$listElements.is(e.target) && $listElements.has(e.target).length === 0)) {
		$(".dropdownbox, .menubox, .block-popup:not(.not_to_hide)").hide();
		$('.category-menu__list_item').removeAttr('data-click');
	}
});
$(document).on('mouseenter touchstart', '.sub-menu-parent>li', function(e) {
	if (e.type == 'mouseenter' && isMobile()) { // for touch screen
		$('.category-menu__list_item').removeAttr('data-click');
		e.stopPropagation();
		e.preventDefault();
		return false;
	}
	$(".dropdownbox, .menubox").hide();
	var this_element = $(this);
	this_element.find('.menubox').fadeIn(200, 'swing');
}).on('mouseleave', '.sub-menu-parent>li', function(e) {
	if (e.type == 'mouseleave' && isMobile()) { // for touch screen
		e.stopPropagation();
		e.preventDefault();
		return false;
	}
	$('.sub-menu-parent').find('.menubox').hide();
	$('.category-menu__list_item').removeAttr('data-click');
});

function closeEvent(target, id, isConfirm) {
	if (!isConfirm) {
		var isClose = confirm('Вы уверены что хотите закрыть это уведомление?');
		if (!isClose) {
			return false;
		}
	}

	$.ajax({
		type: "GET",
		url: '/api?method=Event.api_delete&eventId=' + id,
		success: function(data) {
			var result = JSON.parse(data);
			if (result.success) {
				target.closest(".event-message").remove();
			}
		}
	});
}

function closeEvent_IE(id) {
	var isClose = confirm('Вы уверены что хотите закрыть это уведомление?');
	if (!isClose)
		return false;

	var date = new Date();
	var days = 360;
	date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
	setCookie('isIE_browser', true, {
		expires: date,
		path: '/'
	});
	var form = $('#event_' + id);
	if (form.length > 0) {
		form.remove();
	}

}

var checkFormModule = (function() {

	return {
		checkForm: function(form) {
			var success = true;
			$(form).find('input.js-required, textarea.js-required, select.js-required').each(function() {

				if (!$(this).is(':visible') && !$(this).hasClass('styled-select')) {
					return;
				}

				$(this).removeClass('input-error');
				if ($(this).val().length == 0) {
					success = false;
					if ($(this).hasClass('styled-select') && !$(this).is(':visible')) {
						$(this).siblings('.chosen-container').find('.chosen-single').addClass(checkFormModule.gerErrorClass(this));
					} else {
						$(this).addClass(checkFormModule.gerErrorClass(this));
					}

				}
			});

			return success;
		},
		gerErrorClass: function(el) {
			var tagName = $(el).prop("tagName").toLowerCase();
			return tagName + '-styled--error';
		}
	}
})();

$(function() {
	$(document).on('submit', 'form', function() {
		if (!checkFormModule.checkForm(this)) {
			return false;
		}
	});

	$(document).on('change, input', '.js-required', function() {
		var tagName = $(this).prop("tagName").toLowerCase();
		if ($(this).val()) {
			$(this).removeClass(checkFormModule.gerErrorClass(this));
		} else {
			$(this).addClass(checkFormModule.gerErrorClass(this));
		}
	});
});



var NotifyModule = (function() {
	var $_noticeBlocks = {};

	var _lastTracks = {};

	var _updateNotifyIcons = function() {
		$.get('/api', 'method=User.checkNotify', function(response) {
			if (response.success != true) {
				return;
			}

			if (_tracksIsChanged(response.data.last_tracks)) {
				_lastTracks = response.data.last_tracks;
				_updateNotifyTracks();
			}

			_setNotifyIcons(response.data);
			tabsInteractionModule.updateTabsEvent('notifications', response.data);
		}, 'json');
	};

	var _tracksIsChanged = function(newTracks) {
		return JSON.stringify(newTracks) != JSON.stringify(_lastTracks);
	};

	var _showIconText = function(el, number) {
		if (number > 0) {
			if (number > 9) {
				el.addClass('f10').text("+");
			} else {
				el.text(number);
			}
			el.show();
		} else {
			el.hide();
		}
	};
	var _updateInboxMessage = function(el, data, newCount) {
		el.find(".notifications-content-block").html('');
		if (newCount) {
			for (i = 0; i < data.length; i++) {
				var item = $(document.createElement('a')).addClass('inbox-message-link').attr('href', data[i].link);
				var image = $(document.createElement('span')).addClass('userimage');
				$(document.createElement('img')).addClass('rounded').attr('src', data[i].image).attr('alt', data[i].login).attr('height', 28).attr('width', 28).appendTo(image);
				image.appendTo(item);
				$(document.createElement('span')).addClass('inbox-message-user-name').html(data[i].text).appendTo(item);
				el.find(".notifications-content-block").append(item);
			}
		} else {
			for (i = 0; i < data.length; i++) {
				var item = $(document.createElement('span')).addClass('inbox-message-link').addClass('empty-inbox-data').html(data[i].text);
				el.find(".notifications-content-block").append(item);
			}
		}
	};

	var _setNotifyIcons = function(data) {
		window.notifyIsLoad = false;
		if (typeof data.new_message !== 'undefined') {
			var massageCounterEl = $_noticeBlocks.inbox.find('.js-notice__link').find('.massage_counter');
			_showIconText(massageCounterEl, data.new_message);
			_updateInboxMessage($_noticeBlocks.inbox, data.dialog_data, data.new_message);
		}

		var notificationPopup = $('.js-notice-other').find('.block-popup:not(.not_to_hide)');
		notificationPopup.addClass('wating').html('');
		if (Utils.isActiveWindow() && notificationPopup.is(':visible')) {
			loadNotify(notificationPopup);
		}

		if (typeof data.notify_unread_count !== 'undefined') {
			var notityCounterEl = $_noticeBlocks.other.find('.js-notice__link').find('.massage_counter');
			_showIconText(notityCounterEl, data.notify_unread_count);
		}
	};

	var _updateNotifyTracks = function() {
		$.get('/new_notify', function(response) {
			if (response != '0') {
				_setNotifyTracks(response);
				tabsInteractionModule.updateTabsEvent('track_messages', response);
			}
		});
	};

	var _setNotifyTracks = function(data) {
		$_noticeBlocks.other.find('.block-popup:not(.not_to_hide)').removeClass('wating').html($(data).html());
		$_noticeBlocks.other.find('.block-popup:not(.not_to_hide)').jScrollPane();
	};

	return {
		init: function(pullEnable) {
			$_noticeBlocks = {
				'inbox': $('.js-notice-inbox'),
				'other': $('.js-notice-other')
			};
			if (!pullEnable) {
				tabsInteractionModule.setTimeoutFunction('notifications', _updateNotifyIcons, _setNotifyIcons, 600000);
			}

			tabsInteractionModule.addListener('track_messages', _setNotifyTracks);
		},
		setNotifyIcons: _setNotifyIcons
	}
})();

$(function() {
	if ($('.needCheckNotify').val() == 1) {
		NotifyModule.init(PULL_MODULE_ENABLE);
		if (PULL_MODULE_ENABLE) {
			PullModule.on(PULL_EVENT_NOTIFY, NotifyModule.setNotifyIcons);
		}
	}
});

function IDGenerator(prefix) {
	this.prefix = prefix;
	this.num = 1;
	this.getID = function() {
		return this.prefix + (this.num++);
	}

}

function getDuration(days, count, rate) {
	return Math.ceil(days + (count - 1) * days * rate);
}

$(document).on('click', '.js-hide-after-press', function(event) {
	$(this).hide();
});


//////
function shortenedTextGetLessSpan() {
	return '<span class="js-shortened-text-less link link_local link_arrow link_arrow_blue link_arrow_up ml10">Свернуть</span>';
}

function shortenedTextGetMoreSpan(customAction) {
	var customActionBlock = '';
	if (typeof(customAction) !== 'undefined') {
		customActionBlock = 'onclick="' + customAction + '"';
	}
	return '<span class="js-shortened-text-more link link_local link_arrow link_arrow_blue link_arrow_down ml10" ' + customActionBlock + '>Развернуть</span>';
}

function shortenedTextReplace(obj, button) {
	var prevTextBlock = $(obj).parent('.js-shortened-text');
	var replaceText = $(prevTextBlock).data('replaceText');

	var $blockClone = $(prevTextBlock).clone();
	$blockClone.find('.js-shortened-text-less, .js-shortened-text-more').remove();
	var curText = $blockClone.html();

	$(prevTextBlock).html(replaceText);
	$(prevTextBlock).data('replaceText', curText);
	if (button === 'less') {
		$(prevTextBlock).append(shortenedTextGetLessSpan());
	} else {
		$(prevTextBlock).append(shortenedTextGetMoreSpan());
	}
}

function initiateShortenedTextMore() {
	$('.js-shortened-text-more').on('click', function() {
		$(this).parent().parent().parent().parent().find('.query-seen_block').removeClass('hide');
		$(this).parent().parent().parent().find('.files-list').removeClass('hide');
		shortenedTextReplace(this, 'less');
		initiateShortenedTextLess();
	});
}

function initiateShortenedTextLess() {
	$('.js-shortened-text-less').on('click', function() {
		$(this).parent().parent().parent().find('.files-list').addClass('hide');
		shortenedTextReplace(this, 'more');
		initiateShortenedTextMore();
	});
}

function initShortenedText() {
	$('.js-shortened-text').each(function(i) {
		if ($(this).attr('data-replace-text').replace(/<[^>]+>/g, '').length > $(this).attr('data-min-length') || $(this).parent().parent().find('.files-list').length > 0) {
			if ($(this).attr('data-custom-action') == '') {
				$(this).append(shortenedTextGetMoreSpan());
			} else {
				$(this).append(shortenedTextGetMoreSpan($(this).attr('data-custom-action')));
			}
		}
	});
	initiateShortenedTextMore();
}

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

function wantAddView(wantId) {
/* TODO
	$.ajax({
		type: "POST",
		url: '/api?method=Want.api_addView&wantId=' + wantId,
		success: function(data, textStatus, xrf) {
			$(".js-card-" + wantId + " .query-seen_block ").removeClass("hide");
		}
	});
*/
}
(function($) {
	$.fn.textAreaMaxLength = function(maxLength) {
		var checkMaxLength = function(el) {
			var maxlength = el.maxLength;
			if ($(el).val().length > maxlength) {
				var newDesc = el.oldDesc + $(el).val().substr(0, maxlength - el.oldDesc.length);
				$(el).val(newDesc);
			}
			el.oldDesc = $(el).val();
		};

		return this.each(function() {
			this.maxLength = maxLength;
			this.oldDesc = '';

			var module = this;
			$(this).keyup(function() {
				checkMaxLength(module);
			});
			$(this).change(function() {
				checkMaxLength(module);
			});
		});
	}
})(jQuery);

function about_text_hide() {
	if ($(window).width() <= 767) {
		if ($('.b-about-text .b-about-text_container .b-about-text_container_text').height() > 54) {
			$('.toggle-about-text').show();
		}
	}

}
$(document).on('click touchstart', '.toggle-about-text', function() {
	$('.b-about-text').toggleClass('active');
	if ($(this).hasClass('toggle-about-text_hide')) {
		$('html, body').scrollTop($('.b-about-text').offset().top - 100);
	}
	return false;
})


$(document).on('touchstart', '.js-tooltip-block', function() {
	if (!$(event.target).is("a")) {
		$(this).remove();
	}
})


$(document).ready(function() {
	about_text_hide();
})
$(document).on('click touchstart', '.render_desktop-js', function() {
	var date = new Date();
	var days = 360;
	date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
	setCookie('only_desktop_version', true, {
		expires: date,
		path: '/'
	});
	setTimeout(function() {
		location.reload();
	}, 300)
})

$(document).on('click touchstart', '.render_mobile-js', function() {
	deleteCookie('only_desktop_version');
	setTimeout(function() {
		location.reload();
	}, 300)
})

$(document).on('ready', function() {
	function slickInit(selectir) {
		if (!selectir) return false;

		jQuery(selectir).slick({
			arrows: false,
			responsive: [{
					breakpoint: 767,
					settings: {
						dots: true,
						infinite: true,
						speed: 300,
						slidesToShow: 1,
						slidesToScroll: 1,
						autoplay: true,
						autoplaySpeed: 3000,
						arrows: false,
					}
				},
				{
					breakpoint: 5000,
					settings: "unslick"
				}
			]
		});
	}
	if ($('.index-advantage-block').length > 0) slickInit('.index-advantage-block');
	if ($('.real-case').length > 0) slickInit('.real-case');
	if ($('.landing-how-it-works .icons').length > 0) slickInit('.landing-how-it-works .icons');
});

function scrollToAnchor(aid) {
	var aTag = $("a[name='" + aid + "']");
	$('html,body').animate({
		scrollTop: aTag.offset().top
	}, 'slow');
}

function getElementTopToScroll($el) {
	return $el.offset().top - ($(window).height() - $el.outerHeight(true)) / 2;
}

$(document).on('keydown', '.js-alt-send', function(e) {
	if (e.ctrlKey && e.keyCode == 13) {
		$(this).closest('form').trigger('submit');
	}
});

$(function() {
	$('.js-show-cart').click(function() {
		$('html, body').animate({
			scrollTop: 0
		}, 'slow', function() {
			$('.cart-popup .block-popup:not(.not_to_hide)').fadeIn(200, 'swing');
			refreshCartScroll();
			$('.cart-popup .block-popup:not(.not_to_hide)').hide();
		});
	});
	$('.js-abandoned-basket__close').on('click', function() {
		$(this).closest('.abandoned-basket').slideUp(300);
		$.post('/api?method=Cart.api_closeAbandonedNotify', function() {});
	});
});

$(document).ready(function() {
	/*Show/hide manu on swipe*/
	if (isMobile() && $(window).width() < 768) {
		$("body").swipe({
			swipeLeft: function() {
				if ($('.header .foxmenubutton').is(':visible')) {
					mobile_menu_hide()
				}

			},
			swipeRight: function() {
				if ($('.header .foxmenubutton').is(':visible')) {
					mobile_menu_toggle()
				}
			},
			threshold: 250
		});
	}

});

$(document).on('submit', '#addextrastop, #addpackagestop, #upgradepackagestop, .worker_extra_suggestion_form, .ds_mk_msgtype_send, .prj_offer_send', function(e) {
	e.preventDefault();
	recentFormToSubmit = $(this);

	var submit_button = $(this).find('button');
	submit_button.prop('disabled', true).addClass('disabled');

	$.ajax({
		url: $(this).attr('action'),
		type: 'post',
		data: $(this).serialize(),
		dataType: 'json',
		success: function(response) {
			if (response.result == 'success') {
				if (typeof(response.redirectUrl) !== 'undefined') {
					document.location.href = response.redirectUrl;
				} else {
					document.location.reload();
				}
			} else {
				if(response.error === 'funds') {
					show_balance_popup(response.difference, (typeof response.newform_type != 'undefined' ? response.newform_type : ''), response.payment_id);
				}
				submit_button.prop('disabled', false).removeClass('disabled');
			}
		},
		error: function() {
			submit_button.prop('disabled', false).removeClass('disabled');
		}
	});
});

$(document).on('input', '.js_clearingInput', function() {
	if ($(this).val() != "") {
		$(this).parent().find('.js_clearBtn').show();
	} else {
		$(this).parent().find('.js_clearBtn').hide();
	}
});
$(document).on('click touchstart', '.js_clearBtn', function() {
	$(this).hide();
	$(this).parent().find('.js_clearingInput').val('');
});
$(document).ready(function() {
	$('.js-poll-notify__close').on('click', function() {
		$(this).closest('.abandoned-basket').slideUp(300);
		$.post('/api?method=User.api_closePollNotify', function() {

		});
	});
	$('.abandoned-basket').each(function(i) {
		$(this).css('bottom', (i * ($(this).height() + 1)) + 'px');
	});
	if ($('.abandoned-basket').length > 1) {
		$('.scrollup').css('bottom', ($('.abandoned-basket').length * $('.scrollup').height()) + 'px');
	}
});

function SlideModule() {
	var _$slider;
	var _count;
	var _deepLoadIframe;
	var _mode;

	var _initSlider = function(settings) {
		_deepLoadIframe = 2;
		_setCount(settings.sliderCount)
		_$slider.slick(settings);
		_count = _$slider.slick('getSlick').slideCount;
		_startLazyLoad();
		_mode = settings.mode;

	};

	var _setEvents = function() {
		_$slider.on('beforeChange', function(event, slick, currentSlide, nextSlide) {
			if (player) {
				player.pauseVideo();
			}
			_lazyLoadBg(nextSlide);
		});


		if (_mode === "desktop") {
			window.onkeydown = pressed;

			function pressed(e) {
				if (e.keyCode === 37) {
					_$slider.slick("slickPrev");
				}
				if (e.keyCode === 39) {
					_$slider.slick("slickNext");
				}
			}
		}
	};

	var _setCount = function(isCount) {
		if (isCount) {
			_$slider.on('init reInit afterChange', function(event, slick, currentSlide, nextSlide) {
				var i = (currentSlide ? currentSlide : 0) + 1;
				if (slick.slideCount > 1) {
					$('.prd_slider_mobile_counter').html('<b>' + i + '</b>' + ' из ' + '<b>' + slick.slideCount + '</b>')
				}
			});
		}
	}

	var _lazyLoadIframe = function(index) {
		var iframes = $('.sliderItem[data-index=' + index + ']').find('iframe');
		if (iframes.length > 0) {
			iframes.each(function(indx, element) {
				var $el = $(element);
				if ($el.prop('src').length > 0)
					return;
				var src = $el.data('lazy');
				if (!src)
					return;
				$el.attr('data-lazy', '');
				$el.prop('src', src);
			});
		}
	};

	var _lazyLoadBg = function(index) {
		var els = $('.sliderItem[data-index=' + index + ']').find('.lazy-bg');
		if (els.length > 0) {
			els.each(function(indx, element) {
				var $el = $(element);
				if ($el.css('background-image') != 'none')
					return;
				var src = $el.data('lazy');
				if (!src)
					return;
				$el.attr('data-lazy', '');
				$el.css('background-image', 'url(' + src + ')');
				$el.onload = function() {
					_lazyLoadIframe(index);
					_lazyLoadSlide(index);
				};
			});
		}
	};

	var _lazyLoadSlide = function(index) {
		var $currentSlide = $('.sliderItem[data-index=' + index + ']');
		var $el = $currentSlide.find('.js-sliderImage-picture');

		if (!$el.length) {
			return;
		}

		var src = $el.data('lazy');
		if (!src) {
			return;
		}

		$el.hide();

		var img = new Image();

		img.onload = function() {
			$el.show();
			$el.show();
			$el.attr('src', src);
		};

		img.src = src;

		$el.attr('data-lazy', '');

	};

	var _startLazyLoad = function() {
		_lazyLoadBg(0);
		_lazyLoadSlide(0);
		_lazyLoadIframe(0);
		var index = 1;
		while (index >= _deepLoadIframe) {
			_lazyLoadIframe(index);
			_lazyLoadIframe(_count - index);
			index++;
		}
	};

	return {
		init: function(options) {
			_$slider = $(options.sliderName);
			_initSlider(options.settings);
			_setEvents();
			_setCount(options.settings.sliderCount);
		}
	}
}

var player;
$(document).on('click', '.play-video-js', function() {
	var current_element = $(this)
	var video_id = $(this).attr('data-video-id');
	var container = $(this).parents('.prd-slider_videoWrapper').find('#player')[0]
	player = new YT.Player(container, {
		height: '433',
		width: '650',
		videoId: video_id,
		events: {
			'onReady': onPlayerReady
		}
	});
})

function onPlayerReady(event) {
	if (isNotMobile()) {
		event.target.playVideo();
	}

}

$(document).on('click', '.signup-promo-placeholder-js', function() {
	$(this).hide();
	$(this).parent().parent().find('.signup-promo-field').show();
});

function getQuickPrice(price) {
	var minPrice = MIN_PRICE;
	if (actor_lang == 'ru' && lang != 'ru') {
		minPrice = minPrice * CURRENCY_RATE * 100;
		minPrice = Math.round(minPrice) / 100.0;
	}
	var newPrice;
	newPrice = Math.floor(price / 2);
	if (newPrice < minPrice) {
		newPrice = minPrice;
	}
	return newPrice;
}

function getQuickTime(time) {
	var minTime = 1;
	var quickTime;
	quickTime = Math.round(1.0972 * Math.pow(time, 0.6305));
	if (quickTime < minTime) {
		quickTime = minTime;
	}
	if (quickTime === 2) {
		quickTime = 1;
	}
	if (time === 4 || time === 5) {
		quickTime = 2;
	}
	if (time === 7) {
		quickTime = 3;
	}
	return quickTime;
}
var notifyIsLoad = false;

function loadNotify(insertTo) {
	if (notifyIsLoad !== false) {
		return false;
	}
	notifyIsLoad = true;
	$.get('/new_notify', function(data) {
		data = $(data).html();
		var notificationBlock = $(insertTo);
		notificationBlock.html(data).promise().done(function() {
			$(insertTo).removeClass('wating');
			notificationBlock.jScrollPane();
			notificationBlock.css({
				'overflow': 'inherit'
			});
		});
	});
}

$(function() {
	$('.js-multi-elipsis').each(function() {
		var $div = $(this).find('div');
		var blockHeight = $(this).height();
		while ($div.height() > blockHeight) {
			$div.text(function(index, text) {
				return text.replace(/\s*(\S+)$/, '...');
			});
		}
	});
});

$(document).on('click', '.js-reorder', function() {
	var prdId = $(this).data('prdId');
	var packageType = $(this).data('package');
	var isQuick = !!$(this).data('quick');
	var params = {};

	var button = $(this);
	button.prop('disabled', true).addClass('disabled');

  if(isQuick) {
  	params = {
  		EPID: prdId,
  		packageType: packageType,
  		isQuick: 1
  	};
  	$.post('/api?method=cart_order', params, function(data) {
  		if (data.success === true) {
  			window.location = data.redirect;
  		} else {
        $('#header_cart_morder_ispay').hide(); $('#header_cart_morder').show();
  			button.prop('disabled', false).removeClass('disabled');
  			show_balance_popup(data.purse_amount, 'prd', data.id);
  		}
  	}, 'json');
   } else {
  	params = {
  		prdId: prdId,
  		packageType: packageType,
  		isQuick: 0
  	};
  	$.post('/api?method=cart_add', params, function(data) {
      if(data.success) {
        $('#header_cart_morder_ispay').hide(); $('#header_cart_morder').show();
        if(data.item.ciexists == 1) {
          $('.cart-popup .block-popup .block-popup_body_conteiner .cart-popup_row[data-id="' + data.id + '"]').remove();
        }

        var newitem = '<div class="cart-popup_row" data-id="' + data.id + '">' +
                        '<div class="cart-popup__col cart-popup__image"><a role="button"><img src="' + data.item.photo_first + '" width="90" height="60" alt=""></a></div>' +
                        '<div class="cart-popup__col cart-popup__name"><a role="button" class="cart-popup_text">' + data.item.title + '</a></div>' +
                        '<div class="cart-popup__col cart-popup__count">' + data.item.cnt_item + '</div><div class="cart-popup__col cart-popup__extras">' + data.item.cnt_extras + '</div>' +
                        '<div class="cart-popup__col cart-popup__sum"><span class="cart-popup_price_prd-js" data-price="' + data.item.cost + '">' + data.item.cost_format + '</span>&nbsp;<span class="rouble">Р</span></div>' +
                        '<div class="cart-popup__col cart-popup__delete-block">' +
                          '<div class="cart-popup_delete" onclick="CartModule.deleteItem(this, ' + data.id + ');"></div>' +
                        '</div>' +
                      '</div>';

        $('.cart-popup').addClass('active').find('.block-popup .cart-popup_empty_block').hide();
        $('.cart-popup .block-popup .block-popup_body_conteiner').prepend(newitem);
    		$('.dropdownbox').hide();
    		$('.cart-popup').find('.block-popup:not(.not_to_hide)').fadeIn(200, 'swing');
    		$('.cart-popup .block-popup_body').jScrollPane();
    		update_cart();
    		refreshCartScroll();
    		$('.cart-popup .cart-popup_icon').addClass('active');
    		$('.massage .block-popup:not(.not_to_hide)').hide();
      }
  	}, 'json');
   }

});

function nl2br(str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br/>';
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

$(function() {
	if (typeof ion !== 'undefined') {
		ion.sound({
			sounds: [{
				name: "new_message",
				preload: false
			}],
			volume: 0.2,
			path: "/js/libs/sounds/",
			preload: true
		});

		if (typeof(Storage) !== "undefined") {
			var tabId = Math.random();
			localStorage.setItem("soundTabId", tabId);
			setInterval(function() {
				localStorage.setItem("soundTabId", tabId);
			}, 3000);
		}

		PullModule.on(PULL_EVENT_NEW_INBOX, function() {
			if (MESSAGE_SOUND_ENABLE == 1) {
				if (typeof(Storage) === "undefined" || localStorage.getItem("soundTabId") == tabId) {
					ion.sound.play("new_message");
				}
			}
		});
	}
});

function setMessageSound(target) {
	MESSAGE_SOUND_ENABLE = (MESSAGE_SOUND_ENABLE == 1) ? 0 : 1;
	$(".message_sound_block .js-message-sound-ico").toggleClass("hidden");
  localStorage.setItem('change-sound-message', MESSAGE_SOUND_ENABLE);
}

$(window).bind('storage', function(e) {
	if (e.originalEvent.key === 'change-sound-message') {
		MESSAGE_SOUND_ENABLE = e.originalEvent.newValue;
		$(".message_sound_block .js-message-sound-ico").toggleClass("hidden");
	}
});

function getBillAmount(amount) {
	var sum = parseInt(amount);
	var sumComission = 0;
	if (sum > 0) {
		sumComission = Math.round(sum + (sum * parseFloat(BILL_COMISSION)) / 100);
	}
	return sumComission;
}

function ValidInputsModule() {
	var _selectors = {
		inputError: '.input-error',
		input: '.input_field-js',
		inputName: '.input_name-js',
		inputEmail: '.input_email-js',
		inputMessage: '.input_message-js',
		form: '.send_contact_message-js',
	};


	_checkInputs = function() {
		var isError = false;

		var nameError = _checkName();
		if (nameError.length > 0) {
			isError = true;
			_showError(_selectors.inputName, nameError);

		}

		var messageError = _checkMessage();
		if (messageError.length > 0) {
			isError = true;
			_showError(_selectors.inputMessage, messageError);
		}

		var emailError = _checkEmail();
		if (emailError.length > 0) {
			isError = true;
			_showError(_selectors.inputEmail, emailError);
		}

		if (isError) {
			return false;
		}
	};

	_showError = function(selector, text) {
		$(selector).find(_selectors.inputError).text(text);
		$(selector).find(_selectors.inputError).show();
	}

	_checkName = function() {
		var val = $(_selectors.inputName + ' input').val();
		if (val.length == 0) {
			return 'Нужно ввести имя';
		}
		return '';
	};

	_checkMessage = function() {
		var val = $(_selectors.inputMessage + ' textarea').val();
		if (val.length == 0) {
			return 'Нужно ввести сообщение';
		}
		return '';
	};

	_checkEmail = function() {
		var val = $(_selectors.inputEmail + ' input').val();
		if (val.length == 0) {
			return 'Нужно ввести email';
		}
		if (!validateEmail(val)) {
			return 'Неверный формат email';
		}
		return '';
	};

	_scrollToError = function(selector) {
		if ($(selector).length > 0) {
			$('html,body').animate({
				scrollTop: $(selector).offset().top
			}, 800);
		}
	};

	_clearError = function(el) {
		var $errorCon = $(el).closest(_selectors.input).find(_selectors.inputError);
		$errorCon.text("");
		$errorCon.hide();
		return true;
	};

	var _setEvents = function() {
		$(_selectors.form).on('submit', _checkInputs);

		$(_selectors.input + ' input, ' + _selectors.input + ' textarea').each(function(i, el) {
			$(el).keyup(function() {
				_clearError(el)
			});
		});
	};

	return {
		init: function() {
			_setEvents();
			_scrollToError(_selectors.inputError + ':visible');
		}
	};
};

function addT(base, translate) {
  //todo delete
}

function t(base, params) {
	return replacePlaceHolders(base, params);
}

function replacePlaceHolders(template, placeholders) {
	var result = template;
	if (typeof placeholders != 'undefined') {
		for (var i = 0; i < placeholders.length; i++) {
			result = result.replace('{{' + i + '}}', placeholders[i]);
		}
	}
	return result;
}
/**
 * Аналог функции in_array в php для Javascript
 * @param {string|int} needle
 * @param {array} haystack
 * @param {bool} strict
 * @returns {Boolean}
 */
function in_array(needle, haystack, strict) { // Checks if a value exists in an array
	//
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	var found = false,
		key, strict = !!strict;
	for (key in haystack) {
		if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
			found = true;
			break;
		}
	}
	return found;
}

/**
 * Проверка email согласно формата RFC 822
 * @param {string} email
 * @return bool
 */
function validateEmail(email) {
	var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
	return re.test(email);
}

/**
 * Сделать первую букву заглавной
 * @returns {String}
 */
String.prototype.ucFirst = function() {
	var str = this;
	if (str.length) {
		str = str.charAt(0).toUpperCase() + str.slice(1);
	}
	return str;
};

$(document).on('change', '.count-order-in-page-js', function() {
	if ($(this).val().length > 0) {
		window.location.href = '?s=' + $(this).data('page') + '&limit=' + $(this).val();
	}
});

// Выпадающий список выбора языка
$(document).ready(function() {
	$(".lang-selector")
		.mouseenter(function() {
			$(this).find(".lang-selector-link").addClass("active");
			$(this).find(".block-popup:not(.not_to_hide)").fadeIn(200, 'swing');
		})
		.mouseleave(function() {
			$(this).find(".lang-selector-link").removeClass("active");
			$(this).find(".block-popup:not(.not_to_hide)").hide();
		});
});

function clearPriceStr(str) {
	if (typeof str == "string") {
		str = str.replace(" ", "");
	}
	return str;
}

function btnDisableToggle(action) {
  if (action === 'on') {
    $('.btn-disable-toggle').prop('disabled', true).addClass('disabled');
  } else if (action === 'off') {
    $('.btn-disable-toggle').prop('disabled', false).removeClass('disabled');
  }
}

function showDodjiDescription(target) {
	target.closest('table').find('.track-order_description').toggle();
	target.find('img').toggleClass('rotate180');
}

function hideDodjiDescription(target) {
	target.closest('.track-order_description').hide();
	target.closest('table').find('.prd img').toggleClass('rotate180');
	$('html, body').animate({
		scrollTop: target.closest('.track-head').offset().top
	}, 1);
}

function showInworkInfo(target) {
	target.find('img').toggleClass('rotate180');
	$(".js-block-inwork-info").toggleClass("hidden");

}

function hideInworkInfo() {
	$(".js-link-show-inwork-info").find('img').removeClass('rotate180');
	$(".js-block-inwork-info").addClass("hidden");
}

$(document).on('click', '.bages-show-all', function() {
	$('.bages-container').toggleClass('h48px');
	$(this).remove();
});
$(document).on('click', '.prds-show-all', function() {
	$('.user-prd-list-container').removeClass('user-prd-list');
	$(this).addClass('hidden');
	$('.prds-hide-all').removeClass('hidden');
});
$(document).on('click', '.prds-hide-all', function() {
	$('.user-prd-list-container').addClass('user-prd-list');
	$(this).addClass('hidden');
	$('.prds-show-all').removeClass('hidden');
});

$(document).on('click', '.inbox-allow-request-notification button', function() {
	var container = $(this).closest('.inbox-allow-request-notification');
	var inboxId = $(container).data('id');
	$.ajax({
		type: 'POST',
		url: '',
		async: true,
		data: {
			action: 'allowRequest',
			inboxId: inboxId,
			isAccept: ($(this).hasClass('accept') ? 1 : 0)
		},
		success: function(r) {
			$(container).next('span').removeClass('hidden');
			$(container).remove();
		}
	}, 'json');
});

function makeOrderShortLink(id) {
	return '/z/' + parseInt(id + '', 10).toString(36);
}

function replaceTextMessage(message) {
	var newmsg = message.replace(/<br\s*[\/]?>/gi, '\n').replace(/<b>/g, '[b]').replace(/<\/b>/g, '[/b]');
	if (message.match(/<noindex>(.+?)<\/noindex>/g)) {
		newmsg = newmsg.replace(/<noindex>(.+?)<\/noindex>/g, '$1').replace(/<a.*?>(.+?)<\/a>/g, '$1');
	}
	return newmsg.replace(/<a[^>]+?href\s*?=\s*?"([^\"]+)".*?<\/a>/g, '$1');
}

var linkOnceClicked = false;
$(document).on("click", "a.js-link-once", function() {
	if (!linkOnceClicked) {
		linkOnceClicked = true;
		return true;
	}
	return false;
});

// Проверять вводимый текст на наличие стоп-слов (#4444)
var StopwordsModule = {

	_config: {
		defaultSelector: '.js-stopwords-check',
		defaultWarningsContainerClass: 'js-stopwords-warning-container'
	},

	_components: {
		commission: {
			pattern: /(?:^|[^а-яa-z])(комисс?[а-я]{2,3}|fees?)(?![а-яa-z])|(?:^|[^\d])20\s?%/gi,
			message: 'Не следует обсуждать в переписке с покупателем комиссию сервиса. Комиссия ' + cot_sitename['name_en'] + ' обеспечивает развитие проекта и безопасность сделок. Каждая успешная сделка в системе увеличивает ваши продажи.'
		},
		contacts: {
			pattern: /(?:^|[^а-яa-z@])(мейл|mail|email|почт[а-я]{1,2}|скайп|skype|vk\.com)(?![а-яa-z])|(?:^|[^\d])\+?[\d]{11}(?!\d)|@[\w]+\.[\w]{2,4}(?![а-яa-z])/gi,
			message: 'Не сообщайте контакты без крайней необходимости. Общение и заказы за пределами ' + cot_sitename['name_en'] + ' несут высокий риск мошенничества. А внутри RZ-WORK - проходят гладко и безопасно.'
		}
	},

	_exclude: /^(почти|комиссар|комисар)$/i,

	_exists: function(component, text) {
		var matches = text.match(component.pattern);
		if (matches) {
			matches = matches.filter(function(n) {
				return !StopwordsModule._exclude.test(n.trim())
			});
		}
		return (matches) ? (matches.length > 0) : false;
	},

	_getWarningContainer: function(element) {
		var warningContainer = $('<div/>', {
			class: this._config.defaultWarningsContainerClass
		});
		var form = element.closest('form');
		if (form.length !== 0) {
			var submitButton = form.find('input[type=submit]');
			if (submitButton.length !== 0) {
				warningContainer.insertBefore(submitButton);
			} else {
				form.append(warningContainer);
			}
		} else {
			warningContainer.insertAfter(element);
		}
		return warningContainer;
	},

	_getWarningBlock: function(component) {
		return $('<div/>', {
			class: 'js-stopwords-warning'
		}).append(
			$('<div/>', {
				class: 'position-r mt10'
			}).append(
				$('<div/>', {
					class: 'position-a'
				}).html('<i class="icon ico-warningSmall"></i>'),
				$('<div/>', {
					class: 'dib v-align-t fs12 lh15 color-red pl30'
				}).text(component.message)
			)
		);
	},

	_toggleWarnings: function(warningContainer, found) {
		warningContainer.empty();
		for (var i = 0; i < found.length; i++) {
			warningContainer.append(this._getWarningBlock(found[i]));
		}
	},

	_test: function(text) {
		var found = [];
		for (var c in this._components) {
			if (this._components.hasOwnProperty(c)) {
				var component = this._components[c];
				if (this._exists(component, text)) {
					found.push(component);
				}
			}
		}
		return found;
	},

	init: function(selector) {
		selector = (typeof selector !== 'undefined') ? selector : this._config.defaultSelector;

		$(document).on('input', selector, function() {
			var element = $(this),
				text = element.val(),
				found = StopwordsModule._test(text),
				warningContainer = (this.dataset.stopwordsWarningContainer) ? $(this.dataset.stopwordsWarningContainer) : $('.' + StopwordsModule._config.defaultWarningsContainerClass + ':visible');

			if (warningContainer.length === 0) {
				warningContainer = StopwordsModule._getWarningContainer(element);
			}

			StopwordsModule._toggleWarnings(warningContainer, found);
		});
	}
};

StopwordsModule.init();

/**
 * Инициализация функционала копирования ссылки на якорь
 */
function anchorInit() {
	var hash = window.location.hash;
	$('.anchor-init').each(function() {
		var anchor = $(this);
		anchor.append("<div class='js-tooltip anchor-init-obj  fa-anchor' onclick='copyAnchor(this)'  data-tooltip-text='Скопировать'></div>");
		if (hash == ("#" + anchor.attr("id"))) {
			anchor.parents('.faq_page-block_item').addClass('active');
			anchor.parents('.faq_sub-cat').addClass('active');
		}
	});
	var item = $(document.getElementById(hash.replace("#", "")));
	if (item.length) {
		setTimeout(function() {
			if ($('.faq_page-block').length) {
				$(window).scrollTop(item.position().top + $('.header').height() + 20);
			} else {
				$(window).scrollTop(item.position().top - $('.header').height() - 10);
			}
		}, 50);
	}
}


/**
 * Копирует из элемента idи создает ссылку якорь на этот элемент
 * @param elm
 */
function copyAnchor(elm) {
	var obj = $(elm);
	var url = window.location.protocol + "//" + window.location.host + window.location.pathname;
	var hash = obj.parent().attr('id');
	copyTextToClipboard(url + "#" + hash);
	obj.tooltip('update', 'Скопировано');
	obj.tooltip('show');
	event.stopPropagation();
}

/**
 * Скопировать текст в буффер обмена
 * @param text
 */
function copyTextToClipboard(text) {
	var textArea = document.createElement("textarea");
	textArea.style.position = 'fixed';
	textArea.style.top = 0;
	textArea.style.left = 0;
	textArea.style.width = '2em';
	textArea.style.height = '2em';
	textArea.style.padding = 0;
	textArea.style.border = 'none';
	textArea.style.outline = 'none';
	textArea.style.boxShadow = 'none';
	textArea.style.background = 'transparent';
	textArea.value = text;
	document.body.appendChild(textArea);
	textArea.select();
	try {
		var successful = document.execCommand('copy');
	} catch (err) {
		console.log('Oops, unable to copy');
	}
	document.body.removeChild(textArea);
}

function isMobile() {
	return $("body").hasClass("is_mobile");
}

function isNotMobile() {
	return !isMobile();
}

// Обновление описания промо
jQuery(function() {
	initPromoCounter();
	$('body').on('click', '[name="update_promo"]', function() {
		var $el = $(this);
		var $form = $el.closest('.prd_promo');
		var prdId = $form.attr('data-prd-id');
		var promoText = $form.find('[name="promo_text"]').val();

		updatePromo(prdId, promoText);
	});
	$('.prd_promo_wrapper [name="promo_text"]').keyup(function() {
		var $parent = $(this).closest('.prd_promo_wrapper');
		var characterCount = $(this).val().length;
		var current = $parent.find('.promo_counter_current');

		current.text(characterCount);
	});
});

function initPromoCounter() {
	var $allPromo = $('.prd_promo_wrapper .promo_text');
	$allPromo.each(function() {
		var $el = $(this);
		var textLength = $el.find('[name="promo_text"]').val().length;
		var $counter = $el.find('.promo_counter_current');
		$counter.text(textLength);
	});
};

function prdPromoEdit(prdId) {
	var $el = $('.prd_promo[data-prd-id="' + prdId + '"]');
	var $promoEditBlock = $el.find('.prd_promo_edit');
	var $promoAddBlock = $el.find('.prd_promo_add');

	$promoEditBlock.hide();
	$promoAddBlock.fadeIn();
};

function prdPromoSuccess(prdId, bonusText) {
	var $el = $('.prd_promo[data-prd-id="' + prdId + '"]');
	var $promoEditBlock = $el.find('.prd_promo_edit');
	var $promoAddBlock = $el.find('.prd_promo_add');
	var $promoInModeration = $promoEditBlock.find('.prd_promo_in_moderation');

	$promoAddBlock.hide();
	$promoEditBlock.find('.prd_promo_content_edit').text(removePlusAtBeginingString(bonusText));
	$promoEditBlock.fadeIn();
	$promoInModeration.show();
};

function updatePromo(prdId, bonusText) {
	if (!prdId) return;

	var $el = $('.prd_promo[data-prd-id="' + prdId + '"]');
	var $btn = $el.find('[name="update_promo"]');

	function startLoader() {
		var loader = '<div class="promo_loader"><span class="preloader__ico"></span></div>';
		$btn.replaceWith(loader);
	};

	function stopLoader() {
		$el.find('.promo_loader').replaceWith($btn);
	};

	startLoader();
	$.ajax({
		type: "POST",
		url: '/manage_prds',
		dataType: 'json',
		data: {
			'action': 'add_bonus',
			'prdId': prdId,
			'bonusText': bonusText
		},
		success: function(data) {
			if (data.response) {
				if (bonusText) prdPromoSuccess(prdId, bonusText);
			} else {
				console.log('error');
			}
			stopLoader();
		}
	});
};

function removePlusAtBeginingString(text) {
	var textClean = $.trim(text);
	return $.trim(textClean.replace(/^(\+)/, ""));
}

var Base64 = {
	_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	encode: function(e) {
		var t = "";
		var n, r, i, s, o, u, a;
		var f = 0;
		e = Base64._utf8_encode(e);
		while (f < e.length) {
			n = e.charCodeAt(f++);
			r = e.charCodeAt(f++);
			i = e.charCodeAt(f++);
			s = n >> 2;
			o = (n & 3) << 4 | r >> 4;
			u = (r & 15) << 2 | i >> 6;
			a = i & 63;
			if (isNaN(r)) {
				u = a = 64
			} else if (isNaN(i)) {
				a = 64
			}
			t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
		}
		return t
	},
	decode: function(e) {
		var t = "";
		var n, r, i;
		var s, o, u, a;
		var f = 0;
		e = e.replace(/[^A-Za-z0-9+/=]/g, "");
		while (f < e.length) {
			s = this._keyStr.indexOf(e.charAt(f++));
			o = this._keyStr.indexOf(e.charAt(f++));
			u = this._keyStr.indexOf(e.charAt(f++));
			a = this._keyStr.indexOf(e.charAt(f++));
			n = s << 2 | o >> 4;
			r = (o & 15) << 4 | u >> 2;
			i = (u & 3) << 6 | a;
			t = t + String.fromCharCode(n);
			if (u != 64) {
				t = t + String.fromCharCode(r)
			}
			if (a != 64) {
				t = t + String.fromCharCode(i)
			}
		}
		t = Base64._utf8_decode(t);
		return t
	},
	_utf8_encode: function(e) {
		e = e.replace(/rn/g, "n");
		var t = "";
		for (var n = 0; n < e.length; n++) {
			var r = e.charCodeAt(n);
			if (r < 128) {
				t += String.fromCharCode(r)
			} else if (r > 127 && r < 2048) {
				t += String.fromCharCode(r >> 6 | 192);
				t += String.fromCharCode(r & 63 | 128)
			} else {
				t += String.fromCharCode(r >> 12 | 224);
				t += String.fromCharCode(r >> 6 & 63 | 128);
				t += String.fromCharCode(r & 63 | 128)
			}
		}
		return t
	},
	_utf8_decode: function(e) {
		var t = "";
		var n = 0;
		var r = c1 = c2 = 0;
		while (n < e.length) {
			r = e.charCodeAt(n);
			if (r < 128) {
				t += String.fromCharCode(r);
				n++
			} else if (r > 191 && r < 224) {
				c2 = e.charCodeAt(n + 1);
				t += String.fromCharCode((r & 31) << 6 | c2 & 63);
				n += 2
			} else {
				c2 = e.charCodeAt(n + 1);
				c3 = e.charCodeAt(n + 2);
				t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
				n += 3
			}
		}
		return t
	}
}

/**
 * #5118 Статусы продавца «Занят» и «Принимаю заказы»
 */
$(function() {
	var titles = {
		free: 'Принимаю заказы',
		busy: 'Занят'
	};

	var $status = $('.js-worker-status');
	var $help = $('.js-worker-status-help');
	var $tooltip = $('.js-tooltip-status');

	/**
	 * Переключение статуса
	 */
	$(document).on('click', '.js-worker-status-switch', function() {
		var status = $(this).data('status');
		var newStatus = status === 'free' ? 'busy' : 'free';
		var switchAll = $(this).data('switch-all');

		var params = {
			status: newStatus
		};
		if (typeof switchAll !== 'undefined') {
			params.switch_all = switchAll;
		}

		// Кнопка может находится в попапе, тогда после выполнения запроса
		// попап нужно будет закрыть
		var $popupClose = $(this).closest('.popup').find('.popup-close-js').eq(0);

		Api.request("changeworkstatus", params, function(data) {
			$popupClose.click();
			if (data.error) {
				alert(data.error);
			} else {
				if (data.status === 'none') {
					$status.remove();
					$help.remove();
					$tooltip.remove();
					$('.logoutheader .userdata').removeClass('has-status');
					alert(data.message);
				} else {
					$status.removeClass('worker-status-' + status)
						.addClass('worker-status-' + data.status)
						.text(titles[data.status])
						.data('status', data.status);

					var tooltipActive = $('.js-tooltip-' + data.status);
					$tooltip.addClass('hidden');
					tooltipActive.removeClass('hidden');
				}
				if (location.pathname === '/manage_items') {
					location.assign(location.pathname);
				}
			}
		});
	});
});

// TOOLTIPSTER

var TOOLTIP_CIRCLE = ".tooltip_circle, .btn-title_right";
var TOOLTIP_CIRCLE_HOVER = "tooltip_circle_hover";

/**
 * Конфиг для подсказок плагина - tooltipster
 * http://iamceege.github.io/tooltipster/#options
 */
var TOOLTIP_CONFIG = {
	animationDuration: 200,
	distance: 4,
	contentAsHTML: true,
	interactive: true,
	contentCloning: true,
	side: 'top',
	theme: 'tooltipster-light',
	minIntersection: 14,
	zIndex: 999,
	delay: [50, 90],
	trigger: 'custom',
	triggerOpen: {
		mouseenter: true,
		touchstart: true
	},
	triggerClose: {
		mouseleave: true,
		scroll: true,
		tap: true
	},
	functionInit: function(instance, helper) {
		var $origin = $(helper.origin),
			_data = $origin.attr()['data']['tooltip'],
			_maxWidth = null;

		// Задаем опции через атрибуты [data-tooltip-*]
		// Кастомные опции
		if (_data) {
			$.each(_data, function(option, value) {
				switch (option) {
					case 'text':
						if (!instance.content() && value)
							instance.content(value);
						break;
					case 'theme':
						if (value == 'dark') {
							instance.option('theme', 'tooltipster-borderless');
							instance.option('minIntersection', 12);
						}
						break;
					case 'width':
						if (value == 'auto') {
							_maxWidth = value;
						} else {
							instance.option('maxWidth', value);
						}
						break;
					case 'destroy':
						if (value == true) {
							instance.option('functionAfter', function(instance, helper) {
								instance.destroy();
							});
						}
						break;
					default:
						instance.option(option, value);
				}
			});
		}

		// Выставляем максимальную ширину
		var _content = instance.content();

		if (_content && _maxWidth != 'auto') {
			var _length = '';

			if (typeof _content == 'object') {
				_content = jQuery(_content[0]).html();
			}
			_length = _content.replace(/<[^>]+>/g, '').length;

			if (_length > 40 && _length < 100) _maxWidth = 220;
			if (_length > 100 && _length < 200) _maxWidth = 280;
			if (_length > 200) _maxWidth = 400;

			instance.option('maxWidth', _maxWidth); // Старый нормальный вариант, но не красивый внешне
		}
	},
	functionBefore: function(instance, helper) {
		$.each($.tooltipster.instances(), function(i, instance) {
			instance.close();
		});

		// Подсветить (?)
		var $origin = $(helper.origin);
		if ($origin.is(TOOLTIP_CIRCLE)) $origin.addClass(TOOLTIP_CIRCLE_HOVER);
	},
	functionAfter: function(instance, helper) {
		// Убрать подсветку (?)
		var $origin = $(helper.origin);
		if ($origin.is(TOOLTIP_CIRCLE)) $origin.removeClass(TOOLTIP_CIRCLE_HOVER);
	}
};

jQuery(function() {
	jQuery('.tooltipster').tooltipster(TOOLTIP_CONFIG);
	// Навешиваем подсказку на все новые элементы
	jQuery('body').on('mouseenter', '.tooltipster:not(.tooltipstered)', function() {
		jQuery(this)
			.tooltipster(TOOLTIP_CONFIG)
			.tooltipster('open');
	});
});

// TOOLTIPSTER END