/* global Bdf,$$ */

Bdf.Conditional = {};

Bdf.Conditional.init = function ($element) {
    var $conditionalElements = $$($element, {conditionalValues: true});
    $conditionalElements.each(function (index, element) {
        let selectSource = $$.one(element.dataset.conditionalSource);
        let valueArray = element.dataset.conditionalValues.split(" ");
        _setVisible(element, _testValue(selectSource, valueArray));
        $(selectSource).change(function () {
            _setVisible(element, _testValue(selectSource, valueArray));
        });
    });
    
    
    function _testValue(selectElement, valueArray) {
        let selectedOption = selectElement.selectedOptions[0];
        return (valueArray.indexOf(selectedOption.value) > -1);
    }
    
    function _setVisible(element, visible) {
        let $block;
        if (element.dataset.conditionalParent) {
            $block = $(element).parents(element.dataset.conditionalParent);
        } else {
            $block = $(element);
        }
        if (visible) {
            $block.removeClass("hidden");
        } else {
            $block.addClass("hidden");
        }
    }
    
};


$(function () {
    Bdf.Conditional.init($("body"));
});
