<% if models %> (function($) { var original; var settings = {}; var defaults = $.enlightenment.validator.settings; <% if config %> settings = <%= config.html_safe %>; <% end %> $(function() { original = rulemap(<%= models.html_safe %>); $.each(original, function(name, rules) { attach($(['form', name, 'validate'].join('.')), rules.real); }); }); <% if config %> $(document).ajaxComplete(function(e, xhr, options) { var text = xhr.responseText; var conf, json, keys; try { json = JSON.parse(text); keys = settings.keys || []; $.each(keys, function(i, key) { var html = json[key]; var current; if(html) { $('form', html).each(function() { var converted = rulemap(this); $.each(converted, function(type, rules) { attach($(['form', type, 'validate'].join('.')), rules.real); }); }); } }); } catch(e) {} }); <% end %> // ??? $.enlightenment.rules = function rules() { return original; }; // ??? $(document).on('revalidate', 'form', function(e) { rulemap(this); }); // TODO: move to $.enlightenment function attach(forms, config) { if(forms.length) { forms.validate(config); } return forms; } function elements(selector, context) { return context .find('input, select, textarea') .not(':submit, :reset, :image, [disabled]') .filter(selector); } function rulemap(config) { var context; var converted = {}; var resources = config.resources; var nestedWrap = 'div.form-inputs'; // TODO: determine better way to handle nested fields_for function map(ruleSet, context, mapping) { // only map for existing content (avoids infinite loop) if(context.length) { $.each(ruleSet, function(attribute, rules) { var nested, associated; if(rules.associated) { nested = $([nestedWrap, attribute].join('.'), context); associated = resources[rules.associated]; if(associated) { map((associated.rules || associated.base.rules), nested, mapping); } } else { $(elements('.' + attribute, context)).each(function() { var name = this.name; if( ! mapping.rules[name]) { mapping.rules[name] = rules; } }); } }); } } // top-level/ready setup if(resources) { $.each(resources, function(name, config) { var context = $(['form', name, 'validate'].join('.')); var mapping = converted[name] = { base : $.extend(true, {}, config), real : $.extend(true, {}, defaults) }; map(config.rules, context, mapping.real); }); } // contextual additions else { resources = original; context = $(config); $.each(original, function(type, config) { if(context.hasClass(type)) { converted[type] = original[type]; map(config.base.rules, context, config.real); context.removeData('validator'); attach(context, config.real); } }); } return converted; } })(jQuery); <% end %>