function setupBrandPicker(options){
    var categories = new URI().getData('c').split(','),
        link = document.getElement(options.link);

    function updateLink(brands){
        var str = brands.join(','),
            // clone the url, because I'm going
            // to mutate it 
            url = new URI(link.retrieve("original"));
        
        if (str.match(/\d+(,\d+)*/)) {
            url.setData({c: str}, true); // merge
            link.set('href', url);
        }
    }

    link.store("original", new URI());

    options.onChange = function (elements, values){
        var checked = this.getOn();
        var keys = checked.length > 0 ? checked : this.states.getKeys();

        updateLink(keys);
    };

    updateLink(categories);

    return new CheckboxManager(options);
}

window.addEvent('domready', function (){
    if ($("ChooseBrands")){
        setupBrandPicker({
            link: "#ChooseBrands",
            checkboxes: "#BrandChooser .checkbox",
            onSwitch: "#turnAllOn",
            offSwitch: "#turnAllOff",
            baseUrl: "/catalog.aspx?c="
        });
    }

    if ($("ChooseBrandsUsed")){
            setupBrandPicker({
            link: "#ChooseBrandsUsed",
            checkboxes: "#BrandChooserUsed .checkbox",
            onSwitch: "#turnAllOnUsed",
            offSwitch: "#turnAllOffUsed",
            baseUrl: "/used-store.aspx?c="
        });
    }

    if(document.getElement(".ratingFilter")){
        var checkboxes = $$(".ratingFilter input[type=checkbox]");

        $$("#allOnRating").addEvent('click', function (event){
            event.stop();
            checkboxes.setProperty("checked", "checked");
        });

        $$("#allOffRating").addEvent('click', function (event){
            event.stop();
            checkboxes.removeProperty("checked");
        });
    }
});


