You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by ns...@apache.org on 2013/12/14 12:41:27 UTC
[21/51] [partial] Bring Fauxton directories together
http://git-wip-us.apache.org/repos/asf/couchdb/blob/c14b2991/share/www/fauxton/src/assets/js/plugins/backbone.layoutmanager.js
----------------------------------------------------------------------
diff --git a/share/www/fauxton/src/assets/js/plugins/backbone.layoutmanager.js b/share/www/fauxton/src/assets/js/plugins/backbone.layoutmanager.js
new file mode 100644
index 0000000..b8296b4
--- /dev/null
+++ b/share/www/fauxton/src/assets/js/plugins/backbone.layoutmanager.js
@@ -0,0 +1,996 @@
+/*!
+ * backbone.layoutmanager.js v0.9.1
+ * Copyright 2013, Tim Branyen (@tbranyen)
+ * backbone.layoutmanager.js may be freely distributed under the MIT license.
+ */
+(function(window, factory) {
+ "use strict";
+ var Backbone = window.Backbone;
+
+ // AMD. Register as an anonymous module. Wrap in function so we have access
+ // to root via `this`.
+ if (typeof define === "function" && define.amd) {
+ return define(["backbone", "underscore", "jquery"], function() {
+ return factory.apply(window, arguments);
+ });
+ }
+
+ // Browser globals.
+ Backbone.Layout = factory.call(window, Backbone, window._, Backbone.$);
+}(typeof global === "object" ? global : this, function (Backbone, _, $) {
+"use strict";
+
+// Create a reference to the global object. In browsers, it will map to the
+// `window` object; in Node, it will be `global`.
+var window = this;
+
+// Hoisted, referenced at the bottom of the source. This caches a list of all
+// LayoutManager options at definition time.
+var keys;
+
+// Maintain references to the two `Backbone.View` functions that are
+// overwritten so that they can be proxied.
+var _configure = Backbone.View.prototype._configure;
+
+// Cache these methods for performance.
+var aPush = Array.prototype.push;
+var aConcat = Array.prototype.concat;
+var aSplice = Array.prototype.splice;
+
+// LayoutManager is a wrapper around a `Backbone.View`.
+var LayoutManager = Backbone.View.extend({
+ _render: function(manage, options) {
+ // Keep the view consistent between callbacks and deferreds.
+ var view = this;
+ // Shorthand the manager.
+ var manager = view.__manager__;
+ // Cache these properties.
+ var beforeRender = options.beforeRender;
+ // Create a deferred instead of going off
+ var def = options.deferred();
+
+ // Ensure all nested Views are properly scrubbed if re-rendering.
+ if (view.hasRendered) {
+ view._removeViews();
+ }
+
+ // This continues the render flow after `beforeRender` has completed.
+ manager.callback = function() {
+ // Clean up asynchronous manager properties.
+ delete manager.isAsync;
+ delete manager.callback;
+
+ // Always emit a beforeRender event.
+ view.trigger("beforeRender", view);
+
+ // Render!
+ manage(view, options).render().then(function() {
+ // Complete this deferred once resolved.
+ def.resolve();
+ });
+ };
+
+ // If a beforeRender function is defined, call it.
+ if (beforeRender) {
+ beforeRender.call(view, view);
+ }
+
+ if (!manager.isAsync) {
+ manager.callback();
+ }
+
+ // Return this intermediary promise.
+ return def.promise();
+ },
+
+ // This named function allows for significantly easier debugging.
+ constructor: function Layout(options) {
+ // Options may not always be passed to the constructor, this ensures it is
+ // always an object.
+ options = options || {};
+
+ // Grant this View superpowers.
+ LayoutManager.setupView(this, options);
+
+ // Have Backbone set up the rest of this View.
+ Backbone.View.call(this, options);
+ },
+
+ // This method is used within specific methods to indicate that they should
+ // be treated as asynchronous. This method should only be used within the
+ // render chain, otherwise unexpected behavior may occur.
+ async: function() {
+ var manager = this.__manager__;
+
+ // Set this View's action to be asynchronous.
+ manager.isAsync = true;
+
+ // Return the callback.
+ return manager.callback;
+ },
+
+ promise: function() {
+ return this.__manager__.renderDeferred.promise();
+ },
+
+ // Sometimes it's desirable to only render the child views under the parent.
+ // This is typical for a layout that does not change. This method will
+ // iterate over the child Views and aggregate all child render promises and
+ // return the parent View. The internal `promise()` method will return the
+ // aggregate promise that resolves once all children have completed their
+ // render.
+ renderViews: function() {
+ var root = this;
+ var manager = root.__manager__;
+ var options = root.getAllOptions();
+ var newDeferred = options.deferred();
+
+ // Collect all promises from rendering the child views and wait till they
+ // all complete.
+ var promises = root.getViews().map(function(view) {
+ return view.render().__manager__.renderDeferred;
+ }).value();
+
+ // Simulate a parent render to remain consistent.
+ manager.renderDeferred = newDeferred.promise();
+
+ // Once all child views have completed rendering, resolve parent deferred
+ // with the correct context.
+ options.when(promises).then(function() {
+ newDeferred.resolveWith(root, [root]);
+ });
+
+ // Allow this method to be chained.
+ return root;
+ },
+
+ // Shorthand to `setView` function with the `insert` flag set.
+ insertView: function(selector, view) {
+ // If the `view` argument exists, then a selector was passed in. This code
+ // path will forward the selector on to `setView`.
+ if (view) {
+ return this.setView(selector, view, true);
+ }
+
+ // If no `view` argument is defined, then assume the first argument is the
+ // View, somewhat now confusingly named `selector`.
+ return this.setView(selector, true);
+ },
+
+ // Iterate over an object and ensure every value is wrapped in an array to
+ // ensure they will be inserted, then pass that object to `setViews`.
+ insertViews: function(views) {
+ // If an array of views was passed it should be inserted into the
+ // root view. Much like calling insertView without a selector.
+ if (_.isArray(views)) {
+ return this.setViews({ "": views });
+ }
+
+ _.each(views, function(view, selector) {
+ views[selector] = _.isArray(view) ? view : [view];
+ });
+
+ return this.setViews(views);
+ },
+
+ // Returns the View that matches the `getViews` filter function.
+ getView: function(fn) {
+ // If `getView` is invoked with undefined as the first argument, then the
+ // second argument will be used instead. This is to allow
+ // `getViews(undefined, fn)` to work as `getViews(fn)`. Useful for when
+ // you are allowing an optional selector.
+ if (fn == null) {
+ fn = arguments[1];
+ }
+
+ return this.getViews(fn).first().value();
+ },
+
+ // Provide a filter function to get a flattened array of all the subviews.
+ // If the filter function is omitted it will return all subviews. If a
+ // String is passed instead, it will return the Views for that selector.
+ getViews: function(fn) {
+ var views;
+
+ // If the filter argument is a String, then return a chained Version of the
+ // elements. The value at the specified filter may be undefined, a single
+ // view, or an array of views; in all cases, chain on a flat array.
+ if (typeof fn === "string") {
+ fn = this.sections[fn] || fn;
+ views = this.views[fn] || [];
+
+ // If Views is undefined you are concatenating an `undefined` to an array
+ // resulting in a value being returned. Defaulting to an array prevents
+ // this.
+ //return _.chain([].concat(views || []));
+ return _.chain([].concat(views));
+ }
+
+ // Generate an array of all top level (no deeply nested) Views flattened.
+ views = _.chain(this.views).map(function(view) {
+ return _.isArray(view) ? view : [view];
+ }, this).flatten();
+
+ // If the argument passed is an Object, then pass it to `_.where`.
+ if (typeof fn === "object") {
+ return views.where(fn);
+ }
+
+ // If a filter function is provided, run it on all Views and return a
+ // wrapped chain. Otherwise, simply return a wrapped chain of all Views.
+ return typeof fn === "function" ? views.filter(fn) : views;
+ },
+
+ // Use this to remove Views, internally uses `getViews` so you can pass the
+ // same argument here as you would to that method.
+ removeView: function(fn) {
+ // Allow an optional selector or function to find the right model and
+ // remove nested Views based off the results of the selector or filter.
+ return this.getViews(fn).each(function(nestedView) {
+ nestedView.remove();
+ });
+ },
+
+ // This takes in a partial name and view instance and assigns them to
+ // the internal collection of views. If a view is not a LayoutManager
+ // instance, then mix in the LayoutManager prototype. This ensures
+ // all Views can be used successfully.
+ //
+ // Must definitely wrap any render method passed in or defaults to a
+ // typical render function `return layout(this).render()`.
+ setView: function(name, view, insert) {
+ var manager, options, selector;
+ // Parent view, the one you are setting a View on.
+ var root = this;
+
+ // If no name was passed, use an empty string and shift all arguments.
+ if (typeof name !== "string") {
+ insert = view;
+ view = name;
+ name = "";
+ }
+
+ // Shorthand the `__manager__` property.
+ manager = view.__manager__;
+
+ // If the View has not been properly set up, throw an Error message
+ // indicating that the View needs `manage: true` set.
+ if (!manager) {
+ throw new Error("The argument associated with selector '" + name +
+ "' is defined and a View. Set `manage` property to true for " +
+ "Backbone.View instances.");
+ }
+
+ // Assign options.
+ options = view.getAllOptions();
+
+ // Add reference to the parentView.
+ manager.parent = root;
+
+ // Add reference to the placement selector used.
+ selector = manager.selector = root.sections[name] || name;
+
+ // Call the `setup` method, since we now have a relationship created.
+ _.result(view, "setup");
+
+ // Code path is less complex for Views that are not being inserted. Simply
+ // remove existing Views and bail out with the assignment.
+ if (!insert) {
+ // If the View we are adding has already been rendered, simply inject it
+ // into the parent.
+ if (view.hasRendered) {
+ // Apply the partial.
+ options.partial(root.$el, view.$el, root.__manager__, manager);
+ }
+
+ // Ensure remove is called when swapping View's.
+ root.removeView(name);
+
+ // Assign to main views object and return for chainability.
+ return root.views[selector] = view;
+ }
+
+ // Ensure this.views[selector] is an array and push this View to
+ // the end.
+ root.views[selector] = aConcat.call([], root.views[name] || [], view);
+
+ // Put the parent view into `insert` mode.
+ root.__manager__.insert = true;
+
+ return view;
+ },
+
+ // Allows the setting of multiple views instead of a single view.
+ setViews: function(views) {
+ // Iterate over all the views and use the View's view method to assign.
+ _.each(views, function(view, name) {
+ // If the view is an array put all views into insert mode.
+ if (_.isArray(view)) {
+ return _.each(view, function(view) {
+ this.insertView(name, view);
+ }, this);
+ }
+
+ // Assign each view using the view function.
+ this.setView(name, view);
+ }, this);
+
+ // Allow for chaining
+ return this;
+ },
+
+ // By default this should find all nested views and render them into
+ // the this.el and call done once all of them have successfully been
+ // resolved.
+ //
+ // This function returns a promise that can be chained to determine
+ // once all subviews and main view have been rendered into the view.el.
+ render: function() {
+ var root = this;
+ var options = root.getAllOptions();
+ var manager = root.__manager__;
+ var parent = manager.parent;
+ var rentManager = parent && parent.__manager__;
+ var def = options.deferred();
+
+ // Triggered once the render has succeeded.
+ function resolve() {
+ var next;
+
+ // Insert all subViews into the parent at once.
+ _.each(root.views, function(views, selector) {
+ // Fragments aren't used on arrays of subviews.
+ if (_.isArray(views)) {
+ options.htmlBatch(root, views, selector);
+ }
+ });
+
+ // If there is a parent and we weren't attached to it via the previous
+ // method (single view), attach.
+ if (parent && !manager.insertedViaFragment) {
+ if (!options.contains(parent.el, root.el)) {
+ // Apply the partial using parent's html() method.
+ parent.getAllOptions().partial(parent.$el, root.$el, rentManager,
+ manager);
+ }
+ }
+
+ // Ensure events are always correctly bound after rendering.
+ root.delegateEvents();
+
+ // Set this View as successfully rendered.
+ root.hasRendered = true;
+
+ // Only process the queue if it exists.
+ if (next = manager.queue.shift()) {
+ // Ensure that the next render is only called after all other
+ // `done` handlers have completed. This will prevent `render`
+ // callbacks from firing out of order.
+ next();
+ } else {
+ // Once the queue is depleted, remove it, the render process has
+ // completed.
+ delete manager.queue;
+ }
+
+ // Reusable function for triggering the afterRender callback and event
+ // and setting the hasRendered flag.
+ function completeRender() {
+ var console = window.console;
+ var afterRender = options.afterRender;
+
+ if (afterRender) {
+ afterRender.call(root, root);
+ }
+
+ // Always emit an afterRender event.
+ root.trigger("afterRender", root);
+
+ // If there are multiple top level elements and `el: false` is used,
+ // display a warning message and a stack trace.
+ if (manager.noel && root.$el.length > 1) {
+ // Do not display a warning while testing or if warning suppression
+ // is enabled.
+ if (_.isFunction(console.warn) && !options.suppressWarnings) {
+ console.warn("`el: false` with multiple top level elements is " +
+ "not supported.");
+
+ // Provide a stack trace if available to aid with debugging.
+ if (_.isFunction(console.trace)) {
+ console.trace();
+ }
+ }
+ }
+ }
+
+ // If the parent is currently rendering, wait until it has completed
+ // until calling the nested View's `afterRender`.
+ if (rentManager && rentManager.queue) {
+ // Wait until the parent View has finished rendering, which could be
+ // asynchronous, and trigger afterRender on this View once it has
+ // compeleted.
+ parent.once("afterRender", completeRender);
+ } else {
+ // This View and its parent have both rendered.
+ completeRender();
+ }
+
+ return def.resolveWith(root, [root]);
+ }
+
+ // Actually facilitate a render.
+ function actuallyRender() {
+ var options = root.getAllOptions();
+
+ // The `_viewRender` method is broken out to abstract away from having
+ // too much code in `actuallyRender`.
+ root._render(LayoutManager._viewRender, options).done(function() {
+ // If there are no children to worry about, complete the render
+ // instantly.
+ if (!_.keys(root.views).length) {
+ return resolve();
+ }
+
+ // Create a list of promises to wait on until rendering is done.
+ // Since this method will run on all children as well, its sufficient
+ // for a full hierarchical.
+ var promises = _.map(root.views, function(view) {
+ var insert = _.isArray(view);
+
+ // If items are being inserted, they will be in a non-zero length
+ // Array.
+ if (insert && view.length) {
+ // Mark each subview's manager so they don't attempt to attach by
+ // themselves. Return a single promise representing the entire
+ // render.
+ return options.when(_.map(view, function(subView) {
+ subView.__manager__.insertedViaFragment = true;
+ return subView.render().__manager__.renderDeferred;
+ }));
+ }
+
+ // Only return the fetch deferred, resolve the main deferred after
+ // the element has been attached to it's parent.
+ return !insert ? view.render().__manager__.renderDeferred : view;
+ });
+
+ // Once all nested Views have been rendered, resolve this View's
+ // deferred.
+ options.when(promises).done(resolve);
+ });
+ }
+
+ // Another render is currently happening if there is an existing queue, so
+ // push a closure to render later into the queue.
+ if (manager.queue) {
+ aPush.call(manager.queue, actuallyRender);
+ } else {
+ manager.queue = [];
+
+ // This the first `render`, preceeding the `queue` so render
+ // immediately.
+ actuallyRender(root, def);
+ }
+
+ // Put the deferred inside of the `__manager__` object, since we don't want
+ // end users accessing this directly anymore in favor of the `afterRender`
+ // event. So instead of doing `render().then(...` do
+ // `render().once("afterRender", ...`.
+ root.__manager__.renderDeferred = def;
+
+ // Return the actual View for chainability purposes.
+ return root;
+ },
+
+ // Ensure the cleanup function is called whenever remove is called.
+ remove: function() {
+ // Force remove itself from its parent.
+ LayoutManager._removeView(this, true);
+
+ // Call the original remove function.
+ return this._remove.apply(this, arguments);
+ },
+
+ // Merge instance and global options.
+ getAllOptions: function() {
+ // Instance overrides take precedence, fallback to prototype options.
+ return _.extend({}, this, LayoutManager.prototype.options, this.options);
+ }
+},
+{
+ // Clearable cache.
+ _cache: {},
+
+ // Creates a deferred and returns a function to call when finished.
+ // This gets passed to all _render methods. The `root` value here is passed
+ // from the `manage(this).render()` line in the `_render` function
+ _viewRender: function(root, options) {
+ var url, contents, def, renderedEl;
+ var manager = root.__manager__;
+
+ // This function is responsible for pairing the rendered template into
+ // the DOM element.
+ function applyTemplate(rendered) {
+ // Actually put the rendered contents into the element.
+ if (_.isString(rendered)) {
+ // If no container is specified, we must replace the content.
+ if (manager.noel) {
+ // Trim off the whitespace, since the contents are passed into `$()`.
+ rendered = $.trim(rendered);
+
+ // Hold a reference to created element as replaceWith doesn't return
+ // new el.
+ renderedEl = $(rendered);
+
+ // Remove extra root elements.
+ root.$el.slice(1).remove();
+
+ // Swap out the View on the first top level element to avoid
+ // duplication.
+ root.$el.replaceWith(renderedEl);
+
+ // Don't delegate events here - we'll do that in resolve()
+ root.setElement(renderedEl, false);
+ } else {
+ options.html(root.$el, rendered);
+ }
+ }
+
+ // Resolve only after fetch and render have succeeded.
+ def.resolveWith(root, [root]);
+ }
+
+ // Once the template is successfully fetched, use its contents to proceed.
+ // Context argument is first, since it is bound for partial application
+ // reasons.
+ function done(context, contents) {
+ // Store the rendered template someplace so it can be re-assignable.
+ var rendered;
+
+ // Trigger this once the render method has completed.
+ manager.callback = function(rendered) {
+ // Clean up asynchronous manager properties.
+ delete manager.isAsync;
+ delete manager.callback;
+
+ applyTemplate(rendered);
+ };
+
+ // Ensure the cache is up-to-date.
+ LayoutManager.cache(url, contents);
+
+ // Render the View into the el property.
+ if (contents) {
+ rendered = options.renderTemplate.call(root, contents, context);
+ }
+
+ // If the function was synchronous, continue execution.
+ if (!manager.isAsync) {
+ applyTemplate(rendered);
+ }
+ }
+
+ return {
+ // This `render` function is what gets called inside of the View render,
+ // when `manage(this).render` is called. Returns a promise that can be
+ // used to know when the element has been rendered into its parent.
+ render: function() {
+ var context = root.serialize || options.serialize;
+ var template = root.template || options.template;
+
+ // Create a deferred specifically for fetching.
+ def = options.deferred();
+
+ // If data is a function, immediately call it.
+ if (_.isFunction(context)) {
+ context = context.call(root);
+ }
+
+ // Set the internal callback to trigger once the asynchronous or
+ // synchronous behavior has completed.
+ manager.callback = function(contents) {
+ // Clean up asynchronous manager properties.
+ delete manager.isAsync;
+ delete manager.callback;
+
+ done(context, contents);
+ };
+
+ // Set the url to the prefix + the view's template property.
+ if (typeof template === "string") {
+ url = options.prefix + template;
+ }
+
+ // Check if contents are already cached and if they are, simply process
+ // the template with the correct data.
+ if (contents = LayoutManager.cache(url)) {
+ done(context, contents, url);
+
+ return def;
+ }
+
+ // Fetch layout and template contents.
+ if (typeof template === "string") {
+ contents = options.fetchTemplate.call(root, options.prefix +
+ template);
+ // If the template is already a function, simply call it.
+ } else if (typeof template === "function") {
+ contents = template;
+ // If its not a string and not undefined, pass the value to `fetch`.
+ } else if (template != null) {
+ contents = options.fetchTemplate.call(root, template);
+ }
+
+ // If the function was synchronous, continue execution.
+ if (!manager.isAsync) {
+ done(context, contents);
+ }
+
+ return def;
+ }
+ };
+ },
+
+ // Remove all nested Views.
+ _removeViews: function(root, force) {
+ // Shift arguments around.
+ if (typeof root === "boolean") {
+ force = root;
+ root = this;
+ }
+
+ // Allow removeView to be called on instances.
+ root = root || this;
+
+ // Iterate over all of the nested View's and remove.
+ root.getViews().each(function(view) {
+ // Force doesn't care about if a View has rendered or not.
+ if (view.hasRendered || force) {
+ LayoutManager._removeView(view, force);
+ }
+ });
+ },
+
+ // Remove a single nested View.
+ _removeView: function(view, force) {
+ var parentViews;
+ // Shorthand the managers for easier access.
+ var manager = view.__manager__;
+ var rentManager = manager.parent && manager.parent.__manager__;
+ // Test for keep.
+ var keep = typeof view.keep === "boolean" ? view.keep : view.options.keep;
+
+ // In insert mode, remove views that do not have `keep` attribute set,
+ // unless the force flag is set.
+ if ((!keep && rentManager && rentManager.insert === true) || force) {
+ // Clean out the events.
+ LayoutManager.cleanViews(view);
+
+ // Since we are removing this view, force subviews to remove
+ view._removeViews(true);
+
+ // Remove the View completely.
+ view.$el.remove();
+
+ // Bail out early if no parent exists.
+ if (!manager.parent) { return; }
+
+ // Assign (if they exist) the sibling Views to a property.
+ parentViews = manager.parent.views[manager.selector];
+
+ // If this is an array of items remove items that are not marked to
+ // keep.
+ if (_.isArray(parentViews)) {
+ // Remove duplicate Views.
+ return _.each(_.clone(parentViews), function(view, i) {
+ // If the managers match, splice off this View.
+ if (view && view.__manager__ === manager) {
+ aSplice.call(parentViews, i, 1);
+ }
+ });
+ }
+
+ // Otherwise delete the parent selector.
+ delete manager.parent.views[manager.selector];
+ }
+ },
+
+ // Cache templates into LayoutManager._cache.
+ cache: function(path, contents) {
+ // If template path is found in the cache, return the contents.
+ if (path in this._cache && contents == null) {
+ return this._cache[path];
+ // Ensure path and contents aren't undefined.
+ } else if (path != null && contents != null) {
+ return this._cache[path] = contents;
+ }
+
+ // If the template is not in the cache, return undefined.
+ },
+
+ // Accept either a single view or an array of views to clean of all DOM
+ // events internal model and collection references and all Backbone.Events.
+ cleanViews: function(views) {
+ // Clear out all existing views.
+ _.each(aConcat.call([], views), function(view) {
+ var cleanup;
+
+ // Remove all custom events attached to this View.
+ view.unbind();
+
+ // Automatically unbind `model`.
+ if (view.model instanceof Backbone.Model) {
+ view.model.off(null, null, view);
+ }
+
+ // Automatically unbind `collection`.
+ if (view.collection instanceof Backbone.Collection) {
+ view.collection.off(null, null, view);
+ }
+
+ // Automatically unbind events bound to this View.
+ view.stopListening();
+
+ // If a custom cleanup method was provided on the view, call it after
+ // the initial cleanup is done
+ cleanup = view.getAllOptions().cleanup;
+ if (_.isFunction(cleanup)) {
+ cleanup.call(view);
+ }
+ });
+ },
+
+ // This static method allows for global configuration of LayoutManager.
+ configure: function(options) {
+ _.extend(LayoutManager.prototype.options, options);
+
+ // Allow LayoutManager to manage Backbone.View.prototype.
+ if (options.manage) {
+ Backbone.View.prototype.manage = true;
+ }
+
+ // Disable the element globally.
+ if (options.el === false) {
+ Backbone.View.prototype.el = false;
+ }
+
+ // Allow global configuration of `suppressWarnings`.
+ if (options.suppressWarnings === true) {
+ Backbone.View.prototype.suppressWarnings = true;
+ }
+ },
+
+ // Configure a View to work with the LayoutManager plugin.
+ setupView: function(views, options) {
+ // Set up all Views passed.
+ _.each(aConcat.call([], views), function(view) {
+ // If the View has already been setup, no need to do it again.
+ if (view.__manager__) {
+ return;
+ }
+
+ var views, declaredViews, viewOptions;
+ var proto = LayoutManager.prototype;
+ var viewOverrides = _.pick(view, keys);
+
+ // Ensure necessary properties are set.
+ _.defaults(view, {
+ // Ensure a view always has a views object.
+ views: {},
+
+ // Ensure a view always has a sections object.
+ sections: {},
+
+ // Internal state object used to store whether or not a View has been
+ // taken over by layout manager and if it has been rendered into the
+ // DOM.
+ __manager__: {},
+
+ // Add the ability to remove all Views.
+ _removeViews: LayoutManager._removeViews,
+
+ // Add the ability to remove itself.
+ _removeView: LayoutManager._removeView
+
+ // Mix in all LayoutManager prototype properties as well.
+ }, LayoutManager.prototype);
+
+ // Extend the options with the prototype and passed options.
+ options = view.options = _.defaults(options || {}, view.options,
+ proto.options);
+
+ // Ensure view events are properly copied over.
+ viewOptions = _.pick(options, aConcat.call(["events", "sections"],
+ _.values(options.events)));
+
+ // Merge the View options into the View.
+ _.extend(view, viewOptions);
+
+ // Pick out the specific properties that can be dynamically added at
+ // runtime and ensure they are available on the view object.
+ _.extend(options, viewOverrides);
+
+ // By default the original Remove function is the Backbone.View one.
+ view._remove = Backbone.View.prototype.remove;
+
+ // Ensure the render is always set correctly.
+ view.render = LayoutManager.prototype.render;
+
+ // If the user provided their own remove override, use that instead of
+ // the default.
+ if (view.remove !== proto.remove) {
+ view._remove = view.remove;
+ view.remove = proto.remove;
+ }
+
+ // Normalize views to exist on either instance or options, default to
+ // options.
+ views = options.views || view.views;
+
+ // Set the internal views, only if selectors have been provided.
+ if (_.keys(views).length) {
+ // Keep original object declared containing Views.
+ declaredViews = views;
+
+ // Reset the property to avoid duplication or overwritting.
+ view.views = {};
+
+ // Set the declared Views.
+ view.setViews(declaredViews);
+ }
+
+ // If a template is passed use that instead.
+ if (view.options.template) {
+ view.options.template = options.template;
+ // Ensure the template is mapped over.
+ } else if (view.template) {
+ options.template = view.template;
+ }
+ });
+ }
+});
+
+// Tack on the version.
+LayoutManager.VERSION = "0.9.1";
+
+Backbone.Layout = LayoutManager;
+
+// Override _configure to provide extra functionality that is necessary in
+// order for the render function reference to be bound during initialize.
+Backbone.View.prototype._configure = function(options) {
+ var noel, retVal;
+
+ // Remove the container element provided by Backbone.
+ if ("el" in options ? options.el === false : this.el === false) {
+ noel = true;
+ }
+
+ // Run the original _configure.
+ retVal = _configure.apply(this, arguments);
+
+ // If manage is set, do it!
+ if (options.manage || this.manage) {
+ // Set up this View.
+ LayoutManager.setupView(this);
+ }
+
+ // Assign the `noel` property once we're sure the View we're working with is
+ // managed by LayoutManager.
+ if (this.__manager__) {
+ this.__manager__.noel = noel;
+ this.__manager__.suppressWarnings = options.suppressWarnings;
+ }
+
+ // Act like nothing happened.
+ return retVal;
+};
+
+// Default configuration options; designed to be overriden.
+LayoutManager.prototype.options = {
+ // Prefix template/layout paths.
+ prefix: "",
+
+ // Can be used to supply a different deferred implementation.
+ deferred: function() {
+ return $.Deferred();
+ },
+
+ // Fetch is passed a path and is expected to return template contents as a
+ // function or string.
+ fetchTemplate: function(path) {
+ return _.template($(path).html());
+ },
+
+ // By default, render using underscore's templating.
+ renderTemplate: function(template, context) {
+ return template(context);
+ },
+
+ // This is the most common way you will want to partially apply a view into
+ // a layout.
+ partial: function($root, $el, rentManager, manager) {
+ var $filtered;
+
+ // If selector is specified, attempt to find it.
+ if (manager.selector) {
+ if (rentManager.noel) {
+ $filtered = $root.filter(manager.selector);
+ $root = $filtered.length ? $filtered : $root.find(manager.selector);
+ } else {
+ $root = $root.find(manager.selector);
+ }
+ }
+
+ // Use the insert method if the parent's `insert` argument is true.
+ if (rentManager.insert) {
+ this.insert($root, $el);
+ } else {
+ this.html($root, $el);
+ }
+ },
+
+ // Override this with a custom HTML method, passed a root element and content
+ // (a jQuery collection or a string) to replace the innerHTML with.
+ html: function($root, content) {
+ $root.html(content);
+ },
+
+ // Used for inserting subViews in a single batch. This gives a small
+ // performance boost as we write to a disconnected fragment instead of to the
+ // DOM directly. Smarter browsers like Chrome will batch writes internally
+ // and layout as seldom as possible, but even in that case this provides a
+ // decent boost. jQuery will use a DocumentFragment for the batch update,
+ // but Cheerio in Node will not.
+ htmlBatch: function(rootView, subViews, selector) {
+ // Shorthand the parent manager object.
+ var rentManager = rootView.__manager__;
+ // Create a simplified manager object that tells partial() where
+ // place the elements.
+ var manager = { selector: selector };
+
+ // Get the elements to be inserted into the root view.
+ var els = _.reduce(subViews, function(memo, sub) {
+ // Check if keep is present - do boolean check in case the user
+ // has created a `keep` function.
+ var keep = typeof sub.keep === "boolean" ? sub.keep : sub.options.keep;
+ // If a subView is present, don't push it. This can only happen if
+ // `keep: true`. We do the keep check for speed as $.contains is not
+ // cheap.
+ var exists = keep && $.contains(rootView.el, sub.el);
+
+ // If there is an element and it doesn't already exist in our structure
+ // attach it.
+ if (sub.el && !exists) {
+ memo.push(sub.el);
+ }
+
+ return memo;
+ }, []);
+
+ // Use partial to apply the elements. Wrap els in jQ obj for cheerio.
+ return this.partial(rootView.$el, $(els), rentManager, manager);
+ },
+
+ // Very similar to HTML except this one will appendChild by default.
+ insert: function($root, $el) {
+ $root.append($el);
+ },
+
+ // Return a deferred for when all promises resolve/reject.
+ when: function(promises) {
+ return $.when.apply(null, promises);
+ },
+
+ // A method to determine if a View contains another.
+ contains: function(parent, child) {
+ return $.contains(parent, child);
+ }
+};
+
+// Maintain a list of the keys at define time.
+keys = _.keys(LayoutManager.prototype.options);
+
+// Assign `LayoutManager` object for AMD loaders.
+return LayoutManager;
+
+}));
http://git-wip-us.apache.org/repos/asf/couchdb/blob/c14b2991/share/www/fauxton/src/assets/js/plugins/jquery.form.js
----------------------------------------------------------------------
diff --git a/share/www/fauxton/src/assets/js/plugins/jquery.form.js b/share/www/fauxton/src/assets/js/plugins/jquery.form.js
new file mode 100644
index 0000000..e3126ca
--- /dev/null
+++ b/share/www/fauxton/src/assets/js/plugins/jquery.form.js
@@ -0,0 +1,1190 @@
+/*!
+ * jQuery Form Plugin
+ * version: 3.35.0-2013.05.23
+ * @requires jQuery v1.5 or later
+ * Copyright (c) 2013 M. Alsup
+ * Examples and documentation at: http://malsup.com/jquery/form/
+ * Project repository: https://github.com/malsup/form
+ * Dual licensed under the MIT and GPL licenses.
+ * https://github.com/malsup/form#copyright-and-license
+ */
+/*global ActiveXObject */
+;(function($) {
+"use strict";
+
+/*
+ Usage Note:
+ -----------
+ Do not use both ajaxSubmit and ajaxForm on the same form. These
+ functions are mutually exclusive. Use ajaxSubmit if you want
+ to bind your own submit handler to the form. For example,
+
+ $(document).ready(function() {
+ $('#myForm').on('submit', function(e) {
+ e.preventDefault(); // <-- important
+ $(this).ajaxSubmit({
+ target: '#output'
+ });
+ });
+ });
+
+ Use ajaxForm when you want the plugin to manage all the event binding
+ for you. For example,
+
+ $(document).ready(function() {
+ $('#myForm').ajaxForm({
+ target: '#output'
+ });
+ });
+
+ You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
+ form does not have to exist when you invoke ajaxForm:
+
+ $('#myForm').ajaxForm({
+ delegation: true,
+ target: '#output'
+ });
+
+ When using ajaxForm, the ajaxSubmit function will be invoked for you
+ at the appropriate time.
+*/
+
+/**
+ * Feature detection
+ */
+var feature = {};
+feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
+feature.formdata = window.FormData !== undefined;
+
+var hasProp = !!$.fn.prop;
+
+// attr2 uses prop when it can but checks the return type for
+// an expected string. this accounts for the case where a form
+// contains inputs with names like "action" or "method"; in those
+// cases "prop" returns the element
+$.fn.attr2 = function() {
+ if ( ! hasProp )
+ return this.attr.apply(this, arguments);
+ var val = this.prop.apply(this, arguments);
+ if ( ( val && val.jquery ) || typeof val === 'string' )
+ return val;
+ return this.attr.apply(this, arguments);
+};
+
+/**
+ * ajaxSubmit() provides a mechanism for immediately submitting
+ * an HTML form using AJAX.
+ */
+$.fn.ajaxSubmit = function(options) {
+ /*jshint scripturl:true */
+
+ // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
+ if (!this.length) {
+ log('ajaxSubmit: skipping submit process - no element selected');
+ return this;
+ }
+
+ var method, action, url, $form = this;
+
+ if (typeof options == 'function') {
+ options = { success: options };
+ }
+
+ method = options.type || this.attr2('method');
+ action = options.url || this.attr2('action');
+
+ url = (typeof action === 'string') ? $.trim(action) : '';
+ url = url || window.location.href || '';
+ if (url) {
+ // clean url (don't include hash vaue)
+ url = (url.match(/^([^#]+)/)||[])[1];
+ }
+
+ options = $.extend(true, {
+ url: url,
+ success: $.ajaxSettings.success,
+ type: method || 'GET',
+ iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
+ }, options);
+
+ // hook for manipulating the form data before it is extracted;
+ // convenient for use with rich editors like tinyMCE or FCKEditor
+ var veto = {};
+ this.trigger('form-pre-serialize', [this, options, veto]);
+ if (veto.veto) {
+ log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
+ return this;
+ }
+
+ // provide opportunity to alter form data before it is serialized
+ if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
+ log('ajaxSubmit: submit aborted via beforeSerialize callback');
+ return this;
+ }
+
+ var traditional = options.traditional;
+ if ( traditional === undefined ) {
+ traditional = $.ajaxSettings.traditional;
+ }
+
+ var elements = [];
+ var qx, a = this.formToArray(options.semantic, elements);
+ if (options.data) {
+ options.extraData = options.data;
+ qx = $.param(options.data, traditional);
+ }
+
+ // give pre-submit callback an opportunity to abort the submit
+ if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
+ log('ajaxSubmit: submit aborted via beforeSubmit callback');
+ return this;
+ }
+
+ // fire vetoable 'validate' event
+ this.trigger('form-submit-validate', [a, this, options, veto]);
+ if (veto.veto) {
+ log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
+ return this;
+ }
+
+ var q = $.param(a, traditional);
+ if (qx) {
+ q = ( q ? (q + '&' + qx) : qx );
+ }
+ if (options.type.toUpperCase() == 'GET') {
+ options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
+ options.data = null; // data is null for 'get'
+ }
+ else {
+ options.data = q; // data is the query string for 'post'
+ }
+
+ var callbacks = [];
+ if (options.resetForm) {
+ callbacks.push(function() { $form.resetForm(); });
+ }
+ if (options.clearForm) {
+ callbacks.push(function() { $form.clearForm(options.includeHidden); });
+ }
+
+ // perform a load on the target only if dataType is not provided
+ if (!options.dataType && options.target) {
+ var oldSuccess = options.success || function(){};
+ callbacks.push(function(data) {
+ var fn = options.replaceTarget ? 'replaceWith' : 'html';
+ $(options.target)[fn](data).each(oldSuccess, arguments);
+ });
+ }
+ else if (options.success) {
+ callbacks.push(options.success);
+ }
+
+ options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
+ var context = options.context || this ; // jQuery 1.4+ supports scope context
+ for (var i=0, max=callbacks.length; i < max; i++) {
+ callbacks[i].apply(context, [data, status, xhr || $form, $form]);
+ }
+ };
+
+ if (options.error) {
+ var oldError = options.error;
+ options.error = function(xhr, status, error) {
+ var context = options.context || this;
+ oldError.apply(context, [xhr, status, error, $form]);
+ };
+ }
+
+ if (options.complete) {
+ var oldComplete = options.complete;
+ options.complete = function(xhr, status) {
+ var context = options.context || this;
+ oldComplete.apply(context, [xhr, status, $form]);
+ };
+ }
+
+ // are there files to upload?
+
+ // [value] (issue #113), also see comment:
+ // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
+ var fileInputs = $('input[type=file]:enabled[value!=""]', this);
+
+ var hasFileInputs = fileInputs.length > 0;
+ var mp = 'multipart/form-data';
+ var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
+
+ var fileAPI = feature.fileapi && feature.formdata;
+ log("fileAPI :" + fileAPI);
+ var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
+
+ var jqxhr;
+
+ // options.iframe allows user to force iframe mode
+ // 06-NOV-09: now defaulting to iframe mode if file input is detected
+ if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
+ // hack to fix Safari hang (thanks to Tim Molendijk for this)
+ // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
+ if (options.closeKeepAlive) {
+ $.get(options.closeKeepAlive, function() {
+ jqxhr = fileUploadIframe(a);
+ });
+ }
+ else {
+ jqxhr = fileUploadIframe(a);
+ }
+ }
+ else if ((hasFileInputs || multipart) && fileAPI) {
+ jqxhr = fileUploadXhr(a);
+ }
+ else {
+ jqxhr = $.ajax(options);
+ }
+
+ $form.removeData('jqxhr').data('jqxhr', jqxhr);
+
+ // clear element array
+ for (var k=0; k < elements.length; k++)
+ elements[k] = null;
+
+ // fire 'notify' event
+ this.trigger('form-submit-notify', [this, options]);
+ return this;
+
+ // utility fn for deep serialization
+ function deepSerialize(extraData){
+ var serialized = $.param(extraData, options.traditional).split('&');
+ var len = serialized.length;
+ var result = [];
+ var i, part;
+ for (i=0; i < len; i++) {
+ // #252; undo param space replacement
+ serialized[i] = serialized[i].replace(/\+/g,' ');
+ part = serialized[i].split('=');
+ // #278; use array instead of object storage, favoring array serializations
+ result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
+ }
+ return result;
+ }
+
+ // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
+ function fileUploadXhr(a) {
+ var formdata = new FormData();
+
+ for (var i=0; i < a.length; i++) {
+ formdata.append(a[i].name, a[i].value);
+ }
+
+ if (options.extraData) {
+ var serializedData = deepSerialize(options.extraData);
+ for (i=0; i < serializedData.length; i++)
+ if (serializedData[i])
+ formdata.append(serializedData[i][0], serializedData[i][1]);
+ }
+
+ options.data = null;
+
+ var s = $.extend(true, {}, $.ajaxSettings, options, {
+ contentType: false,
+ processData: false,
+ cache: false,
+ type: method || 'POST'
+ });
+
+ if (options.uploadProgress) {
+ // workaround because jqXHR does not expose upload property
+ s.xhr = function() {
+ var xhr = jQuery.ajaxSettings.xhr();
+ if (xhr.upload) {
+ xhr.upload.addEventListener('progress', function(event) {
+ var percent = 0;
+ var position = event.loaded || event.position; /*event.position is deprecated*/
+ var total = event.total;
+ if (event.lengthComputable) {
+ percent = Math.ceil(position / total * 100);
+ }
+ options.uploadProgress(event, position, total, percent);
+ }, false);
+ }
+ return xhr;
+ };
+ }
+
+ s.data = null;
+ var beforeSend = s.beforeSend;
+ s.beforeSend = function(xhr, o) {
+ o.data = formdata;
+ if(beforeSend)
+ beforeSend.call(this, xhr, o);
+ };
+ return $.ajax(s);
+ }
+
+ // private function for handling file uploads (hat tip to YAHOO!)
+ function fileUploadIframe(a) {
+ var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
+ var deferred = $.Deferred();
+
+ if (a) {
+ // ensure that every serialized input is still enabled
+ for (i=0; i < elements.length; i++) {
+ el = $(elements[i]);
+ if ( hasProp )
+ el.prop('disabled', false);
+ else
+ el.removeAttr('disabled');
+ }
+ }
+
+ s = $.extend(true, {}, $.ajaxSettings, options);
+ s.context = s.context || s;
+ id = 'jqFormIO' + (new Date().getTime());
+ if (s.iframeTarget) {
+ $io = $(s.iframeTarget);
+ n = $io.attr2('name');
+ if (!n)
+ $io.attr2('name', id);
+ else
+ id = n;
+ }
+ else {
+ $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
+ $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
+ }
+ io = $io[0];
+
+
+ xhr = { // mock object
+ aborted: 0,
+ responseText: null,
+ responseXML: null,
+ status: 0,
+ statusText: 'n/a',
+ getAllResponseHeaders: function() {},
+ getResponseHeader: function() {},
+ setRequestHeader: function() {},
+ abort: function(status) {
+ var e = (status === 'timeout' ? 'timeout' : 'aborted');
+ log('aborting upload... ' + e);
+ this.aborted = 1;
+
+ try { // #214, #257
+ if (io.contentWindow.document.execCommand) {
+ io.contentWindow.document.execCommand('Stop');
+ }
+ }
+ catch(ignore) {}
+
+ $io.attr('src', s.iframeSrc); // abort op in progress
+ xhr.error = e;
+ if (s.error)
+ s.error.call(s.context, xhr, e, status);
+ if (g)
+ $.event.trigger("ajaxError", [xhr, s, e]);
+ if (s.complete)
+ s.complete.call(s.context, xhr, e);
+ }
+ };
+
+ g = s.global;
+ // trigger ajax global events so that activity/block indicators work like normal
+ if (g && 0 === $.active++) {
+ $.event.trigger("ajaxStart");
+ }
+ if (g) {
+ $.event.trigger("ajaxSend", [xhr, s]);
+ }
+
+ if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
+ if (s.global) {
+ $.active--;
+ }
+ deferred.reject();
+ return deferred;
+ }
+ if (xhr.aborted) {
+ deferred.reject();
+ return deferred;
+ }
+
+ // add submitting element to data if we know it
+ sub = form.clk;
+ if (sub) {
+ n = sub.name;
+ if (n && !sub.disabled) {
+ s.extraData = s.extraData || {};
+ s.extraData[n] = sub.value;
+ if (sub.type == "image") {
+ s.extraData[n+'.x'] = form.clk_x;
+ s.extraData[n+'.y'] = form.clk_y;
+ }
+ }
+ }
+
+ var CLIENT_TIMEOUT_ABORT = 1;
+ var SERVER_ABORT = 2;
+
+ function getDoc(frame) {
+ /* it looks like contentWindow or contentDocument do not
+ * carry the protocol property in ie8, when running under ssl
+ * frame.document is the only valid response document, since
+ * the protocol is know but not on the other two objects. strange?
+ * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
+ */
+
+ var doc = null;
+
+ // IE8 cascading access check
+ try {
+ if (frame.contentWindow) {
+ doc = frame.contentWindow.document;
+ }
+ } catch(err) {
+ // IE8 access denied under ssl & missing protocol
+ log('cannot get iframe.contentWindow document: ' + err);
+ }
+
+ if (doc) { // successful getting content
+ return doc;
+ }
+
+ try { // simply checking may throw in ie8 under ssl or mismatched protocol
+ doc = frame.contentDocument ? frame.contentDocument : frame.document;
+ } catch(err) {
+ // last attempt
+ log('cannot get iframe.contentDocument: ' + err);
+ doc = frame.document;
+ }
+ return doc;
+ }
+
+ // Rails CSRF hack (thanks to Yvan Barthelemy)
+ var csrf_token = $('meta[name=csrf-token]').attr('content');
+ var csrf_param = $('meta[name=csrf-param]').attr('content');
+ if (csrf_param && csrf_token) {
+ s.extraData = s.extraData || {};
+ s.extraData[csrf_param] = csrf_token;
+ }
+
+ // take a breath so that pending repaints get some cpu time before the upload starts
+ function doSubmit() {
+ // make sure form attrs are set
+ var t = $form.attr2('target'), a = $form.attr2('action');
+
+ // update form attrs in IE friendly way
+ form.setAttribute('target',id);
+ if (!method) {
+ form.setAttribute('method', 'POST');
+ }
+ if (a != s.url) {
+ form.setAttribute('action', s.url);
+ }
+
+ // ie borks in some cases when setting encoding
+ if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
+ $form.attr({
+ encoding: 'multipart/form-data',
+ enctype: 'multipart/form-data'
+ });
+ }
+
+ // support timout
+ if (s.timeout) {
+ timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
+ }
+
+ // look for server aborts
+ function checkState() {
+ try {
+ var state = getDoc(io).readyState;
+ log('state = ' + state);
+ if (state && state.toLowerCase() == 'uninitialized')
+ setTimeout(checkState,50);
+ }
+ catch(e) {
+ log('Server abort: ' , e, ' (', e.name, ')');
+ cb(SERVER_ABORT);
+ if (timeoutHandle)
+ clearTimeout(timeoutHandle);
+ timeoutHandle = undefined;
+ }
+ }
+
+ // add "extra" data to form if provided in options
+ var extraInputs = [];
+ try {
+ if (s.extraData) {
+ for (var n in s.extraData) {
+ if (s.extraData.hasOwnProperty(n)) {
+ // if using the $.param format that allows for multiple values with the same name
+ if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
+ extraInputs.push(
+ $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
+ .appendTo(form)[0]);
+ } else {
+ extraInputs.push(
+ $('<input type="hidden" name="'+n+'">').val(s.extraData[n])
+ .appendTo(form)[0]);
+ }
+ }
+ }
+ }
+
+ if (!s.iframeTarget) {
+ // add iframe to doc and submit the form
+ $io.appendTo('body');
+ if (io.attachEvent)
+ io.attachEvent('onload', cb);
+ else
+ io.addEventListener('load', cb, false);
+ }
+ setTimeout(checkState,15);
+
+ try {
+ form.submit();
+ } catch(err) {
+ // just in case form has element with name/id of 'submit'
+ var submitFn = document.createElement('form').submit;
+ submitFn.apply(form);
+ }
+ }
+ finally {
+ // reset attrs and remove "extra" input elements
+ form.setAttribute('action',a);
+ if(t) {
+ form.setAttribute('target', t);
+ } else {
+ $form.removeAttr('target');
+ }
+ $(extraInputs).remove();
+ }
+ }
+
+ if (s.forceSync) {
+ doSubmit();
+ }
+ else {
+ setTimeout(doSubmit, 10); // this lets dom updates render
+ }
+
+ var data, doc, domCheckCount = 50, callbackProcessed;
+
+ function cb(e) {
+ if (xhr.aborted || callbackProcessed) {
+ return;
+ }
+
+ doc = getDoc(io);
+ if(!doc) {
+ log('cannot access response document');
+ e = SERVER_ABORT;
+ }
+ if (e === CLIENT_TIMEOUT_ABORT && xhr) {
+ xhr.abort('timeout');
+ deferred.reject(xhr, 'timeout');
+ return;
+ }
+ else if (e == SERVER_ABORT && xhr) {
+ xhr.abort('server abort');
+ deferred.reject(xhr, 'error', 'server abort');
+ return;
+ }
+
+ if (!doc || doc.location.href == s.iframeSrc) {
+ // response not received yet
+ if (!timedOut)
+ return;
+ }
+ if (io.detachEvent)
+ io.detachEvent('onload', cb);
+ else
+ io.removeEventListener('load', cb, false);
+
+ var status = 'success', errMsg;
+ try {
+ if (timedOut) {
+ throw 'timeout';
+ }
+
+ var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
+ log('isXml='+isXml);
+ if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
+ if (--domCheckCount) {
+ // in some browsers (Opera) the iframe DOM is not always traversable when
+ // the onload callback fires, so we loop a bit to accommodate
+ log('requeing onLoad callback, DOM not available');
+ setTimeout(cb, 250);
+ return;
+ }
+ // let this fall through because server response could be an empty document
+ //log('Could not access iframe DOM after mutiple tries.');
+ //throw 'DOMException: not available';
+ }
+
+ //log('response detected');
+ var docRoot = doc.body ? doc.body : doc.documentElement;
+ xhr.responseText = docRoot ? docRoot.innerHTML : null;
+ xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
+ if (isXml)
+ s.dataType = 'xml';
+ xhr.getResponseHeader = function(header){
+ var headers = {'content-type': s.dataType};
+ return headers[header];
+ };
+ // support for XHR 'status' & 'statusText' emulation :
+ if (docRoot) {
+ xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
+ xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
+ }
+
+ var dt = (s.dataType || '').toLowerCase();
+ var scr = /(json|script|text)/.test(dt);
+ if (scr || s.textarea) {
+ // see if user embedded response in textarea
+ var ta = doc.getElementsByTagName('textarea')[0];
+ if (ta) {
+ xhr.responseText = ta.value;
+ // support for XHR 'status' & 'statusText' emulation :
+ xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
+ xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
+ }
+ else if (scr) {
+ // account for browsers injecting pre around json response
+ var pre = doc.getElementsByTagName('pre')[0];
+ var b = doc.getElementsByTagName('body')[0];
+ if (pre) {
+ xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
+ }
+ else if (b) {
+ xhr.responseText = b.textContent ? b.textContent : b.innerText;
+ }
+ }
+ }
+ else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
+ xhr.responseXML = toXml(xhr.responseText);
+ }
+
+ try {
+ data = httpData(xhr, dt, s);
+ }
+ catch (err) {
+ status = 'parsererror';
+ xhr.error = errMsg = (err || status);
+ }
+ }
+ catch (err) {
+ log('error caught: ',err);
+ status = 'error';
+ xhr.error = errMsg = (err || status);
+ }
+
+ if (xhr.aborted) {
+ log('upload aborted');
+ status = null;
+ }
+
+ if (xhr.status) { // we've set xhr.status
+ status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
+ }
+
+ // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
+ if (status === 'success') {
+ if (s.success)
+ s.success.call(s.context, data, 'success', xhr);
+ deferred.resolve(xhr.responseText, 'success', xhr);
+ if (g)
+ $.event.trigger("ajaxSuccess", [xhr, s]);
+ }
+ else if (status) {
+ if (errMsg === undefined)
+ errMsg = xhr.statusText;
+ if (s.error)
+ s.error.call(s.context, xhr, status, errMsg);
+ deferred.reject(xhr, 'error', errMsg);
+ if (g)
+ $.event.trigger("ajaxError", [xhr, s, errMsg]);
+ }
+
+ if (g)
+ $.event.trigger("ajaxComplete", [xhr, s]);
+
+ if (g && ! --$.active) {
+ $.event.trigger("ajaxStop");
+ }
+
+ if (s.complete)
+ s.complete.call(s.context, xhr, status);
+
+ callbackProcessed = true;
+ if (s.timeout)
+ clearTimeout(timeoutHandle);
+
+ // clean up
+ setTimeout(function() {
+ if (!s.iframeTarget)
+ $io.remove();
+ xhr.responseXML = null;
+ }, 100);
+ }
+
+ var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
+ if (window.ActiveXObject) {
+ doc = new ActiveXObject('Microsoft.XMLDOM');
+ doc.async = 'false';
+ doc.loadXML(s);
+ }
+ else {
+ doc = (new DOMParser()).parseFromString(s, 'text/xml');
+ }
+ return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
+ };
+ var parseJSON = $.parseJSON || function(s) {
+ /*jslint evil:true */
+ return window['eval']('(' + s + ')');
+ };
+
+ var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
+
+ var ct = xhr.getResponseHeader('content-type') || '',
+ xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
+ data = xml ? xhr.responseXML : xhr.responseText;
+
+ if (xml && data.documentElement.nodeName === 'parsererror') {
+ if ($.error)
+ $.error('parsererror');
+ }
+ if (s && s.dataFilter) {
+ data = s.dataFilter(data, type);
+ }
+ if (typeof data === 'string') {
+ if (type === 'json' || !type && ct.indexOf('json') >= 0) {
+ data = parseJSON(data);
+ } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
+ $.globalEval(data);
+ }
+ }
+ return data;
+ };
+
+ return deferred;
+ }
+};
+
+/**
+ * ajaxForm() provides a mechanism for fully automating form submission.
+ *
+ * The advantages of using this method instead of ajaxSubmit() are:
+ *
+ * 1: This method will include coordinates for <input type="image" /> elements (if the element
+ * is used to submit the form).
+ * 2. This method will include the submit element's name/value data (for the element that was
+ * used to submit the form).
+ * 3. This method binds the submit() method to the form for you.
+ *
+ * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
+ * passes the options argument along after properly binding events for submit elements and
+ * the form itself.
+ */
+$.fn.ajaxForm = function(options) {
+ options = options || {};
+ options.delegation = options.delegation && $.isFunction($.fn.on);
+
+ // in jQuery 1.3+ we can fix mistakes with the ready state
+ if (!options.delegation && this.length === 0) {
+ var o = { s: this.selector, c: this.context };
+ if (!$.isReady && o.s) {
+ log('DOM not ready, queuing ajaxForm');
+ $(function() {
+ $(o.s,o.c).ajaxForm(options);
+ });
+ return this;
+ }
+ // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
+ log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
+ return this;
+ }
+
+ if ( options.delegation ) {
+ $(document)
+ .off('submit.form-plugin', this.selector, doAjaxSubmit)
+ .off('click.form-plugin', this.selector, captureSubmittingElement)
+ .on('submit.form-plugin', this.selector, options, doAjaxSubmit)
+ .on('click.form-plugin', this.selector, options, captureSubmittingElement);
+ return this;
+ }
+
+ return this.ajaxFormUnbind()
+ .bind('submit.form-plugin', options, doAjaxSubmit)
+ .bind('click.form-plugin', options, captureSubmittingElement);
+};
+
+// private event handlers
+function doAjaxSubmit(e) {
+ /*jshint validthis:true */
+ var options = e.data;
+ if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
+ e.preventDefault();
+ $(this).ajaxSubmit(options);
+ }
+}
+
+function captureSubmittingElement(e) {
+ /*jshint validthis:true */
+ var target = e.target;
+ var $el = $(target);
+ if (!($el.is("[type=submit],[type=image]"))) {
+ // is this a child element of the submit el? (ex: a span within a button)
+ var t = $el.closest('[type=submit]');
+ if (t.length === 0) {
+ return;
+ }
+ target = t[0];
+ }
+ var form = this;
+ form.clk = target;
+ if (target.type == 'image') {
+ if (e.offsetX !== undefined) {
+ form.clk_x = e.offsetX;
+ form.clk_y = e.offsetY;
+ } else if (typeof $.fn.offset == 'function') {
+ var offset = $el.offset();
+ form.clk_x = e.pageX - offset.left;
+ form.clk_y = e.pageY - offset.top;
+ } else {
+ form.clk_x = e.pageX - target.offsetLeft;
+ form.clk_y = e.pageY - target.offsetTop;
+ }
+ }
+ // clear form vars
+ setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
+}
+
+
+// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
+$.fn.ajaxFormUnbind = function() {
+ return this.unbind('submit.form-plugin click.form-plugin');
+};
+
+/**
+ * formToArray() gathers form element data into an array of objects that can
+ * be passed to any of the following ajax functions: $.get, $.post, or load.
+ * Each object in the array has both a 'name' and 'value' property. An example of
+ * an array for a simple login form might be:
+ *
+ * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
+ *
+ * It is this array that is passed to pre-submit callback functions provided to the
+ * ajaxSubmit() and ajaxForm() methods.
+ */
+$.fn.formToArray = function(semantic, elements) {
+ var a = [];
+ if (this.length === 0) {
+ return a;
+ }
+
+ var form = this[0];
+ var els = semantic ? form.getElementsByTagName('*') : form.elements;
+ if (!els) {
+ return a;
+ }
+
+ var i,j,n,v,el,max,jmax;
+ for(i=0, max=els.length; i < max; i++) {
+ el = els[i];
+ n = el.name;
+ if (!n || el.disabled) {
+ continue;
+ }
+
+ if (semantic && form.clk && el.type == "image") {
+ // handle image inputs on the fly when semantic == true
+ if(form.clk == el) {
+ a.push({name: n, value: $(el).val(), type: el.type });
+ a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
+ }
+ continue;
+ }
+
+ v = $.fieldValue(el, true);
+ if (v && v.constructor == Array) {
+ if (elements)
+ elements.push(el);
+ for(j=0, jmax=v.length; j < jmax; j++) {
+ a.push({name: n, value: v[j]});
+ }
+ }
+ else if (feature.fileapi && el.type == 'file') {
+ if (elements)
+ elements.push(el);
+ var files = el.files;
+ if (files.length) {
+ for (j=0; j < files.length; j++) {
+ a.push({name: n, value: files[j], type: el.type});
+ }
+ }
+ else {
+ // #180
+ a.push({ name: n, value: '', type: el.type });
+ }
+ }
+ else if (v !== null && typeof v != 'undefined') {
+ if (elements)
+ elements.push(el);
+ a.push({name: n, value: v, type: el.type, required: el.required});
+ }
+ }
+
+ if (!semantic && form.clk) {
+ // input type=='image' are not found in elements array! handle it here
+ var $input = $(form.clk), input = $input[0];
+ n = input.name;
+ if (n && !input.disabled && input.type == 'image') {
+ a.push({name: n, value: $input.val()});
+ a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
+ }
+ }
+ return a;
+};
+
+/**
+ * Serializes form data into a 'submittable' string. This method will return a string
+ * in the format: name1=value1&name2=value2
+ */
+$.fn.formSerialize = function(semantic) {
+ //hand off to jQuery.param for proper encoding
+ return $.param(this.formToArray(semantic));
+};
+
+/**
+ * Serializes all field elements in the jQuery object into a query string.
+ * This method will return a string in the format: name1=value1&name2=value2
+ */
+$.fn.fieldSerialize = function(successful) {
+ var a = [];
+ this.each(function() {
+ var n = this.name;
+ if (!n) {
+ return;
+ }
+ var v = $.fieldValue(this, successful);
+ if (v && v.constructor == Array) {
+ for (var i=0,max=v.length; i < max; i++) {
+ a.push({name: n, value: v[i]});
+ }
+ }
+ else if (v !== null && typeof v != 'undefined') {
+ a.push({name: this.name, value: v});
+ }
+ });
+ //hand off to jQuery.param for proper encoding
+ return $.param(a);
+};
+
+/**
+ * Returns the value(s) of the element in the matched set. For example, consider the following form:
+ *
+ * <form><fieldset>
+ * <input name="A" type="text" />
+ * <input name="A" type="text" />
+ * <input name="B" type="checkbox" value="B1" />
+ * <input name="B" type="checkbox" value="B2"/>
+ * <input name="C" type="radio" value="C1" />
+ * <input name="C" type="radio" value="C2" />
+ * </fieldset></form>
+ *
+ * var v = $('input[type=text]').fieldValue();
+ * // if no values are entered into the text inputs
+ * v == ['','']
+ * // if values entered into the text inputs are 'foo' and 'bar'
+ * v == ['foo','bar']
+ *
+ * var v = $('input[type=checkbox]').fieldValue();
+ * // if neither checkbox is checked
+ * v === undefined
+ * // if both checkboxes are checked
+ * v == ['B1', 'B2']
+ *
+ * var v = $('input[type=radio]').fieldValue();
+ * // if neither radio is checked
+ * v === undefined
+ * // if first radio is checked
+ * v == ['C1']
+ *
+ * The successful argument controls whether or not the field element must be 'successful'
+ * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
+ * The default value of the successful argument is true. If this value is false the value(s)
+ * for each element is returned.
+ *
+ * Note: This method *always* returns an array. If no valid value can be determined the
+ * array will be empty, otherwise it will contain one or more values.
+ */
+$.fn.fieldValue = function(successful) {
+ for (var val=[], i=0, max=this.length; i < max; i++) {
+ var el = this[i];
+ var v = $.fieldValue(el, successful);
+ if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
+ continue;
+ }
+ if (v.constructor == Array)
+ $.merge(val, v);
+ else
+ val.push(v);
+ }
+ return val;
+};
+
+/**
+ * Returns the value of the field element.
+ */
+$.fieldValue = function(el, successful) {
+ var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
+ if (successful === undefined) {
+ successful = true;
+ }
+
+ if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
+ (t == 'checkbox' || t == 'radio') && !el.checked ||
+ (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
+ tag == 'select' && el.selectedIndex == -1)) {
+ return null;
+ }
+
+ if (tag == 'select') {
+ var index = el.selectedIndex;
+ if (index < 0) {
+ return null;
+ }
+ var a = [], ops = el.options;
+ var one = (t == 'select-one');
+ var max = (one ? index+1 : ops.length);
+ for(var i=(one ? index : 0); i < max; i++) {
+ var op = ops[i];
+ if (op.selected) {
+ var v = op.value;
+ if (!v) { // extra pain for IE...
+ v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
+ }
+ if (one) {
+ return v;
+ }
+ a.push(v);
+ }
+ }
+ return a;
+ }
+ return $(el).val();
+};
+
+/**
+ * Clears the form data. Takes the following actions on the form's input fields:
+ * - input text fields will have their 'value' property set to the empty string
+ * - select elements will have their 'selectedIndex' property set to -1
+ * - checkbox and radio inputs will have their 'checked' property set to false
+ * - inputs of type submit, button, reset, and hidden will *not* be effected
+ * - button elements will *not* be effected
+ */
+$.fn.clearForm = function(includeHidden) {
+ return this.each(function() {
+ $('input,select,textarea', this).clearFields(includeHidden);
+ });
+};
+
+/**
+ * Clears the selected form elements.
+ */
+$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
+ var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
+ return this.each(function() {
+ var t = this.type, tag = this.tagName.toLowerCase();
+ if (re.test(t) || tag == 'textarea') {
+ this.value = '';
+ }
+ else if (t == 'checkbox' || t == 'radio') {
+ this.checked = false;
+ }
+ else if (tag == 'select') {
+ this.selectedIndex = -1;
+ }
+ else if (t == "file") {
+ if (/MSIE/.test(navigator.userAgent)) {
+ $(this).replaceWith($(this).clone(true));
+ } else {
+ $(this).val('');
+ }
+ }
+ else if (includeHidden) {
+ // includeHidden can be the value true, or it can be a selector string
+ // indicating a special test; for example:
+ // $('#myForm').clearForm('.special:hidden')
+ // the above would clean hidden inputs that have the class of 'special'
+ if ( (includeHidden === true && /hidden/.test(t)) ||
+ (typeof includeHidden == 'string' && $(this).is(includeHidden)) )
+ this.value = '';
+ }
+ });
+};
+
+/**
+ * Resets the form data. Causes all form elements to be reset to their original value.
+ */
+$.fn.resetForm = function() {
+ return this.each(function() {
+ // guard against an input with the name of 'reset'
+ // note that IE reports the reset function as an 'object'
+ if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
+ this.reset();
+ }
+ });
+};
+
+/**
+ * Enables or disables any matching elements.
+ */
+$.fn.enable = function(b) {
+ if (b === undefined) {
+ b = true;
+ }
+ return this.each(function() {
+ this.disabled = !b;
+ });
+};
+
+/**
+ * Checks/unchecks any matching checkboxes or radio buttons and
+ * selects/deselects and matching option elements.
+ */
+$.fn.selected = function(select) {
+ if (select === undefined) {
+ select = true;
+ }
+ return this.each(function() {
+ var t = this.type;
+ if (t == 'checkbox' || t == 'radio') {
+ this.checked = select;
+ }
+ else if (this.tagName.toLowerCase() == 'option') {
+ var $sel = $(this).parent('select');
+ if (select && $sel[0] && $sel[0].type == 'select-one') {
+ // deselect all other options
+ $sel.find('option').selected(false);
+ }
+ this.selected = select;
+ }
+ });
+};
+
+// expose debug var
+$.fn.ajaxSubmit.debug = false;
+
+// helper fn for console logging
+function log() {
+ if (!$.fn.ajaxSubmit.debug)
+ return;
+ var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
+ if (window.console && window.console.log) {
+ window.console.log(msg);
+ }
+ else if (window.opera && window.opera.postError) {
+ window.opera.postError(msg);
+ }
+}
+
+})(jQuery);