<commit_before>//= require miq_global
//= require jquery
//= require jquery_overrides
//= require angular
//= require angular-patternfly
//= require angular-ui-bootstrap
//= require angular-ui-bootstrap-tpls
//= require moment
//= require moment-strftime
//= require moment-timezone
//= require sprintf
//= require numeral
//= require miq_angular_application
//= require services/miq_service
//= require services/miq_db_backup_service
//= require directives/scheduler/updateDropdownForFilter
//= require directives/scheduler/updateDropdownForTimer
//= require directives/miq_calendar
//= require directives/autofocus
//= require directives/miqrequired
//= require directives/checkchange
//= require directives/clear_field_set_focus
//= require directives/datepicker
//= require directives/verifypasswd
//= require directives/required_depends_on
//= require directives/selectpickerForSelectTag
//= require directives/repository/valid_unc_path
//= require services/miq_service
//= require services/timer_option_service
//= require controllers/buttons/button_group_controller
//= require controllers/credentials/credentials_controller
//= require controllers/ems_common/ems_common_form_controller
//= require controllers/host/host_form_controller
//= require controllers/provider_foreman/provider_foreman_form_controller
//= require controllers/repository/repository_form_controller
//= require controllers/retirement/retirement_form_controller
//= require controllers/schedule/schedule_form_controller
//= require controllers/ops/diagnostics_database_form_controller
//= require controllers/ops/log_collection_form_controller
//= require controllers/ops/tenant_form_controller
//= require controllers/ops/tenant_quota_form_controller
//= require controllers/container_dashboard/container_dashboard_controller
//= require controllers/container_dashboard/container_dashboard_utils
//= require controllers/container_topology/container_topology_controller
//= require d3/d3
//= require c3/c3
//= require kubernetes-topology-graph/topology-graph
//= require miq_application
//= require miq_change_stored_password
//= require miq_dynatree_replacement
//= require dialog_import_export
//= require widget_import_export
//= require automate_import_export
//= require dialog_field_refresh
//= require excanvas
//= require jquery.jqplot
//= require jqplot-plugins/jqplot.pieRenderer
//= require jqplot-plugins/jqplot.donutRenderer
//= require jqplot-plugins/jqplot.barRenderer
//= require jqplot-plugins/jqplot.categoryAxisRenderer
//= require jqplot-plugins/jqplot.highlighter
//= require jqplot-plugins/jqplot.cursor
//= require jqplot-plugins/jqplot.enhancedLegendRenderer
//= require jqplot-plugins/jqplot.canvasAxisTickRenderer
//= require jqplot-plugins/jqplot.canvasTextRenderer
//= require miq_jqplot
//= require jqueryui
//= require bootstrap
//= require bootstrap-datepicker
//= require bootstrap-filestyle
//= require bootstrap-select
//= require bootstrap-hover-dropdown
//= require patternfly
//= require jquery.observe_field
//= require miq_jquery_ujs_rails3
//= require miq_ujs_bindings
//= require dynatree/jquery.dynatree
//= require miq_dynatree
//= require slickgrid/lib/jquery.event.drag-2.2
//= require slickgrid/slick.core
//= require slickgrid/slick.grid
//= require slickgrid/slick.dataview
//= require slickgrid/plugins/slick.autotooltips
//= require slickgrid/plugins/slick.rowselectionmodel
//= require slickgrid/plugins/slick.checkboxselectcolumn
//= require miq_slickgrid
//= require codemirror
//= require codemirror/modes/yaml
//= require spin
//= require jquery-hotkeys
//= require lodash
//= require miq_formatters
//= require miq_grid
//= require miq_list_grid
//= require miq_toolbar
//= require resizable_sidebar

<commit_msg>Fixes 5271 - Add ng-sanitize dependency for patternfly 2.5.0 (transferred from ManageIQ/manageiq@8cc8fdc33a040954e8e49a9ca90c8e84a8f9e742)<commit_after>//= require miq_global
//= require jquery
//= require jquery_overrides
//= require angular
//= require angular-patternfly
//= require angular-ui-bootstrap
//= require angular-ui-bootstrap-tpls
//= require angular-sanitize
//= require moment
//= require moment-strftime
//= require moment-timezone
//= require sprintf
//= require numeral
//= require miq_angular_application
//= require services/miq_service
//= require services/miq_db_backup_service
//= require directives/scheduler/updateDropdownForFilter
//= require directives/scheduler/updateDropdownForTimer
//= require directives/miq_calendar
//= require directives/autofocus
//= require directives/miqrequired
//= require directives/checkchange
//= require directives/clear_field_set_focus
//= require directives/datepicker
//= require directives/verifypasswd
//= require directives/required_depends_on
//= require directives/selectpickerForSelectTag
//= require directives/repository/valid_unc_path
//= require services/miq_service
//= require services/timer_option_service
//= require controllers/buttons/button_group_controller
//= require controllers/credentials/credentials_controller
//= require controllers/ems_common/ems_common_form_controller
//= require controllers/host/host_form_controller
//= require controllers/provider_foreman/provider_foreman_form_controller
//= require controllers/repository/repository_form_controller
//= require controllers/retirement/retirement_form_controller
//= require controllers/schedule/schedule_form_controller
//= require controllers/ops/diagnostics_database_form_controller
//= require controllers/ops/log_collection_form_controller
//= require controllers/ops/tenant_form_controller
//= require controllers/ops/tenant_quota_form_controller
//= require controllers/container_dashboard/container_dashboard_controller
//= require controllers/container_dashboard/container_dashboard_utils
//= require controllers/container_topology/container_topology_controller
//= require d3/d3
//= require c3/c3
//= require kubernetes-topology-graph/topology-graph
//= require miq_application
//= require miq_change_stored_password
//= require miq_dynatree_replacement
//= require dialog_import_export
//= require widget_import_export
//= require automate_import_export
//= require dialog_field_refresh
//= require excanvas
//= require jquery.jqplot
//= require jqplot-plugins/jqplot.pieRenderer
//= require jqplot-plugins/jqplot.donutRenderer
//= require jqplot-plugins/jqplot.barRenderer
//= require jqplot-plugins/jqplot.categoryAxisRenderer
//= require jqplot-plugins/jqplot.highlighter
//= require jqplot-plugins/jqplot.cursor
//= require jqplot-plugins/jqplot.enhancedLegendRenderer
//= require jqplot-plugins/jqplot.canvasAxisTickRenderer
//= require jqplot-plugins/jqplot.canvasTextRenderer
//= require miq_jqplot
//= require jqueryui
//= require bootstrap
//= require bootstrap-datepicker
//= require bootstrap-filestyle
//= require bootstrap-select
//= require bootstrap-hover-dropdown
//= require patternfly
//= require jquery.observe_field
//= require miq_jquery_ujs_rails3
//= require miq_ujs_bindings
//= require dynatree/jquery.dynatree
//= require miq_dynatree
//= require slickgrid/lib/jquery.event.drag-2.2
//= require slickgrid/slick.core
//= require slickgrid/slick.grid
//= require slickgrid/slick.dataview
//= require slickgrid/plugins/slick.autotooltips
//= require slickgrid/plugins/slick.rowselectionmodel
//= require slickgrid/plugins/slick.checkboxselectcolumn
//= require miq_slickgrid
//= require codemirror
//= require codemirror/modes/yaml
//= require spin
//= require jquery-hotkeys
//= require lodash
//= require miq_formatters
//= require miq_grid
//= require miq_list_grid
//= require miq_toolbar
//= require resizable_sidebar

<|endoftext|>


<commit_before>(function() {

    var formCheckValid = function(el) {
        var inputType = (el.tagName.toLowerCase() == 'textarea') ? 'textarea' : $(el).attr('type');

        switch (inputType) {
            case 'radio':
            case 'checkbox':
                return (el.checked) ? el.name : null;
                break;
            case 'text':
            case 'number':
            case 'textarea':
                var pattern = (pattern = $(el).attr('data-pattern')) ? pattern : $(el).attr('pattern');
                if (pattern != null) {
                    var result = $(el).val().match(new RegExp(pattern,"gi"));
                    return (result!= null && result.length > 0 && result[0] != '') ?el.name : null;
                } else {
                    return ($(el).val() != '') ? el.name : null;
                }
                break;
            default:
                return null;
        }
    };

    $(document).ready(function() {
        $('a.previousPage').each(function() {
            $(this).on('click', function() {
                if (!confirm('Are you sure you want to go back? You may lose form data.\n\nNB: We need to assess the need and functionality of this link')) {
                    return false;
                }
            });

        });

        /* display-none-js is a class that should only work to hide information when javascript is enabled */
        $('.display-none-js').hide();

        /* generic toggle functionality */
        $('.toggle-section').on('click', function() {
            var sections = $(this).parents('.form-group').attr('data-target');
            var sectionOn = $(this).parents('.form-group').attr('data-target') + '__' + $(this).val().toLowerCase();
            $('.' + sections).hide();
            $('.' + sectionOn).show();
        });

        //$('form.crm-check input[type="submit"]').on('click', function(e) {
        var f = document.querySelector('form.crm-check');
        f.addEventListener ('submit', function (e) {

            //e.preventDefault();

            var form = $('form.crm-check') /*'$(this).parents('form')*/,
                validationMessage = '',
                errorMessages = '',
                validationType = '',
                inputFields = ['input[type="text"]', 'input[type="number"]', 'input[type="checkbox"]', 'input[type="radio"]', 'select', 'textarea'],
                fieldsWithValidValue,
                fields;

            form.find('div.validation-message').remove();

            // loop each validation-group

            form.find('.validation-group:visible').each(function() {

                validationType = $(this).attr('data-validation-type');
                validationMessage = $(this).attr('data-validation-message');

                var tmp = ['required--one-or-more', 'required--one', 'required--all']
                if (tmp.indexOf(validationType) != -1) {
                    fieldsWithValidValue = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function () {
                        return formCheckValid(this);
                    }).get());
                }

                switch (validationType) {
                    case 'required--one-or-more':
                    case 'required--one':
                        if (fieldsWithValidValue.length == 0) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--all':
                        fields = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function() {
                            return this.name;
                        }).get());

                        if (fields.length > fieldsWithValidValue.length) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--set':

                        var fields, setOK,
                            setsOK = false,
                            sets = $(this).removeClass('invalid').attr('data-validation-set').split('|');

                        for (var s = 0, sl = sets.length; s < sl; s ++) {

                            fields = sets[s].split(',');
                            setOK = true;
                            for (var f = 0, fl = fields.length; f < fl; f ++) {
                                if (!formCheckValid($(this).find('input[name="' + fields[f] + '"]').get(0))) {
                                    setOK = false;
                                    break;
                                }
                            }
                            if (setOK) {
                                setsOK = true;
                                break;
                            }
                        }
                        if (!setsOK) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;
                }
            });

            if (errorMessages != '') {
                e.preventDefault();
                form.find('input[type="submit"]').before('

' + errorMessages + '

');
            }

            /* Not ready yet
            // all the validate-groups have been checked - now check the form
            if (formValidationType = form.attr('data-form-validation-type')) {
                switch (formValidationType) {
                    case 'required--set':
                        var groups, groupOK,
                            setsOK = false,
                            sets = $(form).removeClass('invalid').attr('data-form-validation-set').split('|');

                        console.log(sets);

                        for (var s = 0, sl = sets.length; s < sl; s ++) {

                            groups = sets[s].split(',');
                            groupOK = true;
                            for (var f = 0, fl = groups.length; f < fl; f ++) {
                                if (true ) {
                                    groupOK = false;
                                    break;
                                }
                            }
                            if (groupOK) {
                                setsOK = true;
                                break;
                            }
                        }
                        if (!setsOK) {
                            form.addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    break;
                }
            }
            */

            // MANUAL OVERRIDES HERE

            if (form.attr('id') == 'form__fraud-type') { // redirect to new or old website based on user input
                var redirects = ['disabilityCarers', 'abroad', 'idFraud', 'savingsCapital'];
                var selected = form.find('input[type="checkbox"][name="fraud-type"]:checked').map(function() {
                    return this.value;
                }).get();
                var redirectsSelected = $.grep(selected, function(n) {
                    return ( redirects.indexOf(n) != -1 );
                });
                if (redirectsSelected.length > 0) {
                    e.preventDefault();
                    document.location.href = 'https://secure.dwp.gov.uk/benefitfraud/';
                }

            }
        });
    });
})();

    /*

    $('form.crm-check-form').on('submit', function(e) {

        var form = $(this), errorMessage = '';

        // check (groups of) checkboxes where (at least) one must be checked
        var ids = $.unique(form.find('.fieldset').removeClass('invalid').find('input[type="checkbox"].required--one-or-more').map(function() {
            return this.name;
        }).get());
        if (ids.length > 0) {
            var idsChecked = $.unique(form.find('input[type="checkbox"].required--one-or-more:checked').map(function () {
                return (this.name);
            }).get());

            if (idsChecked.length < ids.length) { // not all groups of checkboxes have at least one checked
                // report the issue. Filter out the checked IDs
                ids = $.grep(ids, function (n) {
                    return ( idsChecked.indexOf(n) == -1 );
                });

                for (var i = 0, il = ids.length; i < il; i++) {
                    form.find('#fieldset--' + ids[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';

                    });
                };
            }
        }

        // check required radio buttons

        var ids = $.unique(form.find('.fieldset').find('input[type="radio"].required').map(function() {
            return this.name.replace('helper--', '');
        }).get());
        if (ids.length > 0) {
            var idsChecked = $.unique(form.find('input[type="radio"].required:checked').map(function () {
                return this.name.replace('helper--', '');
            }).get());

            if (idsChecked.length < ids.length) { // not all required sets of radio buttons have been ticked
                // report the issue. Filter out the checked IDs
                ids = $.grep(ids, function (n) {
                    return (idsChecked.indexOf(n) == -1);
                });

                for (var i = 0, il = ids.length; i < il; i++) {
                    form.find('#fieldset--' + ids[i]).each(function() {
                        // set the invalid class and add functionality to remove it
                        $(this).addClass('invalid').attr('data-error-id', i).find('input[type="radio"]').each(function() {

                            $(this).on('click', function () {
                                var errorID = $(this).parents('.invalid').removeClass('invalid').attr('data-error-id');
                                $('#error__' + errorID).remove();
                                if (form.find('div.validation-message').find('li').length == 0) {
                                    form.find('div.validation-message').remove();
                                }
                            });
                        });
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };
            }
        }

        // check required text fields
        var parentNames = [];

        var ids = $.unique(form.find('.fieldset').removeClass('invalid').find('input[type="text"].required:visible, input[type="number"].required:visible').map(function() {
            return this.name.replace('helper--', '');
        }).get());
        console.log(ids);
        if (ids.length > 0) {
            var idsValid = $.unique(form.find('input[type="text"].required:visible, input[type="number"].required:visible').map(function () {
                // TODO: add validation based on regexp
                if ($(this).val() == '') {
                    parentNames.push($(this).attr('data-parent-fieldset'));
                    return null
                } else {
                    return this.name.replace('helper--', '');
                }

            }).get());
console.log(idsValid);
            if (idsValid.length < ids.length) { // not all required sets of radio buttons have been ticked
                // report the issue. Filter out the valid IDs
                ids = $.grep(ids, function (n) {
                    return (idsValid.indexOf(n) == -1);
                });

                console.log(ids);

                for (var i = 0, il = ids.length; i < il; i++) {
                    console.log('invalidating #fieldset--' + ids[i]);
                    form.find('#fieldset--' + ids[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };
                for (var i = 0, il = parentNames.length; i < il; i++) {
                    console.log('invalidating #fieldset--' + parentNames[i]);
                    form.find('#fieldset--' + parentNames[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };

            }
            console.log('------');
        }

        if (errorMessage != '') {
            form.find('div.validation-message').remove();
            form.find('input[type="submit"]').before('

' + errorMessage + '

');

            return false
        }

return false;

    });
    */
<commit_msg>fix in progress<commit_after>(function() {

    var formCheckValid = function(el) {
        var inputType = (el.tagName.toLowerCase() == 'textarea') ? 'textarea' : $(el).attr('type');

        switch (inputType) {
            case 'radio':
            case 'checkbox':
                return (el.checked) ? el.name : null;
                break;
            case 'text':
            case 'number':
            case 'textarea':
                var pattern = (pattern = $(el).attr('data-pattern')) ? pattern : $(el).attr('pattern');
                if (pattern != null) {
                    var result = $(el).val().match(new RegExp(pattern,"gi"));
                    return (result!= null && result.length > 0 && result[0] != '') ?el.name : null;
                } else {
                    return ($(el).val() != '') ? el.name : null;
                }
                break;
            default:
                return null;
        }
    };

    $(document).ready(function() {
        $('a.previousPage').each(function() {
            $(this).on('click', function() {
                if (!confirm('Are you sure you want to go back? You may lose form data.\n\nNB: We need to assess the need and functionality of this link')) {
                    return false;
                }
            });

        });

        /* display-none-js is a class that should only work to hide information when javascript is enabled */
        $('.display-none-js').hide();

        /* generic toggle functionality */
        $('.toggle-section').on('click', function() {
            var sections = $(this).parents('.form-group').attr('data-target');
            var sectionOn = $(this).parents('.form-group').attr('data-target') + '__' + $(this).val().toLowerCase();
            $('.' + sections).hide();
            $('.' + sectionOn).show();
        });

        $('form.crm-check input[type="submit"]').on('click', function(e) {

            //e.preventDefault();

            var form = $(this).parents('form'),
                validationMessage = '',
                errorMessages = '',
                validationType = '',
                inputFields = ['input[type="text"]', 'input[type="number"]', 'input[type="checkbox"]', 'input[type="radio"]', 'select', 'textarea'],
                fieldsWithValidValue,
                fields;

            form.find('div.validation-message').remove();

            // loop each validation-group

            form.find('.validation-group:visible').each(function() {

                validationType = $(this).attr('data-validation-type');
                validationMessage = $(this).attr('data-validation-message');

                var tmp = ['required--one-or-more', 'required--one', 'required--all']
                if (tmp.indexOf(validationType) != -1) {
                    fieldsWithValidValue = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function () {
                        return formCheckValid(this);
                    }).get());
                }

                switch (validationType) {
                    case 'required--one-or-more':
                    case 'required--one':
                        if (fieldsWithValidValue.length == 0) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--all':
                        fields = $.unique($(this).removeClass('invalid').find(inputFields.join(',')).map(function() {
                            return this.name;
                        }).get());

                        if (fields.length > fieldsWithValidValue.length) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    case 'required--set':

                        var fields, setOK,
                            setsOK = false,
                            sets = $(this).removeClass('invalid').attr('data-validation-set').split('|');

                        for (var s = 0, sl = sets.length; s < sl; s ++) {

                            fields = sets[s].split(',');
                            setOK = true;
                            for (var f = 0, fl = fields.length; f < fl; f ++) {
                                if (!formCheckValid($(this).find('input[name="' + fields[f] + '"]').get(0))) {
                                    setOK = false;
                                    break;
                                }
                            }
                            if (setOK) {
                                setsOK = true;
                                break;
                            }
                        }
                        if (!setsOK) {
                            $(this).addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;
                }
            });

            if (errorMessages != '') {
                e.preventDefault();
                form.find('input[type="submit"]').before('

' + errorMessages + '

');
            }

            /* Not ready yet
            // all the validate-groups have been checked - now check the form
            if (formValidationType = form.attr('data-form-validation-type')) {
                switch (formValidationType) {
                    case 'required--set':
                        var groups, groupOK,
                            setsOK = false,
                            sets = $(form).removeClass('invalid').attr('data-form-validation-set').split('|');

                        console.log(sets);

                        for (var s = 0, sl = sets.length; s < sl; s ++) {

                            groups = sets[s].split(',');
                            groupOK = true;
                            for (var f = 0, fl = groups.length; f < fl; f ++) {
                                if (true ) {
                                    groupOK = false;
                                    break;
                                }
                            }
                            if (groupOK) {
                                setsOK = true;
                                break;
                            }
                        }
                        if (!setsOK) {
                            form.addClass('invalid');
                            errorMessages += '
' + validationMessage + '
';
                        }
                        break;

                    break;
                }
            }
            */

            // MANUAL OVERRIDES HERE

            if (form.attr('id') == 'form__fraud-type') { // redirect to new or old website based on user input
                var redirects = ['disabilityCarers', 'abroad', 'idFraud', 'savingsCapital'];
                var selected = form.find('input[type="checkbox"][name="fraud-type"]:checked').map(function() {
                    return this.value;
                }).get();
                var redirectsSelected = $.grep(selected, function(n) {
                    return ( redirects.indexOf(n) != -1 );
                });
                if (redirectsSelected.length > 0) {
                    e.preventDefault();
                    document.location.href = 'https://secure.dwp.gov.uk/benefitfraud/';
                }
            }

            return true;
        });
    });
})();

    /*

    $('form.crm-check-form').on('submit', function(e) {

        var form = $(this), errorMessage = '';

        // check (groups of) checkboxes where (at least) one must be checked
        var ids = $.unique(form.find('.fieldset').removeClass('invalid').find('input[type="checkbox"].required--one-or-more').map(function() {
            return this.name;
        }).get());
        if (ids.length > 0) {
            var idsChecked = $.unique(form.find('input[type="checkbox"].required--one-or-more:checked').map(function () {
                return (this.name);
            }).get());

            if (idsChecked.length < ids.length) { // not all groups of checkboxes have at least one checked
                // report the issue. Filter out the checked IDs
                ids = $.grep(ids, function (n) {
                    return ( idsChecked.indexOf(n) == -1 );
                });

                for (var i = 0, il = ids.length; i < il; i++) {
                    form.find('#fieldset--' + ids[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';

                    });
                };
            }
        }

        // check required radio buttons

        var ids = $.unique(form.find('.fieldset').find('input[type="radio"].required').map(function() {
            return this.name.replace('helper--', '');
        }).get());
        if (ids.length > 0) {
            var idsChecked = $.unique(form.find('input[type="radio"].required:checked').map(function () {
                return this.name.replace('helper--', '');
            }).get());

            if (idsChecked.length < ids.length) { // not all required sets of radio buttons have been ticked
                // report the issue. Filter out the checked IDs
                ids = $.grep(ids, function (n) {
                    return (idsChecked.indexOf(n) == -1);
                });

                for (var i = 0, il = ids.length; i < il; i++) {
                    form.find('#fieldset--' + ids[i]).each(function() {
                        // set the invalid class and add functionality to remove it
                        $(this).addClass('invalid').attr('data-error-id', i).find('input[type="radio"]').each(function() {

                            $(this).on('click', function () {
                                var errorID = $(this).parents('.invalid').removeClass('invalid').attr('data-error-id');
                                $('#error__' + errorID).remove();
                                if (form.find('div.validation-message').find('li').length == 0) {
                                    form.find('div.validation-message').remove();
                                }
                            });
                        });
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };
            }
        }

        // check required text fields
        var parentNames = [];

        var ids = $.unique(form.find('.fieldset').removeClass('invalid').find('input[type="text"].required:visible, input[type="number"].required:visible').map(function() {
            return this.name.replace('helper--', '');
        }).get());
        console.log(ids);
        if (ids.length > 0) {
            var idsValid = $.unique(form.find('input[type="text"].required:visible, input[type="number"].required:visible').map(function () {
                // TODO: add validation based on regexp
                if ($(this).val() == '') {
                    parentNames.push($(this).attr('data-parent-fieldset'));
                    return null
                } else {
                    return this.name.replace('helper--', '');
                }

            }).get());
console.log(idsValid);
            if (idsValid.length < ids.length) { // not all required sets of radio buttons have been ticked
                // report the issue. Filter out the valid IDs
                ids = $.grep(ids, function (n) {
                    return (idsValid.indexOf(n) == -1);
                });

                console.log(ids);

                for (var i = 0, il = ids.length; i < il; i++) {
                    console.log('invalidating #fieldset--' + ids[i]);
                    form.find('#fieldset--' + ids[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };
                for (var i = 0, il = parentNames.length; i < il; i++) {
                    console.log('invalidating #fieldset--' + parentNames[i]);
                    form.find('#fieldset--' + parentNames[i]).each(function () {
                        $(this).addClass('invalid');
                        errorMessage += '
' + $(this).attr('data-error-message') + '
';
                    });
                };

            }
            console.log('------');
        }

        if (errorMessage != '') {
            form.find('div.validation-message').remove();
            form.find('input[type="submit"]').before('

' + errorMessage + '

');

            return false
        }

return false;

    });
    */
<|endoftext|>


<commit_before>//= require jquery
//= require jquery.ui.all
//= require jquery_ujs
//= require nyulibraries
//= require bootstrap-modal
//= require bootstrap-popover
//= require jquery-ui-timepicker-addon.js
//= require temporal
//= require_tree ./partials
//= require room_reservation
<commit_msg>Bootstrap uses new format for modal and popover<commit_after>//= require jquery
//= require jquery.ui.all
//= require jquery_ujs
//= require nyulibraries
//= require bootstrap/modal
//= require bootstrap/popover
//= require jquery-ui-timepicker-addon.js
//= require temporal
//= require_tree ./partials
//= require room_reservation
<|endoftext|>


<commit_before>/* eslint-disable max-len */
'use strict';

// MODULES //

var erfcinv = require( '@stdlib/math/base/special/erfcinv' );
var floor = require( '@stdlib/math/base/special/floor' );
var ldexp = require( '@stdlib/math/base/special/ldexp' );
var round = require( '@stdlib/math/base/special/round' );
var acos = require( '@stdlib/math/base/special/acos' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var cos = require( '@stdlib/math/base/special/cos' );
var pow = require( '@stdlib/math/base/special/pow' );
var sin = require( '@stdlib/math/base/special/sin' );
var SQRT2 = require( '@stdlib/math/constants/float64-sqrt-two' );
var PI = require( '@stdlib/math/constants/float64-pi' );
var inverseStudentsTBodySeries = require( './inverse_students_t_body_series.js' );
var inverseStudentsTTailSeries = require( './inverse_students_t_tail_series.js' );
var inverseStudentsTHill = require( './inverse_students_t_hill.js' );

// VARIABLES //

var DF_THRESHOLD = 0x10000000; // 2^28
var ONE_THIRD = 1.0 / 3.0;
var EXP = ( 2.0 * 53.0 ) / 3.0;
var C = 0.85498797333834849467655443627193;

// MAIN //

/**
* Evaluates Student's t quantiles.
*
* @private
* @param {PositiveNumber} df - degrees of freedom
* @param {Probability} u - input probability
* @param {Probability} v - probability equal to `1-u`
*@returns {number} function value
*/
function inverseStudentsT( df, u, v ) {
	var crossover;
	var tolerance;
	var rootAlpha;
	var invert;
	var result;
	var alpha;
	var tmp;
	var p0;
	var p2;
	var p4;
	var p5;
	var p;
	var r;
	var x;
	var a;
	var b;

	result = 0;
	if ( u > v ) {
		// Function is symmetric, so invert it:
		tmp = v;
		v = u;
		u = tmp;
		invert = true;
	} else {
		invert = false;
	}
	if ( floor(df) === df && df < 20 ) {
		// We have integer degrees of freedom, try for the special cases first:
		tolerance = ldexp( 1.0, EXP );

		switch ( floor( df ) ) {
		case 1:
			// `df = 1` is the same as the Cauchy distribution, see Shaw Eq 35:
			if ( u === 0.5 ) {
				result = 0.0;
			} else {
				result = -cos( PI * u ) / sin( PI * u );
			}
			break;
		case 2:
			// `df = 2` has an exact result, see Shaw Eq 36:
			result = ( (2.0*u) - 1.0 ) / sqrt( 2.0 * u * v );
			break;
		case 4:
			// `df = 4` has an exact result, see Shaw Eq 38 & 39:
			alpha = 4.0 * u * v;
			rootAlpha = sqrt( alpha );
			r = 4 * cos( acos( rootAlpha ) / 3.0 ) / rootAlpha;
			x = sqrt( r - 4.0 );
			result = ( u - 0.5 < 0.0 ) ? -x : x;
			break;
		case 6:
			// We get numeric overflow in this area:
			if ( u < 1.0e-150 ) {
				return ( invert ? -1 : 1 ) * inverseStudentsTHill( df, u );
			}
			// Newton-Raphson iteration of a polynomial case, choice of seed value is taken from Shaw's online supplement:
			a = 4.0 * ( u - (u*u) );// 1 - 4 * (u - 0.5f) * (u - 0.5f);
			b = pow( a, ONE_THIRD );
			p = 6.0 * ( 1.0 + ( C * ( (1.0/b) - 1.0 ) ) );
			do {
				p2 = p * p;
				p4 = p2 * p2;
				p5 = p * p4;
				p0 = p;

				// Next term is given by Eq 41:
				p = 2.0 * ( (8.0*a*p5) - (270.0*p2) + 2187 ) /
					( 5.0 * ( (4.0*a*p4) - (216.0*p) - 243.0 ) );
			} while ( abs( (p - p0) / p ) > tolerance );
			// Use Eq 45 to extract the result:
			p = sqrt( p - df );
			result = ( u - 0.5 ) < 0.0 ? -p : p;
			break;
		default:
			if ( df > DF_THRESHOLD ) { // 2^28
				result = erfcinv( 2.0 * u ) * SQRT2;
			} else if ( df < 3 ) {
				// Use a roughly linear scheme to choose between Shaw's tail series and body series:
				crossover = 0.2742 - ( df * 0.0242143 );
				if ( u > crossover ) {
					result = inverseStudentsTBodySeries( df, u );
				} else {
					result = inverseStudentsTTailSeries( df, u );
				}
			} else {
				// Use Hill's method except in the extreme tails where we use Shaw's tail series. The crossover point is roughly exponential in -df:
				crossover = ldexp( 1.0, round( df / -0.654 ) );
				if ( u > crossover ) {
					result = inverseStudentsTHill( df, u );
				} else {
					result = inverseStudentsTTailSeries( df, u );
				}
			}
		}
	} else if ( df > DF_THRESHOLD ) {
		result = -erfcinv( 2.0 * u ) * SQRT2;
	} else if ( df < 3 ) {
		// Use a roughly linear scheme to choose between Shaw's tail series and body series:
		crossover = 0.2742 - ( df * 0.0242143 );
		if ( u > crossover ) {
			result = inverseStudentsTBodySeries( df, u );
		} else {
			result = inverseStudentsTTailSeries( df, u );
		}
	} else {
		// Use Hill's method except in the extreme tails where we use Shaw's tail series. The crossover point is roughly exponential in -df:
		crossover = ldexp( 1.0, round( df / -0.654 ) );
		if ( u > crossover ) {
			result = inverseStudentsTHill( df, u );
		} else {
			result = inverseStudentsTTailSeries( df, u );
		}
	}
	return invert ? -result : result;
} // end FUNCTION inverseStudentsT()

// EXPORTS //

module.exports = inverseStudentsT;
<commit_msg>Add missing empty line<commit_after>/* eslint-disable max-len */
'use strict';

// MODULES //

var erfcinv = require( '@stdlib/math/base/special/erfcinv' );
var floor = require( '@stdlib/math/base/special/floor' );
var ldexp = require( '@stdlib/math/base/special/ldexp' );
var round = require( '@stdlib/math/base/special/round' );
var acos = require( '@stdlib/math/base/special/acos' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var cos = require( '@stdlib/math/base/special/cos' );
var pow = require( '@stdlib/math/base/special/pow' );
var sin = require( '@stdlib/math/base/special/sin' );
var SQRT2 = require( '@stdlib/math/constants/float64-sqrt-two' );
var PI = require( '@stdlib/math/constants/float64-pi' );
var inverseStudentsTBodySeries = require( './inverse_students_t_body_series.js' );
var inverseStudentsTTailSeries = require( './inverse_students_t_tail_series.js' );
var inverseStudentsTHill = require( './inverse_students_t_hill.js' );

// VARIABLES //

var DF_THRESHOLD = 0x10000000; // 2^28
var ONE_THIRD = 1.0 / 3.0;
var EXP = ( 2.0 * 53.0 ) / 3.0;
var C = 0.85498797333834849467655443627193;

// MAIN //

/**
* Evaluates Student's t quantiles.
*
* @private
* @param {PositiveNumber} df - degrees of freedom
* @param {Probability} u - input probability
* @param {Probability} v - probability equal to `1-u`
*@returns {number} function value
*/
function inverseStudentsT( df, u, v ) {
	var crossover;
	var tolerance;
	var rootAlpha;
	var invert;
	var result;
	var alpha;
	var tmp;
	var p0;
	var p2;
	var p4;
	var p5;
	var p;
	var r;
	var x;
	var a;
	var b;

	result = 0;
	if ( u > v ) {
		// Function is symmetric, so invert it:
		tmp = v;
		v = u;
		u = tmp;
		invert = true;
	} else {
		invert = false;
	}
	if ( floor(df) === df && df < 20 ) {
		// We have integer degrees of freedom, try for the special cases first:
		tolerance = ldexp( 1.0, EXP );

		switch ( floor( df ) ) {
		case 1:
			// `df = 1` is the same as the Cauchy distribution, see Shaw Eq 35:
			if ( u === 0.5 ) {
				result = 0.0;
			} else {
				result = -cos( PI * u ) / sin( PI * u );
			}
			break;
		case 2:
			// `df = 2` has an exact result, see Shaw Eq 36:
			result = ( (2.0*u) - 1.0 ) / sqrt( 2.0 * u * v );
			break;
		case 4:
			// `df = 4` has an exact result, see Shaw Eq 38 & 39:
			alpha = 4.0 * u * v;
			rootAlpha = sqrt( alpha );
			r = 4 * cos( acos( rootAlpha ) / 3.0 ) / rootAlpha;
			x = sqrt( r - 4.0 );
			result = ( u - 0.5 < 0.0 ) ? -x : x;
			break;
		case 6:
			// We get numeric overflow in this area:
			if ( u < 1.0e-150 ) {
				return ( invert ? -1 : 1 ) * inverseStudentsTHill( df, u );
			}
			// Newton-Raphson iteration of a polynomial case, choice of seed value is taken from Shaw's online supplement:
			a = 4.0 * ( u - (u*u) );// 1 - 4 * (u - 0.5f) * (u - 0.5f);
			b = pow( a, ONE_THIRD );
			p = 6.0 * ( 1.0 + ( C * ( (1.0/b) - 1.0 ) ) );
			do {
				p2 = p * p;
				p4 = p2 * p2;
				p5 = p * p4;
				p0 = p;

				// Next term is given by Eq 41:
				p = 2.0 * ( (8.0*a*p5) - (270.0*p2) + 2187 ) /
					( 5.0 * ( (4.0*a*p4) - (216.0*p) - 243.0 ) );
			} while ( abs( (p - p0) / p ) > tolerance );

			// Use Eq 45 to extract the result:
			p = sqrt( p - df );
			result = ( u - 0.5 ) < 0.0 ? -p : p;
			break;
		default:
			if ( df > DF_THRESHOLD ) { // 2^28
				result = erfcinv( 2.0 * u ) * SQRT2;
			} else if ( df < 3 ) {
				// Use a roughly linear scheme to choose between Shaw's tail series and body series:
				crossover = 0.2742 - ( df * 0.0242143 );
				if ( u > crossover ) {
					result = inverseStudentsTBodySeries( df, u );
				} else {
					result = inverseStudentsTTailSeries( df, u );
				}
			} else {
				// Use Hill's method except in the extreme tails where we use Shaw's tail series. The crossover point is roughly exponential in -df:
				crossover = ldexp( 1.0, round( df / -0.654 ) );
				if ( u > crossover ) {
					result = inverseStudentsTHill( df, u );
				} else {
					result = inverseStudentsTTailSeries( df, u );
				}
			}
		}
	} else if ( df > DF_THRESHOLD ) {
		result = -erfcinv( 2.0 * u ) * SQRT2;
	} else if ( df < 3 ) {
		// Use a roughly linear scheme to choose between Shaw's tail series and body series:
		crossover = 0.2742 - ( df * 0.0242143 );
		if ( u > crossover ) {
			result = inverseStudentsTBodySeries( df, u );
		} else {
			result = inverseStudentsTTailSeries( df, u );
		}
	} else {
		// Use Hill's method except in the extreme tails where we use Shaw's tail series. The crossover point is roughly exponential in -df:
		crossover = ldexp( 1.0, round( df / -0.654 ) );
		if ( u > crossover ) {
			result = inverseStudentsTHill( df, u );
		} else {
			result = inverseStudentsTTailSeries( df, u );
		}
	}
	return invert ? -result : result;
} // end FUNCTION inverseStudentsT()

// EXPORTS //

module.exports = inverseStudentsT;
<|endoftext|>


<commit_before>//= require jquery
//= require jquery_ujs
//= require jquery.ui.datepicker
//= require jquery.ui.autocomplete
//= require jquery.spin
//= require cocoon
//= require autocomplete-rails
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/2/jquery.dataTables.bootstrap
//= require bootstrap-transition
//= require bootstrap-alert
//= require bootstrap-button
//= require bootstrap-collapse
//= require bootstrap-dropdown
//= require bootstrap-modal
//= require bootstrap-scrollspy
//= require bootstrap-tab
//= require bootstrap-tooltip
//= require bootstrap-popover
//= require variables.js
//= require select2
//= require_tree
//= require_self

function truncate() {
  if ($(".caption_cat").length) {
    $(".caption_cat").dotdotdot({
      height: 150,
      after: ".more_info",
      watch: 'window'
    });
  }

  if ($(".equipment_title").length) {
    $(".equipment_title").dotdotdot({
      height: 27, // must match .equipment_title height
      watch: 'window'
    });
  }

  // TODO: Refactor this so it won't so drastically impact client-side performance.
  // Until it's refactored, it's better off disabled.
  // This code displays a tooltip in the catalog if the equipment model name is truncated.
  //
  // This code was re-enabled on 2014-07-28 and no noticeable
  // performance hit was noted

   $(".equipment_title").each(function(){
     $(this).trigger("isTruncated", function( isTruncated ) {
       if ( isTruncated ) {
         $(this).children(".equipment_title_link").tooltip();
       }
     });
   });
};

// general submit on change class
$(document).on('change', '.autosubmitme', function() {
  // test for cart date fields to toggle cart spinner
  if ( $(this).parents('div:first').is("#cart_dates") ) {
    pause_cart();
  }
  $(this).parents('form:first').submit();
});

$(document).on('railsAutocomplete.select', '#fake_searched_id', function(){
  $(this).parents('form').submit();
});

$(document).ready(function() {

  // For DataTables and Bootstrap
  $('.datatable').dataTable({
    "sDom": "<'row'<'span4'l><'span5'f>r>t<'row'<'span3'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "sScrollX": "100%",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  wideDataTables = $('.datatable-wide').dataTable({
    "sDom": "<'row'<'span5'l><'span7'f>r>t<'row'<'span5'i><'span7'p>>",
    "sPaginationType": "bootstrap",
    "sScrollX": "100%",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  // ### LOG JS ### //

  // Ugly hack to avoid reinitializing #table_log with the correct order
  try {
    if (wideDataTables[0].id == "table_log") {
      wideDataTables.fnSort([[0, "desc"]]);
    }
  } catch (TypeError) {}

  $('.history_table').dataTable({
    "sDom": "<'row'<l><f>r>t<'row'<'span3'i><p>>",
    "bLengthChange": false,
    "sPaginationType": "bootstrap",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  // ### REPORTS JS ### //

  $('.report_table').dataTable({
    "sDom": "<'row'<'span3'l>fr>t<'row'<'span3'i><p>>",
    "sPaginationType": "bootstrap",
    "iDisplayLength" : 25,
    "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
    "aoColumnDefs": [{ "bSortable": false, "aTargets": [ "no_sort" ] }]
  });

  // For fading out flash notices
  $(".alert .close").click( function() {
       $(this).parent().addClass("fade");
  });

  // make the sidebar follow you down the page
  if ($(window).width() > 767) {
    $("#sidebarbottom").sticky({topSpacing: 50, bottomSpacing: 200});
  }

  // truncate catalog descriptions
  truncate();

  $(".btn#modal").tooltip();
  $(".not-qualified-icon").tooltip();
  $(".not-qualified-icon-em").tooltip();

  $('.associated_em_box img').popover({ placement: 'bottom' });
  $("#my_reservations .dropdown-menu a").popover({ placement: 'bottom' });
  $("#my_equipment .dropdown-menu a").popover({ placement: 'bottom' });

  // fix sub nav on scroll
  var $win = $(window)
    , $nav = $('.subnav')
    , navTop = $('.subnav').length && $('.subnav').offset().top - 40
    , isFixed = 0
    , $hiddenName = $('.subnav .hide')

  processScroll()

  // hack sad times - holdover until rewrite for 2.1
  $nav.on('click', function () {
    if (!isFixed) setTimeout(function () {  $win.scrollTop($win.scrollTop() - 47) }, 10)
  })

  $win.on('scroll', processScroll)

  function processScroll() {
    var i, scrollTop = $win.scrollTop()
    if (scrollTop >= navTop && !isFixed) {
      isFixed = 1
      $nav.addClass('subnav-fixed')
      $hiddenName.removeClass('hide')
      if (!$('.subnav li').hasClass('active')) {
        $('.subnav li:eq(1)').addClass('active')
      }
    } else if (scrollTop <= navTop && isFixed) {
      isFixed = 0
      $nav.removeClass('subnav-fixed')
      $hiddenName.addClass('hide')
      $('.subnav li').removeClass('active')
    }
  }

  $('#modal').click(function() {
    $('#userModal div.modal-body').load(new_user, {possible_netid : $('#fake_reserver_id').val() }); // new_user defined in variables.js.erb
  });

  load_datepicker();

  // Select2 - fancy select lists
  $('select#equipment_model_category_id').select2();
  $('select#equipment_model_associated_equipment_model_ids').select2();
  $('select#equipment_model_requirements').select2();
  $('select#equipment_object_equipment_model_id').select2();
  $('select#requirement_equipment_model').select2();
  $('select.dropdown.dropselect').select2();

});

<commit_msg>add confirmation selectively using JS<commit_after>//= require jquery
//= require jquery_ujs
//= require jquery.ui.datepicker
//= require jquery.ui.autocomplete
//= require jquery.spin
//= require cocoon
//= require autocomplete-rails
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/2/jquery.dataTables.bootstrap
//= require bootstrap-transition
//= require bootstrap-alert
//= require bootstrap-button
//= require bootstrap-collapse
//= require bootstrap-dropdown
//= require bootstrap-modal
//= require bootstrap-scrollspy
//= require bootstrap-tab
//= require bootstrap-tooltip
//= require bootstrap-popover
//= require variables.js
//= require select2
//= require_tree
//= require_self

function truncate() {
  if ($(".caption_cat").length) {
    $(".caption_cat").dotdotdot({
      height: 150,
      after: ".more_info",
      watch: 'window'
    });
  }

  if ($(".equipment_title").length) {
    $(".equipment_title").dotdotdot({
      height: 27, // must match .equipment_title height
      watch: 'window'
    });
  }

  // TODO: Refactor this so it won't so drastically impact client-side performance.
  // Until it's refactored, it's better off disabled.
  // This code displays a tooltip in the catalog if the equipment model name is truncated.
  //
  // This code was re-enabled on 2014-07-28 and no noticeable
  // performance hit was noted

   $(".equipment_title").each(function(){
     $(this).trigger("isTruncated", function( isTruncated ) {
       if ( isTruncated ) {
         $(this).children(".equipment_title_link").tooltip();
       }
     });
   });
};

// general submit on change class
$(document).on('change', '.autosubmitme', function() {
  // test for cart date fields to toggle cart spinner
  if ( $(this).parents('div:first').is("#cart_dates") ) {
    pause_cart();
  }
  $(this).parents('form:first').submit();
});

$(document).on('railsAutocomplete.select', '#fake_searched_id', function(){
  $(this).parents('form').submit();
});

$(document).ready(function() {

  // For DataTables and Bootstrap
  $('.datatable').dataTable({
    "sDom": "<'row'<'span4'l><'span5'f>r>t<'row'<'span3'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "sScrollX": "100%",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  wideDataTables = $('.datatable-wide').dataTable({
    "sDom": "<'row'<'span5'l><'span7'f>r>t<'row'<'span5'i><'span7'p>>",
    "sPaginationType": "bootstrap",
    "sScrollX": "100%",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  // ### LOG JS ### //

  // Ugly hack to avoid reinitializing #table_log with the correct order
  try {
    if (wideDataTables[0].id == "table_log") {
      wideDataTables.fnSort([[0, "desc"]]);
    }
  } catch (TypeError) {}

  $('.history_table').dataTable({
    "sDom": "<'row'<l><f>r>t<'row'<'span3'i><p>>",
    "bLengthChange": false,
    "sPaginationType": "bootstrap",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  // ### REPORTS JS ### //

  $('.report_table').dataTable({
    "sDom": "<'row'<'span3'l>fr>t<'row'<'span3'i><p>>",
    "sPaginationType": "bootstrap",
    "iDisplayLength" : 25,
    "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
    "aoColumnDefs": [{ "bSortable": false, "aTargets": [ "no_sort" ] }]
  });

  // For fading out flash notices
  $(".alert .close").click( function() {
       $(this).parent().addClass("fade");
  });

  // make the sidebar follow you down the page
  if ($(window).width() > 767) {
    $("#sidebarbottom").sticky({topSpacing: 50, bottomSpacing: 200});
  }

  // truncate catalog descriptions
  truncate();

  $(".btn#modal").tooltip();
  $(".not-qualified-icon").tooltip();
  $(".not-qualified-icon-em").tooltip();

  $('.associated_em_box img').popover({ placement: 'bottom' });
  $("#my_reservations .dropdown-menu a").popover({ placement: 'bottom' });
  $("#my_equipment .dropdown-menu a").popover({ placement: 'bottom' });

  // fix sub nav on scroll
  var $win = $(window)
    , $nav = $('.subnav')
    , navTop = $('.subnav').length && $('.subnav').offset().top - 40
    , isFixed = 0
    , $hiddenName = $('.subnav .hide')

  processScroll()

  // hack sad times - holdover until rewrite for 2.1
  $nav.on('click', function () {
    if (!isFixed) setTimeout(function () {  $win.scrollTop($win.scrollTop() - 47) }, 10)
  })

  $win.on('scroll', processScroll)

  function processScroll() {
    var i, scrollTop = $win.scrollTop()
    if (scrollTop >= navTop && !isFixed) {
      isFixed = 1
      $nav.addClass('subnav-fixed')
      $hiddenName.removeClass('hide')
      if (!$('.subnav li').hasClass('active')) {
        $('.subnav li:eq(1)').addClass('active')
      }
    } else if (scrollTop <= navTop && isFixed) {
      isFixed = 0
      $nav.removeClass('subnav-fixed')
      $hiddenName.addClass('hide')
      $('.subnav li').removeClass('active')
    }
  }

  $('#modal').click(function() {
    $('#userModal div.modal-body').load(new_user, {possible_netid : $('#fake_reserver_id').val() }); // new_user defined in variables.js.erb
  });

  load_datepicker();

  // Select2 - fancy select lists
  $('select#equipment_model_category_id').select2();
  $('select#equipment_model_associated_equipment_model_ids').select2();
  $('select#equipment_model_requirements').select2();
  $('select#equipment_object_equipment_model_id').select2();
  $('select#requirement_equipment_model').select2();
  $('select.dropdown.dropselect').select2();

  // Popup confirmation when editing reservation equipment objects
  $('.reservation_eq_objects').on('change', function() {
    newMsg = ($('.select2-choice > .select2-chosen').text() == $('#equipment_object').attr('placeholder'))
      ? ""
      : "Be aware that changing the reservation equipment item may have an effect on another reservation. If you set this reservation's equipment item to an item that has already been checked out, the reservations will be swapped.";
    $('.form-actions').children('input').data('confirm', newMsg);
  });

});

<|endoftext|>


<commit_before>//= require require_config

if (MAS.fonts.loadWithJS && MAS.fonts.url && !MAS.fonts.localstorage) {
  require(['jquery', 'common'], function ($, MAS) {
    'use strict';

    MAS.log('FONTS: load via ajax');
    $.ajax({
      url: MAS.fonts.url,
      success: function (res) {
        MAS.log('FONTS: ajax load success > stylesheet appended to page > load class added');
        $('html').addClass(MAS.fonts.loadClass);
        $('head').append('<style>' + res + '</style>');
        if (MAS.supports.localstorage) {
          MAS.log('FONTS: localstorage supported, fonts saved');
          localStorage.setItem(MAS.fonts.cacheName, res);
        }
      },
      dataType: 'text'
    });
  });
}

require(['jquery', 'collapsable'], function ($, Collapsable) {
  'use strict';

  // Primary Nav
  new Collapsable({
    name: 'primaryNav',
    closeOffFocus: true,
    accordion: true,
    triggerEl: '#primary-nav > li > a',
    targetEl: '.primary-nav__dropdown',
    parentWrapper: '#primary-nav'
  });

  // Mobile Nav
  new Collapsable({
    name: 'mobileNav',
    closeOffFocus: false,
    accordion: true,
    triggerEl: '.mobile-nav a',
    targetType: 'href',
    parentWrapper: '#primary-nav'
  });

  // Article Collapsables
  new Collapsable({
    name: 'articleCollapsables',
    showOnlyFirst: true,
    showIcon: true,
    useButton: true
  });
});

require(['jquery', 'ujs'], function ($) {
  'use strict';

  $(document).ready(function(){
    // Cookie message
    $('.js-cookie-message').bind('ajax:success', function () {
      $('.cookie-message').hide();
      $('.footer-site-links__cookie-link').removeClass('is-on');
    });

    // Responsive Opt Out
    $('.js-close-opt-out').bind('ajax:success', function () {
      $('.opt-out').addClass('is-hidden');
    });
  });
});

require(['jquery', 'scrollTracking'], function ($, scrollTracking) {
  'use strict';

  // Analytics scroll tracking on editorial pages
  scrollTracking({
    el: '.editorial',
    triggerPoints: [0.25, 0.5, 0.75, 1]
  });
});
<commit_msg>wrap scrollTracking in GTM controlled variable<commit_after>//= require require_config

if (MAS.fonts.loadWithJS && MAS.fonts.url && !MAS.fonts.localstorage) {
  require(['jquery', 'common'], function ($, MAS) {
    'use strict';

    MAS.log('FONTS: load via ajax');
    $.ajax({
      url: MAS.fonts.url,
      success: function (res) {
        MAS.log('FONTS: ajax load success > stylesheet appended to page > load class added');
        $('html').addClass(MAS.fonts.loadClass);
        $('head').append('<style>' + res + '</style>');
        if (MAS.supports.localstorage) {
          MAS.log('FONTS: localstorage supported, fonts saved');
          localStorage.setItem(MAS.fonts.cacheName, res);
        }
      },
      dataType: 'text'
    });
  });
}

require(['jquery', 'collapsable'], function ($, Collapsable) {
  'use strict';

  // Primary Nav
  new Collapsable({
    name: 'primaryNav',
    closeOffFocus: true,
    accordion: true,
    triggerEl: '#primary-nav > li > a',
    targetEl: '.primary-nav__dropdown',
    parentWrapper: '#primary-nav'
  });

  // Mobile Nav
  new Collapsable({
    name: 'mobileNav',
    closeOffFocus: false,
    accordion: true,
    triggerEl: '.mobile-nav a',
    targetType: 'href',
    parentWrapper: '#primary-nav'
  });

  // Article Collapsables
  new Collapsable({
    name: 'articleCollapsables',
    showOnlyFirst: true,
    showIcon: true,
    useButton: true
  });
});

require(['jquery', 'ujs'], function ($) {
  'use strict';

  $(document).ready(function(){
    // Cookie message
    $('.js-cookie-message').bind('ajax:success', function () {
      $('.cookie-message').hide();
      $('.footer-site-links__cookie-link').removeClass('is-on');
    });

    // Responsive Opt Out
    $('.js-close-opt-out').bind('ajax:success', function () {
      $('.opt-out').addClass('is-hidden');
    });
  });
});

if(window.enableScrollTracking){
  require(['jquery', 'scrollTracking'], function ($, scrollTracking) {
    'use strict';

    // Analytics scroll tracking on editorial pages
    scrollTracking({
      el: '.editorial',
      triggerPoints: [0.25, 0.5, 0.75, 1]
    });
  });
}
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery3
//= require jquery_ujs

//= require popper
//= require bootstrap-sprockets
//= require cocoon

//= require autosize
//= require choices
//= require multirange

//= require_tree .

//= require components/form
//= require components/editor

$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});

$(function() {
    if($('[data-choices]').length > 0) {
        new Choices('[data-choices]', {shouldSort: false});
    }
});

$(function() {
  autosize($('textarea[data-autosize]'));
})

$(function() {
    $('.range').each(function() {
        var $elm = $(this);

        $elm.range({
            valueFormatter: function(value) {
                return value + ' ' + $elm.data('unit')
            }
        });
    });

    $('.trigger-conditions').on('cocoon:before-insert', function(e, item) {
        var $item = $(item);

        $item.find('.range').range();
    });

    $(document).on('change', 'select.choose_sensor', function(e) {
        var $select = $(e.target);
        var $fields = $select.parents('.nested-fields');

        var options = $select.find('option:selected').data();

        $fields.find('.range').data('range').reinit({
            min: options.rangeMin,
            max: options.rangeMax,
            step: options.rangeStep,
            valueFormatter: function(value) {
                return value + ' ' + options.rangeUnit;
            }
        });

    });
});

$(function() {
    $('.text-editor').editor();

    $('.qa').on('cocoon:after-insert', function(e, item) {
        $(item).find('.text-editor').editor();
    });
});
<commit_msg>close #624<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery3
//= require jquery_ujs

//= require popper
//= require bootstrap-sprockets
//= require cocoon

//= require autosize
//= require choices
//= require multirange

//= require_tree .

//= require components/form
//= require components/editor

$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});

$(function() {
    if($('[data-choices]').length > 0) {
        new Choices('[data-choices]', {shouldSort: false});
    }
});

$(function() {
  autosize($('textarea[data-autosize]'));
})

$(function() {
    $('.range').each(function() {
        var $elm = $(this);

        $elm.range({
            valueFormatter: function(value) {
                return value + ' ' + $elm.data('unit')
            }
        });
    });

    $('.trigger-conditions').on('cocoon:before-insert', function(e, item) {
        var $item = $(item);

        $item.find('.range').range();
    });

    $(document).on('change', 'select.choose_sensor', function(e) {
        var $select = $(e.target);
        var $fields = $select.parents('.nested-fields');

        var options = $select.find('option:selected').data();

        $fields.find('.range').data('range').reinit({
            min: options.rangeMin,
            max: options.rangeMax,
            step: options.rangeStep,
            valueFormatter: function(value) {
                return value + ' ' + options.rangeUnit;
            }
        });

    });
});

$(function() {
    $('.text-editor').editor();

    $('.links').on('cocoon:after-insert', function(e, item) {
        $(item).find('.text-editor').editor();
        autosize($('textarea[data-autosize]'));
    });
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require decidim<commit_msg>Remove unneeded ujs<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require_tree .
//= require decidim
<|endoftext|>


<commit_before>// In-place editing via x-editable-rails
$(function() {
  return $("[data-xeditable=true]").each(function() {
    return $(this).editable({
      ajaxOptions: {
        type: "PUT",
        dataType: "json"
      },
      params: function(params) {
        var railsParams = {};
        railsParams[$(this).data("model")] = {};
        railsParams[$(this).data("model")][params.name] = params.user_count;
        return railsParams;
      },
      success: function(response) {
        var cellName = $(this).closest("td").attr("id");
        var rowID = $(this).closest("tr").attr("id");
        return $(this).trigger('onAfterUpdate', [rowID, cellName, response]);
      }
    });
  });
})

var showDepartmentStats = function(locale) {
  $.ajax({
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    url: '/' + locale.to_s + '/departments/',
    dataType: 'json',
    success: function(data) { drawDepartmentBar(data); },
    failure: function(result) {
      console.log("Something went wrong in function showDepartmentStatus!");
    }
  });
};

//var datademo = [{dept_name:"department_1953", user_count: 55},{dept_name:"department_1954", user_count: 57},{dept_name:"department_1955", user_count: 143},{dept_name:"department_1956", user_count: 77},{dept_name:"department_1957", user_count: 57},{dept_name:"department_1958", user_count: 37},{dept_name:"department_1959", user_count: 83},{dept_name:"department_1960", user_count: 55},{dept_name:"department_1961", user_count: 57},{dept_name:"department_1962", user_count: 60},{dept_name:"department_1963", user_count: 50},{dept_name:"department_1964", user_count: 57},{dept_name:"department_1965", user_count: 7},{dept_name:"department_1966", user_count: 91},{dept_name:"department_1967", user_count: 55},{dept_name:"department_1968", user_count: 57},{dept_name:"department_1969", user_count: 43},{dept_name:"department_1970", user_count: 77},{dept_name:"department_1971", user_count: 57},{dept_name:"department_1972", user_count: 57},{dept_name:"department_1973", user_count: 93},{dept_name:"department_1974", user_count: 55},{dept_name:"department_1975", user_count: 57},{dept_name:"department_1976", user_count: 60},{dept_name:"department_1977", user_count: 50},{dept_name:"department_1978", user_count: 57},{dept_name:"department_1979", user_count: 7},{dept_name:"department_1980", user_count: 91},{dept_name:"department_1981", user_count: 19},{dept_name:"department_1982", user_count: 37},{dept_name:"department_1983", user_count: 47},{dept_name:"department_1984", user_count: 237},{dept_name:"department_1985", user_count: 67},{dept_name:"department_1986", user_count: 64},{dept_name:"department_1987", user_count: 182},{dept_name:"department_1988", user_count: 7},{dept_name:"department_1989", user_count: 67},{dept_name:"department_1990", user_count: 55},{dept_name:"department_1991", user_count: 57}];

//var margin = {top: 40, right: 30, bottom: 180, left: 50};

var drawDepartmentBar = function(dataset){

  var chartDiv = document.getElementById("lan-chart-div");
  var margin = {top: 40, right: 30, bottom: 180, left: 50};
  var svg = d3.select("#lan-chart")
              .attr("width", chartDiv.clientWidth);
  var width = +svg.attr("width") - margin.left - margin.right;
  var height = +svg.attr("height") - margin.top - margin.bottom;

  var x;
  var xAxis;
  var y = d3.scaleLinear().range([height + margin.top, margin.top]);
  y.domain([0, d3.max(dataset, function(d) { return d.user_count; })]);

  var yAxis = d3.axisLeft(y).tickFormat(formatPercent);

  var formatPercent = d3.format("d");

  function update(dataset) {
    x = d3.scaleBand()
          .range([margin.left, width + margin.left])
          .padding(0.1);

    svg.append("g")
       .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    xAxis = d3.axisBottom(x).tickSizeOuter(0);
    x.domain(dataset.map(function(d) { return d.dept_name; }));

    var h = margin.top + height;

    svg.append("g")
       .attr("class", "x axis")
       .attr("transform", "translate(0," + h + ")")
       .call(xAxis)
       // .selectAll("text")
       // .data(dataset)

  var text = svg.call(xAxis).selectAll("text")
                .data(dataset)

       text.exit().remove();

       text.enter().append("text")
       .attr("class", "text")
       .merge(text)
       .attr("y", 0)
       .attr("x", 9)
       .attr("dy", ".35em")
       .attr("transform", "rotate(75)")
       .style("text-anchor", "start");

    svg.append("g")
       .attr("class","y axis")
       .attr("transform", "translate(" + margin.left + ",0)")
       .call(yAxis);

    /* I. Bars */

    // 1. Joins data
    var bars = svg.selectAll(".bar").data(dataset);

    // 2. Exits and removes to get rid of any redundant DOM elements
    bars.exit().remove();

    // 3. Enters & appends a group — making sure you assign the same class
    // 4. Appends the DOM elements you need to the group
    // 5. Merges groups
    bars.enter().append("rect")
        .merge(bars)
        .attr("class", "bar")
        .style("display", function(d) { return d.user_count === null ? "none" : null; })
        .style("fill",  "#861930")
        .attr("x",  function(d) { return x(d.dept_name); })
        .attr("width", x.bandwidth())
        // .attr("y",  d => { return height; })
        // .attr("height", 0)
        .transition().duration(750)
        .delay(function(d, i) { return i * 50; })
        .attr("y",  function(d) { return y(d.user_count); })
        .attr("height",  function(d) { return height + margin.top - y(d.user_count); });

    /* II. Labels */

    // 1. Joins data
    var labels = svg.selectAll(".label").data(dataset);

    // 2. Exits and removes to get rid of any redundant DOM elements
    labels.exit().remove();

    // 3. Enters & appends a group — making sure you assign the same class
    // 4. Appends the DOM elements you need to the group
    // 5. Merges groups
    // labels is the.user_count of rect bars
    labels.enter().append("text")
          .merge(labels)
          .attr("class", "label")
          .style("display",  function(d) { return d.user_count === null ? "none" : null; })
          .attr("x", ( function(d) { return x(d.dept_name) + (x.bandwidth() / 2) -8 ; }))
          .style("fill",  "#898989")
          .attr("y",  function(d) { return height; })
          .attr("height", 0)
          .transition().duration(750)
          .delay(function(d, i) { return i * 50; })
          .text( function(d) { return formatPercent(d.user_count); })
          .attr("y",  function(d) { return y(d.user_count) + .1; })
          .attr("dy", "-.8em");
  }

  update(dataset);

  window.addEventListener("resize", updateClientWidth);

  function updateClientWidth() {
    svg = d3.select("#lan-chart")
            .attr("width", chartDiv.clientWidth);
    width = +svg.attr("width") - margin.left - margin.right;

    update(dataset);

    div_legend = d3.select("#lan-bar-chart-legend")
                   .attr("width", window.innerWidth);
  }
}
<commit_msg>Reset font-size<commit_after>// In-place editing via x-editable-rails
$(function() {
  return $("[data-xeditable=true]").each(function() {
    return $(this).editable({
      ajaxOptions: {
        type: "PUT",
        dataType: "json"
      },
      params: function(params) {
        var railsParams = {};
        railsParams[$(this).data("model")] = {};
        railsParams[$(this).data("model")][params.name] = params.user_count;
        return railsParams;
      },
      success: function(response) {
        var cellName = $(this).closest("td").attr("id");
        var rowID = $(this).closest("tr").attr("id");
        return $(this).trigger('onAfterUpdate', [rowID, cellName, response]);
      }
    });
  });
})

var showDepartmentStats = function(locale) {
  $.ajax({
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    url: '/' + locale.to_s + '/departments/',
    dataType: 'json',
    success: function(data) { drawDepartmentBar(data); },
    failure: function(result) {
      console.log("Something went wrong in function showDepartmentStatus!");
    }
  });
};

//var datademo = [{dept_name:"department_1953", user_count: 55},{dept_name:"department_1954", user_count: 57},{dept_name:"department_1955", user_count: 143},{dept_name:"department_1956", user_count: 77},{dept_name:"department_1957", user_count: 57},{dept_name:"department_1958", user_count: 37},{dept_name:"department_1959", user_count: 83},{dept_name:"department_1960", user_count: 55},{dept_name:"department_1961", user_count: 57},{dept_name:"department_1962", user_count: 60},{dept_name:"department_1963", user_count: 50},{dept_name:"department_1964", user_count: 57},{dept_name:"department_1965", user_count: 7},{dept_name:"department_1966", user_count: 91},{dept_name:"department_1967", user_count: 55},{dept_name:"department_1968", user_count: 57},{dept_name:"department_1969", user_count: 43},{dept_name:"department_1970", user_count: 77},{dept_name:"department_1971", user_count: 57},{dept_name:"department_1972", user_count: 57},{dept_name:"department_1973", user_count: 93},{dept_name:"department_1974", user_count: 55},{dept_name:"department_1975", user_count: 57},{dept_name:"department_1976", user_count: 60},{dept_name:"department_1977", user_count: 50},{dept_name:"department_1978", user_count: 57},{dept_name:"department_1979", user_count: 7},{dept_name:"department_1980", user_count: 91},{dept_name:"department_1981", user_count: 19},{dept_name:"department_1982", user_count: 37},{dept_name:"department_1983", user_count: 47},{dept_name:"department_1984", user_count: 237},{dept_name:"department_1985", user_count: 67},{dept_name:"department_1986", user_count: 64},{dept_name:"department_1987", user_count: 182},{dept_name:"department_1988", user_count: 7},{dept_name:"department_1989", user_count: 67},{dept_name:"department_1990", user_count: 55},{dept_name:"department_1991", user_count: 57}];

//var margin = {top: 40, right: 30, bottom: 180, left: 50};

var drawDepartmentBar = function(dataset){

  var chartDiv = document.getElementById("lan-chart-div");
  var margin = {top: 40, right: 30, bottom: 180, left: 50};
  var svg = d3.select("#lan-chart")
              .attr("width", chartDiv.clientWidth);
  var width = +svg.attr("width") - margin.left - margin.right;
  var height = +svg.attr("height") - margin.top - margin.bottom;

  var x;
  var xAxis;
  var y = d3.scaleLinear().range([height + margin.top, margin.top]);
  y.domain([0, d3.max(dataset, function(d) { return d.user_count; })]);

  var yAxis = d3.axisLeft(y).tickFormat(formatPercent);

  var formatPercent = d3.format("d");

  function update(dataset) {
    x = d3.scaleBand()
          .range([margin.left, width + margin.left])
          .padding(0.1);

    svg.append("g")
       .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    xAxis = d3.axisBottom(x).tickSizeOuter(0);
    x.domain(dataset.map(function(d) { return d.dept_name; }));

    var h = margin.top + height;

    svg.append("g")
       .attr("class", "x axis")
       .attr("transform", "translate(0," + h + ")")
       .call(xAxis)
       // .selectAll("text")
       // .data(dataset)

  var text = svg.call(xAxis).selectAll("text")
                .data(dataset)

       text.exit().remove();

       text.enter().append("text")
       .attr("class", "text")
       .merge(text)
       .attr("y", 0)
       .attr("x", 9)
       .attr("dy", ".35em")
       .attr("transform", "rotate(75)")
       .style("text-anchor", "start");

    svg.append("g")
       .attr("class","y axis")
       .attr("transform", "translate(" + margin.left + ",0)")
       .call(yAxis);

    /* I. Bars */

    // 1. Joins data
    var bars = svg.selectAll(".bar").data(dataset);

    // 2. Exits and removes to get rid of any redundant DOM elements
    bars.exit().remove();

    // 3. Enters & appends a group — making sure you assign the same class
    // 4. Appends the DOM elements you need to the group
    // 5. Merges groups
    bars.enter().append("rect")
        .merge(bars)
        .attr("class", "bar")
        .style("display", function(d) { return d.user_count === null ? "none" : null; })
        .style("fill",  "#861930")
        .attr("x",  function(d) { return x(d.dept_name); })
        .attr("width", x.bandwidth())
        // .attr("y",  d => { return height; })
        // .attr("height", 0)
        .transition().duration(750)
        .delay(function(d, i) { return i * 50; })
        .attr("y",  function(d) { return y(d.user_count); })
        .attr("height",  function(d) { return height + margin.top - y(d.user_count); });

    /* II. Labels */

    // 1. Joins data
    var labels = svg.selectAll(".label").data(dataset);

    // 2. Exits and removes to get rid of any redundant DOM elements
    labels.exit().remove();

    // 3. Enters & appends a group — making sure you assign the same class
    // 4. Appends the DOM elements you need to the group
    // 5. Merges groups
    // labels is the.user_count of rect bars
    labels.enter().append("text")
          .merge(labels)
          .attr("class", "label")
          .style("display",  function(d) { return d.user_count === null ? "none" : null; })
          .attr("x", ( function(d) { return x(d.dept_name) + (x.bandwidth() / 2) -8 ; }))
          .style("fill",  "#898989")
          .style("font-size", "12px")
          .attr("y",  function(d) { return height; })
          .attr("height", 0)
          .transition().duration(750)
          .delay(function(d, i) { return i * 50; })
          .text( function(d) { return formatPercent(d.user_count); })
          .attr("y",  function(d) { return y(d.user_count) + .1; })
          .attr("dy", "-.8em");
  }

  update(dataset);

  window.addEventListener("resize", updateClientWidth);

  function updateClientWidth() {
    svg = d3.select("#lan-chart")
            .attr("width", chartDiv.clientWidth);
    width = +svg.attr("width") - margin.left - margin.right;

    update(dataset);

    div_legend = d3.select("#lan-bar-chart-legend")
                   .attr("width", window.innerWidth);
  }
}
<|endoftext|>


<commit_before>import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createUploadLink } from 'apollo-upload-client';
import csrf from '~/lib/utils/csrf';

export default (resolvers = {}) =>
  new ApolloClient({
    link: createUploadLink({
      uri: `${gon.relative_url_root}/api/graphql`,
      headers: {
        [csrf.headerKey]: csrf.token,
      },
    }),
    cache: new InMemoryCache(),
    resolvers,
  });
<commit_msg>Add support for baseUrl in ApolloClient instance<commit_after>import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createUploadLink } from 'apollo-upload-client';
import csrf from '~/lib/utils/csrf';

export default (resolvers = {}, baseUrl = '') => {
  let uri = `${gon.relative_url_root}/api/graphql`;

  if (baseUrl) {
    // Prepend baseUrl and ensure that `///` are replaced with `/`
    uri = `${baseUrl}${uri}`.replace(/\/{3,}/g, '/');
  }

  return new ApolloClient({
    link: createUploadLink({
      uri,
      headers: {
        [csrf.headerKey]: csrf.token,
      },
    }),
    cache: new InMemoryCache(),
    resolvers,
  });
};
<|endoftext|>


<commit_before>ManageIQ.toolbars = {};

ManageIQ.toolbars.findByDataClick = function (toolbar, data_click) {
  $(toolbar).find("[data-click='" + attr_click + "']")
};

ManageIQ.toolbars.enableItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).removeClass('disabled');
};

ManageIQ.toolbars.disableItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).addClass('disabled');
};

ManageIQ.toolbars.setItemTooltip = function (toolbar, attr_click, tooltip) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).attr('title', tooltip);
};

ManageIQ.toolbars.showItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).show();
};

ManageIQ.toolbars.hideItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).hide();
};

ManageIQ.toolbars.markItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).addClass('active');
};

ManageIQ.toolbars.unmarkItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).removeClass('active');
};
<commit_msg>Toolbars - fix findByDataClick<commit_after>ManageIQ.toolbars = {};

ManageIQ.toolbars.findByDataClick = function (toolbar, attr_click) {
  return $(toolbar).find("[data-click='" + attr_click + "']");
};

ManageIQ.toolbars.enableItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).removeClass('disabled');
};

ManageIQ.toolbars.disableItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).addClass('disabled');
};

ManageIQ.toolbars.setItemTooltip = function (toolbar, attr_click, tooltip) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).attr('title', tooltip);
};

ManageIQ.toolbars.showItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).show();
};

ManageIQ.toolbars.hideItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).hide();
};

ManageIQ.toolbars.markItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).addClass('active');
};

ManageIQ.toolbars.unmarkItem = function (toolbar, attr_click) {
  ManageIQ.toolbars.findByDataClick(toolbar, attr_click).removeClass('active');
};
<|endoftext|>


<commit_before>$(function ()
{

	//populates the game types dropdowns
	$.getJSON( "game_types", function(json)
	{
		var values = [];

	  	json.forEach(function (item)
	  	{
	  		values.push('<option value="' + item.id + '">' + item.name + '</option>');
	  	});

	  	var html = values.join("");

	  	$("#game_type").html(html);
	  	$("#game_type_leader").html(html);

	  	console.log( "game_type load success" );
	})

	.fail( function ()
	{
		console.log( "game_types failed to load" );
	});

	// populates the players dropdowns
	$.getJSON( "players", function(json)
	{
		var values = [];

	  	json.forEach(function (item)
	  	{
	  		values.push('<option value="' + item.id + '">' + item.first_name + ' \"' + item.nickname + '\" ' + item.last_name + '</option>');
	  	});

	  	var html = values.join("");

	  	$("#player1").html(html);
	  	$("#player2").html(html);

	  	console.log( "players load success" );
	})

	.fail( function ()
	{
		console.log( "players failed to load" );
	});

	// populates the ranking table
	// $.getJSON( "players", function(json)
	// {
	// 	var values = [];

	//   	json.forEach(function (item)
	//   	{
	//   		values.push('<option value="' + item.id + '">' + item.first_name + ' \"' + item.nickname + '\" ' + item.last_name + '</option>');
	//   	});

	//   	var html = values.join("");

	//   	$("#player1").html(html);
	//   	$("#player2").html(html);

	//   	console.log( "players load success" );
	// })

	// .fail( function ()
	// {
	// 	console.log( "players failed to load" );
	// });

	//create a new game in the DB
	$("#new_game_form").submit( function(event)
	{
		event.preventDefault();

		var game_form = $(this);

		var a = [];
		var type = $("#game_type").value();

		var p1 = new Object();
		p1.score = $("#part1_score").value();
		p1.players = [$("#player1").value()]; //TODO: will eventually need to change to add multiple
		a.push(p1);

		var p2 = new Object();
		p2.score = $("#part2_score").value();
		p2.players = [$("#player2").value()]; //TODO: will eventually need to change to add multiple players
		a.push(p2);

		var pars = JSON.stringify(a);

		$.post(game_form.attr("action"), {game_type: type, participants: pars}, function ()
		{
			//TODO: update rankings based on new game

			console.log( "game created" );
		})

		.fail( function ()
		{
			console.log( "game not created" );
		});

	});

	//create a new player in the DB
	$("#new_player_form").submit( function(event)
	{
		event.preventDefault();

		var player_form = $(this);

		$.post(player_form.attr("action"), {first_name: $("#first_name").val(), nickname: $("#nickname").val(), last_name: $("#last_name").val()}, function (json)
		{
			// $("#player1").children().show();

			// $('<option value="' + item.id + '">' + item.first_name + ' \"' + item.nickname + '\" ' + item.last_name + '</option>')

			console.log( "player created" );
		})

		.fail( function ()
		{
			console.log( "player not created" );
		});
	});

	// remove selected player from other drop down list
	$("#player1").on("select", function() {
		var player1 = $(this).val();
		// get the second player list

	});

	// function to hide player from other drop down
	function hidePlayer(id1, id2) {
		// unhide all names

		$(id1).on("select", function() {
			// get the value of the selected player
			var player1 = $(this).val();
			// get the players from the other list
			var players2 = [];
			var values = [];
			$(id2).each(function() {
			    players2.push( $(this).attr('value') );
			});
			// remove the player from the other list
			for (String player : players2)
			{
				if (player1 == player2)
				{
					$("#" + id2 + " option[value='" + player1 + "'']").remove();
				}
			}
		});
	};
});<commit_msg>remove selected player from other drop down<commit_after>$(function ()
{

	//populates the game types dropdowns
	$.getJSON( "game_types", function(json)
	{
		var values = [];

	  	json.forEach(function (item)
	  	{
	  		values.push('<option value="' + item.id + '">' + item.name + '</option>');
	  	});

	  	var html = values.join("");

	  	$("#game_type").html(html);
	  	$("#game_type_leader").html(html);

	  	console.log( "game_type load success" );
	})

	.fail( function ()
	{
		console.log( "game_types failed to load" );
	});

	// populates the players dropdowns
	$.getJSON( "players", function(json)
	{
		var values = [];

	  	json.forEach(function (item)
	  	{
	  		values.push('<option value="' + item.id + '">' + item.first_name + ' \"' + item.nickname + '\" ' + item.last_name + '</option>');
	  	});

	  	var html = values.join("");

	  	$("#player1").html(html);
	  	$("#player2").html(html);

	  	console.log( "players load success" );
	})

	.fail( function ()
	{
		console.log( "players failed to load" );
	});

	// populates the ranking table
	// $.getJSON( "players", function(json)
	// {
	// 	var values = [];

	//   	json.forEach(function (item)
	//   	{
	//   		values.push('<option value="' + item.id + '">' + item.first_name + ' \"' + item.nickname + '\" ' + item.last_name + '</option>');
	//   	});

	//   	var html = values.join("");

	//   	$("#player1").html(html);
	//   	$("#player2").html(html);

	//   	console.log( "players load success" );
	// })

	// .fail( function ()
	// {
	// 	console.log( "players failed to load" );
	// });

	//create a new game in the DB
	$("#new_game_form").submit( function(event)
	{
		event.preventDefault();

		var game_form = $(this);

		var a = [];
		var type = $("#game_type").val();

		var p1 = new Object();
		p1.score = $("#part1_score").val();
		p1.players = [$("#player1").val()]; //TODO: will eventually need to change to add multiple
		a.push(p1);

		var p2 = new Object();
		p2.score = $("#part2_score").val();
		p2.players = [$("#player2").val()]; //TODO: will eventually need to change to add multiple players
		a.push(p2);

		var pars = JSON.stringify(a);

		$.post(game_form.attr("action"), {game_type: type, participants: pars}, function ()
		{
			//TODO: update rankings based on new game

			console.log( "game created" );
		})

		.fail( function ()
		{
			console.log( "game not created" );
		});

	});

	//create a new player in the DB
	$("#new_player_form").submit( function(event)
	{
		event.preventDefault();

		var player_form = $(this);

		$.post(player_form.attr("action"), {first_name: $("#first_name").val(), nickname: $("#nickname").val(), last_name: $("#last_name").val()}, function (json)
		{
			// $("#player1").children().show();

			// $('<option value="' + item.id + '">' + item.first_name + ' \"' + item.nickname + '\" ' + item.last_name + '</option>')

			console.log( "player created" );
		})

		.fail( function ()
		{
			console.log( "player not created" );
		});
	});

	// remove selected player from other drop down list
	$("#player1").on("change", function() {
		hidePlayer("#player1", "#player2");
	});

	$("#player2").on("change", function() {
		hidePlayer("#player2", "#player1");
	});

	// function to hide player from other drop down
	function hidePlayer(id1, id2) {
		// unhide all names

		// get the value of the selected player
		var player1 = $(id1).val();
		// get the players from the other list
		var players2 = [];
		$(id2).children().each(function() {
		    players2.push( $(this).attr('value') );
		});
		// remove the player from the other list
		for (var i = 0; i < players2.length; i++)
		{
			if (player1 == players2[i])
			{
				$(id2 + " option[value='" + player1 + "']").remove();
			}
		}
	}
});<|endoftext|>