define(['jquery', './field_groups/field.js', './field_groups/fields.js', './field_groups/group.js', './field_groups/groups.js', './field_groups/undo.js', './field_groups/undo.js', 'jquery.validate', './utilities.js'],
    function (jQuery, Field, Fields, Group, Groups, Undo) {

    var $ = jQuery;

    /** @namespace */
    var ICFieldGroups = window.ICFieldGroups || {};

    /** @namespace */
    var Instance = window.Instance || {};
    window.Instance = Instance;

    ICFieldGroups.init = function () {
        Instance.Undo = new ICFieldGroups.Undo();
        Instance.Groups = new ICFieldGroups.Groups();
        Instance.Groups.collection.setData(window.groups);
        Instance.Groups.view.render();
        window.onbeforeunload = function () {
            if (Instance.Undo.model.history.length > 0) {
                return lmsg('infocapture.admin.general.unsaved_changes', Instance.Undo.model.history.length);
            }
        };
    };

    ICFieldGroups.Field = Field;
    ICFieldGroups.Fields = Fields;
    ICFieldGroups.Group = Group;
    ICFieldGroups.Groups = Groups;
    ICFieldGroups.Undo = Undo;

    /**
     * Custom validation for group name
     * @returns {bool}
     */
    jQuery.validator.addMethod("unique", function(value, element) {
        var input = $(element);
        var groupModels = [];
        _.each(Instance.Groups.collection.groups, function(group) {
            if(group.model.id !== parseInt(input.data('group-id'), 10)) {
                groupModels.push(group.model);
            }
        });
        var match = _.where(groupModels, {
            name : value
        });
        return match.length > 0 ? false : true;
    });

    jQuery.validator.addMethod("not_placeholder", function(value, element) {
        /* Flipping IE! */
        if($(element).val() === lmsg('infocapture.admin.field_groups.add_group_input')) {
            return false;
        } else {
            return true;
        }
    });

    return ICFieldGroups;
});