roseweixel/lacquer-lover

View on GitHub
app/assets/javascripts/brand_dropdown.js.erb

Summary

Maintainability
Test Coverage
var BRANDS = {};

var BRANDS_SHORT = {};

var brandNames = <%= Brand.all.pluck(:name) %>;
var brandAbbreviations = <%= Brand.all.map {|b| b.abbreviation} %>;
brandNames.forEach(function(name, index){
    BRANDS[name] = "#"+brandAbbreviations[index]+"-dropdown";
    BRANDS_SHORT[name] = ".other-lacquer#"+brandAbbreviations[index];
})

$(function(){
    $('.main-color-dropdown').hide();
    $('.main-finish-dropdown').hide();
    $('.lacquer-dropdown').hide();
    $('.other-lacquer').hide();
    
    $('#brand-selection').change(function(event){
        event.stopPropagation();
        var brand = $(this).val();
        $('.lacquer-dropdown').hide();
        $('.other-lacquer').hide();
        $('.add-lacquer').hide();
        $('.add-lacquer').addClass("disabled");
        $('.lacquer-dropdown').find('select').val($("#target option:first").val());
        $('.main-color-dropdown').hide();
        $('.main-finish-dropdown').hide();
        $.each(BRANDS, function(key, value){
            if(brand === key){
                $(value).show();
            }
        });
    });

    $('.lacquer-dropdown').change(function(event){
        event.stopPropagation();
        $('.other-lacquer').hide();
        $('.main-color-dropdown').hide();
        $('.main-finish-dropdown').hide();
        var brand = $('#brand-selection').val();
        var lacquerID = $(this).find("select").val();
        if(lacquerID === "") {
            $('.add-lacquer').addClass("disabled");
            $('.add-lacquer').hide();
        } else if(lacquerID === "new") {
            $('.main-color-dropdown').hide();
            $('.main-finish-dropdown').hide();
            $('.add-lacquer').hide();
            $.each(BRANDS_SHORT, function(key, value){
                if(brand === key){
                    $(value).show();
                }
            });
            $('.add-lacquer').addClass("disabled");
        } else {
            $('.add-lacquer').removeClass("disabled");
            $('.add-lacquer').show();
            $('.main-color-dropdown').show();
            $('.main-finish-dropdown').show();
        }
    });

    $('.page-header').on("click", '.main-finish-dropdown', function(event){
        event.stopPropagation();
        $(this).siblings().toggle();
        $(this).siblings().css({"background-color": "white", "color": "black"});
    });

    $('.page-header').on("click", '.main-color-dropdown', function(event){
        event.stopPropagation();
        $(this).siblings().toggle();
        $(this).siblings().css({"background-color": "white", "color": "black"});
    });


    $('.page-header').on("click", '.dropdown-menu', function(event){
        event.stopPropagation();
        $('this').show();
    });

});