var $ = window.jQuery;
var $obj = $('form.webform-submission-contact-us-form');

if ($obj.length) {
  var contactUs = {};

  var $productCat = $obj.find('select[name="product_category"]');

  var targetObject = {
    ALL: ''
  };

  ([
    {
      mapName: 'marketProductMap',
      optionParent: $productCat,
      dataKey: 'segment',
      optionsKey: '$productCatOptions',
      optionAllKey: '$productCatOptionAll'
    },
    {
      mapName: 'categoryModelMap',
      optionParent: $obj.find('select[name="product_model"]'),
      dataKey: 'category',
      optionsKey: '$productModelOptions',
      optionAllKey: '$productModelOptionAll'
    }
  ])
  .forEach(function(config) {
    var map = {};

    config.optionParent.children().each(function(index, item) {
      var $item = $(item);
      var id = $item.data(config.dataKey);

      if (id !== undefined) {
        var optionId = $item.attr('value');

        id.toString().split(',').forEach(function(item) {
          map[item] = map[item] || [];
          map[item].push(optionId);
        });
      }
    });

    targetObject[config.mapName] = map;
    targetObject[config.optionsKey] = config.optionParent.children();
    targetObject[config.optionAllKey] = targetObject[config.optionsKey].filter('[value="' + targetObject.ALL + '"]');
  });

  contactUs = targetObject;

  contactUs.$market = $obj.find('select[name="market_segment"]').change(function(e) {
    var value = this.value;

    if (value === contactUs.ALL) {
      contactUs.$productCatOptions.prop('disabled', false);
    }
    else {
      contactUs.$productCatOptions.prop('disabled', true);

      (contactUs.marketProductMap[value] || []).forEach(function(item) {
        contactUs.$productCatOptions.filter('[value="' + item + '"]').prop('disabled', false);
      });
    }

    contactUs.$productCatOptionAll.prop('disabled', false);
  });

  $productCat.change(function(e) {
    var value = this.value;
    var activeMarket;

    if (value === contactUs.ALL) {
      var market = contactUs.$market.val();

      if (market === contactUs.ALL) {
        contactUs.$productModelOptions.prop('disabled', false);
      }
      else {
        activeMarket = contactUs.marketProductMap[market];
      }
    }
    else {
      activeMarket = [value];
    }

    if (activeMarket) {
      contactUs.$productModelOptions.prop('disabled', true);

      activeMarket.forEach(function(name) {
        (contactUs.categoryModelMap[name] || []).forEach(function(item) {
          contactUs.$productModelOptions.filter('[value="' + item + '"]').prop('disabled', false);
        });
      });
    }

    contactUs.$productModelOptionAll.prop('disabled', false);
  });
}
