  $('#request-prd-id').chosen({
      width: "100%",
      disable_search: true
  });
  $('#request-prd-count').chosen({
      width: "100%",
      disable_search: true
  });
  $('#request-prd-package-type').chosen({
      width: "100%",
      disable_search: true
  });
  $('#request-prd-duration').chosen({
      width: "100%",
      disable_search: true
  });

  function validateOffer() {
      var formValid = false;
      if ($("#customDodji").hasClass("hidden")) {
          formValid = validateDodji();
      } else {
          formValid = validateCustomDodji();
      }

      if (formValid) {
          btnDisableToggle("off");
      } else {
          btnDisableToggle("on");
      }
  }

  function validateDodji() {
      if ($("#request-prd-id").val() == '')
          return false;
      return true;
  }

  function validateCustomDodji() {
      if ($('#request-prd-name').is(":visible") && ($('#request-prd-name').val() === "")) {// || StopwordsModule._testContacts($('#request-prd-name').val()).length != 0)) {
          return false;
      }
      if ($('#request-prd-desc').is(":visible") && ($('#request-prd-desc').val() === "" || $('#request-prd-desc').val().length < 100 || $('#request-prd-desc').val().length > 1200)) {// || StopwordsModule._testContacts($('#request-prd-desc').val()).length != 0)) {
          return false;
      }
      if ($('#request-prd-price').is(":visible") && validateCustomDodjiPrice($('#request-prd-price'))) {
          return false;
      }

      //if ($('#offer_description').length && StopwordsModule._testContacts($('#offer_description').val()).length != 0) {
      //    return false;
      //}

      if ($("#request-prd-id").length && $("#request-prd-id").is(":visible") && !$("#request-prd-id").val()) {
          return false;
      }

      return true;
  }

  $(function() {
      $(document).on('change', '#request-prd-id', function() {
          if ($(this).val()) {
              $('.js-send-request__total').show();
              $('.js-order-extras').show();
          } else {
              $('.js-send-request__total').hide();
              $('.js-order-extras').hide();
          }
          if ($(this).find('option:checked').data('package')) {
              $('.request-prd-count-block').hide();
              $('.request-prd-package-block').show();
          } else {
              $('.request-prd-count-block').show();
              $('.request-prd-package-block').hide();
          }
          calcPrice();
          validateOffer();
      });
      $(document).on('change', '#request-prd-id, #request-prd-count, #request-prd-package-type, .order-extras__input, .js-order-extras__count, .js-new-extra-select', calcPrice);
      $(document).on('change', '.js-new-extra-price', function() {
          var price = $(this).find('option:checked').data('sellerValue');
          var $countSelect = $(this).closest('.new-order-extras__select-block').find('.js-new-extra-count');
          $countSelect.find('option').each(function() {
              var sum = price * $(this).attr('value');
              $(this).text($(this).attr('value') + "(" + Utils.priceFormatWithSign(sum, offer.lang) + ")");
          });
          $countSelect.trigger("chosen:updated");
      });
  });

  function calcPrice() {

      var isPackage = $('#request-prd-id option:selected').data('package');

      var payerSum = 0;
      if (isPackage !== 1) {
          var sum = ($('#request-prd-count').val() ^ 0) * $('#request-prd-id option:selected').data('workerprice'),
              days = $('#request-prd-id option:selected').data('time') ^ 0,
              count = $('#request-prd-count').val() ^ 0;
          payerSum = ($('#request-prd-count').val() ^ 0) * $('#request-prd-id option:selected').data('price');
      } else {
          var packageType = $("#request-prd-package-type").val();
          if (!packageType) {
              return false;
          }
          var package = offer.prdPackages[$('#request-prd-id').val()][packageType];
          var sum = package.price,
              days = package.duration ^ 0,
              count = 1;
          payerSum = package.payerPrice;

          /*! меняем тип переменной */
          if ($.type(payerSum) === 'string') {
              payerSum = parseFloat(payerSum);
          }
      }

      days = getDuration(days, count, offer.multiDodjiRate);
      $('.order-extras__input:checked').each(function() {
          var count = $('#extra_count' + $(this).val()).val() ^ 0;
          payerSum += ($(this).data('payerPrice') ^ 0) * count;
          sum += $(this).data('price') * count;
          days += getDuration($(this).data('time') ^ 0, count, offer.multiDodjiRate);
      });
      $('.new-order-extras__select-block').each(function() {
          var count = 1;
          payerSum += $(this).find('.js-new-extra-price').find('option:checked').data('payerValue') * count;
          sum += ($(this).find('.js-new-extra-price').find('option:checked').data('sellerValue') ^ 0) * count;
          days += getDuration($(this).find('.js-new-extra-days').val() ^ 0, count, offer.multiDodjiRate);
      });

      var payerSumString = Utils.priceFormat(payerSum, offer.lang, '&nbsp;');
      var sumString = Utils.priceFormat(sum, offer.lang, '&nbsp;');
      if (offer.lang === "ru") {
          payerSumString += '&nbsp;<span class="rouble">Р</span>';
          sumString += '&nbsp;<span class="rouble">Р</span>';
      } else {
          payerSumString = '<span class="usd">$</span>' + payerSumString;
          sumString = '<span class="usd">$</span>' + sumString;
      }
      $('.js-total-sum').html('Стоимость: ' + payerSumString);
      $('.js-total-worker-sum').html('Вы получите' + ': ' + sumString);
      $('.js-total-time').html(days + ' ' + Utils.declOfNum(days, ['день', 'дня', 'дней']));
  }

  $('select[name=prd_id]').change(function() {
      $('select[name=prd_id] .empty').remove();
      var pid = $('select[name=prd_id] option:checked').val();
      $('.order-extras li').hide();
      $('.order-extras__list input[type=checkbox]').prop('checked', false).trigger('change');
      if ($('.order-extras li[data-pid=' + pid + ']').length > 0) {
          $('.order-extras li[data-pid=' + pid + ']').show();
      } else {
          $.ajax({
              url: '/api?method=getExtrasByItem',
              type: 'post',
              dataType: 'json',
              data: {
                'item_id': pid
              },
              success: function(response) {
                  if (response.success == true) {
                      for (var i in response.extras) {
                          var extra = response.extras[i];
                          var html = "";
                          html = '<li class="order-extras__item order-extras__item_old" data-pid="' + pid + '" data-id="' + extra.id + '" style="display:none;">' + '<input class="order-extras__input styled-checkbox" data-payer-price="' + extra.payerPrice + '" data-price="' + extra.price + '" data-time="' + extra.duration + '" data-id="' + extra.id + '" name="gextras[]" type="checkbox" value="' + extra.id + '">' + '<label for="order-extras_' + extra.id + '" class="w460">' + extra.name.ucFirst() + '</label>' + '<div class="order-extras__select-block">' + '<select class="js-order-extras__count styled input input_size_s" data-affected-checkbox="' + extra.id + '" id="extra_count' + extra.id + '" name="extra_count' + extra.id + '">';
                          for (var j = 0; j < offer.maxDodjiCount; j++) {
                              var value = j + 1;
                              var price = Utils.priceFormatWithSign(extra.price * value, offer.lang, "&nbsp;", "Р");
                              html += '<option value="' + value + '">' + value + ' (' + price + ')</option>';
                          }
                          html += '</select>' + '</div>' + '</li>';
                          $('.order-extras__list').prepend(html);
                          $('.js-order-extras__count[data-affected-checkbox]').on('change', function(e) {
                              var t = $(e.delegateTarget);
                              $('.order-extras__item_old[data-id="' + t.data('affected-checkbox') + '"] .order-extras__input').prop('checked', true);
                          });
                          $('.order-extras li[data-pid=' + pid + ']').show();
                          $('.order-extras li[data-pid=' + pid + '] select').chosen({
                              width: "108px",
                              disable_search: true
                          });
                      }
                  }
              }
          });
      }
      $('.order-extras li.custom').show();
  });
  $(window).load(function() {
      $('.order-extras__select-block select.styled').chosen({
          width: "108px",
          disable_search: true
      });
  });
  $(document).on('click', '.order-extras__item', function(e) {
      if ($('.styled-checkbox[data-id=' + $(this).data('id') + ']').prop('checked')) {
          if (!$(e.target).is('.chosen-container') && $(e.target).closest('.chosen-container').length === 0) {
              $('.styled-checkbox[data-id=' + $(this).data('id') + ']').prop('checked', false).trigger('change');
          }
      } else {
          $('.styled-checkbox[data-id=' + $(this).data('id') + ']').prop('checked', true).trigger('change');
      }
  });

  function showCustomOptionForm(el) {
      var html = '<li class="order-extras__item extrasping-settings extra-field-block-css extra-edit-block-css custom">' + '<div class="offer-sprite offer-sprite-option pull-left m-hidden mt2"></div>' + '<input name="customExtraName[]" maxlength="50" value="" style="width:340px;" class="textthree styled-input f14 pull-left m-wMax m-border-box order-new-extras__input" type="text">' + '<div class="new-order-extras__select-block">' + '<select id="extratime" class="js-new-extra-select js-new-extra-days textthree input input_size_s" name="customExtraTime[]" style="width:16%;">' + '<option value="0"> ' + t('{{0}} дней', [0]) + ' </option>' + '<option value="1"> ' + t('{{0}} день', [1]) + ' </option>' + '<option value="2"> ' + t('{{0}} дня', [2]) + ' </option>' + '<option value="3"> ' + t('{{0}} дня', [3]) + ' </option>' + '<option value="4"> ' + t('{{0}} дня', [4]) + ' </option>' + '<option value="5"> ' + t('{{0}} дней', [5]) + ' </option>' + '<option value="6"> ' + t('{{0}} дней', [6]) + ' </option>' + '<option value="7"> ' + t('{{0}} дней', [7]) + ' </option>' + '<option value="8"> ' + t('{{0}} дней', [8]) + ' </option>' + '<option value="9"> ' + t('{{0}} дней', [9]) + ' </option>' + '<option value="10"> ' + t('{{0}} дней', [10]) + ' </option>' + '</select>' + '<select name="customExtraPrice[]" class="js-new-extra-select js-new-extra-price textthree input input_size_s" style="width:16%;">' + offer.customPricesOptionsHtml + '</select>' + '</div>' + '<div class="new-order-extras__delete del-opt cur ml6 dib" data-id="0" title="' + 'Удалить' + '" onclick="removeCustomOptionForm($(this));">' + '<i class="ico-close-14"></i>' + '</div>' + '<div class="clear"></div>' + '</li>';
      var $html = $(html);

      $html.find('.js-new-extra-price').chosen({
          width: "100px",
          disable_search: true
      });
      $html.find('.js-new-extra-days').chosen({
          width: "80px",
          disable_search: true
      });
      $('.order-extras__list').append($html);
      $('#message_body').trigger('input');
      $(el).text('Создать еще опцию');
      calcPrice();
  }

  function removeCustomOptionForm(target) {
      target.closest('li').remove();
      $('#message_body').trigger('input');
      if ($('#addextras li.extrasping-settings').length < 1)
          $('#order-extras__create').text('Создать опцию');
      calcPrice();
  }

  $('#request-prd-price').on('input', function() {
      var $obj = $(this);
      var $desc = $('#prd-price-description');

      var error = validateCustomDodjiPrice($obj);
      if (error) {
          $desc.addClass('color-red').html(error);
      } else {
          var ctp = $obj.val() - $obj.val() * offer.comission / 100;
          $desc.removeClass('color-red').html(t('Вы получите {{0}}', [Utils.priceFormatWithSign(ctp, offer.lang)]));
      }
  });

  $('#suggestDodji').on('input', '#request-prd-name, #request-prd-desc, #request-prd-price, #offer_description', function() {
      validateOffer();
  });

  function validateCustomDodjiPrice($obj) {
      if (/[^0-9]/ig.test($obj.val())) {
          $obj.val($obj.val().replace(/[^0-9]/ig, ''));
          return 'Ввод только цифр';
      }

      var price = parseInt($obj.val());

      if (isNaN(price)) {
          return 'Введите стоимость';
      }

      if (price < offer.customMinPrice || price > offer.customMaxPrice) {
          return t('Стоимость может быть от {{0}} до {{1}}', [Utils.priceFormatWithSign(offer.customMinPrice, offer.lang), Utils.priceFormatWithSign(offer.customMaxPrice, offer.lang)]);
      }
  }

  //Переключение на предложить
  $('#change-to-prd-choose').click(function() {
      $('#suggestCustomDodjiToggle, #change-to-prd-choose').addClass('hidden');
      $('#suggestDodjiToggle, #change-to-custom-prd').removeClass('hidden');
  });
  //Переключение на индивидуальное предложение
  $('#change-to-custom-prd').click(function() {
      $('#suggestDodjiToggle, #change-to-custom-prd').addClass('hidden');
      $('#suggestCustomDodjiToggle, #change-to-prd-choose').removeClass('hidden');
  });

  var descAreaHint = (function() {

      var $input = $('#request-prd-desc');
      var $hint = $('#request-prd-desc-hint');
      var min = 100;
      var max = 1200;

      var _init = function() {
          if ($input.length) {
              $input.keyup(_update);
              $input.change(_change);
              $input.textAreaMaxLength(max);
              _update();
          }
      };

      var _update = function() {
          $hint.removeClass('color-red');

          var used = $input.val().length;

          if (used < min) {
              $hint.html(t('{{0}} из {{1}} минимум', [used, min]));
          } else {
              $hint.html(t('{{0}} из {{1}} максимум', [used, max]));
          }
      };

      var _change = function() {
          var used = $input.val().length;

          if (used < min || used > max) {
              $hint.addClass('color-red');
          }
      };

      return {
          init: _init
      };

  })();

  descAreaHint.init();