-
Notifications
You must be signed in to change notification settings - Fork 20
/
torso-bundle.min.js
1 lines (1 loc) · 75.1 KB
/
torso-bundle.min.js
1
!function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone")):(e.Torso=e.Torso||{},e.Torso.Events=t(e._,e.Backbone))}(this,function(e,t){"use strict";return e.extend({},t.Events)}),function(e,t){"function"==typeof define&&define.amd?define(["backbone"],t):"object"==typeof exports?module.exports=t(require("backbone")):(e.Torso=e.Torso||{},e.Torso.Router=t(e.Backbone))}(this,function(e){"use strict";return e.Router.extend({})}),function(e,t){"function"==typeof define&&define.amd?define(["backbone","jquery"],t):"object"==typeof exports?module.exports=t(require("backbone"),require("jquery")):t(e.Backbone,e.$)}(this,function(e,t){"use strict";return e.$=t,!0}),function(e,t){"function"==typeof define&&define.amd?define(["underscore"],t):"object"==typeof exports?module.exports=t(require("underscore")):(e.Torso=e.Torso||{},e.Torso.Utils=e.Torso.Utils||{},e.Torso.Utils.handlebarsUtils=t(e._))}(this,function(o){"use strict";return function(l){var h="feedback",u="model";l.registerHelper("labelFor",function(e,t){return t=o.extend(t,{noValueAttr:!0}),l.helpers.formAttr(e,"for",t)}),l.registerHelper("bindModel",function(e,t){return l.helpers.formAttr(e,u+", "+h+", name, id",t)}),l.registerHelper("feedback",function(e,t){return t=o.extend(t,{noValueAttr:!0}),l.helpers.formAttr(e,h,t)}),l.registerHelper("formAttr",function(e,t,i){var n,s,r=i.hash?i.hash.value:void 0,o=l.helpers.injectFieldIndices(e,i.hash),a=l.helpers.injectFieldIndices(e,i.hash,{forceArrayNotation:!0}),d="";for(t=t.split(","),n=0;n<t.length;n++){s=t[n].trim();var c=n===t.length-1?'"':'" ';s===h?d+='data-feedback="'+a+c:s===u?d+='data-model="'+o+c:"name"===s?d+='name="'+l.helpers.dasherize(o)+c:"id"===s?(d+='id="'+l.helpers.dasherize(o),void 0!==r&&(d+="-"+r),d+=c):"for"===s&&(d+='for="'+l.helpers.dasherize(o),void 0!==r&&(d+="-"+r),d+=c)}return void 0===r||i.noValueAttr||(d+=' value="'+r+'"'),new l.SafeString(d)}),l.registerHelper("dasherize",function(e){return e.replace(/([A-Z])/g,function(e){return"-"+e.toLowerCase()}).replace(/\./g,function(){return"_"}).replace(/\[[0-9]+\]/g,function(e){return"-"+e.substring(1,e.length-1)})}),l.registerHelper("injectFieldIndices",function(e,s,r){return s?e.replace(/\[.+?\]/g,function(e){var t=s[e.substring(1,e.length-1)],i="["+(void 0===t?"":t)+"]",n=r&&r.forceArrayNotation;return o.isString(t)&&isNaN(t)&&!n&&(i="."+t),i}):e})}}),function(e,t){"function"==typeof define&&define.amd?define(["backbone"],t):"object"==typeof exports?module.exports=t(require("backbone")):(e.Torso=e.Torso||{},e.Torso.history=t(e.Backbone))}(this,function(e){"use strict";return e.history}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone")):(e.Torso=e.Torso||{},e.Torso.registry=t(e._,e.Backbone))}(this,function(i,e){"use strict";function t(){this.cells={},this.models={},this.services={},this.views={}}return i.extend(t.prototype,e.Events,{cidPrefix:"r",modelInitialized:function(e){this.__initialize(e,this.models)},cellInitialized:function(e){this.__initialize(e,this.cells)},viewInitialized:function(e){this.__initialize(e,this.views)},serviceInitialized:function(e){this.__initialize(e,this.services)},__initialize:function(e,t){t[e.cid]=e,this.listenToOnce(e,"before-dispose",function(){delete t[e.cid]})},disposeAll:function(){this.disposeAllModels(),this.disposeAllCells(),this.disposeAllServices(),this.disposeAllViews()},disposeAllModels:function(){this.__disposeCache(this.models)},disposeAllCells:function(){this.__disposeCache(this.cells)},disposeAllServices:function(){this.__disposeCache(this.services)},disposeAllViews:function(){this.__disposeCache(this.views)},__disposeCache:function(e){var t=i.values(e);i.invoke(t,"dispose")}}),new t}),function(e,t){"function"==typeof define&&define.amd?define(["backbone","backbone.stickit"],t):"object"==typeof exports?(require("backbone.stickit"),t(require("backbone"))):t(e.Backbone)}(this,function(e){"use strict";e.Stickit.addHandler({selector:'input[type="radio"]',events:["change"],update:function(e,t){e.prop("checked",!1),e.filter('[value="'+t+'"]').prop("checked",!0)},getVal:function(e){return e.filter(":checked").val()}})}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone")):(e.Torso=e.Torso||{},e.Torso.Utils=e.Torso.Utils||{},e.Torso.Utils.templateRenderer=t(e._,e.Backbone))}(this,function(h,e){"use strict";var u=e.$;function f(e,t,i){var n=t.nodeType;n!==e.nodeType?u(e).replaceWith(t):(s[n]||s.default)(e,t,i)}function t(e,t){t.nodeValue!==e.nodeValue&&u(e).replaceWith(t)}var s={1:function(t,e,i){var n,s,r,o,a=u(t),d=u(e),c=0;if(!h.some(i,function(e){return a.is(e)}))if(e.tagName===t.tagName){for(var l=(o=t.attributes).length;c<o.length;)if(n=o[c].name,e.getAttribute(n))c++;else{if(t.removeAttribute(n),l===o.length)return void a.replaceWith(e);l=o.length}h.each(e.attributes,function(e){t.setAttribute(e.name,e.value)}),function(e){var t=u(e),i=t.data("stickit-bind-val");"OPTION"===e.tagName&&void 0!==e.value&&i!==e.value&&t.removeData("stickit-bind-val")}(t),a.html()!==d.html()&&(r=d.contents(),s=a.contents(),r.length===s.length?s.each(function(e,t){f(t,r.get(e),i)}):a.html(d.html()))}else a.replaceWith(e)},3:t,4:t,8:t,default:function(e,t){u(e).replaceWith(t)}};return{render:function(e,t,i,n){var s,r,o=e.get(0);r=(n=n||{}).newHTML||t(i),n.force?e.html(r):(s=this.copyTopElement(o),u(s).html(r),this.hotswapKeepCaret(o,s,n.ignoreElements))},hotswapKeepCaret:function(e,t,i){var n,s,r=!1;try{s=document.activeElement}catch(e){s=null}s&&e&&u.contains(s,e)&&(r=!0),r&&this.supportsSelection(s)&&(n=this.getCaretPosition(s)),this.hotswap(e,t,i),r&&this.supportsSelection(s)&&this.setCaretPosition(s,n)},hotswap:f,copyTopElement:function(e){var t=document.createElement(e.tagName);return h.each(e.attributes,function(e){t.setAttribute(e.name,e.value)}),t},supportsSelection:function(e){return/text|password|search|tel|url/.test(e.type)},getCaretPosition:function(e){var t,i=0;return document.selection?(e.focus(),(t=document.selection.createRange()).moveStart("character",-e.value.length),i=t.text.length):!e.selectionStart&&0!==e.selectionStart||(i=e.selectionStart),i},setCaretPosition:function(e,t){var i;e&&(e.createTextRange?((i=e.createTextRange()).move("character",t),i.select()):e.selectionStart||0===e.selectionStart?(e.focus(),e.setSelectionRange(t,t)):e.focus())}}}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone")):(e.Torso=e.Torso||{},e.Torso.Mixins=e.Torso.Mixins||{},e.Torso.Mixins.cache=t(e._,e.Backbone))}(this,function(p,e){var a=e.$;return function(n){var s,r;return r=function(e,t){return e.constructor.extend((n=e.constructor.__super__,o=e,i=t,{getTrackedIds:function(){return this.trackedIds},fetch:function(e){return(e=e||{}).idsToFetch=e.idsToFetch||this.trackedIds,e.setOptions=e.setOptions||{remove:!1},this.__loadWrapper(function(){return e.idsToFetch&&e.idsToFetch.length?o.fetchByIds(e):a.Deferred().resolve().promise()})},fetchByIds:function(e,t){return(t=t||{}).idsToFetch=p.intersection(e,this.getTrackedIds()),this.fetch(t)},trackIds:function(e){this.remove(p.difference(this.trackedIds,e)),o.registerIds(e,i),this.trackedIds=e},addModelAndTrack:function(e){this.add(e),o.add(e),this.trackNewId(e.id)},trackNewId:function(e){this.trackIds(this.getTrackedIds().concat(e))},trackAndFetch:function(e){return this.trackIds(e),this.fetch()},pull:function(e){e=e||{};var t=p.difference(this.getTrackedIds(),p.pluck(o.models,"id")),i=p.pick(o.idPromises,t);e.idsToFetch=p.difference(t,p.uniq(p.flatten(p.keys(i))));var n=this.fetch(e),s=p.flatten(p.values(i));s.push(n);var r=p.uniq(s);return a.when.apply(a,r).then(function(){var e=p.zip(arguments)[0];return p.flatten(e)})},trackAndPull:function(e){return this.trackIds(e),this.pull()},requesterDispose:function(){o.removeRequester(i)},remove:function(e){var t=this.get(e);if(n.remove.apply(this,arguments),t){var i=this.getTrackedIds();i=p.without(i,t.id),this.trackIds(i)}}}));var n,o,i},s=function(f){f.getRequesterIds=function(e){return this.requestMap[e]&&this.requestMap[e].array},f.getRequesterIdsAsDictionary=function(e){return this.requestMap[e]&&this.requestMap[e].dict},f.removeRequester=function(e){delete this.requestMap[e],delete this.knownPrivateCollections[e]},f.getRequesters=function(){return p.keys(this.requestMap)},f.getAllRequestedIds=function(){return this.collectionTrackedIds},f.createPrivateCollection=function(e,t){(t=t||{}).isRequester=!0,t.parentInstance=f;var i=r(f,e);return this.knownPrivateCollections[e]=new i(null,t),this.knownPrivateCollections[e]},f.registerIds=function(e,t){var i,n,s,r,o,a,d,c,l=[],h={},u=[];for(function(e,t){f.requestMap[e]={array:t,dict:p.object(p.map(t,function(e){return[e,e]}))}}(t,e),d=(a=f.getRequesters()).length,n=0;n<e.length;n++)(s=f.get(e[n]))&&l.push(s);for((c=f.knownPrivateCollections[t])&&c.set(l,{remove:!1}),r=0;r<d;r++)if(o=this.getRequesterIds(a[r]),!p.isUndefined(o))for(i=0;i<o.length;i++)h[o[i]]=!0;for(i in h)u.push(i);this.collectionTrackedIds=u,this.polledFetch=function(){f.fetchByIds({setOptions:{remove:!0}})}},f.fetch=function(e){return e=e||{},this.fetchUsingTrackedIds?this.fetchByIds({setOptions:p.extend({remove:!0},e)}):n.prototype.fetch.call(this,e)},f.fetchByIds=function(e){var u=(e=e||{}).idsToFetch||f.collectionTrackedIds,t=!1,n=this.__loadWrapper(function(h){var e=h.fetchContentType||f.fetchContentType,t={type:f.fetchHttpAction,url:p.result(f,"url")+f.getByIdsUrl,data:{ids:u.join(",")}};return(e||t.type&&"GET"!==t.type.toUpperCase())&&(t.contentType=e||"application/json; charset=utf-8",t.data=JSON.stringify(u)),a.ajax(t).done(function(e){var t,i,n,s,r,o,a,d,c=u.length,l=h.setOptions;for(f.set(f.parse(e),l),o=(a=f.getRequesters()).length,i=0;i<o;i++){for(n=f.getRequesterIdsAsDictionary(a[i]),s=[],t=0;t<c;t++)n[u[t]]&&(d=f.get(u[t]))&&s.push(d);(r=f.knownPrivateCollections[a[i]])&&r.set(s,{remove:!1})}})},e).always(function(){t=!0,p.each(u,function(e){if(f.idPromises){var t=f.idPromises[e],i=p.without(t,n);p.isEmpty(i)?delete f.idPromises[e]:f.idPromises[e]=i}})});return t||p.each(u,function(e){var t=f.idPromises[e];t||(t=[],f.idPromises[e]=t),t.push(n)}),n}},{constructor:function(e,t){if(t=t||{},n.call(this,e,t),this.isRequester=t.isRequester,this.parentInstance=t.parentInstance,this.isRequester)this.trackedIds=[],this.listenTo(this.parentInstance,"load-begin",function(){this.trigger("cache-load-begin")}),this.listenTo(this.parentInstance,"load-complete",function(){this.trigger("cache-load-complete")});else{this.requestMap={},this.collectionTrackedIds=[],this.knownPrivateCollections={},this.idPromises={};var i=p.defaults(p.pick(t,"getByIdsUrl","fetchHttpAction","fetchUsingTrackedIds"),p.pick(this,"getByIdsUrl","fetchHttpAction","fetchUsingTrackedIds"),{getByIdsUrl:"/ids",fetchHttpAction:"GET",fetchUsingTrackedIds:!0});p.extend(this,i),s(this)}}}}}),function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():(e.Torso=e.Torso||{},e.Torso.Mixins=e.Torso.Mixins||{},e.Torso.Mixins.cell=t())}(this,function(){"use strict";return{isModelCompatible:!1,save:function(){if(!this.isModelCompatible)throw"Cell does not have save"},fetch:function(){if(!this.isModelCompatible)throw"Cell does not have fetch"},sync:function(){if(!this.isModelCompatible)throw"Cell does not have sync"},url:function(){if(!this.isModelCompatible)throw"Cell does not have url"}}}),function(e,t){"function"==typeof define&&define.amd?define(["backbone"],t):"object"==typeof exports?module.exports=t(require("backbone")):(e.Torso=e.Torso||{},e.Torso.Mixins=e.Torso.Mixins||{},e.Torso.Mixins.loading=t(e.Backbone))}(this,function(e){var i=e.$;return function(t){return{constructor:function(e){t.call(this,e),this.loadedOnceDeferred=new i.Deferred,this.loadedOnce=!1,this.loadingCount=0,this.loading=!1},hasLoadedOnce:function(){return this.loadedOnce},isLoading:function(){return this.loading},getLoadedOncePromise:function(){return this.loadedOnceDeferred.promise()},fetch:function(e){return this.__loadWrapper(t.prototype.fetch,e)},__loadWrapper:function(e,t){var n=this;return this.loadingCount++,this.loading=!0,this.trigger("load-begin"),i.when(e.call(n,t)).always(function(){n.loadedOnce||(n.loadedOnce=!0,n.loadedOnceDeferred.resolve()),n.loadingCount--,n.loadingCount<=0&&(n.loadingCount=0,n.loading=!1)}).done(function(e,t,i){n.trigger("load-complete",{success:!0,data:e,textStatus:t,jqXHR:i})}).fail(function(e,t,i){n.trigger("load-complete",{success:!1,jqXHR:e,textStatus:t,errorThrown:i})})}}}}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","../registry"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("../registry")):(e.Torso=e.Torso||{},e.Torso.Mixins=e.Torso.Mixins||{},e.Torso.Mixins.model=t(e._,e.Torso.registry))}(this,function(e,t){"use strict";return{__register:function(){t.modelInitialized(this)},dispose:function(){this.trigger("before-dispose"),this._dispose(),this.off(),this.trigger("after-dispose")},_dispose:function(){}}}),function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():(e.Torso=e.Torso||{},e.Torso.Mixins=e.Torso.Mixins||{},e.Torso.Mixins.polling=t())}(this,function(){return{pollTimeoutId:void 0,__pollStarted:!1,__pollInterval:5e3,isPolling:function(){return this.__pollStarted},startPolling:function(e){var t=this;e&&(this.__pollInterval=e),this.__pollStarted||(this.__pollStarted=!0,this.pollTimeoutId=window.setInterval(function(){t.__poll()},this.__pollInterval),this.__poll())},stopPolling:function(){window.clearInterval(this.pollTimeoutId),this.__pollStarted=!1},polledFetch:function(){this.fetch()},__poll:function(){this.polledFetch()}}}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","./Model","./mixins/cellMixin","./registry"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("./Model"),require("./mixins/cellMixin"),require("./registry")):(e.Torso=e.Torso||{},e.Torso.Cell=t(e._,e.Torso.Model,e.Torso.Mixins.cell,e.Torso.registry))}(this,function(e,t,i,n){"use strict";var s=t.extend({__register:function(){n.cellInitialized(this)}});return e.extend(s.prototype,i),s}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone","./mixins/pollingMixin","./mixins/cacheMixin","./mixins/loadingMixin"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone"),require("./mixins/pollingMixin"),require("./mixins/cacheMixin"),require("./mixins/loadingMixin")):(e.Torso=e.Torso||{},e.Torso.Collection=t(e._,e.Backbone,e.Torso.Mixins.polling,e.Torso.Mixins.cache,e.Torso.Mixins.loading))}(this,function(e,t,i,n,s){"use strict";var r=t.Collection.extend({filterDefault:function(){return this.constructor(this)},dispose:function(){this.unbind(),this.off(),this.stopListening(),this.stopPolling(),this.isRequester&&this.requesterDispose()}});return e.extend(r.prototype,i),r=(r=r.extend(s(r))).extend(n(r))}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone","./mixins/pollingMixin","./mixins/modelMixin"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone"),require("./mixins/pollingMixin"),require("./mixins/modelMixin")):(e.Torso=e.Torso||{},e.Torso.Mixins=e.Torso.Mixins||{},e.Torso.Model=t(e._,e.Backbone,e.Torso.Mixins.polling,e.Torso.Mixins.model))}(this,function(e,i,t,n){"use strict";var s=i.Model.extend({constructor:function(e,t){i.Model.apply(this,arguments),(t=t||{}).register&&this.__register(),this.trigger("post-initialize")}});return e.extend(s.prototype,t,n),s}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","./NestedModel","./mixins/cellMixin","./registry"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("./NestedModel"),require("./mixins/cellMixin"),require("./registry")):(e.Torso=e.Torso||{},e.Torso.NestedCell=t(e._,e.Torso.NestedModel,e.Torso.Mixins.cell,e.Torso.registry))}(this,function(e,t,i,n){"use strict";var s=t.extend({__register:function(){n.cellInitialized(this)}});return e.extend(s.prototype,i),s}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone","./mixins/pollingMixin","./mixins/modelMixin","backbone-nested"],t):"object"==typeof exports?(require("backbone-nested"),module.exports=t(require("underscore"),require("backbone"),require("./mixins/pollingMixin"),require("./mixins/modelMixin"))):(e.Torso=e.Torso||{},e.Torso.NestedModel=t(e._,e.Backbone,e.Torso.Mixins.polling,e.Torso.Mixins.model))}(this,function(e,i,t,n){"use strict";var s=i.NestedModel.extend({constructor:function(e,t){i.NestedModel.apply(this,arguments),(t=t||{}).register&&this.__register(),this.trigger("post-initialize")}});return e.extend(s.prototype,t,n),s}),function(e,t){if("function"==typeof define&&define.amd)define(["underscore","./NestedCell"],t);else if("object"==typeof exports){var i=require("underscore"),n=require("./NestedCell");module.exports=t(i,n)}else e.Torso=e.Torso||{},e.Torso.Behavior=t(e._,e.Torso.NestedCell)}(this,function(s,n){"use strict";var e={"before-attached-callback":"_attached","before-detached-callback":"_detached","before-activate-callback":"_activate","before-deactivate-callback":"_deactivate","before-dispose-callback":"_dispose","render:before-attach-tracked-views":"attachTrackedViews","render:begin":"prerender","render:complete":"postrender","initialize:begin":"preinitialize","initialize:complete":"postinitialize"};return n.extend({cidPrefix:"b",mixin:{},prepare:function(){},constructor:function(e,t,i){if(!(t=t||{}).view)throw new Error("Torso Behavior constructed without behaviorOptions.view");if(this.view=t.view,!t.alias)throw new Error("Torso Behavior constructed without behaviorOptions.alias");this.alias=t.alias,this.cid=this.cid||s.uniqueId(this.cidPrefix),this.__bindLifecycleMethods(),n.apply(this,arguments),this.__bindEventCallbacks()},__augmentViewPrepare:function(){var e=s.bind(this.view.prepare,this.view),t=s.wrap(e,this.__viewPrepareWrapper);this.view.prepare=s.bind(t,this)},__viewPrepareWrapper:function(e){var t=e()||{},i=s.omit(this.toJSON(),"view");return s.extend(i,this.prepare()),t[this.alias]=i,t},__bindLifecycleMethods:function(){this.listenTo(this.view,"initialize:complete",this.__augmentViewPrepare),this.listenTo(this.view,"before-dispose-callback",this.__dispose),s.each(e,function(e,t){this.listenTo(this.view,t,this[e])},this)},__bindEventCallbacks:function(){var e=s.result(this,"events"),t=this.view.events;if(!t){if(!e)return;t={}}var i=this.__namespaceEvents(e),n=this.__bindEventCallbacksToBehavior(i);s.isFunction(t)?this.view.events=s.wrap(s.bind(t,this.view),function(e){return s.extend(n,e())}):s.isObject(t)&&(this.view.events=s.extend(n,t))},__namespaceEvents:function(e){var r=/^(\S+)\s*(.*)$/,o={},a=this.cid;return s.each(e,function(e,t){var i=t.match(r),n=i[1],s=i[2];o[[n+".behavior."+a,s].join(" ")]=e}),o},__bindEventCallbacksToBehavior:function(e){return s.mapObject(e,function(e){return s.isFunction(e)||(e=this[e]),s.bind(e,this)},this)},__dispose:function(){this.trigger("before-dispose-callback"),this.stopListening(),this.off(),this.__isDisposed=!0},_dispose:function(){},isDisposed:function(){return this.__isDisposed}})}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","./Cell","./registry"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("./Cell"),require("./registry")):(e.Torso=e.Torso||{},e.Torso.ServiceCell=t(e._,e.Torso.Cell,e.Torso.registry))}(this,function(t,i,e){"use strict";return i.extend({constructor:function(){var e=Array.prototype.slice.call(arguments);e[1]=e[1]||{},e[1].register=t.isUndefined(e[1].register)||t.isNull(e[1].register)||e[1].register,i.apply(this,e)},__register:function(){e.serviceInitialized(this)}})}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone","./templateRenderer","./Cell","./NestedCell","./registry"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone"),require("./templateRenderer"),require("./Cell"),require("./NestedCell"),require("./registry")):(e.Torso=e.Torso||{},e.Torso.View=t(e._,e.Backbone,e.Torso.Utils.templateRenderer,e.Torso.Cell,e.Torso.NestedCell,e.Torso.registry))}(this,function(u,s,r,t,i,n){"use strict";var f=s.$,o=i.extend({initialize:function(e,t){t=t||{},this.view=t.view},trigger:function(e){"change"!==e&&0!==e.indexOf("change:")||a.prototype.trigger.apply(this.view,arguments),0===e.indexOf("change:hide:")&&this.view.render(),i.prototype.trigger.apply(this,arguments)}}),a=s.View.extend({viewState:null,template:void 0,feedback:null,feedbackCell:null,behaviors:null,templateRendererOptions:void 0,prepareFields:null,injectionSites:null,__behaviorInstances:null,__childViews:null,__sharedViews:null,__isActive:!1,__isAttachedToParent:!1,__isDisposed:!1,__attachedCallbackInvoked:!1,__feedbackOnEvents:null,__feedbackListenToEvents:null,constructor:function(e){e=e||{},this.viewState=new o({},{view:this}),this.feedbackCell=new t,this.__childViews={},this.__sharedViews={},this.__injectionSiteMap={},this.__feedbackOnEvents=[],this.__feedbackListenToEvents=[],this.template=e.template||this.template,this.templateRendererOptions=e.templateRendererOptions||this.templateRendererOptions,this.__initializeBehaviors(e),this.trigger("initialize:begin"),s.View.apply(this,arguments),this.trigger("initialize:complete"),e.noActivate||this.activate(),(u.isUndefined(e.register)||u.isNull(e.register)||e.register)&&n.viewInitialized(this)},get:function(){return this.viewState.get.apply(this.viewState,arguments)},set:function(){return this.viewState.set.apply(this.viewState,arguments)},has:function(){return this.viewState.has.apply(this.viewState,arguments)},unset:function(){return this.viewState.unset.apply(this.viewState,arguments)},toJSON:function(){return this.viewState.toJSON()},getBehavior:function(e){if(this.__behaviorInstances)return this.__behaviorInstances[e]},prepare:function(){return this.__getPrepareFieldsContext()},_prepare:function(){},render:function(){if(this.isDisposed())throw new Error("Render called on a view that has already been disposed.");var e=this;if(this.trigger("render:begin"),!1===this.prerender())return this.trigger("render:aborted"),f.Deferred().resolve().promise();this.__updateInjectionSiteMap(),this.trigger("render:before-dom-update"),this.detachTrackedViews(),this.updateDOM(),this.__pendingAttachInfo&&this.__performPendingAttach(),this.trigger("render:after-dom-update"),this.delegateEvents(),this.trigger("render:after-delegate-events"),this.unregisterTrackedViews({shared:!0}),this.trigger("render:before-attach-tracked-views"),this.__attachViewsFromInjectionSites();var t=this.attachTrackedViews();return f.when.apply(f,u.flatten([t])).done(function(){e.postrender(),e.trigger("render:complete"),e.__injectionSiteMap={},e.__lastTrackedViews={}})},prerender:function(){},updateDOM:function(){if(this.template){var e=u.result(this,"templateRendererOptions");this.templateRender(this.$el,this.template,this.prepare(),e)}},updateClassName:function(e){void 0===e?this.$el.removeAttr("class"):this.$el.attr("class",e)},postrender:function(){},templateRender:function(e,t,i,n){n=n||{},u.isString(t)&&(n.newHTML=t),r.render(e,t,i,n)},delegateEvents:function(){this.undelegateEvents(),s.View.prototype.delegateEvents.call(this),this.__generateFeedbackBindings(),this.__generateFeedbackCellCallbacks(),u.each(this.getTrackedViews(),function(e){e.isAttachedToParent()&&e.delegateEvents()})},undelegateEvents:function(){s.View.prototype.undelegateEvents.call(this),u.each(this.getTrackedViews(),function(e){e.undelegateEvents()})},attachTo:function(e,t){t=t||{};var i=this;return this.isAttachedToParent()?f.Deferred().resolve().promise():(this.__pendingAttachInfo={$el:e,options:t},this.render().done(function(){!i.__attachedCallbackInvoked&&i.isAttached()&&i.__invokeAttached(),i.__isAttachedToParent=!0}))},attachView:function(e,t,i){var n,s;if(i=i||{},u.isString(e)){if(s=e,!(n=this.$("[inject="+s+"]")))throw"View.attachView: No injection site found with which to attach this view. View.cid="+this.cid}else n=e;return i.useTransition?this.__transitionNewViewIntoSite(s,t,i):(t.detach(),this.registerTrackedView(t,i),t.attachTo(n,i),i.noActivate||t.activate(),f.Deferred().resolve().promise())},attachTrackedViews:function(){},_attached:function(){},isAttachedToParent:function(){return this.__isAttachedToParent},isAttached:function(){return this.$el&&f.contains(document,this.$el[0])},detach:function(){var e;this.isAttachedToParent()&&(e=this.isAttached(),this.trigger("before-dom-detach"),this.injectionSite?(this.$el.replaceWith(this.injectionSite),this.injectionSite=void 0):this.$el.detach(),e&&this.__invokeDetached(),this.undelegateEvents(),this.__isAttachedToParent=!1)},detachTrackedViews:function(e){var t=this.getTrackedViews(e);u.each(t,function(e){e.detach()})},_detached:function(){},activate:function(){this.__activateTrackedViews(),this.isActive()||(this.trigger("before-activate-callback"),this._activate(),this.__isActive=!0)},_activate:function(){},isActive:function(){return this.__isActive},deactivate:function(){this.__deactivateTrackedViews(),this.isActive()&&(this.trigger("before-deactivate-callback"),this._deactivate(),this.__isActive=!1)},_deactivate:function(){},dispose:function(){this.trigger("before-dispose"),this.trigger("before-dispose-callback"),this._dispose(),this.detach(),this.deactivate(),this.__disposeChildViews(),this.$el&&this.remove(),this.off(),this.stopListening(),this.viewState&&(this.viewState.off(),this.viewState.stopListening()),this.feedbackCell&&(this.feedbackCell.off(),this.feedbackCell.stopListening()),delete this.$el,delete this.el,this.__isDisposed=!0,this.trigger("after-dispose")},_dispose:function(){},isDisposed:function(){return this.__isDisposed},hasTrackedViews:function(e){return!u.isEmpty(this.getTrackedViews(e))},getTrackedViews:function(e){return u.values(this.__getTrackedViewsHash(e))},getTrackedView:function(e){var t=this.__childViews[e],i=this.__sharedViews[e];return t||i},registerTrackedView:function(e,t){return t=t||{},this.unregisterTrackedView(e),t.child||!t.shared?this.__childViews[e.cid]=e:this.__sharedViews[e.cid]=e,e},unregisterTrackedView:function(e){return delete this.__childViews[e.cid],delete this.__sharedViews[e.cid],e},unregisterTrackedViews:function(t){var e=this.getTrackedViews(t);u.each(e,function(e){this.unregisterTrackedView(e,t)},this)},transitionOut:function(e,t){this.detach(),e()},transitionIn:function(e,t,i){e(),t()},invokeFeedback:function(i,e,t){var n,s=u.find(this.feedback,function(e){var t=e.to;return u.isArray(t)?u.contains(t,i):i===t}),r=i;s&&(t&&(r=this.__substituteIndicesUsingMap(i,t)),n=s.then.call(this,e,t),this.__processFeedbackThenResult(n,r))},__attachViewsFromInjectionSites:function(){var e=u.result(this,"injectionSites");u.each(e,function(e,t){if(!this.get("hide:"+t)){var i,n={};u.isFunction(e)&&(e=e.call(this)),e instanceof s.View?i=e:u.isObject(e)&&(n=e.options,e=e.view),i||(u.isString(e)?i=u.result(this,e):e instanceof s.View?i=e:u.isFunction(e)&&(i=e.call(this))),i&&this.attachView(t,i,n)}},this)},__getPrepareFieldsContext:function(){var e={},t=u.result(this,"prepareFields");if(t&&u.isObject(t)&&!u.isArray(t)){var i=u.keys(t);t=u.map(i,function(e){return{name:e,value:t[e]}})}if((t=u.union(t,[{name:"view",value:"viewState"},"model"]))&&0<t.length)for(var n=0;n<t.length;n++){var s=t[n],r=u.isString(s),o=s,a=s;if(!r){if(!u.isString(s.name))throw"prepareFields items need to either be a string or define a .name property that is a simple string to use for the key in the template context.";if(u.isUndefined(s.value))throw"prepareFields items need a value property if it is not a string.";o=s.name,a=s.value}if(!u.isUndefined(e[o]))throw"duplicate prepareFields name ("+o+"). Note 'view' and 'model' are reserved names.";var d=!1;if(u.isFunction(a))a=a.call(this);else{var c=u.result(this,a);(d=!u.isUndefined(c))&&(a=c)}a&&u.isFunction(a.toJSON)?e[o]=a.toJSON():r&&!d||(e[o]=a)}var l=this._prepare(e);return l=u.isUndefined(l)?e:u.extend(e,l)},__initializeBehaviors:function(a){var d=this;u.isEmpty(this.behaviors)||(d.__behaviorInstances={},u.each(this.behaviors,function(e,t){u.has(e,"behavior")||(e={behavior:e});var i=e.behavior;if(!i||!u.isFunction(i))throw new Error('Incorrect behavior definition. Expected key "behavior" to be a class but instead got '+String(i));var n=u.pick(e,function(e,t){return"behavior"!==t});n.view=d,n.alias=t;var s=e.attributes||{},r=d.__behaviorInstances[t]=new i(s,n,a);if(r.mixin){var o=u.result(r,"mixin");u.each(o,function(e,t){u.isUndefined(d[t])&&(u.isFunction(e)?d[t]=u.bind(e,r):d[t]=e)})}}))},__performPendingAttach:function(){this.trigger("before-dom-attach"),this.__replaceInjectionSite(this.__pendingAttachInfo.$el,this.__pendingAttachInfo.options),delete this.__pendingAttachInfo},__deactivateTrackedViews:function(e){u.each(this.getTrackedViews(e),function(e){e.deactivate()})},__activateTrackedViews:function(e){u.each(this.getTrackedViews(e),function(e){e.activate()})},__disposeChildViews:function(){u.each(this.__childViews,function(e){e.dispose()})},__transitionNewViewIntoSite:function(e,t,i){var n,s;return n=(n=(i=i||{}).previousView)||this.__injectionSiteMap[e],u.defaults(i,{parentView:this,newView:t,previousView:n}),i.useTransition=!1,n==t?this.attachView(e,t,i):n?this.__performTwoWayTransition(e,n,t,i):(s=this.$("[inject="+e+"]"),this.__transitionInView(s,t,i))},__performTwoWayTransition:function(e,t,i,n){var s,r,o=f.Deferred();return this.attachView(e,t,n),n.cachedInjectionSite=t.injectionSite,s=n.newInjectionSite=f('<span inject="'+e+'">'),n.addBefore?t.$el.before(s):t.$el.after(s),t.injectionSite=void 0,t.transitionOut(o.resolve,n),r=this.__transitionInView(s,i,n),f.when(o.promise(),r)},__transitionInView:function(e,t,i){var n=f.Deferred(),s=this;return i=u.extend({},i),u.defaults(i,{parentView:this,newView:t}),t.transitionIn(function(){s.attachView(e,t,i)},n.resolve,i),n.promise()},__getTrackedViewsHash:function(e){var t={};return(e=e||{}).shared&&(t=u.extend(t,this.__sharedViews)),e.child&&(t=u.extend(t,this.__childViews)),e.child||e.shared||(t=u.extend(t,this.__sharedViews,this.__childViews)),t},__updateInjectionSiteMap:function(){var t=this;this.__injectionSiteMap={},this.__lastTrackedViews={},u.each(this.getTrackedViews(),function(e){e.isAttachedToParent()&&e.injectionSite&&(t.__injectionSiteMap[e.injectionSite.attr("inject")]=e),t.__lastTrackedViews[e.cid]=e})},__replaceInjectionSite:function(e,t){t=t||{},this.injectionSite=t.replaceMethod?t.replaceMethod(this.$el):e.replaceWith(this.$el),t.discardInjectionSite&&(this.injectionSite=void 0)},__invokeAttached:function(){this.__attachedCallbackInvoked||(this.trigger("before-attached-callback"),this._attached(),this.__attachedCallbackInvoked=!0,u.each(this.getTrackedViews(),function(e){e.isAttachedToParent()&&e.__invokeAttached()}))},__invokeDetached:function(){this.__attachedCallbackInvoked&&(this.trigger("before-detached-callback"),this._detached(),this.__attachedCallbackInvoked=!1),u.each(this.getTrackedViews(),function(e){e.isAttachedToParent()&&e.__invokeDetached()})},__generateFeedbackCellCallbacks:function(){var s=this;s.feedbackCell.off(),u.each(this.$("[data-feedback]"),function(e){var t,i=f(e).data("feedback");s.feedbackCell.on("change:"+i,(t=i,function(){var n,e=s.feedbackCell.get(t);e&&(n=s.$el.find('[data-feedback="'+t+'"]'),u.each(e,function(e,t){var i;i="_"===u.first(t)?s[t.slice(1)]:n[t],u.isArray(e)?i.apply(n,e):void 0!==e&&i.call(n,e)}))}))}),u.each(s.feedbackCell.attributes,function(e,t){s.feedbackCell.trigger("change:"+t)})},__processFeedbackThenResult:function(e,t){var i=f.extend({},e);this.feedbackCell.set(t,i,{silent:!0}),this.feedbackCell.trigger("change:"+t)},__generateFeedbackBindings:function(){var e,h=this;for(e=0;e<this.__feedbackOnEvents.length;e++)this.off(null,this.__feedbackOnEvents[e]);for(e=0;e<this.__feedbackListenToEvents.length;e++){var t=this.__feedbackListenToEvents[e];this.stopListening(t.obj,t.name,t.callback)}this.__feedbackOnEvents=[],this.__feedbackListenToEvents=[],u.each(this.feedback,function(l){var e=[l.to];u.isArray(l.to)&&(e=l.to),u.each(e,function(e){var t=h.__getFeedbackDestinations(e),c=h.__getAllIndexTokens(e);u.each(t,function(e){var t,i,n,s,r,o,a,d;t=(e=f(e)).data("feedback"),i=h.__getAllIndexTokens(t),n={},u.each(c,function(e,t){n[e]=i[t]}),s=l.then,u.isString(s)?s=h[s]:u.isArray(s)&&(o=(r=s.slice())[0],r.shift(),s=h[o].apply(h,r)),d={feedbackCellField:t,fn:s,indices:n},a=h.__generateWhenEvents(l.when,n),u.each(a,function(e){var t,i;i=/^(\S+)\s*(.*)$/,t=e.match(i),h.$el.on(t[1]+".delegateEvents"+h.cid,t[2],u.bind(function(e){var t,i;(t=[e]).push(d.indices),i=d.fn.apply(h,t),h.__processFeedbackThenResult(i,d.feedbackCellField)},h))}),u.each(l.when.on,function(e){var t=h.__generateThenCallback(d,e);h.on(e,t,h),h.__feedbackOnEvents.push(t)}),u.each(l.when.listenTo,function(e){var t=e.object;if(u.isFunction(t)?t=u.bind(e.object,h)():u.isString(t)&&(t=u.result(h,e.object)),t){var i=u.bind(h.__generateThenCallback(d,e.events),h);h.listenTo(t,e.events,i),h.__feedbackListenToEvents.push({object:t,name:e.events,callback:i})}})})})})},__generateThenCallback:function(i,n){return function(){var e,t=[{args:arguments,type:n}];t.push(i.indices),e=i.fn.apply(this,t),this.__processFeedbackThenResult(e,i.feedbackCellField)}},__getFeedbackDestinations:function(e){var t=this,i=this.__stripAllAttribute(e),n=e,s=e.indexOf("[");return 0<s&&(n=e.substring(0,s)),this.$('[data-feedback^="'+n+'"]').filter(function(){return t.__stripAllAttribute(f(this).data("feedback"))===i})},__generateWhenEvents:function(e,r){var o=this,a=[];return u.each(e,function(e,t){var i,n=[t],s="@"===t.charAt(0);"on"!==t&&"listenTo"!==t&&(s&&(t=t.substring(1),i=o.__substituteIndicesUsingMap(t,r),n=u.flatten(o.__generateSubAttributes(i,o.model))),u.each(n,function(i){u.each(e,function(e){var t=e+" "+i;s&&(t=e+' [data-model="'+i+'"]'),a.push(t)})}))}),a},__getAllIndexTokens:function(e){return u.reduce(e.match(/\[.+?\]/g),function(e,t){var i=t.substring(1,t.length-1);return isNaN(i)?e.push(i):e.push(parseInt(i,10)),e},[])},__stripAllAttribute:function(e){return e=e.replace(/\[.+?\]/g,function(){return"[]"})},__substituteIndicesUsingMap:function(e,t){var i;return e.replace(/\[[^\]]*\]/g,function(e){return e.match(/\[\d+\]/g)||e.match(/\[\]/g)?e:(i=t[e.substring(1,e.length-1)],u.isString(i)?"."+i:"["+(void 0===i?"":i)+"]")})},__generateSubAttributes:function(e,i){var t=e.indexOf("[]");if(-1===t)return[e];var n,s=e.substring(0,t),r=e.substring(t+2),o=[],a=i.get(s);return a?(n=u.isArray(a)?u.range(a.length):u.keys(a),u.each(n,function(e){var t="["+e+"]";u.isString(e)&&(t="."+e),o.push(this.__generateSubAttributes(s+t+r,i))},this),o):[e]}});return a}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","./NestedModel"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("./NestedModel")):(e.Torso=e.Torso||{},e.Torso.Mixins=e.Torso.Mixins||{},e.Torso.validation=t(e._,e.Torso.NestedModel),e.Torso.Mixins.validation=e.Torso.validation.mixin)}(this,function(c,t){"use strict";var l,h,d,u,i={forceUpdate:!1,selector:"name",labelFormatter:"sentenceCase",messageFormatter:"none",valid:Function.prototype,invalid:Function.prototype},f={formatLabel:function(e,t){return m[i.labelFormatter](e,t)},format:function(){return b[i.messageFormatter].apply(b,arguments)}},p=function(i,n,s){return n=n||{},s=s||"",c.each(i,function(e,t){i.hasOwnProperty(t)&&(e&&"object"==typeof e&&e.constructor===Object&&p(e,n,s+t+"."),n[s+t]=e)}),n},e=(h=function(e,i,n){var s,r,o,a,t=e.indexOf("[]");if(c.isEmpty(n)&&(n=[]),-1===t)return{attr:e,index:n};s=e.substring(0,t),r=e.substring(t+2),o=[];var d=i.get(s);return c.each(d,function(e,t){(a=n.slice()).push(t),o.push(h(s+"["+t+"]"+r,i,a))}),o},d=function(i,e,n,s,r,o){var t,a;return c.isArray(e)?c.reduce(e,function(e,t){return e.push(d(i,t,n,s,r,o+1)),e},[]):(a=e.index,t=e.attr,c.isUndefined(n)&&function(e){return 0<e.indexOf(".")||0<e.indexOf("]")}(t)&&(n=i.get(t)),u(r,i,n,t,s,a))},u=function(e,s,r,o,a,d){return c.reduce(e,function(e,t){var i=c.extend({msgKey:t.msgKey},f,F),n=t.fn.call(i,r,o,t.val,s,a,d);return!1!==n&&!1!==e&&(n&&!e?c.result(c.extend({},t,f,F),"msg")||n:e)},"")},{version:"0.11.3",configure:function(e){c.extend(i,e)},mixin:(l=i,{preValidate:function(e,t){var i,n=this,s={};return c.isArray(e)?(c.each(e,function(e){(i=n.preValidate(e))&&(s[e]=i)}),c.isEmpty(s)?void 0:s):c.isObject(e)?(c.each(e,function(e,t){(i=n.preValidate(t,e))&&(s[t]=i)}),c.isEmpty(s)?void 0:s):(c.isUndefined(t)&&r(this)&&(t=this.get(e)),o(this,t,e))},isValid:function(e){var t,i,n;return e=e||_(l),c.isString(e)?t=[e]:c.isArray(e)&&(t=e),t&&c.each(t,function(e){var t;t=r(this)?this.get(e):p(this.attributes)[e],(i=o(this,t,e))&&((n=n||{})[e]=i)},this),!0===e&&(n=this.validate()),n&&this.trigger("invalid",this,n,{validationError:n}),t?!n:!this.validation||this._isValid},validate:function(e,t){var i=this,n=c.extend({},l,t),s=function(e,t){return t=t||c.keys(c.result(e,"validation")||{}),c.reduce(t,function(e,t){return e[t]=void 0,e},{})}(i,_(l)),r=c.extend({},s,i.attributes,e),o=c.extend(p(r),e),a=e?p(e):o,d=function(i,e,t){var n,s={},r=!0,o=c.clone(e);return c.each(t,function(e,t){(n=g(i,t,e,o))&&(s[t]=n,r=!1)}),{invalidAttrs:s,isValid:r}}(i,r,c.pick(o,c.keys(s)));if(i._isValid=d.isValid,c.defer(function(){i.trigger("validated",i._isValid,i,d.invalidAttrs),i.trigger("validated:"+(i._isValid?"valid":"invalid"),i,d.invalidAttrs)}),!n.forceUpdate&&0<c.intersection(c.keys(d.invalidAttrs),c.keys(a)).length)return d.invalidAttrs}})});function _(e){var t=e.attributes;if(c.isFunction(t)&&(t=t()),c.isArray(t))return t}function a(e,t){var i=e.validation&&c.result(e,"validation")[t]||{};return(c.isFunction(i)||c.isString(i))&&(i={fn:i}),c.isArray(i)||(i=[i]),c.reduce(i,function(t,i){return c.each(c.without(c.keys(i),"msg","msgKey"),function(e){t.push({fn:F[e],val:i[e],msg:i.msg,msgKey:i.msgKey})}),t},[])}function r(e){return t&&e instanceof t}function g(e,t,i,n){var s,r,o=a(e,t);return s=h(t,e),r=d(e,s,i,n,o,0),c.isArray(r)&&!c.reduce(c.flatten(r),function(e,t){return e||t},!1)?"":r}function o(e,t,i){var n,s,r=e.validation&&c.result(e,"validation")||{};return c.contains(c.keys(r),i)?g(e,i,t,c.extend({},e.attributes)):(n=function(e){var t,i,n=0,s=!0,r=[];for(t=e.indexOf("[",n);0<t&&s;)i=e.indexOf("]",n),r.push(parseInt(e.substring(t+1,i),10)),s=0<(n=i+1),t=e.indexOf("[",n);return r}(i),i=function(e){var t,i,n=0,s=!0;if((t=e.indexOf("[",n))<0)return e;for(i=e.substring(0,t+1);0<t&&s;)s=0<(n=e.indexOf("]",n)+1),0<(t=e.indexOf("[",n))&&(i+=e.substring(n-1,t+1));return i+=e.substring(n-1)}(i),s=a(e,i),u(s,e,t,i,c.extend({},e.attributes),n))}var n,s=e.patterns={digits:/^\d+$/,number:/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/,email:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,url:/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i},v=e.messages={required:"{0} is required",acceptance:"{0} must be accepted",min:"{0} must be greater than or equal to {1}",max:"{0} must be less than or equal to {1}",range:"{0} must be between {1} and {2}",length:"{0} must be {1} characters",minLength:"{0} must be at least {1} characters",maxLength:"{0} must be at most {1} characters",rangeLength:"{0} must be between {1} and {2} characters",oneOf:"{0} must be one of: {1}",equalTo:"{0} must be the same as {1}",digits:"{0} must only contain digits",number:"{0} must be a number",email:"{0} must be a valid email",url:"{0} must be a valid url",inlinePattern:"{0} is invalid"},m=e.labelFormatters={none:function(e){return e},sentenceCase:function(e){return e.replace(/(?:^\w|[A-Z]|\b\w)/g,function(e,t){return 0===t?e.toUpperCase():" "+e.toLowerCase()}).replace(/_/g," ")},label:function(e,t){return t.labels&&t.labels[e]||m.sentenceCase(e,t)}},b=e.messageFormatters={none:function(){var i=Array.prototype.slice.call(arguments);return i.shift().replace(/\{(\d+)\}/g,function(e,t){return void 0!==i[t]?i[t]:e})}},F=e.validators=(n=String.prototype.trim?function(e){return null===e?"":String.prototype.trim.call(e)}:function(e){return null===e?"":e.toString().replace(/^\s+/,"").replace(/\s+$/,"")},{format:f.format,formatLabel:f.formatLabel,fn:function(e,t,i,n,s){return c.isString(i)&&(i=n[i]),i.call(n,e,t,s)},inlineFn:function(e,t,i,n,s,r){return i.call(this,e,t,n,s,r)},required:function(e,t,i,n,s){var r=c.isFunction(i)?i.call(n,e,t,s):i;return!(!r&&!w(e))&&(r&&!w(e)?this.format(k(this.msgKey,v.required),this.formatLabel(t,n)):void 0)},acceptance:function(e,t,i,n){if("true"!==e&&(!c.isBoolean(e)||!1===e))return this.format(k(this.msgKey,v.acceptance),this.formatLabel(t,n))},min:function(e,t,i,n){if(!T(e)||e<i)return this.format(k(this.msgKey,v.min),this.formatLabel(t,n),i)},max:function(e,t,i,n){if(!T(e)||i<e)return this.format(k(this.msgKey,v.max),this.formatLabel(t,n),i)},range:function(e,t,i,n){if(!T(e)||e<i[0]||e>i[1])return this.format(k(this.msgKey,v.range),this.formatLabel(t,n),i[0],i[1])},length:function(e,t,i,n){if(!c.isString(e)||e.length!==i)return this.format(k(this.msgKey,v.length),this.formatLabel(t,n),i)},minLength:function(e,t,i,n){if(!c.isString(e)||e.length<i)return this.format(k(this.msgKey,v.minLength),this.formatLabel(t,n),i)},maxLength:function(e,t,i,n){if(!c.isString(e)||e.length>i)return this.format(k(this.msgKey,v.maxLength),this.formatLabel(t,n),i)},rangeLength:function(e,t,i,n){if(!c.isString(e)||e.length<i[0]||e.length>i[1])return this.format(k(this.msgKey,v.rangeLength),this.formatLabel(t,n),i[0],i[1])},oneOf:function(e,t,i,n){if(!c.include(i,e))return this.format(k(this.msgKey,v.oneOf),this.formatLabel(t,n),i.join(", "))},equalTo:function(e,t,i,n,s){if(e!==s[i])return this.format(k(this.msgKey,v.equalTo),this.formatLabel(t,n),this.formatLabel(i,n))},pattern:function(e,t,i,n){if(!w(e)||!e.toString().match(s[i]||i))return this.format(k(this.msgKey,v[i])||v.inlinePattern,this.formatLabel(t,n),i)}});function T(e){return c.isNumber(e)||c.isString(e)&&e.match(s.number)}function w(e){return!(c.isNull(e)||c.isUndefined(e)||c.isString(e)&&""===n(e)||c.isArray(e)&&c.isEmpty(e))}function k(e,t){return e||t}return e}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone","./NestedModel","./validation"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone"),require("./NestedModel"),require("./validation")):(e.Torso=e.Torso||{},e.Torso.FormModel=t(e._,e.Backbone,e.Torso.NestedModel,e.Torso.validation))}(this,function(h,e,r,t){"use strict";var o=e.$,i=r.extend({mapping:void 0,models:void 0,constructor:function(e,t){t=t||{},this.__cache={},this.__currentUpdateEvents=[],this.__currentMappings={},this.__currentObjectModels={},this.validation=h.extend({},this.validation,t.validation),this.labels=h.extend({},this.labels,t.labels),r.apply(this,arguments),this.__initMappings(t),this.pull(),e&&this.set(e),t.startUpdating&&this.startUpdating(),this.trigger("initialization-complete")},getMapping:function(e){return this.__currentMappings[e]},getMappings:function(){return this.__currentMappings},setMapping:function(e,t,i,n){var s,r,o={};h.isString(t)?r=t.split(" "):!0===t?r=void 0:h.isObject(t)&&(t=h.clone(t),s=!0),(o.computed=s)?(o.mapping=t,h.each(this.__getModelAliases(o),function(e){var t=o.mapping[e];h.isString(t)?t=t.split(" "):!0===t&&(t=void 0),o.mapping[e]=t})):o.mapping=r,this.__currentMappings[e]=o,i&&(s?this.trackModels(i,n):this.trackModel(e,i,n))},setMappings:function(e,t,i){h.each(e,function(e,t){this.setMapping(t,e)},this),t&&this.trackModels(t,i)},unsetMapping:function(e,t){var i=this.__findAlias(e);i&&delete this.__currentMappings[i];var n=this.getTrackedModel(i);t&&n&&h.isEmpty(this.__getTrackedModelFields(n))&&this.untrackModel(n)},unsetMappings:function(){this.__currentMappings={},this.resetUpdating()},getTrackedModel:function(e){return this.__currentObjectModels[e]},getTrackedModels:function(){return h.values(this.__currentObjectModels)},setTrackedModel:function(){this.trackModel.apply(this,arguments)},trackModel:function(n,e,t){this.__currentObjectModels[n]=e,this.__updateCache(e),this.resetUpdating(),t&&h.each(this.getMappings(),function(e,t){var i;n===t&&this.__pull(t),e.computed&&(i=this.__getModelAliases(t),h.contains(i,n)&&this.__pull(t))},this)},setTrackedModels:function(){this.trackModels.apply(this,arguments)},trackModels:function(e,i){h.each(e,function(e,t){this.trackModel(t,e,i)},this)},unsetTrackedModel:function(){this.untrackModel.apply(this,arguments)},untrackModel:function(e){var t,i=this.__findAlias(e);i&&(t=this.__currentObjectModels[i],delete this.__currentObjectModels[i],this.__updateCache(t)),this.resetUpdating()},unsetTrackedModels:function(){this.untrackModels.apply(this,arguments)},untrackModels:function(){this.__currentObjectModels=[],this.__updateCache(),this.resetUpdating()},push:function(){h.each(this.getMappings(),function(e,t){this.__push(t)},this)},pull:function(){h.each(this.getMappings(),function(e,t){this.__pull(t)},this),this.__updateCache()},save:function(e){var t,i,n=new o.Deferred,s=this;e=e||{},h.defaults(e,{rollback:!0,force:!0});try{i=h.result(s,"url")}catch(e){}return i?r.prototype.save.apply(s,arguments).done(function(){s.push()}):this.isTrackingAnyObjectModel()?(this.__saveToModels(n,e),n.promise()):(t={none:{success:!1,response:[{responseJSON:{generalReasons:[{messageKey:"no.models.were.bound.to.form"}]}}]}},this.trigger("save-fail",t),(new o.Deferred).reject(t).promise())},isTrackingAnyObjectModel:function(){return 0<h.size(this.__currentObjectModels)},isUpdating:function(){return 0<this.__currentUpdateEvents.length},startUpdating:function(e){this.isTrackingAnyObjectModel()&&!this.isUpdating()&&(e&&this.pull(),this.__setupListeners())},stopUpdating:function(){h.each(this.__currentUpdateEvents,function(e){this.stopListening(e.model,e.eventName)},this),this.__currentUpdateEvents=[]},resetUpdating:function(){this.isUpdating()&&(this.stopUpdating(),this.startUpdating())},isModelStale:function(e,t,i){var n;(i=i||{})[e.cid]||(i[e.cid]=this.__generateHashValue(e)),n=i[e.cid];var s=this.__cache[e.cid]!==n;return t&&(s?t[e.cid]=e:t[e.cid]&&delete t[e.cid]),s},checkIfModelsAreStale:function(){var t={},i=this.__generateAllHashValues();return h.each(this.getTrackedModels(),function(e){this.isModelStale(e,t,i)},this),h.values(t)},__listenToModelField:function(e,t){var i,n;i=t?(n="change:"+t,h.bind(this.__updateFormField,{formModel:this,field:t})):(n="change",this.__updateFormModel),this.listenTo(e,n,i),this.__currentUpdateEvents.push({model:e,eventName:n})},__listenToComputedValuesDependency:function(e,t,i){var n,s;s=t?"change:"+t:"change",n=h.bind(this.__invokeComputedPull,{formModel:this,alias:i}),this.listenTo(e,s,n),this.__currentUpdateEvents.push({model:e,eventName:s})},__getComputedModels:function(e){var i=!h.isUndefined(this.getMapping(e)),n={};return h.each(this.__getModelAliases(e),function(e){var t=this.getTrackedModel(e);t?n[e]=t:i=!1},this),i?n:void 0},__getModelAliases:function(e){var t;return t=h.isString(e)?this.getMapping(e):e,h.filter(h.keys(t.mapping),function(e){return"pull"!=e&&"push"!=e})},__getComputedModelConfigs:function(e){var i=!0,n=this.getMapping(e),s=[];return h.each(this.__getModelAliases(e),function(e){var t=this.__createModelConfig(e,n.mapping[e]);t?s.push(t):i=!1},this),i?s:void 0},__saveToModels:function(n,s){var e,r=this,o=0,a=0,d={},c={},t=r.getTrackedModels(),l=t.length;if(!s.force&&0<(e=r.checkIfModelsAreStale()).length)throw{name:"Stale data",staleModels:e};function i(e,t,i){d[t.cid]={success:i,response:e},a+o===l&&(0<a?(s.rollback&&h.each(r.getTrackedModels(),function(e){e.set(c[e.cid]),d[e.cid].success&&e.save()}),r.trigger("save-fail",d),n.reject(d)):(r.trigger("save-success",d),n.resolve(d)))}h.each(t,function(e){c[e.cid]=r.__getTrackedModelFields(e)}),r.push(),h.each(t,function(e){e.save().fail(function(){a++,i(arguments,e,!1)}).done(function(){o++,i(arguments,e,!0)})})},__pull:function(e){var i=this.getMapping(e);if(i.computed&&i.mapping.pull)this.__invokeComputedPull.call({formModel:this,alias:e});else if(i.computed){var t=this.__getModelAliases(e);h.each(t,function(e){var t=this.getTrackedModel(e);t&&this.__copyFields(i.mapping[e],this,t)},this)}else{var n=this.getTrackedModel(e);n&&this.__copyFields(i.mapping,this,n)}},__push:function(e){var i=this.getMapping(e);if(i.computed&&i.mapping.push){var t=this.__getComputedModels(e);t&&i.mapping.push.call(this,t)}else if(i.computed){var n=this.__getModelAliases(e);h.each(n,function(e){var t=this.getTrackedModel(e);t&&this.__copyFields(i.mapping[e],t,this)},this)}else{var s=this.getTrackedModel(e);s&&this.__copyFields(i.mapping,s,this)}},__updateFormField:function(e,t){this.formModel.set(this.field,t),this.formModel.__updateCache(e)},__updateFormModel:function(e){h.each(e.changedAttributes(),function(e,t){this.set(t,this.__cloneVal(e))},this),this.__updateCache(e)},__updateCache:function(e){e?this.__cache[e.cid]=this.__generateHashValue(e):(this.__cache={},h.each(this.getTrackedModels(),function(e){e&&this.__updateCache(e)},this))},__hashValue:function(e){return JSON.stringify(e)},__findAlias:function(e){var t;return h.isString(e)?e:(t=e,h.find(this.__currentObjectModels,function(e){return e==t}))},__generateHashValue:function(e){var t=this.__getTrackedModelFields(e);return this.__hashValue(t)},__generateAllHashValues:function(){var t={};return h.each(this.getTrackedModels(),function(e){t[e.cid]=this.__generateHashValue(e)},this),t},__cloneVal:function(e){var t;if(h.isArray(e))t=[];else{if(!h.isObject(e))return e;t={}}return o.extend(!0,t,e)},__setupListeners:function(){var t,n,s=this;h.each(s.getMappings(),function(e,i){e.computed?(n=s.__getComputedModelConfigs(i),h.each(n,function(e){var t=e.model;e.fields?h.each(e.fields,function(e){s.__listenToComputedValuesDependency(t,e,i)}):s.__listenToComputedValuesDependency(t,"",i)})):(t=s.getTrackedModel(i))&&(e.mapping?h.each(e.mapping,function(e){s.__listenToModelField(t,e)}):s.__listenToModelField(t))})},__copyFields:function(e,t,i){(!e||!0===e)&&this===i&&1<h.size(this.getTrackedModels())&&(e=h.keys(t.attributes)),e?h.each(e,function(e){t.set(e,this.__cloneVal(i.get(e)))},this):t.set(this.__cloneVal(i.attributes))},__initMappings:function(e){var t,i,n=h.result(this,"mapping"),s=h.result(this,"models");t=e.mapping||n,i=e.models||s,t&&this.setMappings(t,i)},__getTrackedModelFields:function(t){var i={},n={},s=[];return h.each(this.__getAllModelConfigs(),function(e){e.model&&e.model.cid===t.cid&&s.push(e)}),h.reduce(s,function(e,t){return e||!t.fields},!1)?n=this.__cloneVal(t.attributes):h.each(s,function(e){h.each(e.fields,function(e){i[e]||(i[e]=!0,n[e]=this.__cloneVal(t.get(e)))},this)},this),n},__createModelConfig:function(e,t){var i=this.getTrackedModel(e);if(i)return{fields:t,model:i}},__getAllModelConfigs:function(){var s=[];return h.each(this.getMappings(),function(e,t){if(e.computed){var i=this.__getComputedModelConfigs(t);i&&(s=s.concat(i))}else{var n=this.__createModelConfig(t,e.mapping);n&&s.push(n)}},this),s},__invokeComputedPull:function(e){var s,t,r,o,i,a;e&&this.formModel.__updateCache(e),s=this.formModel,t=this.alias,r=!0,o=s.getMapping(t),i=s.__getModelAliases(t),a={},o.mapping.pull?(h.each(i,function(e){var t=o.mapping[e],i=s.getTrackedModel(e),n={};i?(t?h.each(t,function(e){n[e]=s.__cloneVal(i.get(e))}):n=s.__cloneVal(i.attributes),a[e]=n):r=!1}),r&&o.mapping.pull.call(s,a)):console&&h.isFunction(console.log)&&console.log("Not pulling the computed: "+t+", because no pull method was defined for this computed.")}});return h.extend(i.prototype,t.mixin),i}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone","./View","./templateRenderer"],t):"object"==typeof exports?module.exports=t(require("underscore"),require("backbone"),require("./View"),require("./templateRenderer")):(e.Torso=e.Torso||{},e.Torso.ListView=t(e._,e.Backbone,e.Torso.View,e.Torso.Utils.templateRenderer))}(this,function(u,e,i,n){"use strict";var s,r,o,c,a,d,l=e.$;return d=function(e){e.__delayedRenderTimeout&&(clearTimeout(e.__delayedRenderTimeout),e.__delayedRenderTimeout=null,e.isDisposed()||e.render())},a=function(e,t){function i(){t.__delayedRenderTimeout=null,t.isDisposed()||t.render()}return function(){!t.__delayedRenderTimeout&&0<e?t.__delayedRenderTimeout=setTimeout(i,e):e<=0&&!t.isDisposed()&&t.render()}},s=function(e){var t=this.getItemViewFromModel(e);t&&(r.call(this,t,e[this.__modelId],e),this.hasItemViews()||this.__delayedRender())},r=function(e,t,i){e.dispose(),this.unregisterTrackedView(e,{shared:!1}),delete this.__modelToViewMap[t],this.__updateOrderedModelIdList(),this.trigger("item-view-removed",{model:i||e.model,view:e}),this.trigger("child-view-removed",{model:i||e.model,view:e})},o=function(e){var t,i=this.modelsToRender().indexOf(e);-1<i&&(t=this.__createItemView(e),c.call(this,t,i))},c=function(e,t){var i,n,s,r=this.modelsToRender();this.hasItemViews()?(d(this),i=this.getItemViewFromModel(r[t+1]),n=this.getItemViewFromModel(r[t-1]),i?s=u.bind(i.$el.before,i.$el):n?s=u.bind(n.$el.after,n.$el):this.__delayedRender(),s&&this.attachView(null,e,{replaceMethod:s,discardInjectionSite:!0})):this.__delayedRender()},i.extend({collection:null,itemView:null,template:null,emptyTemplate:null,itemContainer:null,__modelName:"",__modelId:"",__modelToViewMap:null,__itemContext:null,__renderWait:0,__delayedRender:null,__delayedRenderTimeout:null,constructor:function(e){i.apply(this,arguments);var t=(e=e||{}).collection||this.collection;if(this.template=e.template||this.template,this.emptyTemplate=e.emptyTemplate||this.emptyTemplate,this.itemView=e.itemView||this.itemView,this.itemContainer=e.itemContainer||this.itemContainer,this.template&&!this.itemContainer)throw"Item container is required when using a template";this.modelsToRender=e.modelsToRender||this.modelsToRender,this.__itemContext=e.itemContext||this.__itemContext,this.__modelToViewMap={},this.__renderWait=e.renderWait||this.__renderWait,this.__modelId=e.modelId||this.modelId||"cid",this.__modelName=e.modelName||this.modelName||"model",this.__orderedModelIdList=[],this.__createItemViews(),this.__delayedRender=a(this.__renderWait,this),t&&this.setCollection(t,!0),this.on("render:after-dom-update",this.__cleanupItemViewsAfterAttachedToParent)},setCollection:function(e,t){this.stopListening(this.collection,"remove",s),this.stopListening(this.collection,"add",o),this.stopListening(this.collection,"sort",this.reorder),this.stopListening(this.collection,"reset",this.update),this.collection=e,this.listenTo(this.collection,"remove",s),this.listenTo(this.collection,"add",o),this.listenTo(this.collection,"sort",this.reorder),this.listenTo(this.collection,"reset",this.update),t||this.update()},updateDOM:function(){var e,t=l(n.copyTopElement(this.el));this.template?(t.html(this.template(this.prepare())),e=t.find("[inject="+this.itemContainer+"]")):(e=l("<span>"),t.append(e)),this.hasItemViews()?e.replaceWith(this.__emptyAndRebuildItemViewsFragment()):this.emptyTemplate&&e.replaceWith(this.emptyTemplate(this.prepareEmpty())),this.$el.html(t.contents())},__cleanupItemViewsAfterAttachedToParent:function(){u.each(this.modelsToRender(),function(e){var t=this.getItemViewFromModel(e);t&&(t.delegateEvents(),!t.__attachedCallbackInvoked&&t.isAttached()&&t.__invokeAttached(),t.activate())},this)},renderChildViews:function(){u.each(this.getTrackedViews({child:!0}),function(e){e.render()})},reorder:function(){var n,e,s=[],t=this.modelsToRender(),r=u.pluck(t,this.__modelId),i=u.size(r);if(!(i===u.size(this.__orderedModelIdList)))throw"Reorder should not be invoked if the number of models have changed";if(e=u.reduce(this.__orderedModelIdList,function(e,t,i){return e&&r[i]==t},!0),i&&!e){if(u.each(t,function(e,t){var i=this.getItemViewFromModel(e);i&&s.push(i.$el),0===t&&(n=i)},this),this.itemContainer){if(n){var o=l("<span>");n.$el.before(o),o.after(s),o.remove()}}else this.$el.append(s);this.__updateOrderedModelIdList(r),this.trigger("reorder-complete")}},prepareEmpty:function(){return this.prepare()},modelsToRender:function(){return this.collection?this.collection.models:[]},update:function(){var e=this.getItemViews(),t=this.__createItemViews(),i=this.__getStaleItemViews(),n=u.size(e),s=u.size(t),r=u.size(i),o=n-r+s,a=s+r,d=a/Math.max(o,1),c=!n&&s,l=n&&n===r&&!s,h=(this.updateThreshold||.5)<=d;if(a<=0)return this.reorder();c||l||h?(this.__removeStaleItemViews(i),this.__delayedRender()):this.__updateByAddingRemoving(e,t,i)},getItemViewFromModel:function(e){return e?this.getTrackedView(this.__modelToViewMap[e[this.__modelId]]):void 0},hasItemViews:function(){return!u.isEmpty(this.getItemViews())},getItemViews:function(){var e=u.map(this.__orderedModelIdList,this.__getViewIdFromModelId,this);return u.map(e,this.getTrackedView,this)},__createItemViews:function(){var i=[];return u.each(this.modelsToRender(),function(e,t){this.getItemViewFromModel(e)||i.push({view:this.__createItemView(e,!0),indexOfModel:t})},this),this.__updateOrderedModelIdList(),i},__createItemView:function(e,t){var i,n=this.itemView;return u.isFunction(this.itemView.extend)||(n=this.itemView(e)),i=new n(this.__generateItemViewArgs(e)),this.registerTrackedView(i,{shared:!1}),this.__modelToViewMap[e[this.__modelId]]=i.cid,t||this.__updateOrderedModelIdList(),this.trigger("child-view-added",{model:e,view:i}),this.trigger("item-view-added",{model:e,view:i}),i},__getStaleItemViews:function(){var n=[],t=u.clone(this.__modelToViewMap);return u.each(this.modelsToRender(),function(e){this.getItemViewFromModel(e)&&delete t[e[this.__modelId]]},this),u.each(t,function(e,t){var i=this.getTrackedView(e);i&&n.push({view:i,modelId:t})},this),n},__removeStaleItemViews:function(e){var t=this;e=e||this.__getStaleItemViews(),u.each(e,function(e){r.call(t,e.view,e.modelId)})},__emptyAndRebuildItemViewsFragment:function(){var i=document.createDocumentFragment();return this.$el.empty(),u.each(this.modelsToRender(),function(e){var t=this.getItemViewFromModel(e);t&&(t.detach(),this.registerTrackedView(t,{shared:!1}),t.attachTo(null,{replaceMethod:function(e){i.appendChild(e[0])},discardInjectionSite:!0}))},this),this.__updateOrderedModelIdList(),l(i)},__updateByAddingRemoving:function(e,t,r){var o,a,d=this,i=u.size(e),n=(u.size(t),u.size(r));d.itemContainer&&i&&i==n&&(a=l("<span>"),u.first(e).$el.before(a)),d.__removeStaleItemViews(r),u.each(t,function(e,t){if(0===e.indexOfModel){var i;if(d.itemContainer)if(a)i=u.bind(a.replaceWith,a);else{var n=u.indexBy(r,"modelId"),s=u.find(d.__orderedModelIdList,function(e){return!n[e]});o=d.getTrackedView(d.__modelToViewMap[s]),i=u.bind(o.$el.prepend,o.$el)}else i=u.bind(d.$el.prepend,d.$el);d.attachView(null,e.view,{replaceMethod:i,discardInjectionSite:!0})}else c.call(d,e.view,e.indexOfModel)}),this.reorder()},__updateOrderedModelIdList:function(e){this.__orderedModelIdList=e||u.pluck(this.modelsToRender(),this.__modelId)},__generateItemViewArgs:function(e){var t={context:u.extend({},u.result(this,"__itemContext")),listView:this};return t[this.__modelName]=e,t},__generateChildArgs:function(){return this.__generateItemViewArgs.apply(this,arguments)},__getViewIdFromModelId:function(e){return this.__modelToViewMap[e]}})}),function(e,t){if("function"==typeof define&&define.amd)define(["underscore","backbone","../Behavior","../Collection","../Events"],t);else if("object"==typeof exports){var i=require("underscore"),n=require("backbone"),s=require("../Behavior"),r=require("../Collection"),o=require("../Events");module.exports=t(i,n,s,r,o)}else e.Torso=e.Torso||{},e.Torso.behaviors=e.Torso.behaviors||{},e.Torso.behaviors.DataBehavior=t(e._,e.Backbone,e.Torso.Behavior,e.Torso.Collection,e.Torso.Events)}(this,function(d,e,n,t,i){"use strict";var c=e.$,s={SUCCESS:"success",FAILURE:"failed"};function l(e){return d.isArray(e)?(e=d.flatten(e),d.uniq(e)):d.isString(e)||d.isNumber(e)?[e]:e&&e.skipObjectRetrieval?e:void 0}function h(e){return(d.isUndefined(e)||d.isNull(e))&&(e=[]),e}function u(e,t){var i=(t=(t=t.replace(/\[(\w+)\]/g,".$1")).replace(/^\./,"")).split(".");return d.reduce(i,function(e,t){return d.isUndefined(e)?void 0:e[t]},e)}function f(e){return!!e&&-1<e.indexOf(":")}function r(e){this.initialize(e)}var o=n.extend({cache:void 0,renderOnFetch:!1,skipInitialLoad:!1,returnSingleResult:!1,alwaysFetch:!1,ids:void 0,updateEvents:void 0,data:void 0,FETCHED_STATUSES:s,constructor:function(e,t,i){d.bindAll(this,"__skipRetrieveOnEmptyTrackedIdsAndNewIds","__completeLoadingIds","__fetchSuccess","__fetchFailed","__abortIfDisposed"),t=t||{},t=d.defaults(t,{alwaysFetch:!1}),d.extend(this,d.pick(t,"cache","id","ids","renderOnFetch","skipInitialLoad","returnSingleResult","alwaysFetch","updateEvents")),this.__validateCache(),this.__normalizeAndValidateIds(),this.__normalizeAndValidateUpdateEvents(),this.cid=this.cid||d.uniqueId(this.cidPrefix),this.data=new this.Data({parentBehavior:this,privateCollection:this.cache.createPrivateCollection(this.cid)}),n.apply(this,arguments),this.set("loadingIds",0),this.on("id-container-updated",this.listenToIdsPropertyChangeEvent),this.on("id-container-updated",this.retrieve),this.listenTo(this.view,"initialize:complete",this.listenToIdsPropertyChangeEvent),this.listenTo(this.view,"initialize:complete",this._delegateUpdateEvents),this.skipInitialLoad||this.listenTo(this.view,"initialize:complete",this.retrieve),this.on("fetched",function(){this.renderOnFetch&&this.view.isActive()&&this.view.isAttached()&&this.view.render()}),this.listenTo(this.view,"before-dispose-callback",this.data.dispose)},retrieve:function(){return this.alwaysFetch?this.fetch():this.pull()},pull:function(){var t=this;return this.__getIds().then(this.__skipRetrieveOnEmptyTrackedIdsAndNewIds).then(this.__abortIfDisposed).then(function(e){return e&&!e.skipObjectRetrieval?t.data.privateCollection.trackAndPull(e):e},function(e){return e.failedOnIds=!0,(new c.Deferred).reject(e).promise()}).then(this.__fetchSuccess,this.__fetchFailed)},fetch:function(){var t=this;return this.__getIds().then(this.__skipRetrieveOnEmptyTrackedIdsAndNewIds).then(this.__abortIfDisposed).then(function(e){return e&&!e.skipObjectRetrieval?t.data.privateCollection.trackAndFetch(e):e},function(e){return e.failedOnIds=!0,(new c.Deferred).reject(e).promise()}).then(this.__fetchSuccess,this.__fetchFailed)},prepare:function(){var e=n.prototype.prepare.apply(this)||{};return e.data=this.data.toJSON(),e.loading=this.isLoading(),e.loadingIds=this.isLoadingIds(),e.loadingObjects=this.isLoadingObjects(),e},isLoading:function(){return this.isLoadingIds()||this.isLoadingObjects()},isLoadingIds:function(){return 0<this.get("loadingIds")},isLoadingObjects:function(){return this.data.privateCollection.isLoading()},listenToIdsPropertyChangeEvent:function(){if(!d.isUndefined(this.ids.property)){this.stopListeningToIdsPropertyChangeEvent();var e=this.__parseIdsPropertyNameAndIdContainer(),t=e.idContainer;t&&d.isFunction(t.on)&&(this.__currentContextWithListener=t,this.__currentContextEventName="change:"+e.idsPropertyName,this.listenTo(this.__currentContextWithListener,this.__currentContextEventName,this.retrieve),this.listenTo(this.__currentContextWithListener,"fetched:ids",this.retrieve))}},stopListeningToIdsPropertyChangeEvent:function(){this.__currentContextWithListener&&(this.stopListening(this.__currentContextWithListener,this.__currentContextEventName,this.retrieve),this.stopListening(this.__currentContextWithListener,"fetched:ids",this.retrieve),delete this.__currentContextWithListener,delete this.__currentContextEventName)},retrieveOncePromise:function(){var e=c.Deferred(),t=this.get("fetchSuccess");return t?e.resolve():!1===t?e.reject():this.once("fetched",function(){this.get("fetchSuccess")?e.resolve():e.reject()}),e.promise()},_delegateUpdateEvents:function(){this._undelegateUpdateEvents();var e=this.__parseUpdateEvents();d.each(e,function(e){this.listenTo(e.idContainer,e.eventName,this.retrieve)},this)},_undelegateUpdateEvents:function(){var e=this.__parseUpdateEvents();d.each(e,function(e){this.stopListening(e.idContainer,e.eventName,this.retrieve)},this)},__parseUpdateEvents:function(){this.__normalizeAndValidateUpdateEvents();var e=d.flatten(d.map(this.updateEvents,this.__parseUpdateEvent,this));return d.compact(e)},__parseUpdateEvent:function(e){if(!d.isUndefined(e)){var t=[];if(d.isString(e)){var i=this.__parseStringUpdateEvent(e);d.isUndefined(i)||t.push(i)}else d.isObject(e)&&(t=d.map(e,function(e,t){return{idContainer:e,eventName:t}}));return t}},__validateCache:function(){if(!this.cache)throw new Error("Torso Data Behavior constructed without a cache");if(!(this.cache instanceof t))throw new Error("Torso Data Behavior's cache is not of type Torso.Collection")},__normalizeAndValidateIds:function(){if(!d.isUndefined(this.ids)&&!d.isUndefined(this.id))throw new Error("Torso Data Behavior constructed with both id and ids. Please define only one.");this.ids=this.id||this.ids,this.__validateIds()},__validateIds:function(){if(d.isUndefined(this.ids))throw new Error("Torso Data Behavior constructed without a way to identify the ids for this data. Please define either id, ids.");var e=d.isArray(this.ids),t=d.isString(this.ids)||d.isNumber(this.ids),i=d.isFunction(this.ids),n=d.isString(this.ids.property),s=d.isObject(this.ids),r=e||t||i||n;if(!r&&s)throw new Error("Data Behavior ids invalid definition. It is an object, but the property field is not defined or is not a string: "+JSON.stringify(this.ids));if(!r)throw new Error("Data Behavior ids invalid definition. Not a string, number, object, array or function: "+JSON.stringify(this.ids));if(n){var o=f(this.ids.property);if(!d.isUndefined(this.ids.idContainer)&&o)throw new Error("Data Behavior ids invalid definition. Id container defined on both ids.property and ids.idContainer: ",JSON.stringify(this.ids))}},__normalizeAndValidateUpdateEvents:function(){var e=d.isArray(this.updateEvents),t=!e&&(d.isObject(this.updateEvents)||d.isString(this.updateEvents)),i=d.isUndefined(this.updateEvents),n=e||t||i;if(t&&(this.updateEvents=[this.updateEvents]),!n)throw new Error("Update events are not an array, string or object. Please see parameters for examples of how to define updateEvents. Configured UpdateEvents: ",this.updateEvents);this.updateEvents=d.compact(this.updateEvents),d.each(this.updateEvents,this.__validUpdateEvent)},__validUpdateEvent:function(e){var t=d.isString(e),i=d.isObject(e)&&0<d.keys(e).length;if(!t&&!i)throw new Error("Not a valid updateEvent configuration. Update events need to either be strings or objects with a single property: "+JSON.stringify(e))},__getIds:function(){this.set("loadingIds",this.get("loadingIds")+1),this.__validateIds();var e=c.Deferred(),t=this.ids,i=l(t);if(d.isUndefined(i)){if(d.isFunction(this.ids))i=l(t=this.ids(this.cache)),d.isUndefined(i)?t&&d.isFunction(t.then)?e=t.then(l):e.resolve([]):e.resolve(i);else if(!d.isUndefined(this.ids.property)){var n=this.__parseIdsPropertyNameAndIdContainer(),s=n.idsPropertyName,r=n.idContainer;t=u(r,s);var o=r&&d.isUndefined(t),a=r&&d.isFunction(r.get);o&&a&&(t=r.get(s)),i=l(t),e.resolve(i)}}else e.resolve(i);return e.promise().then(h).always(this.__completeLoadingIds)},__completeLoadingIds:function(){this.set("loadingIds",this.get("loadingIds")-1)},__parseIdsPropertyNameAndIdContainer:function(){var e,t=this.ids.property,i=f(t);if(!d.isUndefined(this.ids.idContainer)&&(e=this.__parseIdContainer()),i){var n=this.__parseContainerDetailString(t);t=n.detail,e=n.idContainer}return d.isUndefined(e)&&(e=this.view),{idsPropertyName:t,idContainer:e}},__parseIdContainer:function(){var e,t=this.ids.idContainer;if(d.isUndefined(t))e=void 0;else if(d.isFunction(t)){e=d.bind(t,this)()}else{if(!d.isObject(t))throw new Error("Invalid idContainer. Not an object or function: "+JSON.stringify(this.ids));e=t}return e},__parseContainerDetailString:function(e){var t="";f(e)&&(t=e.split(":",1)[0]);var i,n=t.split("."),s=n[0];if("this"===s)i=this;else if("behaviors"===s||"behavior"===s){var r=n[1];s+="."+r,i=this.view.getBehavior(r)}else"view"!==s&&(s=""),i=this.view;var o=i,a=t.replace(s,"");return a&&("."===a[0]&&(a=a.slice(1)),o=u(i,a)),{detail:e.replace(t+":",""),idContainer:o}},__parseStringUpdateEvent:function(e){var t=this.__parseContainerDetailString(e);if(t)return{idContainer:t.idContainer,eventName:t.detail}},__abortIfDisposed:function(){var e=c.Deferred();if(this.isDisposed()){var t=Array.prototype.slice.call(arguments);t.push("Data Behavior disposed, aborting."),e.reject.apply(e,t)}else e.resolve.apply(e,arguments);return e.promise()},__fetchSuccess:function(e){return this.set("fetchSuccess",!0),this.set("fetchedOnce",!0),this.__shouldTriggerFetchedEvent(e)&&(this.trigger("fetched",{status:s.SUCCESS,response:e}),this.data.trigger("fetched",{status:s.SUCCESS,response:e})),this.trigger("fetched:ids"),this.data.trigger("fetched:ids"),e},__fetchFailed:function(e){return this.set("fetchSuccess",!1),this.set("fetchedOnce",!0),this.__shouldTriggerFetchedEvent(e)&&(this.trigger("fetched",{status:s.FAILURE,response:e}),this.data.trigger("fetched",{status:s.FAILURE,response:e}),e&&e.emptyIds&&(this.__firstEmptyFetchedTriggered=!0)),this.trigger("fetched:ids"),this.data.trigger("fetched:ids"),(new c.Deferred).reject(e).promise()},__shouldTriggerFetchedEvent:function(e){return!e||!e.skipObjectRetrieval||e.forceFetchedEvent},__skipRetrieveOnEmptyTrackedIdsAndNewIds:function(e){return d.isEmpty(e)&&d.isEmpty(this.data.privateCollection.getTrackedIds())?{skipObjectRetrieval:!0,forceFetchedEvent:!0}:e},_activate:function(){this.listenToIdsPropertyChangeEvent(),this._delegateUpdateEvents(),this.data.activate()},_deactivate:function(){this.stopListeningToIdsPropertyChangeEvent(),this._undelegateUpdateEvents(),this.data.deactivate()}});return d.extend(r.prototype,i,{initialize:function(e){this.parentBehavior=e.parentBehavior,this.privateCollection=e.privateCollection,d.bindAll(this,"dispose")},isLoading:function(){return this.parentBehavior.isLoading()},isLoadingIds:function(){return this.parentBehavior.isLoadingIds()},isLoadingObjects:function(){return this.parentBehavior.isLoadingObjects()},toJSON:function(){var e=this.privateCollection;if(!this.parentBehavior.returnSingleResult)return e.toJSON();if(0!==e.length){if(1!==e.length)throw new Error("Multiple results found, but single result expected: "+JSON.stringify(e.toJSON()));return e.at(0).toJSON()}},get:function(e){var t=this.privateCollection;if(!this.parentBehavior.returnSingleResult)return d.isString(e)?t.pluck(e):t.toJSON();var i=this.getModel();return i?d.isString(e)?i.get(e):i.toJSON():void 0},getModel:function(e){var t=this.privateCollection;if(!this.parentBehavior.returnSingleResult&&d.isUndefined(e))throw new Error("data.getModel() of a DataBehavior is only valid if the behavior is set to returnSingleResult === true");if(!d.isUndefined(e))return t.get(e);if(0!==t.length){if(1===t.length)return t.at(0);throw new Error("Multiple results found, but single result expected: "+JSON.stringify(t.toJSON()))}},getModels:function(){return this.privateCollection.models.slice(0)},activate:function(){this.listenTo(this.privateCollection,"all",this.trigger)},deactivate:function(){this.stopListening(this.privateCollection,"all",this.trigger)},dispose:function(){this.off(),this.stopListening(),this.privateCollection.dispose()}}),o.prototype.Data=r,o.FETCHED_STATUSES=s,o}),function(e,t){"function"==typeof define&&define.amd?define(["underscore","backbone","./View","./FormModel","./Cell","backbone.stickit"],t):"object"==typeof exports?(require("backbone.stickit"),module.exports=t(require("underscore"),require("backbone"),require("./View"),require("./FormModel"),require("./Cell"))):(e.Torso=e.Torso||{},e.Torso.FormView=t(e._,e.Backbone,e.Torso.View,e.Torso.FormModel,e.Torso.Cell))}(this,function(r,e,i,n,t){"use strict";var o=e.$;return i.extend({constructor:function(e){var t=(e=e||{}).FormModelClass||this.FormModelClass||n;this.model=e.model||this.model||new t,this.template=e.template||this.template,this.events=r.extend({},this.events||{},e.events||{}),this.fields=r.extend({},this.fields||{},e.fields||{}),this._errors=[],this._success=!1,this._bindings=r.extend({},this.bindings||{},e.bindings||{}),i.apply(this,arguments),this.resetModelListeners(this.model)},prepare:function(){var e=i.prototype.prepare.apply(this);return e.formErrors=0!==r.size(this._errors)?this._errors:null,e.formSuccess=this._success,e},delegateEvents:function(){this.__generateStickitBindings(),this.stickit(),i.prototype.delegateEvents.call(this)},resetModelListeners:function(e,t){this.model&&t&&this.stopListening(this.model),this.model=e,this.listenTo(this.model,"validated:valid",this.valid),this.listenTo(this.model,"validated:invalid",this.invalid)},valid:function(){this._success=!0,this._errors=[]},invalid:function(e,t){this._success=!1,this._errors=t},deactivate:function(){i.prototype.deactivate.call(this),this.$el&&this.unstickit()},_thenAddClassIfInvalid:function(e,t,i){return!!i==!!this.model.isValid(e)?{addClass:t}:{removeClass:t}},_thenSetTextIfInvalid:function(e,t,i){return!!i==!!this.model.isValid(e)?{text:t}:{text:""}},__generateStickitBindings:function(){var s=this;this.bindings=r.extend({},this._bindings),r.each(this.$("[data-model]"),function(e){var t=o(e).data("model"),i=s.__getFieldOptions(t),n=s.__generateModelFieldBinding(t,i);o(e).is("select")&&(n.selectOptions=s.__generateSelectOptions(e,i)),s.bindings['[data-model="'+t+'"]']=n})},__getFieldOptions:function(e){return e=this.__stripAllAttribute(e),this.fields[e]||{}},__generateModelFieldBinding:function(e,i){var n=this.__getAllIndexTokens(e),t=(i=i||{}).stickit||{};return r.isFunction(t)&&(t=t.call(this,e,i)),r.extend({observe:e,onSet:function(e){var t=[e];return t.push(n),t=r.flatten(t),i.modelFormat?i.modelFormat.apply(this,t):e},onGet:function(e){var t=[e];return t.push(n),t=r.flatten(t),i.viewFormat?i.viewFormat.apply(this,t):e}},t)},__generateSelectOptions:function(e,t){var i=[],n=o(e).children("option");(t=t||{}).stickit=t.stickit||{};var s=t.stickit.selectOptions||{};return r.isFunction(s)&&(s=s.call(this,e,t)),r.each(n,function(e){i.push({label:o(e).text(),value:t.modelFormat?t.modelFormat.apply(this,[o(e).val()]):o(e).val()})}),r.extend({collection:i,labelPath:"label",valuePath:"value"},s)}})});