/**
 *  Initialize acfCheckboxSwitch
 *
 *  Render ACF site option checkboxes as switches
 */
var acfCheckboxSwitch = (function ($) {

    var pub = {}; // public facing functions
    var checkboxSwitches = $('.acf-field-checkbox.reach-switch .acf-checkbox-list li label input');

    pub.init = function () {
        if (checkboxSwitches.length > 0) {
            pub._renderSwitches();
        }
    };

    /**
     * Loop through reach switch checkboxes and add our switch markup
     */
    pub._renderSwitches = function () {
        var switchMarkup = '<div class="acf-switch -on">' +
            '<span class="acf-switch-on" style="min-width: 23px;">On</span>' +
            '<span class="acf-switch-off" style="min-width: 23px;">Off</span>' +
            '<div class="acf-switch-slider"></div>' +
            '</div>';

        $.each(checkboxSwitches, function () {
            var switchHTML = $.parseHTML(switchMarkup);

            this.classList.add('acf-switch-input');
            this.after(switchHTML[0]);

            pub._toggleSwitchState(this);
        });

        pub._listenForSwitchEvents();
    };

    /**
     * Event listener for our newly created switch elements
     */
    pub._listenForSwitchEvents = function () {
        var switches = $('.reach-switch .acf-checkbox-list li input');
        switches.on('click', function () {
            pub._toggleSwitchState(this);
        });
    };

    /**
     * Toggle switch states to show if checked or not
     *
     * @param element
     */
    pub._toggleSwitchState = function (element) {
        // vars
        var elementInput = $(element),
            elementSwitch = elementInput.next('.acf-switch'),
            checked = elementInput.prop('checked');

        if (checked) {
            elementSwitch.addClass('-on');
        } else {
            elementSwitch.removeClass('-on');
        }
    };

    return pub;

})(jQuery);