(function() {
    'use strict';

    function ScholarshipCheckboxFieldset(form, checkbox_field_container, checkbox_field_name, sub_fields, label_text, label_insert_offset) {
        var self = this;

        checkbox_field_container.parents('.form-row').find('td').each(function() {
            if($.trim($(this).find('label').text()) == checkbox_field_name) {
                self.$checkbox = $(this).find('input');
            }
        });
        
        this.sub_fields = [];

        // Populate the list of sub fields
        _.each(sub_fields, function(field_name) {
            self.sub_fields.push(form.fields[field_name].parents('.form-row').eq(0));
        });

        // Insert the optional label
        if(label_text) {
            var $label_el = $('<div class="form-row form-label-row">' + label_text + '</div>');
            self.$checkbox.parent().append($label_el);

            // Optionally insert the label at a given position within the sub-fields.
            if(typeof(label_insert_offset) == 'undefined') {
                label_insert_offset = 0;
            }
            
            this.sub_fields.splice(label_insert_offset, 0, $label_el);
        }

        // Actually add the sub-fields (including label) to the dom
        _.each(this.sub_fields, function(field) {
            self.$checkbox.parent().append(field);
        });
        
        this.updateSubFieldsFromCurrentState();

        checkbox_field_container.change(function() {
            self.updateSubFieldsFromCurrentState();
        });
    }

    ScholarshipCheckboxFieldset.prototype.updateSubFieldsFromCurrentState = function() {
        if(this.$checkbox.is(':checked')) {
            _.each(this.sub_fields, function(sub_field) {
                sub_field.show();
            });
        } else {
            _.each(this.sub_fields, function(sub_field) {
                sub_field.hide();
            });
        }
    }
    
    function ScholarshipForm($el) {
        this.$container = $el;

        this.fields = {};

        var self = this;

        // Populate dictionary of form fields
        this.$container.find('.form-row').each(function() {
            var field_name = $.trim($(this).children('label').text().replace('*',''));
            if(field_name) {
                self.fields[field_name] = $(this).find('input,textarea,select');
            }
        });

        // Toggle between Online and Ground fields
        this.fields['Campus'].change(function() {
            self.updateCampusFieldsFromCurrentState();
        });

        // Setup scholarship checkbox sub-fields
        new ScholarshipCheckboxFieldset(this, this.fields['Scholarship'], 'Community Involvement Scholarship', ['Upload essay']);
        new ScholarshipCheckboxFieldset(this, this.fields['Scholarship'], 'Academic Partner Scholarship', ['Academic Partners']);
        new ScholarshipCheckboxFieldset(this, this.fields['Scholarship'], 'Legacy Scholarship', ['Student status', 'Grandparent', 'Parent', 'Sibling'], "Provide the name of your grandparent, parent, or sibling below:", 1);
        
        // Set initial state
        this.updateCampusFieldsFromCurrentState();
    }

    ScholarshipForm.prototype.updateCampusFieldsFromCurrentState = function() {
        var val = this.fields['Campus'].filter(':checked').val();
        
        if(val == 'Ground') {
            this.hideFields('Online');
            this.showFields('Ground');
        } else if(val == 'Online') {
            this.hideFields('Ground');
            this.showFields('Online');
        }        
    }
    
    ScholarshipForm.prototype.getFieldsByLabelKeyword = function(keyword) {
        // Return an array of input elements whose labels match `keyword`
        return _.filter(_.map(this.fields, function($field, field_name) {
            if(field_name.indexOf(keyword) != -1) {
                return $field;
            } else {
                return null;
            }
        }), function(val) {
            return val != null;
        });
    }
    
    ScholarshipForm.prototype.hideFields = function(keyword) {
        _.each(this.getFieldsByLabelKeyword(keyword), function($field) {
            $field.parents('.form-row').hide();
        });
    }
    
    ScholarshipForm.prototype.showFields = function(keyword) {
        _.each(this.getFieldsByLabelKeyword(keyword), function($field) {
            $field.parents('.form-row').show();
        });
    }
    
    // Init
    $(function() {
        $('.scholarship-application-form').each(function() {
            new ScholarshipForm($(this));
        });
    });
})();
