var DodjiSaveModule = (function() {
	'use strict';

	var MAX_BUNDLE_CUSTOM_EXTRA = 3;

	/**
	 * @type {
	 *          {
	 *              categories: {object},
	 *              selectedCategory: {integer},
	 *              extras: {object},
	 *              categoryExtras: {object},
	 *              categoriesWithAttributes: {array},
	 *              customBundleExtras: {object},
	 *              categoryPrices: {object},
	 *              photo: {object}
	 *          }
	 *       }
	 *
	 * @private
	 */
	var _options = {};
	var _selectedPackageExtras = {};
	var _prdPackages = {};
	var _saveMode = {};
	var _prdId = {};
	var _prdPackage = {};
	var prdPhotos = {};
  var _formCache = '';
	var _prdUrl = '';
  var _minDodjiPrice = 0;
  var _dodjirate = 0;
	var _prdPrice = 0;
  var _prdPriceDodji = 0;
	var timer;

	/**
	 * @readonly
	 *
	 * @namespace
	 * @property {string}  step
	 * @property {string}  secondStep
	 * @property {string}  nextStep
	 * @property {string}  category
	 *
	 * @property {object}  field
	 * @property {string}  field.block
	 * @property {string}  field.hint
	 * @property {string}  field.input
	 * @property {string}  field.error
	 *
	 * @property {object}  bundle
	 * @property {string}  bundle.item
	 * @property {string}  bundle.input
	 * @property {string}  bundle.extras
	 *
	 * @property {object}  bundle.addCustomExtra
	 * @property {string}  bundle.addCustomExtra.btn
	 * @property {string}  bundle.addCustomExtra.type
	 * @property {string}  bundle.addCustomExtra.name
	 *
	 * @property {object}  bundleSize
	 * @property {string}  bundleSize.block
	 * @property {string}  bundleSize.checkbox
	 */
	var _selectors = {
		step: '.js-step',
		secondStep: '.js-step-2',
		nextStep: '.js-next-step-btn',
		nextStepBlock: '.prd-save-step__footer',
		category: '.js-category-select',
		saveButton: '.js-save-prd',
		prdForm: '.js-prd-save-form',
		overlay: '.bundle-overlay',
		overlayButton: '.js-show_lesson-btn',
		lessonPopupContainer: '.js-popup-bundle-overlay__container',
		tooltipLesson: '.js-popup-field-tooltip_bundle',
		content_editor: '.js-content-editor', // поле contenteditable
		content_storage: '.js-content-storage', // поле textarea или input где хрянится строка из contenteditable
		field: {
			block: '.js-field-block',
			hint: '.js-field-input-hint',
			hintBundle: '.js-field-input-hint_bundle',
			input: '.js-field-input',
			select: '.js-field-select',
			inputCategory: '.js-field-input-cat',
			description: '.js-field-input-description',
			instruction: '.js-field-input-instruction',
			error: '.js-prd-save-field-error',
			prdPhoto: '.js-prd-photo-input-first',
			radioBox: '.prd-save-field-radiobox',
			checkBox: '.prd-save-field-checkbox'
		},
		bundle: {
			item: '.js-bundle-item',
			removeCustomExtra: '.js-bundle-item__remove-extra',
			descriptionBlock: '.js-bundle-item__description',
			input: '.js-bundle-item__input',
			inputSelect: '.bundle-item__input_select',
			extras: '.js-bundle-extras',
			addCustomExtra: {
				btn: '.js-add-bundle-extra-btn',
				type: '.js-add-bundle-extra-type',
				name: '.js-add-bundle-extra-name',
				hint: '.js-add-bundle-extra-hint',
				error: '.js-add-bundle-extra-error'
			}
		},
		bundleSize: {
			block: '.js-bundle-size-selector',
			checkbox: '.js-bundle-size-checkbox'
		},
		attribute: {
			addCustomAttribute: {
				btn: '.js-add-custom-attribute-btn'
			},
			removeCustomAttribute: {
				btn: '.js-remove-custom-attribute-btn'
			},
			bindableAttribute: '.js-bindable-attribute'
		}
	};

	var _errorMessages = {
		notCustomName: 'Введите название опции',
		notCustomHint: 'Введите подсказку опции',
		duplicateOption: 'Дублирование опций недопустимо'
	};

	/**
	 * Bundle type of step
	 *
	 * @readonly
	 * @enum {string}
	 */
	var stepType = {
		BUNDLE: 'bundle',
		SINGLE: 'single'
	};

	var that;

	var _lessonPopupClass = 'popup-lesson';

	var $_bundleItems = {};

	var _files = {
		description: {},
	};
	/**
	 * Show next step
	 * @private
	 */
	var _nextStep = function() {
		if (!_checkAllStepFields($(this).closest(_selectors.step), true)) {
			_scrollOnTopError();
			return false;
		}

		$(this).closest(_selectors.step).next(_selectors.step).removeClass('prd-save-step_inactive');
		$(this).css('visibility', 'hidden');
		$(this).parent().addClass('prd-save-step__footer_alternative');
	};

	var _checkAllStepFields = function($stepBlock, isShowText) {
		if (isShowText !== true) {
			isShowText = false;
		}
		$stepBlock.find(_selectors.field.input + ', ' + _selectors.field.inputCategory + ', ' + _selectors.field.prdPhoto).each(function() {
			if ($(this).hasClass('js-add-extra-row__name-input') && $(_selectors.secondStep).hasClass('prd-save-step_type_bundle')) {
				that.validator.hideError($(this));
				return;
			}

			that.validator.checkField($(this), isShowText);
			if ($(this).val() !== null) {
				_setCurrentInputSymbolCount($(this));
			}
		});

		$stepBlock.find(_selectors.bundle.input).each(function() {
			that.validator.checkField($(this), isShowText);
			_setCurrentInputSymbolCount($(this));
		});

		$stepBlock.find(_selectors.field.radioBox).each(function() {
			that.validator.checkField($(this), isShowText);
		});

		$stepBlock.find(_selectors.field.checkBox).each(function() {
			that.validator.checkField($(this), isShowText);
		});

		if ($stepBlock.hasClass('js-step-2')) {
			_checkActiveBundleCustomExtraCount();
		}

		return !$stepBlock.find('.prd-save-step__field-value_error').length;
	};

	/**
	 * Set base events
	 * @private
	 */
	var _setEvents = function() {
		$(_selectors.nextStep).on('click', _nextStep);
		$(_selectors.category).on('change.categoryList', _onChangeCategory);
		$(_selectors.overlay).on('click', _onClickOverlay);
		$(_selectors.overlayButton).on('click', _showLesson);
		$(_selectors.tooltipLesson).on('click', _showLesson);

		$(_selectors.bundleSize.checkbox).on('change', _changeBundleSize);
		$(_selectors.field.block).on('input', _selectors.field.input, _onChangeInput);
		$(_selectors.field.block).on('input', _selectors.bundle.input, _onChangeInput);
		$(_selectors.field.block).on('tbwchange', _selectors.field.description, _onChangeInput);
		$(_selectors.field.block).on('tbwchange', _selectors.field.instruction, _onChangeInput);

		$(_selectors.field.block).on('blur', _selectors.field.input, _onBlurInput);
		$(_selectors.field.block).on('blur', _selectors.bundle.input, _onBlurInput);
		$(_selectors.field.block).on('tbwblur', _selectors.field.input, _onBlurInput);
		$(_selectors.field.block).on('change', _selectors.field.inputCategory, _onBlurInput);

		$(document).on('input', _selectors.content_editor, _onInputEditor);

		$(document).on('click', _selectors.attribute.addCustomAttribute.btn, _onAddCustomAttribute);
		$(document).on('click', _selectors.attribute.removeCustomAttribute.btn, _onRemoveCustomAttribute);

		$(document).on('click', _selectors.bundle.addCustomExtra.btn, _onAddCustomBundleExtra);

		$(document).on('change', _selectors.bundle.inputSelect, _setSelectChecked);

		$(_selectors.saveButton).on('click', _saveDodji);

		$('.js-quick-input').on('click', _onQuickClick);

		$('#step1-auditory').chosen({
			width: '100%',
			disable_search: true
		});

		$('#step1-links').blur(function() {
			var $input = $(this);
			var text = $input.val();
			var lines = text.split(/[,\s]/);

			var sites = [];
			for (var i = 0; i < lines.length; i++) {
				if (lines[i] && sites.indexOf(lines[i]) === -1 && lines[i].match(/.\../)) {
					var hostname = _extractHostname(lines[i]);
					if (hostname) {
						sites.push(hostname);
					}
				}
			}

			sites = sites.slice(0, $input.data('limit'));

			$input.val(sites.join("\n"));
		});

		$(document).on('click', '.js-bundle-item__field_add-custom', function() {
			show_popup($('.js-add-package-extra-popup').html(), 'popup-add-package-extra');
			$('.popup_content').find('.js-tooltip').tooltip();
			$('.popup_content').find('.js-add-bundle-extra-type').each(function() {
				$(this).attr('id', $(this).data('id'));
			});

			$('.popup_content').find('.js-add-bundle-extra-name, .js-add-bundle-extra-hint').on('input', function() {
				_setCurrentInputSymbolCount($(this));
			});
		});

		$(_selectors.secondStep).find('.prd-save-step__container').on('mouseenter', function() {
			var lessonBlock = $(this).find('.js-tooltip-lesson')[0];
			showDodjiTooltip.apply(lessonBlock);
			var timer = setTimeout(function() {

			}, 200);
			$(lessonBlock).data('timer', timer);
		});

		$(_selectors.secondStep).on('input', 'input[name="my_extras_price_dodji[]"]', function(event) {
      var ch = $(this).val().replace(/[^\d]/g, '').replace(/^[0]+/g, '');

      $(this).val(ch);
		});

    $(_selectors.secondStep).on('input', 'input[name^="bundle_free_price_dodji_value"]', function(event) {
      var ch = $(this).val().replace(/[^\d]/g, '').replace(/^[0]+/g, '');
      $(this).val(ch);
		});

		$(_selectors.secondStep).find('.prd-save-step__container').on('mouseleave', function() {
			var lessonBlock = $(this).find('.js-tooltip-lesson')[0];
			clearTimeout($(lessonBlock).data('timer') ^ 0);
			$(lessonBlock).find('.field-tooltip').fadeOut(150);
		});
		setFreeTooltip();
	};
	var unbindFreeTooltip = function() {
		$(_selectors.secondStep).find('.free-price-step .fake-price-cover,.free-price-step .bundle_price').unbind('mouseenter').unbind('mouseleave');
	}
	var setFreeTooltip = function() {
		$(_selectors.secondStep).find('.free-price-step .fake-price-cover,.free-price-step .bundle_price').on('mouseenter', function() {
			var lessonBlock = $(".prd-save-step__container").find('.js-tooltip-lesson')[0];
			showDodjiTooltip.apply(lessonBlock, [".price-tooltip .field-tooltip", '.bundle_price']);
			$(lessonBlock).find('.field-tooltip:not(.field-tooltip_bundle_price)').fadeOut(150);
		});
		$(_selectors.secondStep).find('.free-price-step .fake-price-cover').on('mouseleave', function() {

		});
	}
	var deleteFileCallback = function(file, cb) {
		var html = '<div>' +
			'<h1 class="popup__title">Удаление файла</h1>' +
			'<hr class="gray">' +
			'<div style="display:inline-block;width:100%;">' +
			'<p class="ta-center f15 ml10 mt20 pb20">Вы действительно хотите удалить файл?</p>';

		html += '<button class="file-upload-delete-btn hoverMe white-btn w160 mt20  f16" style="height:40px;">Да</button>' +
			'<button class="hoverMe white-btn w160 mt20 pull-right popup-close-js f16" style="height:40px;">Нет</button></div>' +
			'</div>';

		show_popup(html);

		$('.file-upload-delete-btn').click(function() {
			remove_popup();
			$.ajax({
				type: "POST",
				url: '/api?method=deleteMav',
				dataType: 'json',
				data: {
					code: _prdId,
					file_id: file.id,
          ext: 'market'
				},
				success: function(data) {
					if (data.success === true) {
						cb();
					} else {
						popup_error('Ошибка удаления файла');
					}
				},
				error: function() {
					popup_error('Ошибка удаления файла');
				},
				processData: true
			});
		})
	};

	var _extractHostname = function(url) {
		var hostname;
		//find & remove protocol (http, ftp, etc.) and get hostname

		if (url.indexOf("://") > -1) {
			hostname = url.split('/')[2];
		} else {
			hostname = url.split('/')[0];
		}

		//find & remove port number
		hostname = hostname.split(':')[0];
		//find & remove "?"
		hostname = hostname.split('?')[0];

		return hostname.toLowerCase();
	};

	var _saveDodji = function() {
		if ($(this).data('loading')) {
			return;
		}

		var errorStatus = false;
		$(_selectors.step).each(function() {
			var currentErrorStatus = !_checkAllStepFields($(this), true);
			if (currentErrorStatus && !errorStatus) {
				errorStatus = true;
			}
		});

		if (errorStatus) {
			_scrollOnTopError();
			return false;
		}

		var saveUrl = '';
		if (_saveMode == 'update') {
			saveUrl = '/market/edit/' + _prdId + '?a=update';
		} else {
			saveUrl = '/new?a=add';
		}

		$(this).data('loading', true).addClass('btn_disabled');

		if (!_files.description.canSave()) {
			$(".preloader_prd").show().find('.preloader_prd_text').text('Ожидание загрузки файлов...');
		}

		var thisButton = $(this);
		var timerId = setInterval(function() {
			if (!_files.description.canSave()) {
				return;
			}

			clearInterval(timerId);

			//if (_formCache == $(_selectors.prdForm).serialize() && typeof wasRejected !== 'undefined' && !wasRejected) {
			//	window.location.href = _prdUrl;
			//	return;
			//}

			var formData = new FormData($(_selectors.prdForm)[0]);
			formData = formDataFilter(formData);

			$(".preloader_prd").show().find('.preloader_prd_text').text('Сохранение...');
			$.ajax({
				type: "POST",
				url: saveUrl,
				data: formData,
				success: function(data) {
					var result = JSON.parse(data);
					$(thisButton).data('loading', false).removeClass('btn_disabled');
					$(".preloader_prd").hide();
					if (result.result == 'success') {
						window.location.href = result.redirectUrl;
					} else {
						_showErrors(result.errors);
					}
				},
				contentType: false,
				processData: false
			});
		}, 200);


		return true;
	};

	var _onQuickClick = function() {
		if ($(this).is(':checked')) {
			$(this).val(1);
		} else {
			$(this).val(0);
		}
	};

	var _showErrors = function(errors) {
		var text = '';

		for (var i = 0; i < errors.length; i++) {
			text += '<p>' + errors[i] + '</p>';
		}

		if (text !== '') {
      $('#event_list').find('.fox_error').remove();
      $('#event_list').after('<div class="fox_error">'+text+'</div>');
			$('html, body').animate({
				scrollTop: 0
			}, 200);
		} else {
			_scrollOnTopError();
		}
	};

	var _scrollOnTopError = function() {
		var found = false;
		$('.prd-save-step__field-value_error').each(function() {
			if (!found && $(this).length) {
				$('html, body').animate({
					scrollTop: $(this).offset().top - 100
				}, 200);
				found = true;
			}
		});
	};

	var _onInputEditor = function(e) {
    var $contentStorage = $(this).siblings(_selectors.content_storage);
		var string = $(this).html();
		string = string.replace(/(?!<\/?(word-error)>)<\/?[\s\w="-:&;?]+>/gi, ""); // удаляем все теги кроме word-error

		var max = $contentStorage.data("max");
		var editorLength = _getTextLengthWithoutTags(string);
		// если для поля задано максимальное значение и оно превышено не даём вводить и вставлять текст
		if (max && editorLength > max) {
			var diff = editorLength - _getTextLengthWithoutTags($contentStorage.val());
			var selection = saveSelection($(this)[0]);

			selection.end = selection.end - diff;
			selection.start = selection.start - diff;

			$(this).html($contentStorage.val());
			restoreSelection($(this)[0], selection);

			return;
		}

		$contentStorage.val(string);
		_setCurrentInputSymbolCount($contentStorage);
		that.validator.hideError($contentStorage);
	};

	var _onChangeInput = function() {
		_setCurrentInputSymbolCount($(this));
		$('.js-add-bundle-extra-count-error').addClass('hidden');
		that.validator.hideError($(this));
		if ($(this).data('only-english')) {
			that.validator.checkField($(this), true);
		}

		// проверяем опции на дубли
		if ($(this).hasClass("js-add-extra-row__name-input")) {
			that.validator.checkOptionDuplicate($(this));
		}
	};

	var _onBlurInput = function() {
		var $input = $(this);
		_setCurrentInputSymbolCount($input);
		that.validator.hideError($input, false);
	};

	var _onAddCustomAttribute = function() {
		var list = $(this).closest('.attribute-list'),
			addBtn = list.find(_selectors.attribute.addCustomAttribute.btn),
			parentId = list.data('parent-id'),
			allowMultiple = list.data('allow-multiple'),
			inputType = (allowMultiple) ? 'checkbox' : 'radio',
			inputClass = (allowMultiple) ? 'styled-checkbox' : 'styled-radio',
			inputName = list.data('input-name'),
			customNextId = $(this).data('custom-count'),
			textInputName = 'new_custom_attribute_title[' + parentId + '][' + customNextId + ']',
			inputId = 'attribute_' + parentId + '_item_custom_' + customNextId;
		$('<div/>', {
				class: 'attribute-item-custom'
			})
			.append(
				$('<input/>', {
					type: inputType,
					class: inputClass,
					name: inputName,
					id: inputId,
					value: customNextId,
          checked: (allowMultiple ? 'checked' : false),
          onclick: (allowMultiple ? 'return false;' : false),
				}),
				$('<label/>', {
					for: inputId
				}).append(
					$('<input/>', {
						type: 'text',
						name: textInputName
					}),
					$('<a/>', {
						href: '#',
						onclick: 'return false;',
						class: 'js-remove-custom-attribute-btn',
						html: '&times;'
					})
				)
			)
			.insertBefore(this).change(_onChangeAttributeItem);
		$(this).data('custom-count', ++customNextId);

		var customCount = list.find('.attribute-item-custom').length,
			customMaxCount = list.data('custom-max-count');
		if (customCount < customMaxCount) {
			addBtn.show();
		} else {
			addBtn.hide();
		}
		$(_selectors.field.checkBox).on('change', _changeClassification);
	};

	var _onRemoveCustomAttribute = function() {
		var list = $(this).closest('.attribute-list'),
			addBtn = list.find(_selectors.attribute.addCustomAttribute.btn);
		$(this).closest('.attribute-item-custom').remove();
		var customCount = list.find('.attribute-item-custom').length,
			customMaxCount = list.data('custom-max-count');
		if (customCount < customMaxCount) {
			addBtn.show();
		} else {
			addBtn.hide();
		}
		$(_selectors.field.checkBox).on('change', _changeClassification);
	};

	var _onAddCustomBundleExtra = function() {
		var $popup = $('.popup_content');
		var $name = $popup.find(_selectors.bundle.addCustomExtra.name);
		var $hint = $popup.find(_selectors.bundle.addCustomExtra.hint);
		var $error = $popup.find(_selectors.bundle.addCustomExtra.error);
		var name = _removeSpaces($name.val());
		var hint = _removeSpaces($hint.val());
		var nameLength = _getTextLengthWithoutTags(name);
		var maxLength = $name.data("max");

		// проверяем дли названия опции
		if (!nameLength) {
			$error.text(_errorMessages.notCustomName);
			$error.show();
			return;
		} else if (nameLength > maxLength) {
			var error = that.validator.getErrorText("max_req", {
				name: $name.data("field-name"),
				count: maxLength
			});
			$error.text(error).show();
			return;
		}

		// проверяем длину подсказки
		if (!hint.length) {
			$error.text(_errorMessages.notCustomHint);
			$error.show();
			return;
		}

		// Проверяем не дублирует ли новая опции уже существующие
		var duplicate = false;
		$(".bundle-item__field_header .bundle-item__field-label").each(function(i, el) {
			if (!duplicate && name === $(el).text().trim()) {
				duplicate = true;
			}
		});
		if (duplicate) {
			$error.text(_errorMessages.duplicateOption);
			$error.show();
			return;
		}

		$error.hide();

		var $addButton = $('.js-bundle-item__field_add-custom');
		var iteration = 1 + ($addButton.data('iteration') ^ 0);
        if(iteration == 1) {
          iteration = 1 + $('.bundle-item__field_custom.js-bundle-extra-custom').length;
        }
		var type = $popup.find(_selectors.bundle.addCustomExtra.type).filter(':checked').val();
		var id = 'n' + iteration;

		$addButton.data('iteration', iteration);

		var $extParams = $('<input>');
		$extParams.attr('type', 'hidden')
			.addClass('extra-custom-param-' + id)
			.attr('name', 'bundle_custom_extra_name[' + id + ']')
			.val(name);
		var $fieldsBlock = $('.js-add-bundle-extra-fields');
		$fieldsBlock.append($extParams);

		$extParams = $('<input>');
		$extParams.attr('type', 'hidden')
			.addClass('extra-custom-param-' + id)
			.attr('name', 'bundle_custom_extra_type[' + id + ']')
			.val(type);
		$fieldsBlock.append($extParams);

		$extParams = $('<input>');
		$extParams.attr('type', 'hidden')
			.addClass('extra-custom-param-' + id)
			.attr('name', 'bundle_custom_extra_hint[' + id + ']')
			.val(hint);
		$fieldsBlock.append($extParams);

		var max = 1;
		var can_lower = '';
		switch (type) {
			case 'integer':
				max = 10;
				can_lower = 1;
				break;
			case 'text':
				max = 0;
				break;
			default:
				break;
		}

		var extra = {
			id: id,
			name: name,
			hint: hint,
			type: type,
			min: 1,
			max: max,
			can_lower: can_lower
		};

		for (var bundleType in $_bundleItems) {
			var $bundleItem = $_bundleItems[bundleType];
			_addBundleCustomExtra($bundleItem, extra, {});
		}

		_addBundleHeader(extra, true);

		$name.val('');
		$hint.val('');
		$('.js-tooltip').tooltip();

		$popup.find('.popup-close-js').trigger('click');
	};

	/**
	 * @deprecated
	 * @private
	 */
	var _setSelectChecked = function() {
		if (($(this).val() ^ 0) > 0) {
			$(this).closest('.bundle-item__field').addClass('bundle-item__field_checked');
		} else {
			$(this).closest('.bundle-item__field').removeClass('bundle-item__field_checked');
		}
	};

	var _setCurrentInputSymbolCount = function($input) {
		var current;
		if ($input.data("hasTags") === true) {
			current = _getTextLengthWithoutTags($input.val());
		} else {
			current = _getTextLength($input.val());
		}


		var text = '';

		if ($input.data('min') && $input.data('max')) {
			if ($input.data('min')) {
				if (current < $input.data('min') ^ 0) {
					if (current > 0) {
						text = current + t(' из ');
					}
					text += t('{{0}} минимум', [$input.data('min')]);
				}
			}
			if ($input.data('max')) {
				if (text == '') {
					if (current > 0) {
						text = t('{{0}} из', [current]) + ' ';
					}
					text += t('{{0}} максимум', [$input.data('max')]);
				}
			}
		} else {
			if ($input.data('min')) {
				if (current > 0) {
					text = t('{{0}} из', [current]) + ' ';
				}
				text += t('{{0}} минимум', [$input.data('min')]);
			} else if ($input.data('max')) {
				if (current > 0) {
					text = t('{{0}} из', [current]) + ' ';
				}
				text += t('{{0}} максимум', [$input.data('max')]);
			}
		}


		if ($input.data('min') || $input.data('max')) {
			var $hintCurrent = $input.closest(_selectors.field.block).find(_selectors.field.hint);
			$hintCurrent.text(text);

			if (that.validator.checkMinInput($input) && that.validator.checkMaxInput($input)) {
				$hintCurrent.removeClass('prd-save-step__field-hint_error');
			} else {
				$hintCurrent.addClass('prd-save-step__field-hint_error');
			}
		}
	};

	var _getTextFromHtml = function(html) {
		return $('<div>' + html + '</div>').text();
	};

	var _getTextLength = function(html) {
		return html.replace(/&nbsp;/gi, " ").replace(/\s\s+/g, " ").length ^ 0;
	};

	var _getTextLengthWithoutSpace = function(html) {
		return html.replace(/&nbsp;/gi, " ").replace(/\s/g, "").length ^ 0;
	};

	/*
	 * Получить длину строки без тегов
	 * @param {string} html
	 * @returns {Number}
	 */
	var _getTextLengthWithoutTags = function(html) {
		var pattern = _getPatternTags();
		return _getTextLength(html.replace(pattern, ""));
	};

	/**
	 * Получить паттерн из тегов для замены
	 * @returns {RegExp}
	 */
	var _getPatternTags = function() {
		return /<p>|<\/p>|<li>|<\/li>|<ol>|<\/ol>|<strong>|<\/strong>|<em>|<\/em>|<br>|<\/br>|<div>|<\/div>|<span>|<\/span>|<word-error>|<\/word-error>/gi;
	};

	/**
	 * Заменяет &nbsp; на простой пробел, и удаляет дубли пробелов
	 */
	var _removeSpaces = function(string) {
		return string.replace(/&[a-z]+;/gi, " ").replace(/\s+/gi, " ").trim();
	};

	var _changeBundleSize = function() {
		if ($(this).prop('checked')) {
			$(_selectors.secondStep).removeClass('prd-save-step_type_single').addClass('prd-save-step_type_bundle');
			$(_selectors.bundle.descriptionBlock).find('textarea').data('required', true);
			MyExtras.hideExtras();
		} else {
			$(_selectors.secondStep).removeClass('prd-save-step_type_bundle').addClass('prd-save-step_type_single');
			$(_selectors.bundle.descriptionBlock).find('textarea').data('required', false);
			MyExtras.showExtras();
		}
	};

	var _onChangeAttributeItem = function() {
		that.validator.checkField($(this), true);
	};

	/**
	 * XHR request
	 * @private
	 */
	var _xhr = null;

	/**
	 * Event on changing category
	 * @private
	 */
	var _onChangeCategory = function() {
		if (_xhr) {
			_xhr.abort();
		}
		var categoryId = $(this).categoryList('categoryId');
		_loadClassification('', '');


		_setMaxDuration($(this).categoryList('data', 'maxDays'));
		_setBundleOnChangeCategory(categoryId);

		prdPhotos.changeMaxPhoto($(this).categoryList('data', 'maxPhotoCount'));
	};

	var _loadClassification = function(attributeId, parentId) {
		if (_xhr) {
			_xhr.abort();
		}
		var categoryId = $(_selectors.category).categoryList('categoryId');
		if (categoryId) {
			var $attributeBlock = $('.js-attribute-section-block[data-id="' + parentId + '"]');
			_xhr = $.get('/api', {
					method: 'getCatsRadio',
					categoryId: categoryId,
					attributeId: attributeId,
					prdId: _prdId
				},
				function(response) {
					if (response.success) {
						if (!attributeId && response.html === "") {
							_setFreePricesByCategory(categoryId);
						} else {
							_setFreePricesByAttribute(attributeId, categoryId);
						}

						$attributeBlock.html(response.html);
						_bindAttributes();
						$attributeBlock.find(_selectors.attribute.bindableAttribute + ':checked').change();

						if (attributeId && in_array(categoryId, _options.categoriesWithAttributes)) {
							_getExtrasByAttributes();
						}
						_changeClassification();
					}
				},
				'json');
		}
	};

	var _removeNeedUpdateNotice = function() {
		var $attributes = $('.prd-attribute-need-update');
		$attributes.removeClass('prd-attribute-need-update');
		$('.field-tooltip_attributes').remove();
	};

	/**
	 * Определение есть ли true параметра в выбранных атрибутах
	 *
	 * @param dataKey Ключ подаваемый в $.data() - camelCase
	 * @returns {boolean}
	 * @private
	 */
	var _isTrueInCheckedAttributes = function(dataKey) {
		var need = false;
		$('.attribute-list input:checked').each(function(index, el) {
			if ($(el).data(dataKey)) {
				need = true;
			}
		});

		return need;
	};

	/**
	 * Показвать ли сообщение о необходимости загрузки примеров размещения
	 *
	 * @private
	 */
	var _toggleLinksExamples = function() {
		if (_isTrueInCheckedAttributes('isDodjiLinksExampleImages')) {
			$('#need-prd-links-examples-message').removeClass('hidden');
		} else {
			$('#need-prd-links-examples-message').addClass('hidden');
		}
	};

	/**
	 * Показвать ли блоки связанные с сайтами продвижения ссылок
	 *
	 * @private
	 */
	var _toggleLinksSites = function() {
		if (_isTrueInCheckedAttributes('isDodjiLinksSites')) {
			$('.prd-links-sites-block').removeClass('hidden');
			$('#step1-links').data('required', true);
		} else {
			$('.prd-links-sites-block').addClass('hidden');
			$('#step1-links').data('required', false);
		}
	};

	var _bindAttributes = function() {
		$(_selectors.attribute.bindableAttribute).off('change');
		$(_selectors.attribute.bindableAttribute).on('change', function() {
			_removeNeedUpdateNotice();
			_toggleLinksExamples();
			_toggleLinksSites();

			var attributeId = $(this).val();
			_loadClassification(attributeId, $(this).data('parentId'));
		});
		_toggleLinksExamples();
		_toggleLinksSites();
		$(_selectors.field.checkBox).on('change', _changeClassification);
	};

	var _changeClassification = function() {
		$(_selectors.field.checkBox).each(function() {
			var checkedSize = $(this).find('input[type="checkbox"]:checked').size(),
				addButton = $(this).find(_selectors.attribute.addCustomAttribute.btn),
				customMaxCount = $(this).data('custom-max-count'),
				customCount = $(this).find('.attribute-item-custom').length,
				multipleMaxCount = $(this).data('multiple-max-count');
			if (multipleMaxCount > 0) {
				if (checkedSize >= multipleMaxCount) {
					$(this).find('input[type="checkbox"]').not(':checked').prop('disabled', true).parent().css('opacity', '0.5');
					addButton.hide();
				} else {
					$(this).find('input[type="checkbox"]').not(':checked').prop('disabled', false).parent().css('opacity', '1');
					if (customCount < customMaxCount)
						addButton.show();
				}
			}
		});
	}

	var _checkClassification = function() {
		var result = 0;
		$(_selectors.field.checkBox).each(function() {
			var checkedSize = $(this).find('input[type="checkbox"]:checked').size(),
				multipleMaxCount = $(this).data('multiple-max-count');
			if (multipleMaxCount > 0 && checkedSize > multipleMaxCount) {
				result = multipleMaxCount;
				return false;
			}
		});
		return result;
	}

	var _setFreePricesByAttribute = function(attributeId, categoryId) {
		if (_xhr) {
			_xhr.abort();
		}
		var categoryId = $(_selectors.category).categoryList('categoryId');
		var attributeIds = [];
		$(_selectors.attribute.bindableAttribute + ":checked").map(function() {
			attributeIds.push($(this).val());
		});
		_xhr = $.get('/api', {
				method: 'getCatsPrices',
				attributeIds: attributeIds,
				categoryId: categoryId
			},
			function(response) {
				if (response.prices) {
					PackagePrices.setFreeCategoryPrices(response.prices);
					$(".js-step-2 .prd-save-step__container").addClass("free-price-step");
					setFreeTooltip();
				} else {
					_hideFreePrice();
					var categoryId = $(_selectors.category).categoryList('categoryId');
					PackagePrices.setCategoryPrices(categoryId);
				}
			},
			'json'
		);
	};

	var _setFreePricesByCategory = function(categoryId) {
		if (_xhr) {
			_xhr.abort();
		}
		_xhr = $.get('/api', {
				method: 'getCatsPrices',
				categoryId: categoryId
			},
			function(response) {
				if (response.prices) {
					PackagePrices.setFreeCategoryPrices(response.prices);
					$(".js-step-2 .prd-save-step__container").addClass("free-price-step");
					$(".js-step-2 .prd-save-step__container").addClass("free-price-by-category");
					setFreeTooltip();
				} else {
					_hideFreePrice();
					$(".js-step-2 .prd-save-step__container").removeClass("free-price-by-category");
				}
			},
			'json'
		);
	};

	var _hideFreePrice = function() {
		unbindFreeTooltip();
		$(".js-step-2 .prd-save-step__container").removeClass("free-price-step");
		$(".prd-save-step__prd-price-free-value").addClass("hide");
		$(".prd-save-step__prd-price-free-value").find("option:selected").removeAttr("selected");
		$(".prd-save-step__prd-price-static-value").removeClass("hide");
	};

	var _setMaxDuration = function(days) {
		days = parseInt(days);
		var $select = $('#step2-work-time');
		$select.find('option').each(function(index) {
			if (index < days) {
				$(this).removeClass('hidden');
			} else {
				$(this).addClass('hidden')
			}
		});

		if (parseInt(($select.val())) > days) {
			$select.val(days);
		}
	};

	// Получаем опции по атрибутам и обновляем их на странице
	var _getExtrasByAttributes = function() {
		var categoryId = $(_selectors.category).categoryList('categoryId');
		var attributeIds = [];
		$(_selectors.attribute.bindableAttribute + ":checked").map(function() {
			attributeIds.push($(this).val());
		});
		$.get('/api', {
				method: 'getCatsPlans',
				categoryId: categoryId,
				attributeIds: attributeIds
			},
			function(response) {
				if (response.items) {
					_options.categoryExtras[categoryId] = Object.keys(response.items).map(function(key) { // convert to array
						return response.items[key];
					});

					if (_isBundleCategory(categoryId)) {
						if(_options.prdPackage != 'single') _setSecondStep(stepType.BUNDLE, categoryId);
						$(_selectors.bundle.inputSelect).chosen({
							width: '100%',
							disable_search: true
						});
					}
				}
			},
			'json'
		);
	};

	var _setBundleOnChangeCategory = function(categoryId) {
		var type = stepType.SINGLE;
		var categoryIsBundle = _isBundleCategory(categoryId);
		if (categoryIsBundle) {
			type = stepType.BUNDLE;
			PackagePrices.setCategoryPrices(categoryId);
		}

		_setSecondStep(type, categoryId);

		$(_selectors.bundle.inputSelect).chosen({
			width: '100%',
			disable_search: true
		});
		$(_selectors.bundle.inputSelect).parent().find('.chosen-container').css({
			'float': 'none',
			'margin-top': '5px'
		});
	};

	var _onClickOverlay = function() {
		$(this).hide();
	};

	var _showLesson = function() {
		var content = $(_selectors.lessonPopupContainer).html();
		show_popup(content, _lessonPopupClass);
		_setLookedLesson();
	};

	var _setLookedLesson = function() {
		$.post('/api?method=User.api_setLookedLesson', {}, function() {}, 'json');
	};

	/**
	 * Check if category has bundles
	 *
	 * @param categoryId {string|integer}
	 * @returns {boolean}
	 * @private
	 */
	var _isBundleCategory = function(categoryId) {
		var hasExtras = _options.categoryExtras.hasOwnProperty(categoryId);
		return hasExtras;
	};

	/**
	 * Set view of second step
	 * @param {string} type  Type of second step (stepType.SINGLE|stepType.BUNDLE)
	 * @param {int} categoryId Id of category
	 * @private
	 */
	var _setSecondStep = function(type, categoryId) {
		if (type == stepType.BUNDLE) {
			$(_selectors.bundleSize.block).removeClass('prd-save-step__bundle-size_inactive');
			if (!$(_selectors.bundleSize.checkbox).is(':checked')) {
				$(_selectors.bundleSize.checkbox).trigger('click');
			}
			_setBundleExtras(categoryId);
		} else if (type == stepType.SINGLE) {
			$(_selectors.bundleSize.block).addClass('prd-save-step__bundle-size_inactive');
			if ($(_selectors.bundleSize.checkbox).is(':checked')) {
				$(_selectors.bundleSize.checkbox).trigger('click');
			}
		}
    _changeBundleSize.apply($(_selectors.bundleSize.checkbox));
	};

	var _checkActiveBundleCustomExtraCount = function() {
		var uniqueValues = {};
		var totalCount = 0;

		var bundleValues = {
			'standard': 0,
			'medium': 0,
			'premium': 0
		};
		var bundleValues_select = {
			'standard': [ ],
			'medium': [ ],
			'premium': [ ]
		};

		for (var i in $_bundleItems) {
			$_bundleItems[i]
				.find(_selectors.bundle.extras)
				.find(_selectors.bundle.input)
				.each(function() {
					var val = false;
					if ($(this).is(_selectors.bundle.inputSelect)) {
						val = $(this).val() ^ 0;
            bundleValues_select[i].push(($(this).val()-0));
					} else if ($(this).is('.bundle-item__input_text')) {
						val = $(this).val().length;
					} else {
						val = $(this).is(':checked');
					}

					if (val) {
						bundleValues[i]++;

						if (!uniqueValues.hasOwnProperty($(this).data('uniqueParamId'))) {
							uniqueValues[$(this).data('uniqueParamId')] = 1;
							totalCount++;
						}
					}
				});
		}

  	if(bundleValues_select['standard'].length > 0) for (i=0; i < bundleValues_select['standard'].length; i++) {
      if(bundleValues_select['standard'][i] >= bundleValues_select['medium'][i] && bundleValues_select['standard'][i] >= bundleValues_select['premium'][i]) {
        bundleValues['standard']++;
        if(bundleValues_select['standard'][i] == bundleValues_select['medium'][i]) bundleValues['medium']++;
        if(bundleValues_select['standard'][i] == bundleValues_select['premium'][i]) bundleValues['premium']++;
        if(bundleValues_select['medium'][i] != bundleValues_select['premium'][i]) {
          if(bundleValues_select['standard'][i] > bundleValues_select['medium'][i] && bundleValues_select['medium'][i] > bundleValues_select['premium'][i]) {
            bundleValues['medium']++;
            bundleValues['standard']++;
          }
          if(bundleValues_select['standard'][i] > bundleValues_select['premium'][i] && bundleValues_select['premium'][i] > bundleValues_select['medium'][i]) {
            bundleValues['premium']++;
            bundleValues['standard']++;
          }
        }
      } else if(bundleValues_select['medium'][i] >= bundleValues_select['standard'][i] && bundleValues_select['medium'][i] >= bundleValues_select['premium'][i]) {
        bundleValues['medium']++;
        if(bundleValues_select['medium'][i] == bundleValues_select['standard'][i]) bundleValues['standard']++;
        if(bundleValues_select['medium'][i] == bundleValues_select['premium'][i]) bundleValues['premium']++;
        if(bundleValues_select['standard'][i] != bundleValues_select['premium'][i]) {
          if(bundleValues_select['medium'][i] > bundleValues_select['standard'][i] && bundleValues_select['standard'][i] > bundleValues_select['premium'][i]) {
            bundleValues['standard']++;
            bundleValues['medium']++;
          }
          if(bundleValues_select['medium'][i] > bundleValues_select['premium'][i] && bundleValues_select['premium'][i] > bundleValues_select['standard'][i]) {
            bundleValues['premium']++;
            bundleValues['medium']++;
          }
        }
      } else if(bundleValues_select['premium'][i] >= bundleValues_select['standard'][i] && bundleValues_select['premium'][i] >= bundleValues_select['medium'][i]) {
        bundleValues['premium']++;
        if(bundleValues_select['premium'][i] == bundleValues_select['standard'][i]) bundleValues['standard']++;
        if(bundleValues_select['premium'][i] == bundleValues_select['medium'][i]) bundleValues['medium']++;
        if(bundleValues_select['standard'][i] != bundleValues_select['medium'][i]) {
          if(bundleValues_select['premium'][i] > bundleValues_select['standard'][i] && bundleValues_select['standard'][i] > bundleValues_select['medium'][i]) {
            bundleValues['standard']++;
            bundleValues['premium']++;
          }
          if(bundleValues_select['premium'][i] > bundleValues_select['medium'][i] && bundleValues_select['medium'][i] > bundleValues_select['standard'][i]) {
            bundleValues['medium']++;
            bundleValues['premium']++;
          }
        }
      }
		}

		var minCountError = false;
		if ($(_selectors.secondStep).is('.prd-save-step_type_bundle')) {
			for (i in bundleValues) {
				if (bundleValues[i] === 0) {
					minCountError = true;
				}
			}
		}

		var priceError = false;
		$.each(PackagePrices.getPriceSelectors(), function(key, value) {
      if ($(value).length > 0) {
				if(!$(value).hasClass('range-change')) priceError = true;
			} else if($(value + '_input').length > 0) {
        var curval = ($(value + '_input').val() - 0);
        if(!((curval - 0) > 0)) {
          priceError = true;
        } else {
          if(value == '#priceMediumSelect') {
  					value = '#priceStandardSelect';
  					if ($(value).length > 0) {
  						if(($(value).val() - 0) > curval) priceError = true;
  					} else if($(value + '_input').length > 0) {
  						if(($(value + '_input').val() - 0) > curval) priceError = true;
  					}
  				} else if(value == '#pricePremiumSelect') {
  					value = '#priceMediumSelect';
  					if ($(value).length > 0) {
  						if(($(value).val() - 0) > curval) priceError = true;
  					} else if($(value + '_input').length > 0) {
  						if(($(value + '_input').val() - 0) > curval) priceError = true;
  					}
  				}
        }
      }
		});

		if (totalCount > 14) {
			$('.js-add-bundle-extra-count-error').addClass('prd-save-step__field-value_error').removeClass('hidden');
		} else {
			$('.js-add-bundle-extra-count-error').removeClass('prd-save-step__field-value_error').addClass('hidden');
		}
		if (minCountError) {
			$('.js-add-bundle-extra-min-count-error').addClass('prd-save-step__field-value_error').removeClass('hidden');
		} else {
			$('.js-add-bundle-extra-min-count-error').removeClass('prd-save-step__field-value_error').addClass('hidden');
		}

		$('.js-add-bundle-extra-grade-count-error').removeClass('prd-save-step__field-value_error').addClass('hidden');

		if ($(_selectors.secondStep).is('.prd-save-step_type_bundle')) {
			if (priceError) {
				$('.js-add-bundle-select-price-error').addClass('prd-save-step__field-value_error').removeClass('hidden');
			} else {
				$('.js-add-bundle-select-price-error').removeClass('prd-save-step__field-value_error').addClass('hidden');
			}
			if (bundleValues['standard'] >= bundleValues['medium'] || bundleValues['medium'] >= bundleValues['premium']) {
				$('.js-add-bundle-extra-grade-count-error').addClass('prd-save-step__field-value_error').removeClass('hidden');
			}
		}
		return totalCount <= 9 && !minCountError && !priceError;
	};

	var _setBundleExtras = function(categoryId) {
		var extras = [];
		if (_options.categoryExtras.hasOwnProperty(categoryId)) {
			extras = _options.categoryExtras[categoryId];
		}

		_clearBundleExtras();
		for (var i in extras) {
			extras[i].extraType = 'category';
		}

		var allExtras = extras;

		for (i in _options.customBundleExtras) {
			_options.customBundleExtras[i].extraType = 'custom';
			allExtras = allExtras.concat(_options.customBundleExtras[i]);
		}

		function compare(a, b) {
			if (a.type < b.type)
				return -1;
			if (a.type > b.type)
				return 1;

			return a.id - b.id;
		}

		allExtras.sort(compare);

		for (i = 0; i < allExtras.length; i++) {
			_addBundleHeader(allExtras[i], allExtras[i].extraType == 'custom');
		}

		var $addBlock = $('<div class="js-bundle-item__field_add-custom js-bundle-item__field_add-custom-block bundle-item__field bundle-item__field_add-custom">');

		$addBlock.append('<div class="bundle-item__add-custom">');
		$addBlock.append('<div class="bundle-item__add-custom-text">Добавить свою опцию</div>');

		$('.bundle-item_header').append($addBlock);

		for (type in $_bundleItems) {
			$addBlock = $('<div class="js-bundle-item__field_add-custom-block bundle-item__field_add-custom_empty bundle-item__field">');
			$bundleItem = $_bundleItems[type];
			$bundleItem.append($addBlock);
		}
		for (var type in $_bundleItems) {
			var $bundleItem = $_bundleItems[type],
				$bundleExtraBlock = $bundleItem.find(_selectors.bundle.extras);

			for (i = 0; i < allExtras.length; i++) {
				if (allExtras[i].extraType == 'category') {
					_addBundleExtra($bundleExtraBlock, type, allExtras[i]);
				} else {
					var extra = {
						name: allExtras[i].name,
						hint: allExtras[i].hint,
						type: allExtras[i].type,
						min: 1,
						max: allExtras[i].max_value,
						id: allExtras[i].id,
						can_lower: 1
					};
					_addBundleCustomExtra(
						$bundleItem,
						extra,
						_options.selectedPackageExtras
					);

          var $fieldsBlock = $('.js-add-bundle-extra-fields');
          if($fieldsBlock.find('input[name="bundle_custom_extra_name[' + allExtras[i].id + ']"]').length == 0) {
        		var $extParams = $('<input>');
        		$extParams.attr('type', 'hidden')
        			.addClass('extra-custom-param-' + allExtras[i].id)
        			.attr('name', 'bundle_custom_extra_name[' + allExtras[i].id + ']')
        			.val(allExtras[i].name);
        		var $fieldsBlock = $('.js-add-bundle-extra-fields');
        		$fieldsBlock.append($extParams);

        		$extParams = $('<input>');
        		$extParams.attr('type', 'hidden')
        			.addClass('extra-custom-param-' + allExtras[i].id)
        			.attr('name', 'bundle_custom_extra_type[' + allExtras[i].id + ']')
        			.val(allExtras[i].type);
        		$fieldsBlock.append($extParams);

        		$extParams = $('<input>');
        		$extParams.attr('type', 'hidden')
        			.addClass('extra-custom-param-' + allExtras[i].id)
        			.attr('name', 'bundle_custom_extra_hint[' + allExtras[i].id + ']')
        			.val(allExtras[i].hint);
        		$fieldsBlock.append($extParams);
          }
				}
			}
		}

		if (MAX_BUNDLE_CUSTOM_EXTRA) {}
	};

	var _clearBundleExtras = function() {
		$('.js-bundle-extras').html('');
		$('.js-bundle-item__field_add-custom, .js-bundle-item__field_add-custom-block').remove();
	};

	var _addBundleHeader = function(extra, isCustom) {
		var $header = $('<div class="bundle-item__field bundle-item__field_header">');
		var $label = $('<label class="bundle-item__field-label">');
		$label.text(extra.name);

		$header.append($label);

		if (extra.type == 'bool') {
			$header.addClass('bundle-item__field_header-checkbox');
		}

		if (isCustom) {
			$label.addClass('bundle-item__field-label_custom');
			$header.addClass('js-bundle-extra-custom bundle-item__field_custom extra-id-' + extra.id);
			var $removeButton = $('<div>');
			$removeButton.addClass('js-bundle-item__remove-extra bundle-item__remove-extra').append('<i class="ico-close-12"></i>');
			$removeButton.css('opacity', 0);
			$removeButton.data('id', extra.id);
			$header.append($removeButton);

			$header.append('<div class="bundle-item__field-custom-label">Своя опция</div>');
		}

		$header.on('mouseenter', function() {
			$('.extra-id-' + extra.id).find(_selectors.bundle.removeCustomExtra).css('opacity', 1);
		});

		$header.on('mouseleave', function() {
			$('.extra-id-' + extra.id).find(_selectors.bundle.removeCustomExtra).css('opacity', 0);
		});

		$header.on('click', _selectors.bundle.removeCustomExtra + ' .ico-close-12', _removeCustomBundleExtra);

		var $headerBlock = $('.bundle-item_header');

		if (isCustom && extra.type == 'bool') {
			var $rows = $headerBlock.find(_selectors.bundle.extras).find('.bundle-item__field_header-checkbox');
			if (!$rows.length) {
				$headerBlock.find(_selectors.bundle.extras).prepend($header);
			} else {
				$rows.last().after($header);
			}
		} else {
			$headerBlock.find(_selectors.bundle.extras).append($header);
		}

		_setTooltipExtra($header, extra.hint);
	};

	var _addBundleExtra = function($bundleExtraBlock, type, extra) {
		var selectedExtra = {};

		if (_selectedPackageExtras[type].hasOwnProperty('category')) {
			for (var j = 0; j < _selectedPackageExtras[type]['category'].length; j++) {
				if (extra.id == _selectedPackageExtras[type]['category'][j].item_id) {
					selectedExtra = _selectedPackageExtras[type]['category'][j];
				}
			}
		}

		$bundleExtraBlock.append(_getBundleExtraBlock(type, extra, 'category', selectedExtra));
	};

	var _addBundleCustomExtra = function($bundleExtraBlock, extra, extras) {
		var selectedExtra = undefined;

		if (typeof extras[$bundleExtraBlock.data('type')] == 'object' && extras[$bundleExtraBlock.data('type')].hasOwnProperty('custom')) {
			var customExtras = extras[$bundleExtraBlock.data('type')]['custom'];
			for (var i = 0; i < customExtras.length; i++) {
				if (extra.id == customExtras[i].item_id) {
					selectedExtra = customExtras[i];
				}
			}
		}

		var $item = _getBundleExtraBlock($bundleExtraBlock.data('type'), extra, 'custom', selectedExtra);

		$item.addClass('js-bundle-extra-custom extra-id-' + extra.id).data('id', extra.id);

		if (extra.type == 'bool') {
			var $rows = $bundleExtraBlock.find(_selectors.bundle.extras).find('.bundle-item__field_checkbox');
			if (!$rows.length) {
				$bundleExtraBlock.find(_selectors.bundle.extras).prepend($item);
			} else {
				$rows.last().after($item);
			}
		} else if (extra.type == 'text') {
			$bundleExtraBlock.find(_selectors.bundle.extras).append($item);
		} else {
			$bundleExtraBlock.find(_selectors.bundle.extras).append($item);
		}

		$item.find('select').chosen({
			width: '100%',
			disable_search: true
		});
		$item.find('.chosen-container').css({
			'float': 'none',
			'margin-top': '5px'
		});

		var total = $bundleExtraBlock.find('.js-bundle-extra-custom').length;
		if (total >= MAX_BUNDLE_CUSTOM_EXTRA) {
			$('.js-bundle-item__field_add-custom-block').hide();
		}

		$item.on('mouseenter', function() {
			$('.extra-id-' + extra.id).find(_selectors.bundle.removeCustomExtra).css('opacity', 1);
		});

		$item.on('mouseleave', function() {
			$('.extra-id-' + extra.id).find(_selectors.bundle.removeCustomExtra).css('opacity', 0);
		});
	};

	var _getBundleExtraBlock = function(bundleType, extra, extraType, selectedExtra) {
		var $extra = '';

		switch (extra.type) {
			case 'integer':
				$extra = $('<div class="bundle-item__field bundle-item__field_select">');
				$extra.append(_getBundleExtraTypeInteger(bundleType, extra, extraType, selectedExtra));
				break;
			case 'bool':
				$extra = $('<div class="bundle-item__field bundle-item__field_checkbox">');
				$extra.append(_getBundleExtraTypeBool(bundleType, extra, extraType, selectedExtra));
				break;
			case 'text':
				$extra = $('<div class="bundle-item__field bundle-item__field_text">');
				$extra.append(_getBundleExtraTypeText(bundleType, extra, extraType, selectedExtra));
				break;
		}

		$extra.find(_selectors.bundle.input).data('uniqueParamId', extraType + extra.id);
		return $extra;
	};

	var _getBundleExtraTypeInteger = function(bundleType, extra, extraType, selectedExtra) {
		var $extraLabel = $('<label for="bundle-extra_' + bundleType + '_' + extra.id + '" class="bundle-item__field-label">');

		var $extraSelect = $('<select name="bundle_extra_' + bundleType + '_value[' + extraType + '][' + extra.id + ']" class="js-bundle-item__input bundle-item__input bundle-item__input_select">')
			.attr('id', 'bundle-extra_' + bundleType + '_' + extraType + '_' + extra.id);

		if (parseInt(extra.min) === 0) {
			$extraSelect.append('<option value="0">Нет</option>');
		}


		for (var i = parseInt(extra.min); i <= extra.max; i++) {
			var isSelected = '';
			if (typeof selectedExtra == 'object' && selectedExtra.value == i) {
				isSelected = 'selected';
			}
			var canLower = '';
			if (extra.can_lower == 1 && i > 1) {
				canLower = 'до ';
			}
			if (i !== 0) {
				$extraSelect.append('<option value="' + i + '" ' + isSelected + '>' + canLower + i + '</option>');
			}
		}

		return $extraLabel.add($extraSelect);
	};

	var _getBundleExtraTypeBool = function(bundleType, extra, extraType, selectedExtra) {
		var isSelected = '';
		if (typeof selectedExtra == 'object' && selectedExtra.value == 1) {
			isSelected = 'checked';
		}
		var $extraCheckbox = $('<input name="bundle_extra_' + bundleType + '_value[' + extraType + '][' + extra.id + ']" class="js-bundle-item__input styled-checkbox" type="checkbox" ' + isSelected + '>')
			.val(1).attr('id', 'bundle-extra_' + bundleType + '_' + extraType + '_' + extra.id);

		var $extraLabel = $('<label for="bundle-extra_' + bundleType + '_' + extra.id + '" class="bundle-item__field-label">')
			.html('&nbsp;')
			.attr('for', 'bundle-extra_' + bundleType + '_' + extraType + '_' + extra.id);

		return $extraCheckbox.add($extraLabel);
	};

	var _getBundleExtraTypeText = function(bundleType, extra, extraType, selectedExtra) {
		var value = '';

		if (typeof selectedExtra == 'object' && selectedExtra.value) {
			value = selectedExtra.value;
		}
		var $extraTextInput = $('<input name="bundle_extra_' + bundleType + '_value[' + extraType + '][' + extra.id + ']" class="js-bundle-item__input bundle-item__input_text styled-input" type="text">')
			.val(value).attr({
				'id': 'bundle-extra_' + bundleType + '_' + extraType + '_' + extra.id,
				'maxlength': '16'
			});

		var $extraLabel = $('<label for="bundle-extra_' + bundleType + '_' + extra.id + '" class="bundle-item__field-label">')
			.html('&nbsp;')
			.attr('for', 'bundle-extra_' + bundleType + '_' + extraType + '_' + extra.id);

		return $extraTextInput.add($extraLabel);
	};

	var _setTooltipExtra = function($el, message) {
		if (message != '') {
			$el.find('.bundle-item__field-label').addClass('js-tooltip')
				.data({
					tooltipPosition: 'center',
					tooltipAroundPosition: 'right',
					tooltipText: message,
					tooltipAnimation: true,
					tooltipBlockClass: 'package-edit-tooltip',
					tooltipClass: 'package-edit-tooltip-text',
					tooltipTheme: 'dark',
					proportion: true
				}).tooltip();
		}
	};

	var _removeCustomBundleExtra = function() {
		var id = $(this).closest(_selectors.bundle.removeCustomExtra).data('id');

		$('.extra-id-' + id).each(function() {
			$(this).trigger('mouseleave.tooltip').remove();
		});

		$('.js-bundle-item__field_add-custom-block').show();

		if (id.indexOf('n') === 0) {
			$('.extra-custom-param-' + id).remove();
		} else {
			var $extParams = $('<input>');
			$extParams.attr('type', 'hidden')
				.addClass('extra-custom-param-' + id)
				.attr('name', 'bundle_custom_extra_remove[]')
				.val(id);

			var $fieldsBlock = $('.js-add-bundle-extra-fields').append($extParams);
		}

		return false;
	};

	var _setFileObjects = function(files) {
		 _files.description = new FileUploader({
			files: files.description,
			deleteCallback: deleteFileCallback,
			selector: '#load-files-description',
			input: {
				name: 'description_files'
			},
      cot_ext: 'market',
      cot_cat: 'description'
		});
	};

	return {
		init: function(options) {
			_options = options;
			that = this;

			_saveMode = options.saveMode;
			_prdId = options.prdId;
			_prdPackage = options.prdPackage;
			_prdUrl = options.prdUrl;
      _minDodjiPrice = options.minDodjiPrice;
      _dodjirate = options.cfg.dodjirate;
			_prdPrice = options.prdPrice;
      _prdPriceDodji = options.prdPriceDodji;

			_prdPackages = options.prdPackages;

			_selectedPackageExtras = options.selectedPackageExtras;

			$(_selectors.bundle.item).each(function() {
				$_bundleItems[$(this).data('type')] = $(this);
			});

			_setFileObjects(options.files);
			$(_selectors.category).categoryList({
				categories: _options.categories,
				id: 'step1-category',
				classes: 'js-field-input-cat input input_size_s prd-save-step__field-input',
				data: {
					required: true
				},
				current: _options.selectedCategory,
				// noEmptyOption: true
			});

			MyExtras.init({
				extras: _options.extras,
				selectedCategory: _options.selectedCategory,
				categoryExtras: _options.categoryExtras,
				categoriesWithAttributes: _options.categoriesWithAttributes,
				prdPackage: _prdPackage
			});

			PackagePrices.init({
				categoryPrices: _options.categoryPrices,
				crt: _options.crt,
				prdPrice: _prdPrice,
        prdPriceDodji: _prdPriceDodji,
        minDodjiPrice: _minDodjiPrice,
        dodjirate: _dodjirate,
        prdPackages: _prdPackages
			});

			$(_selectors.field.description).trumbowyg({
				lang: 'ru',
				fullscreenable: false,
				closable: false,
				btns: ['bold', '|', 'italic', '|', 'orderedList'],
				removeformatPasted: true
			});
			$(_selectors.field.instruction).trumbowyg({
				lang: 'ru',
				fullscreenable: false,
				closable: false,
				btns: ['bold', '|', 'italic', '|', 'orderedList'],
				removeformatPasted: true
			});
			$(".trumbowyg-editor").attr("spellcheck", "false");

			prdPhotos = new DodjiPhotoModule();
			prdPhotos.init(_options.photo);

			if (!_options.skip_first_photo_check) {
				$($('.js-prd-photo-input')[1]).data('required', true);
			}
			$($('.js-prd-photo-input')[1]).attr('name', 'first-prd-photo');
			$($('.js-prd-photo-input')[1]).parent().parent().find('.js-photo-size').attr('name', 'first-prd-photo-size');
			$($('.js-prd-photo-input')[1]).parent().parent().find('.js-old-photo-id').attr('name', '');
			$($('.js-prd-photo-input')[1]).addClass('js-prd-photo-input-first');

			_setEvents();

			$(_selectors.category).trigger('change.categoryList');

			if (_prdPackage == 'single') {
				_setSecondStep(stepType.SINGLE, _options.selectedCategory);
			}

			if (_prdId || _saveMode == 'continue') {
				$('.js-next-step-btn').click();
			}
			if (_isBundleCategory(_options.selectedCategory)) {
				$(_selectors.bundleSize.block).removeClass('prd-save-step__bundle-size_inactive');
			}

			_formCache = $(_selectors.prdForm).serialize();

			$(_selectors.bundle.inputSelect).each(_setSelectChecked);

			$('.js-tooltip').tooltip();
		},
		checkMaxFileSize: function() {
			var totalSize = 0;
			$('.js-prd-file').each(function() {
				var file = this.files[0];
				if (typeof file != 'undefined') {
					totalSize += file.size || file.fileSize;
				}
			});

			//totalSize += DodjiPhotoModule.getPhotoSize();

			return totalSize <= 16 * 1024 * 1024;
		},
		validator: (function() {

			var ERRORS = {
				EMPTY: 'empty',
				MIN_REQ: 'min_req',
				MAX_REQ: 'max_req',
				BAD_YOUTUBE_LINK: 'bad_youtube_link',
				FIRST_PHOTO: 'firstPhoto',
				NO_SYMBOLS: 'no_symbols',
				ONLY_ENGLISH: 'only_english',
				MULTIPLE_MAX_COUNT: 'multiple_max_count',
				BAD_RU_LANG: 'bad_ru_lang',
				DUPLICATE_SYMBOLS: 'duplicate_symbols',
				DUPLICATE_OPTIONS: 'duplicate_options',
			};

			/**
			 * Hide error
			 *
			 * @private
			 */
			var _hideError = function($input) {
				var $fieldBlock = $input.closest(_selectors.field.block);

				$fieldBlock.removeClass('prd-save-step__field-value_error');
				$fieldBlock.find(_selectors.field.error).text('').addClass('hidden');
				$fieldBlock.find(_selectors.field.hintBundle).removeClass('hidden');

			};

			/**
			 * Check Field and show error
			 *
			 * @param $input
			 * @returns {boolean} false if error
			 * @private
			 */
			var _checkField = function($input, isShowText) {
				var replaceParams = {},
					$fieldBlock = $input.closest(_selectors.field.block),
					errorText = "",
					errorBlock = "",
					fieldCount = 0;


				if ($input.is('.prd-save-field-radiobox, .prd-save-field-checkbox')) {
					if (_isRequired($input)) {
						var selected = $input.find('input:checked');
						if (!selected.length) {
							if (isShowText) {
								errorText = _getErrorText(ERRORS.EMPTY, replaceParams);
							}
							_setErrorText($fieldBlock, errorText);
							return false;
						}
					}
				} else {
					if (_isRequired($input) && ($input.val() === null || $input.val().length == 0)) {
						if ($input.hasClass('js-prd-photo-input-first')) {
							if (isShowText) {
								$(".js-add-photo_error").html();
								errorText = _getErrorText(ERRORS.FIRST_PHOTO, replaceParams);
								errorBlock = ERRORS.FIRST_PHOTO;
							}
						} else {
							if (isShowText) {
								errorText = _getErrorText(ERRORS.EMPTY, replaceParams);
							}
						}
						_setErrorText($fieldBlock, errorText, errorBlock);
						return false;
					}
				}

				if ($input.data('only-english') && _checkEnglishLang($input)) {
					if (isShowText) {
						errorText = _getErrorText(ERRORS.ONLY_ENGLISH, {});
					}
					_setErrorText($fieldBlock, errorText);
					return false;
				}

				if ($input.is(_selectors.field.checkBox)) {
					var fieldCount = _checkClassification();
					if (fieldCount > 0) {
						if (isShowText) {
							errorText = _getErrorText(ERRORS.MULTIPLE_MAX_COUNT, {
								count: fieldCount
							});
						}
						_setErrorText($fieldBlock, errorText);
						return false;
					}
				}

				if ($input.data('validator') == 'youtube' && $input.val() && !_checkYoutubeLink($input)) {
					if (isShowText) {
						errorText = _getErrorText(ERRORS.BAD_YOUTUBE_LINK, replaceParams);
					}
					_setErrorText($fieldBlock, errorText);
					return false;
				}

				if (!_checkMinInput($input)) {
					replaceParams = {
						count: $input.data('min'),
						name: $input.data('fieldName')
					};
					if (isShowText) {
						errorText = _getErrorText(ERRORS.MIN_REQ, replaceParams);
					}
					_setErrorText($fieldBlock, errorText);
					return false;
				}

				if (!_checkMaxInput($input)) {
					replaceParams = {
						count: $input.data('max'),
						name: $input.data('fieldName')
					};
					if (isShowText) {
						errorText = _getErrorText(ERRORS.MAX_REQ, replaceParams);
					}
					_setErrorText($fieldBlock, errorText);
					return false;
				}

				if ($input.data('no-symbols') && _checkNoSymbols($input)) {
					if (isShowText) {
						errorText = _getErrorText(ERRORS.NO_SYMBOLS, {});
					}
					_setErrorText($fieldBlock, errorText);
					return false;
				}

				// Проверям что большая часть текста на русском
				if ($("#lang").val() === "ru") {
					if ($input.data("min-lang-percent") && !_checkRuLangString($input.val(), $input.data("min-lang-percent"))) {
						if (isShowText) {
							errorText = _getErrorText(ERRORS.BAD_RU_LANG, {});
						}
						_setErrorText($fieldBlock, errorText);
						return false;
					}
				}

				// проверяем опции на дубли
				if ($input.hasClass("js-add-extra-row__name-input") && !_checkOptionDuplicate($input)) {
					return false;
				}

				_hideError($input);
			};

			/**
			 * Check if field is required
			 * @param $input
			 * @returns {boolean}
			 * @private
			 */
			var _isRequired = function($input) {
				return $input.data('required') == true;
			};

			/**
			 * Set error text
			 *
			 * @param $fieldBlock
			 * @param {string} error - Error text
			 * @private
			 */
			var _setErrorText = function($fieldBlock, error, errorBlock) {
				!errorBlock ? "" : errorBlock;
				$fieldBlock.addClass('prd-save-step__field-value_error');
				$fieldBlock.find(_selectors.field.error).text(error).removeClass('hidden');
				if (errorBlock) {
					$fieldBlock.find(_selectors.field.error).addClass(errorBlock);
				}
				$fieldBlock.find(_selectors.field.hintBundle).addClass('hidden');
			};

			var _checkMinInput = function($input) {
				var minSymbols = $input.data('min') ^ 0;
				var textLength = 0;
				if ($input.data("hasTags") === true) {
					textLength = _getTextLengthWithoutTags($input.val());
				} else {
					textLength = _getTextLength($input.val());
				}
				return minSymbols == 0 || minSymbols <= textLength;


			};

			var _checkMaxInput = function($input) {
				var maxSymbols = $input.data('max') ^ 0;
				var textLength = 0;
				if ($input.data("hasTags") === true) {
					textLength = _getTextLengthWithoutTags($input.val());
				} else if ($input.data("withoutSpace") === true) {
					textLength = _getTextLengthWithoutSpace($input.val());
				} else {
					textLength = _getTextLength($input.val());
				}
				return maxSymbols == 0 || maxSymbols >= textLength;
			};

			/**
			 * Проверяет соответсвие процента русских букв в строке
			 * @param string
			 * @param langPercent
			 * @return {boolean}
			 */
			var _checkRuLangString = function(string, langPercent) {
				// очистим теги, чтобы не считались
				string = string.replace(_getPatternTags(), "");

				var match, cAll = 0,
					cRu = 0;
				// посчитаем все буквы
				match = string.replace(/[\d.,;:\/'"<>\?\!@#\$\%\^\&\*\(\)\[\]\{\}\|\_\+\=\-\s]/gi, "");
				if (match) {
					cAll = match.length;
				}
				// посчитаем русские буквы
				match = string.match(/[а-яё]/gi);
				if (match) {
					cRu = match.length;
				}

				cRu = cRu / cAll * 100;

				return (cRu >= langPercent);
			};

			var _checkOptionDuplicate = function($input) {
				var currentVal = $input.val().trim();
				if (currentVal !== "") {
					var duplicate = false;
					$(".js-add-extra-row__name-input").not($input).each(function(i, el) {
						if (currentVal !== "" && currentVal === $(el).val().trim()) {
							duplicate = true;
						}
					});
					if (duplicate) {
						var $fieldBlock = $input.closest(_selectors.field.block);
						var errorText = that.validator.getErrorText(ERRORS.DUPLICATE_OPTIONS, {});
						that.validator.setErrorText($fieldBlock, errorText);

						return false;
					} else {
						return true;
					}
				} else {
					return true;
				}
			};

			var _checkYoutubeLink = function($input) {
				return $input.val().match(/http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/) !== null;
			};

			var _checkNoSymbols = function($input) {
				var string = $input.val();
				if ($input.data("has-tags")) {
					string = string.replace(_getPatternTags(), "");
					string = string.replace(/&[a-z]+;/gi, " ");
				}

				return string.match(/[^а-яА-ЯёЁa-zA-Z0-9,.\+\%\#\s\-]/) !== null;
			};

			var _checkEnglishLang = function($input) {
				return $input.val().match(/^[a-zA-Z0-9.,;:\/'"<>\!@#\$\%\^\&\*\(\)\_\+\=\-\s]*$/) === null;
			};

			var _getErrorText = function(error, replaceParams) {

				var errors = {
					'empty': 'Поле обязательно для заполнения',
					'min_req': 'Минимальная длина {{name}} {{count}} символов',
					'max_req': 'Максимальная длина {{name}} {{count}} символов',
					'bad_youtube_link': 'Некорректная ссылка youtube',
					'firstPhoto': 'Необходимо заполнить поле для первого изображения',
					'no_symbols': 'Название ' + cot_sitename['padeg']['r'] + ' не должно содержать символы кроме букв, цифр, точки и запятой',
					'only_english': 'Текст должен быть только на английском языке',
					'multiple_max_count': 'Максимальное количество категорий {{count}}',
					'bad_ru_lang': 'Текст должен быть на русском языке',
					'duplicate_symbols': 'Текст не соответствует нормам русского языка.',
					'big_word': 'Превышена максимальная длина слов',
					'small_word': 'Текст не соответствует нормам русского языка.',
					'duplicate_options': 'Дублирование опций недопустимо',
					'duplicate_description': 'Не копируйте описание услуги. В инструкции для покупателя укажите данные, необходимые вам для выполнения работы.',
					'word_mistakes': 'Необходимо исправить ошибки или опечатки в тексте.'
				};

				var errorText = errors[error];

				return errorText.replace(/({{.*?}})/g, function(str, p) {
					var param = p.replace(/([{}]*)?/g, '');
					return replaceParams[param];
				});
			};

			return {
				checkField: _checkField,
				hideError: _hideError,
				checkMinInput: _checkMinInput,
				checkMaxInput: _checkMaxInput,
				setErrorText: _setErrorText,
				getErrorText: _getErrorText,
				checkOptionDuplicate: _checkOptionDuplicate
			}
		})(),
		onChangeInput: _onChangeInput,
		onInputEditor: _onInputEditor
	}
})();

var MyExtras = (function() {
	var EXTRA_TYPE_MY = 'my',
		EXTRA_TYPE_CAT = 'cat',
		MAX_CUSTOM_EXTRA = 10;

	var _selectors = {
		myExtraBlock: '.js-my-extras',
		myExtraContainer: '.js-my-extras-container',
		content_editor: '.js-content-editor', // поле contenteditable
		content_storage: '.js-content-storage', // поле textarea или input где хрянится строка из contenteditable
		row: {
			row: '.js-add-extra-row',
			nameBlock: '.js-add-extra-name',
			nameInput: '.js-add-extra-row__name-input',
			nameCat: '.js-add-extra-row__name',
			price: '.js-extra-price',
      price_dodji: '.js-extra-price-dodji',
			duration: '.js-extra-duration',
			catCheckbox: '.js-add-extra-row__cat-checkbox',
			delete: '.js-add-extra-delete',
			catId: '.js-add-extra-row__cat-id'
		},
		add: {
			block: '.js-extra-add-block',
			btn: '.js-extra-add-btn'
		},
		template: {
			templateContainer: '.js-my-extras-templates__item',
			chosen: '.js-chosen-template'
		}
	};

	var $_extraBlock = {};

	var _templates = {};

	var _currentExtras = {
		'cat': {},
		'my': {}
	};

	var _categoryExtras = {};

	var _setRowEvents = function($row) {
		$row.find(_selectors.template.chosen).chosen({
			width: '90px',
			disable_search: true
		});
	};

	var _setEvents = function() {
		$_extraBlock.on('click', _selectors.add.btn, _addNewRowEvent);
		$_extraBlock.on('click', _selectors.row.delete, _deleteRow);
	};

	var _addNewRowEvent = function() {
		_addNewExtraRow({});
	};

	var _deleteRow = function() {

		if (($(this).data('id') ^ 0) == 0) {
			$(this).closest(_selectors.row.row).remove();
			_checkMaxCustomExtras();
			return;
		}

		$(this).closest(_selectors.row.row).parent().prepend($('<input>').attr({
			type: 'hidden',
			name: 'remove_myextra_ids[]',
			value: $(this).data('id')
		}));

		$(this).closest(_selectors.row.row).remove();
		_checkMaxCustomExtras();
	};

	var _clearCategoryRows = function() {
		if (!$_extraBlock.length) {
			return
		}
		$_extraBlock.find(_selectors.row.row).filter('.add-extra__item_category').remove();
	};

	var _checkMaxCustomExtras = function() {
		if ($_extraBlock.find(_selectors.row.row).filter('.add-extra__item_my').length >= MAX_CUSTOM_EXTRA) {
			$(_selectors.add.block).hide();
		} else {
			$(_selectors.add.block).show();
		}
	};

	/**
	 * Add Custom Extra row
	 *
	 * @param values {
	 *                  {
	 *                      id: {integer},
	 *                      name: {string},
	 *                      duration: {integer},
	 *                      price: {integer},
	 *                      priceId: {integer},
	 *                  }
	 *               }
	 * @private
	 */
	var _addNewExtraRow = function(values) {
    console.log(values);
		var $nameBlock;

		$nameBlock = $(_getTemplate('row-name-my'));
		$nameBlock.find(_selectors.row.nameInput).val(values.name);
		$nameBlock.find(_selectors.content_editor).html(values.name);
		$nameBlock.find(_selectors.row.catId).val(values.id);

		var $row = $(_getTemplate('row'));

		$row.addClass('add-extra__item_my');
		$row.find(_selectors.row.nameBlock).append($nameBlock);
		$row.find(_selectors.row.delete).data('id', values.id);

		$_extraBlock.find(_selectors.add.block).before($row);

		_setSelectedOption($row, _selectors.row.price, values.priceId);
		_setSelectedOption($row, _selectors.row.duration, values.duration);
    $row.find(_selectors.row.price_dodji).val(values.price_dodji);

		_setRowEvents($row);

		_checkMaxCustomExtras();

		$nameBlock.find(_selectors.row.nameInput).on("input", DodjiSaveModule.onChangeInput);
		$nameBlock.find(_selectors.content_editor).on("input", DodjiSaveModule.onInputEditor);
	};

	/**
	 * Add Category Extra row
	 *
	 * @param values {
	 *                  {
	 *                      id: {integer},
	 *                      name: {string},
	 *                      checked: {boolean},
	 *                      duration: {integer},
	 *                      price: {integer},
	 *                  }
	 *               }
	 * @private
	 */
	var _addNewCatRow = function(values) {
		var $nameBlock;

		$nameBlock = $(_getTemplate('row-name-cat'));
		$nameBlock.filter(_selectors.row.nameCat)
			.text(values.name)
			.attr('for', 'add-extra-cat-' + values.id);

		$nameBlock.filter(_selectors.row.catCheckbox)
			.attr('id', 'add-extra-cat-' + values.id)
			.prop('checked', values.checked === true);

		var $row = $(_getTemplate('row'));

		$row.addClass('add-extra__item_category');
		$row.find(_selectors.row.nameBlock).append($nameBlock);
		$row.find(_selectors.row.catCheckbox).attr('name', 'bundle_extra_cat[' + values.id + ']');
		$row.find(_selectors.row.price).attr('name', 'bundle_extra_price[' + values.id + ']');
		$row.find(_selectors.row.duration).attr('name', 'bundle_extra_duration[' + values.id + ']');

		if ($_extraBlock.find(_selectors.row.row).filter('.add-extra__item_category').length) {
			$_extraBlock.find(_selectors.row.row).filter('.add-extra__item_category').last().after($row);
		} else {
			$_extraBlock.find(_selectors.myExtraContainer).prepend($row);
		}

		_setSelectedOption($row, _selectors.row.price, values.price);
		_setSelectedOption($row, _selectors.row.duration, values.duration);

		_setRowEvents($row);
	};

	var _setSelectedOption = function($row, selector, value) {
		$row.find(selector).find('option').each(function() {
			if ($(this).attr('value') == value) {
				$(this).prop('selected', true);
			}
		});
	};

	var _getTemplate = function(name) {
		return _templates[name];
	};

	var _setTemplates = function() {
		$(_selectors.template.templateContainer).each(function() {
			_templates[$(this).data('template')] = $(this).html();
		});
	};

	var _preSetExtras = function() {
		if (!_currentExtras[EXTRA_TYPE_MY].length) {
			_addNewExtraRow({});
			return;
		}

		for (var i = 0; i < _currentExtras[EXTRA_TYPE_MY].length; i++) {
			var extra = _currentExtras[EXTRA_TYPE_MY][i];
			_addNewExtraRow(extra);
		}
	};

	/**
	 * Set Category Extras
	 *
	 * @param categoryId {string}
	 *
	 * @private
	 */
	var _setCategoryExtras = function(categoryId) {
		_clearCategoryRows();
		if (_categoryExtras.hasOwnProperty(categoryId)) {
			for (var i = 0; i < _categoryExtras[categoryId].length; i++) {
				var extra = _categoryExtras[categoryId][i];
				extra.duration = 0;
				extra.price = 0;

				var currentExtra = false;
				for (var j = 0; j < _currentExtras[EXTRA_TYPE_CAT].length; j++) {
					if (_currentExtras[EXTRA_TYPE_CAT][j].item_id == extra.id) {
						currentExtra = _currentExtras[EXTRA_TYPE_CAT][j];
						break;
					}
				}

				if (currentExtra !== false) {
					extra.checked = true;
					extra.duration = currentExtra.duration;
					extra.price = currentExtra.price;
					extra.value = 1;
				}

				_addNewCatRow(extra);
			}
		}
	};

	var _hideExtras = function() {
		$('.prd-save-step__field-block_extras').parent().hide();
	};

	var _showExtras = function() {
		$('.prd-save-step__field-block_extras').parent().show();
	};

	return {
		init: function(options) {
			_setTemplates();
			$_extraBlock = $(_selectors.myExtraBlock);

			if (typeof options == 'object' && typeof options.extras == 'object') {
				_currentExtras = options.extras;
			}

			_categoryExtras = options.categoryExtras;

			_preSetExtras();
			if (options.prdPackage == 'single') {
				_showExtras();
			} else {
				_hideExtras();
			}

			_setEvents();
		},
		setCategoryExtras: _setCategoryExtras,
		hideExtras: _hideExtras,
		showExtras: _showExtras
	}
})();

(function($) {
	var _selectors = {
		parent: '.js-category_parent',
		sub: '.js-category_sub'
	};

	var _setEvents = function($block) {
		$block.on('change', _selectors.parent, function() {
			var parentId = $(this).val();

			var $sub = $block.find(_selectors.sub);
			$sub.html('');
			$sub.trigger("chosen:updated");

			if (!parentId) {
				$sub.parent().addClass('hidden');
				return;
			}

			$sub.parent().removeClass('hidden');
			var subList = $block.data('options').categories[parentId]['cats'];
			$sub.append(_buildOptions(subList, 0));
			$sub.trigger("chosen:updated");
			$block.trigger('change.categoryList');
		});
	};

	var _buildList = function($block) {
		var parentSelectedId = _getCurrentParent($block);

		var categories = $block.data('options').categories;

		var $parent = _buildSelect(categories, parentSelectedId, $block.data('options'), 'parent');

		$parent.addClass('js-category_parent');

		if (!$block.data('options').noEmptyOption) {
			// var $emptyOption = $('<option>');
			var $emptyOption = $('<option disabled hidden>Выберите категорию</option>');
			$parent.prepend($emptyOption);
		}

		if (!parentSelectedId) {
			$parent.children('option:first-child').attr('selected', true);
		}

		var subList = [];
		if (parentSelectedId) {
			subList = categories[parentSelectedId]['cats'];
		}

		var $subList = _buildSelect(subList, $block.data('options').current, $block.data('options'), 'sub').addClass('js-category_sub');

		var $parentWrapper = $('<div class="js-category-parent-wrapper prd-save-step__field-input_category">').append($parent);
		var $subWrapper = $('<div class="js-category-sub-wrapper prd-save-step__field-input_category">').append($subList);
		if (!subList.length) {
			$subWrapper.addClass('hidden');
		}

		$block.append($parentWrapper, $subWrapper);

		$parent.chosen({
			disable_search: true,
			width: '100%',
			display_disabled_options: false
		});
		$subList.chosen({
			disable_search: true,
			width: '100%'
		});
	};

	var _setData = function($select, options) {
		if (options.hasOwnProperty('data')) {
			$select.data(options.data);
		}
	};

	var _buildSelect = function(categories, current, options, type) {
		var name = type === 'sub' ? 'name="category_id"' : '';
		var placeholder = "Выберите категорию";
		var $select = $('<select class="' + options.classes + '" ' + name + ' data-placeholder="' + placeholder + '">');
		$select.append(_buildOptions(categories, current));

		_setData($select, options);

		return $select;
	};

	var _buildOptions = function(categories, current) {
		var keys = Object.keys(categories);
		var $options = [];
		for (var i = 0; i < keys.length; i++) {
			var key = keys[i],
				category = categories[key];

			var $option = $('<option value="' + category.id + '">' + category.name + '</option>');

			$option.data('maxPhotoCount', 3);

			if (current == category.id) {
				$option.prop('selected', true);
			}

			$option.data({
				maxDays: category.max_days,
				maxPhotoCount: 3,
				categoryName: category.name
			});

			$options.push($option);
		}

		return $options;
	};

	var _getCurrentParent = function($block) {
		var categories = $block.data('options').categories;
		var categoryIds = Object.keys(categories),
			current = $block.data('options').current;

		for (var i = 0; i < categoryIds.length; i++) {
			var parentId = categoryIds[i];
			var subList = categories[parentId]['cats'];
			for (var j = 0; j < subList.length; j++) {
				if (subList[j].id == current) {
					return parentId;
				}
			}
		}

		return 0;
	};

	var methods = {
		init: function(options) {
			return this.each(function() {
				var $this = $(this);
				$this.data('options', options);

				_buildList($this);
				_setEvents($this);
			});
		},
		categoryId: function() {
			var $sub = $(this).find(_selectors.sub);
			return $sub.find('option:selected').val();
		},
		data: function(name) {
			var $sub = $(this).find(_selectors.sub);
			return $sub.find('option:selected').data(name);
		}

		//TODO: Получить ID дочерней категории и их свойства
	};

	/**
	 * Category List jQuery Plugin
	 * @param method
	 * @returns {*}
	 */
	$.fn.categoryList = 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);


//TODO: переделать под модуль jquery
var SwitchModule = (function() {
	return {
		init: function() {
			$('.js-switch').find('.switch__track').on('click', function() {
				$(this).closest('.js-switch').find('.switch__input').trigger('click');
			});
		}
	}
})();

$(function() {
	SwitchModule.init();
	$('.js-chosen').chosen({
		width: '90px',
		disable_search: true
	});
});

function foxtoggle(obj, obbox) {
	if (obbox == 'favouriteme') {
		if ($('#favouriteme').is(":checked")) {
			$('#favouritemore').show();
			$('#favouritemore').find('.favs').attr('disabled', false);
		} else {
			$('#favouritemore').hide();
			$('#favouritemore').find('.favs').attr('disabled', true);

		}
	}
}

$(window).load(function() {
	$('.favs').on('click', function() {
		var count = $('.favs[type=checkbox]:checked').length;
		if (count > 4) {
			this.checked = '';
		}
	});

	function tooltipShow(e) {
		var timer = setTimeout(function() {
			if (!$(e).find('.field-tooltip').hasClass('field-tooltip-permanent')) {
				$('.field-tooltip-permanent').fadeOut(150);
			}
			showDodjiTooltip.apply(e);
		}, 200);
		$(e).data('timer', timer);
	}

	function tooltipHide(e) {
		if ($(e).hasClass('js-tooltip-lesson')) {
			return false;
		}
		if ($(e).find('.field-tooltip').hasClass('field-tooltip-permanent')) {
			return false;
		}

		clearTimeout($(e).data('timer') ^ 0);
		$(e).find('.field-tooltip').fadeOut(150);
		var $permanentTooltip = $('.field-tooltip-permanent');
		if ($permanentTooltip.length === 1) {
			$('.field-tooltip-permanent').fadeIn(150);
		}
	}

	function bindEvents() {
		$(document).on('mouseenter', '.prd-save-step__field-value_tooltip:not(.js-tooltip-lesson)', function() {
			tooltipShow(this);
		});
		$(document).on('mouseleave', '.prd-save-step__field-value_tooltip', function() {
			tooltipHide(this);
		});
	}

	function unbindEvents() {
		$(document).off('mouseenter', '.prd-save-step__field-value_tooltip:not(.js-tooltip-lesson)');
		$(document).off('mouseleave', '.prd-save-step__field-value_tooltip');
	}

	function showAttributesTooltip() {
		var $attributes = $('#prd-save-attributes');
		if ($attributes.find('.field-tooltip').length === 1) {
			showDodjiTooltip.apply($attributes);
		}
	}

	bindEvents();

	showAttributesTooltip();

	var selectChangeTimer = null;
	$('.js-category-select select').change(function() {
		unbindEvents();
		var e = $(this).closest('.prd-save-step__field-value_tooltip');
		if (selectChangeTimer !== null) {
			clearTimeout(selectChangeTimer);
			selectChangeTimer = null;
		}
		selectChangeTimer = setTimeout(function() {
			bindEvents();
			var element = $(':hover').last().closest('.prd-save-step__field-value_tooltip');
			if (element[0] !== e[0]) {
				e.trigger('mouseleave');
				element.trigger('mouseenter');
			}
			selectChangeTimer = null;
		}, 1000);
	});
});

function showDodjiTooltip(tooltipClass, posElement) {
	if (tooltipClass) {
		var $tooltip = $(this).find(tooltipClass);
	} else {
		var $tooltip = $(this).find('.field-tooltip');
	}
	$tooltip.fadeIn(300);

	var defTop = $(this).offset().top;

	var $corner = $tooltip.find('.field-tooltip__corner');

	$corner.css('top', '65px');
	$tooltip.css('top', '0');

	var tooltipHeight = $tooltip.height(),
		tooltipTop;

	var minOffset = ($('body').scrollTop() ^ 0) + 84 + 20;

	var tooltipMaxTop = Math.max(minOffset, defTop - 65);

	var maxOffset = Math.min(Utils.getWindowOffset() - 20, defTop + tooltipHeight);
	var tooltipMinTop = tooltipHeight - (maxOffset - defTop);

	if (tooltipMaxTop + tooltipHeight > Utils.getWindowOffset() - 20) {
		tooltipTop = tooltipMinTop;
	} else {
		tooltipTop = defTop - tooltipMaxTop;
	}

	tooltipTop = (-tooltipTop);

	if (tooltipTop > -150 && tooltipTop < -130) {
		tooltipTop = -150;
	}

	$tooltip.css('top', tooltipTop + 'px');

	var cornerTop = $corner.offset().top;

	if (cornerTop < defTop) {
		$corner.css({
			top: (defTop - cornerTop + 65) + 'px'
		});
	} else if (cornerTop > defTop + $(this).height()) {
		cornerTop = Math.min(minOffset - $tooltip.offset().top, defTop + $(this).outerHeight(true) - minOffset);
		$corner.css({
			top: cornerTop + 'px'
		});
	} else {
		$corner.css({
			top: +'65px'
		});
	}
	var windowTop = $(window).scrollTop() + 30;
	if ($(posElement).length) {
		var posElementTop = $(posElement).offset().top - $tooltip.height() / 2;
		tooltipTop = Math.abs(posElementTop - defTop);
		$tooltip.css('top', tooltipTop + 'px');
		$corner.css({
			top: $tooltip.height() / 2 + (10) + 'px'
		});
	} else if ($tooltip.offset().top <= windowTop) {
		$tooltip.css('top', (windowTop - $tooltip.offset().top) + 'px');
	}
	if (tooltipTop <= -150 || $(posElement).length) {
		$tooltip.find('.field-tooltip__corner').addClass('field-tooltip__corner_alternative');
	} else {
		$tooltip.find('.field-tooltip__corner').removeClass('field-tooltip__corner_alternative');
	}
}

var PackagePrices = (function() {
	var _selectors = {
		priceStandardBlock: '.js-bundle_standard_price',
		priceMediumBlock: '.js-bundle_medium_price',
		pricePremiumBlock: '.js-bundle_premium_price',
		priceDodjiStandardBlock: '.js-bundle_standard_price_dodji',
		priceDodjiMediumBlock: '.js-bundle_medium_price_dodji',
		priceDodjiPremiumBlock: '.js-bundle_premium_price_dodji'
	};
	var _priceSelectors = {
		priceStandardSelect: '#priceStandardSelect',
		priceMediumSelect: '#priceMediumSelect',
		pricePremiumSelect: '#pricePremiumSelect'
	};
	var _freePriceClassSelector = ".free-category-item__input_select";

	var _categoryPrices = {};
	var _priceGradation = {};
	var _prdPackages = {};
	var _crt = 0;
  var _minDodjiPrice = 0;
  var _dodjirate = 0;
	var _prdPrice = 0;
  var _prdPriceDodji = 0;
  var crt = _crt / 100;

	var _setCategoryPrices = function(categoryId) {
		if (_categoryPrices.hasOwnProperty(categoryId)) {
			var standard_price = _categoryPrices[categoryId]['standard'];
			var standard_price_crt = Math.round(standard_price * crt * 100) / 100;
			var medium_price = _categoryPrices[categoryId]['medium'];
			var medium_price_crt = Math.round(medium_price * crt * 100) / 100;
			var premium_price = _categoryPrices[categoryId]['premium'];
			var premium_price_crt = Math.round(premium_price * crt * 100) / 100;

			$(_selectors.priceStandardBlock + ' .price_value_text').text(Math.round((standard_price - standard_price_crt) * 100) / 100).append('<input type="hidden" name="bundle_free_price_value[priceStandard]" value="' + standard_price +'"/>');
			$(_selectors.priceMediumBlock + ' .price_value_text').text(Math.round((medium_price - medium_price_crt) * 100) / 100).append('<input type="hidden" name="bundle_free_price_value[priceMedium]" value="' + medium_price +'"/>');
			$(_selectors.pricePremiumBlock + ' .price_value_text').text(Math.round((premium_price - premium_price_crt) * 100) / 100).append('<input type="hidden" name="bundle_free_price_value[pricePremium]" value="' + premium_price +'"/>');
    }
		if (_dodjirate > 0) {
			$(_selectors.priceDodjiStandardBlock + ' .price_value_text').html('<input type="text" name="bundle_free_price_dodji_value[priceStandard]" value="' + ((_prdPackages.hasOwnProperty('standard') && _prdPackages['standard']['price_dodji'] > 0) ?  _prdPackages['standard']['price_dodji'] : '') + '" class="input input_size_s bundle-item__input_text"/>');
			$(_selectors.priceDodjiMediumBlock + ' .price_value_text').html('<input type="text" name="bundle_free_price_dodji_value[priceMedium]" value="' + ((_prdPackages.hasOwnProperty('medium') && _prdPackages['medium']['price_dodji'] > 0) ? _prdPackages['medium']['price_dodji'] : '') + '" class="input input_size_s bundle-item__input_text"/>');
			$(_selectors.priceDodjiPremiumBlock + ' .price_value_text').html('<input type="text" name="bundle_free_price_dodji_value[pricePremium]" value="' + ((_prdPackages.hasOwnProperty('premium') && _prdPackages['premium']['price_dodji'] > 0) ?  _prdPackages['premium']['price_dodji'] : '') + '" class="input input_size_s bundle-item__input_text"/>');
		}
	};
	var _setFreeCategoryPrices = function(attributePrices) {
		_priceGradation = attributePrices.priceGradation;
		var priceBlock = $('<select class="js-free-category-item-item__input free-category-item__input_select">');
		$.each(_priceGradation, function(key, value) {
			var selectId = key + "Select";
      if(typeof value == 'object') {
  			var priceGradationBlock = priceBlock.clone().attr({
  				"name": "bundle_free_price_value[" + key + "]",
  				'id': selectId
  			});
  			var min = value[Object.keys(value)[0]];
  			var max = value[Object.keys(value)[Object.keys(value).length - 1]];
  			min = min - (min * (_crt / 100));
  			max = max - (max * (_crt / 100));
  			var hasChange = false;
  			$.each(value, function(index, data) {
  				var selected = false;
  				var crtPrice = data - (data * (_crt / 100));
  				if (_prdPackages) {
  					$.each(_prdPackages, function(type, package) {
  						name = type.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
  							return letter.toUpperCase();
  						});
  						name = "price" + name;
  						if (name == key && package["price"] == data) {
  							selected = hasChange = true;
  						}
  					});
  				}
  				$("<option>").attr({
  					'value': data,
  					'selected': selected
  				}).text(crtPrice).appendTo(priceGradationBlock);
  			});
  			var typeBlock = key + "Block";
  			$(_selectors[typeBlock] + ' .price_value_text').html(priceGradationBlock);
  			priceGradationBlock.chosen({
  				width: '100%',
  				disable_search: true
  			}).on('change', function(e) {});
  			$(".price_value_text").find(".chosen-results").click(function() {
  				var select = $(this).parent().parent().prev();
  				select.addClass("range-change");
  				PackagePrices.rebuildFreeCategoryPrices(select);
  			});
  			if (!hasChange) {
  				$(priceGradationBlock).next().find('.chosen-single span').text(min + " - " + max);
  			} else {
  				$(priceGradationBlock).addClass('range-change');
  			}
      } else {
        var typeBlock = key + "Block";
        if(value == '') {
          //<div contenteditable="true" spellcheck="false" class="js-content-editor add-extra__item-name-input styled-input"></div>
          $(_selectors[typeBlock] + ' .price_value_text').html('<input class="input-styled" id="' + key + 'Select_input" type="text" name="bundle_free_price_value[' + key + ']" value="1000" oninput="var ch = $(this).val().replace(/[^\\d\\.]/g, \'\');$(this).val(ch);" style="height: 32px;line-height: 32px;margin-top: -5px;font-size: 14px;"/><input type="hidden" name="bundle_free_price_value_apply_crt[' + key + ']" value="1" />');
        } else {
          var crt = _crt / 100;
  			  var price_crt = Math.round(value * crt * 100) / 100;
          $(_selectors[typeBlock] + ' .price_value_text').html((Math.round((value - price_crt) * 100) / 100)).append('<input type="hidden" id="' + key + 'Select_input" name="bundle_free_price_value[' + key + ']" value="' + Math.round((value - price_crt) * 100) / 100 +'"/><input type="hidden" name="bundle_free_price_value_apply_crt[' + key + ']" value="1" />');
        }
      }
		});

		var currencyValue = " " + $("#priceInfo").data("currency-val");
    var currencyDodjiValue = " " + $("#priceInfo").data("currency-dodji-val");

		var typicalPriceGradationBlock = priceBlock.clone().attr({
			"name": "typicalPriceSelect",
			'id': "typicalPriceSelect",
			'style': "width: 110px;",
			'class': "input input_size_s"
		});

		$.each(attributePrices.typicalPriceGradation, function(index, data) {
			var selected = false;
			var crtPrice = data - (data * (_crt / 100));
			if (_prdPrice == data) {
				selected = true;
				$(".tooltip__title-payer-price").html(data + currencyValue);
				$(".tooltip__title-worker-price").html(crtPrice + currencyValue);
			}
			$("<option>").attr({
				'value': data,
				'selected': selected
			}).text(crtPrice + currencyValue).appendTo(typicalPriceGradationBlock);
		});
		typicalPriceGradationBlock.on('change', function(e) {
      var payer_price = '',
          worker_price = '';

      var tch = parseInt($(this).val());

      if(tch > 0) {
			   payer_price = tch + currencyValue;
			   worker_price = $(this).find("option:selected").text();
      }
      if(_dodjirate > 0) {
         var ch = typicalPriceDodjiGradationBlock.val().replace(/[^\d]/g, '').replace(/^[0]+/g, '');
         if(ch > 0) {
           var crtPrice = ch - (ch * (_crt / 100));

           payer_price += (tch > 0 ? ' или ' : '') + ch + currencyDodjiValue;
  			   worker_price += (tch > 0 ? ' или ' : '') + crtPrice + currencyDodjiValue;
         } else if(tch == 0) {
           payer_price = 500 + currencyValue;
			     worker_price = (500 - (500 * (_crt / 100))) + currencyValue;
         }
      }

      $(".tooltip__title-payer-price").html(payer_price);
			$(".tooltip__title-worker-price").html(worker_price);
		});
		$('.prd-save-step__prd-price-free-value').html(typicalPriceGradationBlock);



    if(_dodjirate > 0) {
  		var typicalPriceDodjiGradationBlock = $('<input class="input input_size_s" id="typicalPriceDodjiValue" name="typicalPriceDodjiValue" type="text" value="' + _prdPriceDodji + '" placeholder="" style="width: 80px;">');
  		typicalPriceDodjiGradationBlock.on('input', function(e) {
        var ch = $(this).val().replace(/[^\d]/g, '').replace(/^[0]+/g, '');
        $(this).val(ch);

        var tch = typicalPriceGradationBlock.val().replace(/[^\d]/g, '').replace(/^[0]+/g, '');

        var payer_price = '',
            worker_price = '';

        if(ch >= _minDodjiPrice) {
          if(tch > 0) {
      			payer_price = tch + currencyValue;
      			worker_price = typicalPriceGradationBlock.find("option:selected").text();
          }

          var crtPrice = ch - (ch * (_crt / 100));

          payer_price += (tch > 0 ? ' или ' : '') + ch + currencyDodjiValue;
      		worker_price += (tch > 0 ? ' или ' : '') + crtPrice + currencyDodjiValue;

          $(".tooltip__title-payer-price").html(payer_price);
    			$(".tooltip__title-worker-price").html(worker_price);
        } else if(tch == 0) {
          payer_price = 500;
			    worker_price = 500 - (500 * (_crt / 100));

          $(".tooltip__title-payer-price").html(payer_price + currencyValue);
    			$(".tooltip__title-worker-price").html(worker_price + currencyValue);
        }
  		});
  		typicalPriceDodjiGradationBlock.on('change', function(e) {
        var ch = $(this).val().replace(/[^\d]/g, '').replace(/^[0]+/g, '');
        if(ch > 0 && ch < _minDodjiPrice) {
          $(this).val('0');
          var tch = typicalPriceGradationBlock.val().replace(/[^\d]/g, '').replace(/^[0]+/g, '');

          if(tch > 0) {
            $(".tooltip__title-payer-price").html(tch + currencyValue);
    			  $(".tooltip__title-worker-price").html(typicalPriceGradationBlock.find("option:selected").text());
          }
        }
  		});
  		$('.prd-save-step__prd-price-free-value').append('<span style="display: inline-block;font-size: 16px;color: #737373;">&nbsp;&nbsp;или&nbsp;&nbsp;</span>');
      $('.prd-save-step__prd-price-free-value').append(typicalPriceDodjiGradationBlock);
      $('.prd-save-step__prd-price-free-value').append('<span style="display: inline-block;font-size: 16px;color: #737373;">&nbsp;' + currencyDodjiValue + '</span>');

      $('.prd-save-step__prd-price-free-value').addClass('with-dodji');
    }

    $(".prd-save-step__prd-price-free-value").removeClass("hide");
  	$(".prd-save-step__prd-price-static-value").addClass("hide");
  	$(_freePriceClassSelector).parent().find('.chosen-container').css({
  		'float': 'left',
  		'text-align': 'left',
  		'margin': '0 0 5px'
  	});
	};
	var _updatePriceSelect = function(selector, priceType, currentSelectValMin, direction) {
    /*
    console.log(_priceGradation[priceType]);
    if(typeof _priceGradation[priceType] == 'object') {
  		var nextSelect = $(selector);
  		var nextSelectVal = nextSelect.val();
  		nextSelect.find('option').remove();
  		var values = [];
    	$.each(_priceGradation[priceType], function(index, data) {
  			var crtPrice = data - (data * (_crt / 100));
  			if (direction) {
  				if (currentSelectValMin > crtPrice) {
  					if (priceType == 'priceMedium') {
  						var standardSelectVal = $(_priceSelectors.priceStandardSelect).val();
  						var premiumSelectVal = $(_priceSelectors.pricePremiumSelect).val();
  						if ((standardSelectVal < data) && (premiumSelectVal > data)) {
  							$("<option>").attr({
  								'value': data,
  							}).text(crtPrice).appendTo(nextSelect);
  							values.push(crtPrice);
  						}
  					} else {
  						$("<option>").attr({
  							'value': data,
  						}).text(crtPrice).appendTo(nextSelect);
  						values.push(crtPrice);
  					}
  				}
  			} else {
  				if (currentSelectValMin < crtPrice) {
  					if (priceType == 'priceMedium') {
  						var standardSelectVal = $(_priceSelectors.priceStandardSelect).val();
  						var premiumSelectVal = $(_priceSelectors.pricePremiumSelect).val();
  						if (!$(_priceSelectors.pricePremiumSelect).hasClass("range-change")) {
  							premiumSelectVal = $(_priceSelectors.pricePremiumSelect + ' option:last').val();
  						}
  						if ((data > standardSelectVal) && (data < premiumSelectVal)) {
  							$("<option>").attr({
  								'value': data,
  							}).text(crtPrice).appendTo(nextSelect);
  							values.push(crtPrice);
  						}
  					} else {
  						$("<option>").attr({
  							'value': data
  						}).text(crtPrice).appendTo(nextSelect);
  						values.push(crtPrice);
  					}

  				}
  			}
  		});
  		max = Math.max.apply(Math, values);
  		min = Math.min.apply(Math, values);
  		nextSelect.val(nextSelectVal);
  		$(nextSelect).trigger("chosen:updated");
  		if (min != max) {
  			if (!nextSelect.hasClass("range-change")) {
  				nextSelect.next().find('.chosen-single span').text(min + " - " + max);
  			}
  		} else {
  			if (nextSelect.find("option").length == 1) {
  				$(nextSelect).addClass('range-change');
  				nextSelect.next().find('.chosen-single span').text(max);
  			} else {
  				nextSelect.next().find('.chosen-single span').text(nextSelectVal);
  			}
  		}
    }
    */
	}
	var _rebuildFreeCategoryPrices = function(currentSelect) {
		currentSelect = $(currentSelect);
		var currentSelectVal = currentSelect.val() - (currentSelect.val() * (_crt / 100));
		var currentSelectId = "#" + currentSelect.attr('id');
		switch (currentSelectId) {
			case _priceSelectors.priceStandardSelect:
				var nextSelectVal = $(_priceSelectors.pricePremiumSelect).val();
				_updatePriceSelect(_priceSelectors.priceMediumSelect, "priceMedium", currentSelectVal, false, nextSelectVal);
				var premiumPrice = $(_priceSelectors.priceMediumSelect).val();
				if (!$(_priceSelectors.priceMediumSelect).hasClass("range-change")) {
					premiumPrice = $(_priceSelectors.priceMediumSelect).find('option:first').val();
				}
				_updatePriceSelect(_priceSelectors.pricePremiumSelect, "pricePremium", premiumPrice - (premiumPrice * (_crt / 100)), false);
				$(_priceSelectors.pricePremiumSelect).val(nextSelectVal);
				break;
			case _priceSelectors.priceMediumSelect:
				var nextSelectVal = $(_priceSelectors.pricePremiumSelect).val();
				var prevSelectVal = $(_priceSelectors.priceStandardSelect).val();
				_updatePriceSelect(_priceSelectors.pricePremiumSelect, "pricePremium", currentSelectVal, false);
				_updatePriceSelect(_priceSelectors.priceStandardSelect, "priceStandard", currentSelectVal, true);
				$(_priceSelectors.priceStandardSelect).val(prevSelectVal);
				$(_priceSelectors.pricePremiumSelect).val(nextSelectVal);
				break;
			case _priceSelectors.pricePremiumSelect:
				var prevSelectVal = $(_priceSelectors.priceMediumSelect).val();
				_updatePriceSelect(_priceSelectors.priceMediumSelect, "priceMedium", currentSelectVal, true);
				$(_priceSelectors.priceMediumSelect).val(prevSelectVal);
				if (!$(_priceSelectors.priceMediumSelect).hasClass("range-change")) {
					prevSelectVal = $(_priceSelectors.priceMediumSelect).find('option:last').val();
				}
				_updatePriceSelect(_priceSelectors.priceStandardSelect, "priceStandard", prevSelectVal - (prevSelectVal * (_crt / 100)), true);
				break;
		}
	}
	var _getPriceSelectors = function() {
		return _priceSelectors;
	}
	return {
		init: function(options) {
			_categoryPrices = options.categoryPrices;
			_crt = options.crt;
			_prdPrice = options.prdPrice;
      _prdPriceDodji = options.prdPriceDodji;
      _dodjirate = options.dodjirate;
      _minDodjiPrice = options.minDodjiPrice;
			_prdPackages = options.prdPackages;
		},
		setCategoryPrices: _setCategoryPrices,
		setFreeCategoryPrices: _setFreeCategoryPrices,
		rebuildFreeCategoryPrices: _rebuildFreeCategoryPrices,
		getPriceSelectors: _getPriceSelectors
	}
})();


/**
 * Функции сохранения и восстановления позиции курсора в контейнере
 * http://jsfiddle.net/gEhjZ/95/
 */
var saveSelection = function(containerEl) {
	var doc = containerEl.ownerDocument,
		win = doc.defaultView;
	var range = win.getSelection().getRangeAt(0);
	var preSelectionRange = range.cloneRange();
	preSelectionRange.selectNodeContents(containerEl);
	preSelectionRange.setEnd(range.startContainer, range.startOffset);
	var start = preSelectionRange.toString().length;
	return {
		start: start,
		end: start + range.toString().length
	}
};
var restoreSelection = function(containerEl, savedSel) {
	var doc = containerEl.ownerDocument,
		win = doc.defaultView;
	var charIndex = 0,
		range = doc.createRange();
	range.setStart(containerEl, 0);
	range.collapse(true);
	var nodeStack = [containerEl],
		node, foundStart = false,
		stop = false;
	while (!stop && (node = nodeStack.pop())) {
		if (node.nodeType == 3) {
			var nextCharIndex = charIndex + node.length;
			if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
				range.setStart(node, savedSel.start - charIndex);
				foundStart = true;
			}
			if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
				range.setEnd(node, savedSel.end - charIndex);
				stop = true;
			}
			charIndex = nextCharIndex;
		} else {
			var i = node.childNodes.length;
			while (i--) {
				nodeStack.push(node.childNodes[i]);
			}
		}
	}
	var sel = win.getSelection();
	sel.removeAllRanges();
	sel.addRange(range);
};