// Backbone.js 0.9.10

// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
(function(){var n=this,B=n.Backbone,h=[],C=h.push,u=h.slice,D=h.splice,g;g="undefined"!==typeof exports?exports:n.Backbone={};g.VERSION="0.9.10";var f=n._;!f&&"undefined"!==typeof require&&(f=require("underscore"));g.$=n.jQuery||n.Zepto||n.ender;g.noConflict=function(){n.Backbone=B;return this};g.emulateHTTP=!1;g.emulateJSON=!1;var v=/\s+/,q=function(a,b,c,d){if(!c)return!0;if("object"===typeof c)for(var e in c)a[b].apply(a,[e,c[e]].concat(d));else if(v.test(c)){c=c.split(v);e=0;for(var f=c.length;e<
f;e++)a[b].apply(a,[c[e]].concat(d))}else return!0},w=function(a,b){var c,d=-1,e=a.length;switch(b.length){case 0:for(;++d<e;)(c=a[d]).callback.call(c.ctx);break;case 1:for(;++d<e;)(c=a[d]).callback.call(c.ctx,b[0]);break;case 2:for(;++d<e;)(c=a[d]).callback.call(c.ctx,b[0],b[1]);break;case 3:for(;++d<e;)(c=a[d]).callback.call(c.ctx,b[0],b[1],b[2]);break;default:for(;++d<e;)(c=a[d]).callback.apply(c.ctx,b)}},h=g.Events={on:function(a,b,c){if(!q(this,"on",a,[b,c])||!b)return this;this._events||(this._events=
{});(this._events[a]||(this._events[a]=[])).push({callback:b,context:c,ctx:c||this});return this},once:function(a,b,c){if(!q(this,"once",a,[b,c])||!b)return this;var d=this,e=f.once(function(){d.off(a,e);b.apply(this,arguments)});e._callback=b;this.on(a,e,c);return this},off:function(a,b,c){var d,e,t,g,j,l,k,h;if(!this._events||!q(this,"off",a,[b,c]))return this;if(!a&&!b&&!c)return this._events={},this;g=a?[a]:f.keys(this._events);j=0;for(l=g.length;j<l;j++)if(a=g[j],d=this._events[a]){t=[];if(b||
c){k=0;for(h=d.length;k<h;k++)e=d[k],(b&&b!==e.callback&&b!==e.callback._callback||c&&c!==e.context)&&t.push(e)}this._events[a]=t}return this},trigger:function(a){if(!this._events)return this;var b=u.call(arguments,1);if(!q(this,"trigger",a,b))return this;var c=this._events[a],d=this._events.all;c&&w(c,b);d&&w(d,arguments);return this},listenTo:function(a,b,c){var d=this._listeners||(this._listeners={}),e=a._listenerId||(a._listenerId=f.uniqueId("l"));d[e]=a;a.on(b,"object"===typeof b?this:c,this);
return this},stopListening:function(a,b,c){var d=this._listeners;if(d){if(a)a.off(b,"object"===typeof b?this:c,this),!b&&!c&&delete d[a._listenerId];else{"object"===typeof b&&(c=this);for(var e in d)d[e].off(b,c,this);this._listeners={}}return this}}};h.bind=h.on;h.unbind=h.off;f.extend(g,h);var r=g.Model=function(a,b){var c,d=a||{};this.cid=f.uniqueId("c");this.attributes={};b&&b.collection&&(this.collection=b.collection);b&&b.parse&&(d=this.parse(d,b)||{});if(c=f.result(this,"defaults"))d=f.defaults({},
d,c);this.set(d,b);this.changed={};this.initialize.apply(this,arguments)};f.extend(r.prototype,h,{changed:null,idAttribute:"id",initialize:function(){},toJSON:function(){return f.clone(this.attributes)},sync:function(){return g.sync.apply(this,arguments)},get:function(a){return this.attributes[a]},escape:function(a){return f.escape(this.get(a))},has:function(a){return null!=this.get(a)},set:function(a,b,c){var d,e,g,p,j,l,k;if(null==a)return this;"object"===typeof a?(e=a,c=b):(e={})[a]=b;c||(c={});
if(!this._validate(e,c))return!1;g=c.unset;p=c.silent;a=[];j=this._changing;this._changing=!0;j||(this._previousAttributes=f.clone(this.attributes),this.changed={});k=this.attributes;l=this._previousAttributes;this.idAttribute in e&&(this.id=e[this.idAttribute]);for(d in e)b=e[d],f.isEqual(k[d],b)||a.push(d),f.isEqual(l[d],b)?delete this.changed[d]:this.changed[d]=b,g?delete k[d]:k[d]=b;if(!p){a.length&&(this._pending=!0);b=0;for(d=a.length;b<d;b++)this.trigger("change:"+a[b],this,k[a[b]],c)}if(j)return this;
if(!p)for(;this._pending;)this._pending=!1,this.trigger("change",this,c);this._changing=this._pending=!1;return this},unset:function(a,b){return this.set(a,void 0,f.extend({},b,{unset:!0}))},clear:function(a){var b={},c;for(c in this.attributes)b[c]=void 0;return this.set(b,f.extend({},a,{unset:!0}))},hasChanged:function(a){return null==a?!f.isEmpty(this.changed):f.has(this.changed,a)},changedAttributes:function(a){if(!a)return this.hasChanged()?f.clone(this.changed):!1;var b,c=!1,d=this._changing?
this._previousAttributes:this.attributes,e;for(e in a)if(!f.isEqual(d[e],b=a[e]))(c||(c={}))[e]=b;return c},previous:function(a){return null==a||!this._previousAttributes?null:this._previousAttributes[a]},previousAttributes:function(){return f.clone(this._previousAttributes)},fetch:function(a){a=a?f.clone(a):{};void 0===a.parse&&(a.parse=!0);var b=a.success;a.success=function(a,d,e){if(!a.set(a.parse(d,e),e))return!1;b&&b(a,d,e)};return this.sync("read",this,a)},save:function(a,b,c){var d,e,g=this.attributes;
null==a||"object"===typeof a?(d=a,c=b):(d={})[a]=b;if(d&&(!c||!c.wait)&&!this.set(d,c))return!1;c=f.extend({validate:!0},c);if(!this._validate(d,c))return!1;d&&c.wait&&(this.attributes=f.extend({},g,d));void 0===c.parse&&(c.parse=!0);e=c.success;c.success=function(a,b,c){a.attributes=g;var k=a.parse(b,c);c.wait&&(k=f.extend(d||{},k));if(f.isObject(k)&&!a.set(k,c))return!1;e&&e(a,b,c)};a=this.isNew()?"create":c.patch?"patch":"update";"patch"===a&&(c.attrs=d);a=this.sync(a,this,c);d&&c.wait&&(this.attributes=
g);return a},destroy:function(a){a=a?f.clone(a):{};var b=this,c=a.success,d=function(){b.trigger("destroy",b,b.collection,a)};a.success=function(a,b,e){(e.wait||a.isNew())&&d();c&&c(a,b,e)};if(this.isNew())return a.success(this,null,a),!1;var e=this.sync("delete",this,a);a.wait||d();return e},url:function(){var a=f.result(this,"urlRoot")||f.result(this.collection,"url")||x();return this.isNew()?a:a+("/"===a.charAt(a.length-1)?"":"/")+encodeURIComponent(this.id)},parse:function(a){return a},clone:function(){return new this.constructor(this.attributes)},
isNew:function(){return null==this.id},isValid:function(a){return!this.validate||!this.validate(this.attributes,a)},_validate:function(a,b){if(!b.validate||!this.validate)return!0;a=f.extend({},this.attributes,a);var c=this.validationError=this.validate(a,b)||null;if(!c)return!0;this.trigger("invalid",this,c,b||{});return!1}});var s=g.Collection=function(a,b){b||(b={});b.model&&(this.model=b.model);void 0!==b.comparator&&(this.comparator=b.comparator);this.models=[];this._reset();this.initialize.apply(this,
arguments);a&&this.reset(a,f.extend({silent:!0},b))};f.extend(s.prototype,h,{model:r,initialize:function(){},toJSON:function(a){return this.map(function(b){return b.toJSON(a)})},sync:function(){return g.sync.apply(this,arguments)},add:function(a,b){a=f.isArray(a)?a.slice():[a];b||(b={});var c,d,e,g,p,j,l,k,h,m;l=[];k=b.at;h=this.comparator&&null==k&&!1!=b.sort;m=f.isString(this.comparator)?this.comparator:null;c=0;for(d=a.length;c<d;c++)(e=this._prepareModel(g=a[c],b))?(p=this.get(e))?b.merge&&(p.set(g===
e?e.attributes:g,b),h&&(!j&&p.hasChanged(m))&&(j=!0)):(l.push(e),e.on("all",this._onModelEvent,this),this._byId[e.cid]=e,null!=e.id&&(this._byId[e.id]=e)):this.trigger("invalid",this,g,b);l.length&&(h&&(j=!0),this.length+=l.length,null!=k?D.apply(this.models,[k,0].concat(l)):C.apply(this.models,l));j&&this.sort({silent:!0});if(b.silent)return this;c=0;for(d=l.length;c<d;c++)(e=l[c]).trigger("add",e,this,b);j&&this.trigger("sort",this,b);return this},remove:function(a,b){a=f.isArray(a)?a.slice():[a];
b||(b={});var c,d,e,g;c=0;for(d=a.length;c<d;c++)if(g=this.get(a[c]))delete this._byId[g.id],delete this._byId[g.cid],e=this.indexOf(g),this.models.splice(e,1),this.length--,b.silent||(b.index=e,g.trigger("remove",g,this,b)),this._removeReference(g);return this},push:function(a,b){a=this._prepareModel(a,b);this.add(a,f.extend({at:this.length},b));return a},pop:function(a){var b=this.at(this.length-1);this.remove(b,a);return b},unshift:function(a,b){a=this._prepareModel(a,b);this.add(a,f.extend({at:0},
b));return a},shift:function(a){var b=this.at(0);this.remove(b,a);return b},slice:function(a,b){return this.models.slice(a,b)},get:function(a){if(null!=a)return this._idAttr||(this._idAttr=this.model.prototype.idAttribute),this._byId[a.id||a.cid||a[this._idAttr]||a]},at:function(a){return this.models[a]},where:function(a){return f.isEmpty(a)?[]:this.filter(function(b){for(var c in a)if(a[c]!==b.get(c))return!1;return!0})},sort:function(a){if(!this.comparator)throw Error("Cannot sort a set without a comparator");
a||(a={});f.isString(this.comparator)||1===this.comparator.length?this.models=this.sortBy(this.comparator,this):this.models.sort(f.bind(this.comparator,this));a.silent||this.trigger("sort",this,a);return this},pluck:function(a){return f.invoke(this.models,"get",a)},update:function(a,b){b=f.extend({add:!0,merge:!0,remove:!0},b);b.parse&&(a=this.parse(a,b));var c,d,e,g,h=[],j=[],l={};f.isArray(a)||(a=a?[a]:[]);if(b.add&&!b.remove)return this.add(a,b);d=0;for(e=a.length;d<e;d++)c=a[d],g=this.get(c),
b.remove&&g&&(l[g.cid]=!0),(b.add&&!g||b.merge&&g)&&h.push(c);if(b.remove){d=0;for(e=this.models.length;d<e;d++)c=this.models[d],l[c.cid]||j.push(c)}j.length&&this.remove(j,b);h.length&&this.add(h,b);return this},reset:function(a,b){b||(b={});b.parse&&(a=this.parse(a,b));for(var c=0,d=this.models.length;c<d;c++)this._removeReference(this.models[c]);b.previousModels=this.models.slice();this._reset();a&&this.add(a,f.extend({silent:!0},b));b.silent||this.trigger("reset",this,b);return this},fetch:function(a){a=
a?f.clone(a):{};void 0===a.parse&&(a.parse=!0);var b=a.success;a.success=function(a,d,e){a[e.update?"update":"reset"](d,e);b&&b(a,d,e)};return this.sync("read",this,a)},create:function(a,b){b=b?f.clone(b):{};if(!(a=this._prepareModel(a,b)))return!1;b.wait||this.add(a,b);var c=this,d=b.success;b.success=function(a,b,f){f.wait&&c.add(a,f);d&&d(a,b,f)};a.save(null,b);return a},parse:function(a){return a},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0;this.models.length=
0;this._byId={}},_prepareModel:function(a,b){if(a instanceof r)return a.collection||(a.collection=this),a;b||(b={});b.collection=this;var c=new this.model(a,b);return!c._validate(a,b)?!1:c},_removeReference:function(a){this===a.collection&&delete a.collection;a.off("all",this._onModelEvent,this)},_onModelEvent:function(a,b,c,d){("add"===a||"remove"===a)&&c!==this||("destroy"===a&&this.remove(b,d),b&&a==="change:"+b.idAttribute&&(delete this._byId[b.previous(b.idAttribute)],null!=b.id&&(this._byId[b.id]=
b)),this.trigger.apply(this,arguments))},sortedIndex:function(a,b,c){b||(b=this.comparator);var d=f.isFunction(b)?b:function(a){return a.get(b)};return f.sortedIndex(this.models,a,d,c)}});f.each("forEach each map collect reduce foldl inject reduceRight foldr find detect filter select reject every all some any include contains invoke max min toArray size first head take initial rest tail drop last without indexOf shuffle lastIndexOf isEmpty chain".split(" "),function(a){s.prototype[a]=function(){var b=
u.call(arguments);b.unshift(this.models);return f[a].apply(f,b)}});f.each(["groupBy","countBy","sortBy"],function(a){s.prototype[a]=function(b,c){var d=f.isFunction(b)?b:function(a){return a.get(b)};return f[a](this.models,d,c)}});var y=g.Router=function(a){a||(a={});a.routes&&(this.routes=a.routes);this._bindRoutes();this.initialize.apply(this,arguments)},E=/\((.*?)\)/g,F=/(\(\?)?:\w+/g,G=/\*\w+/g,H=/[\-{}\[\]+?.,\\\^$|#\s]/g;f.extend(y.prototype,h,{initialize:function(){},route:function(a,b,c){f.isRegExp(a)||
(a=this._routeToRegExp(a));c||(c=this[b]);g.history.route(a,f.bind(function(d){d=this._extractParameters(a,d);c&&c.apply(this,d);this.trigger.apply(this,["route:"+b].concat(d));this.trigger("route",b,d);g.history.trigger("route",this,b,d)},this));return this},navigate:function(a,b){g.history.navigate(a,b);return this},_bindRoutes:function(){if(this.routes)for(var a,b=f.keys(this.routes);null!=(a=b.pop());)this.route(a,this.routes[a])},_routeToRegExp:function(a){a=a.replace(H,"\\$&").replace(E,"(?:$1)?").replace(F,
function(a,c){return c?a:"([^/]+)"}).replace(G,"(.*?)");return RegExp("^"+a+"$")},_extractParameters:function(a,b){return a.exec(b).slice(1)}});var m=g.History=function(){this.handlers=[];f.bindAll(this,"checkUrl");"undefined"!==typeof window&&(this.location=window.location,this.history=window.history)},z=/^[#\/]|\s+$/g,I=/^\/+|\/+$/g,J=/msie [\w.]+/,K=/\/$/;m.started=!1;f.extend(m.prototype,h,{interval:50,getHash:function(a){return(a=(a||this).location.href.match(/#(.*)$/))?a[1]:""},getFragment:function(a,
b){if(null==a)if(this._hasPushState||!this._wantsHashChange||b){a=this.location.pathname;var c=this.root.replace(K,"");a.indexOf(c)||(a=a.substr(c.length))}else a=this.getHash();return a.replace(z,"")},start:function(a){if(m.started)throw Error("Backbone.history has already been started");m.started=!0;this.options=f.extend({},{root:"/"},this.options,a);this.root=this.options.root;this._wantsHashChange=!1!==this.options.hashChange;this._wantsPushState=!!this.options.pushState;this._hasPushState=!(!this.options.pushState||
!this.history||!this.history.pushState);a=this.getFragment();var b=document.documentMode,b=J.exec(navigator.userAgent.toLowerCase())&&(!b||7>=b);this.root=("/"+this.root+"/").replace(I,"/");b&&this._wantsHashChange&&(this.iframe=g.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo("body")[0].contentWindow,this.navigate(a));if(this._hasPushState)g.$(window).on("popstate",this.checkUrl);else if(this._wantsHashChange&&"onhashchange"in window&&!b)g.$(window).on("hashchange",this.checkUrl);
else this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval));this.fragment=a;a=this.location;b=a.pathname.replace(/[^\/]$/,"$&/")===this.root;if(this._wantsHashChange&&this._wantsPushState&&!this._hasPushState&&!b)return this.fragment=this.getFragment(null,!0),this.location.replace(this.root+this.location.search+"#"+this.fragment),!0;this._wantsPushState&&(this._hasPushState&&b&&a.hash)&&(this.fragment=this.getHash().replace(z,""),this.history.replaceState({},document.title,
this.root+this.fragment+a.search));if(!this.options.silent)return this.loadUrl()},stop:function(){g.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl);clearInterval(this._checkUrlInterval);m.started=!1},route:function(a,b){this.handlers.unshift({route:a,callback:b})},checkUrl:function(){var a=this.getFragment();a===this.fragment&&this.iframe&&(a=this.getFragment(this.getHash(this.iframe)));if(a===this.fragment)return!1;this.iframe&&this.navigate(a);this.loadUrl()||this.loadUrl(this.getHash())},
loadUrl:function(a){var b=this.fragment=this.getFragment(a);return f.any(this.handlers,function(a){if(a.route.test(b))return a.callback(b),!0})},navigate:function(a,b){if(!m.started)return!1;if(!b||!0===b)b={trigger:b};a=this.getFragment(a||"");if(this.fragment!==a){this.fragment=a;var c=this.root+a;if(this._hasPushState)this.history[b.replace?"replaceState":"pushState"]({},document.title,c);else if(this._wantsHashChange)this._updateHash(this.location,a,b.replace),this.iframe&&a!==this.getFragment(this.getHash(this.iframe))&&
(b.replace||this.iframe.document.open().close(),this._updateHash(this.iframe.location,a,b.replace));else return this.location.assign(c);b.trigger&&this.loadUrl(a)}},_updateHash:function(a,b,c){c?(c=a.href.replace(/(javascript:|#).*$/,""),a.replace(c+"#"+b)):a.hash="#"+b}});g.history=new m;var A=g.View=function(a){this.cid=f.uniqueId("view");this._configure(a||{});this._ensureElement();this.initialize.apply(this,arguments);this.delegateEvents()},L=/^(\S+)\s*(.*)$/,M="model collection el id attributes className tagName events".split(" ");
f.extend(A.prototype,h,{tagName:"div",$:function(a){return this.$el.find(a)},initialize:function(){},render:function(){return this},remove:function(){this.$el.remove();this.stopListening();return this},setElement:function(a,b){this.$el&&this.undelegateEvents();this.$el=a instanceof g.$?a:g.$(a);this.el=this.$el[0];!1!==b&&this.delegateEvents();return this},delegateEvents:function(a){if(a||(a=f.result(this,"events"))){this.undelegateEvents();for(var b in a){var c=a[b];f.isFunction(c)||(c=this[a[b]]);
if(!c)throw Error('Method "'+a[b]+'" does not exist');var d=b.match(L),e=d[1],d=d[2],c=f.bind(c,this),e=e+(".delegateEvents"+this.cid);if(""===d)this.$el.on(e,c);else this.$el.on(e,d,c)}}},undelegateEvents:function(){this.$el.off(".delegateEvents"+this.cid)},_configure:function(a){this.options&&(a=f.extend({},f.result(this,"options"),a));f.extend(this,f.pick(a,M));this.options=a},_ensureElement:function(){if(this.el)this.setElement(f.result(this,"el"),!1);else{var a=f.extend({},f.result(this,"attributes"));
this.id&&(a.id=f.result(this,"id"));this.className&&(a["class"]=f.result(this,"className"));a=g.$("<"+f.result(this,"tagName")+">").attr(a);this.setElement(a,!1)}}});var N={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};g.sync=function(a,b,c){var d=N[a];f.defaults(c||(c={}),{emulateHTTP:g.emulateHTTP,emulateJSON:g.emulateJSON});var e={type:d,dataType:"json"};c.url||(e.url=f.result(b,"url")||x());if(null==c.data&&b&&("create"===a||"update"===a||"patch"===a))e.contentType="application/json",
e.data=JSON.stringify(c.attrs||b.toJSON(c));c.emulateJSON&&(e.contentType="application/x-www-form-urlencoded",e.data=e.data?{model:e.data}:{});if(c.emulateHTTP&&("PUT"===d||"DELETE"===d||"PATCH"===d)){e.type="POST";c.emulateJSON&&(e.data._method=d);var h=c.beforeSend;c.beforeSend=function(a){a.setRequestHeader("X-HTTP-Method-Override",d);if(h)return h.apply(this,arguments)}}"GET"!==e.type&&!c.emulateJSON&&(e.processData=!1);var m=c.success;c.success=function(a){m&&m(b,a,c);b.trigger("sync",b,a,c)};
var j=c.error;c.error=function(a){j&&j(b,a,c);b.trigger("error",b,a,c)};a=c.xhr=g.ajax(f.extend(e,c));b.trigger("request",b,a,c);return a};g.ajax=function(){return g.$.ajax.apply(g.$,arguments)};r.extend=s.extend=y.extend=A.extend=m.extend=function(a,b){var c=this,d;d=a&&f.has(a,"constructor")?a.constructor:function(){return c.apply(this,arguments)};f.extend(d,c,b);var e=function(){this.constructor=d};e.prototype=c.prototype;d.prototype=new e;a&&f.extend(d.prototype,a);d.__super__=c.prototype;return d};
var x=function(){throw Error('A "url" property or function must be specified');}}).call(this);
 
/*! messenger 1.4.1 */
(function(){var e,t=window.Messenger;e=window.Messenger=function(){return e._call.apply(this,arguments)},window.Messenger.noConflict=function(){return window.Messenger=t,e}})(),window.Messenger._=function(){if(window._)return window._;var e=Array.prototype,t=Object.prototype,n=Function.prototype,s=(e.push,e.slice),r=(e.concat,t.toString);t.hasOwnProperty;var o=e.forEach,i=(e.map,e.reduce,e.reduceRight,e.filter),a=(e.every,e.some,e.indexOf,e.lastIndexOf,Array.isArray,Object.keys),l=n.bind,u={},c={},h=u.each=u.forEach=function(e,t,n){if(null!=e)if(o&&e.forEach===o)e.forEach(t,n);else if(e.length===+e.length){for(var s=0,r=e.length;r>s;s++)if(t.call(n,e[s],s,e)===c)return}else for(var i in e)if(u.has(e,i)&&t.call(n,e[i],i,e)===c)return};u.result=function(e,t){if(null==e)return null;var n=e[t];return u.isFunction(n)?n.call(e):n},u.once=function(e){var t,n=!1;return function(){return n?t:(n=!0,t=e.apply(this,arguments),e=null,t)}};var p=0;return u.uniqueId=function(e){var t=++p+"";return e?e+t:t},u.filter=u.select=function(e,t,n){var s=[];return null==e?s:i&&e.filter===i?e.filter(t,n):(h(e,function(e,r,o){t.call(n,e,r,o)&&(s[s.length]=e)}),s)},h(["Arguments","Function","String","Number","Date","RegExp"],function(e){u["is"+e]=function(t){return r.call(t)=="[object "+e+"]"}}),u.defaults=function(e){return h(s.call(arguments,1),function(t){if(t)for(var n in t)null==e[n]&&(e[n]=t[n])}),e},u.extend=function(e){return h(s.call(arguments,1),function(t){if(t)for(var n in t)e[n]=t[n]}),e},u.keys=a||function(e){if(e!==Object(e))throw new TypeError("Invalid object");var t=[];for(var n in e)u.has(e,n)&&(t[t.length]=n);return t},u.bind=function(e,t){if(e.bind===l&&l)return l.apply(e,s.call(arguments,1));var n=s.call(arguments,2);return function(){return e.apply(t,n.concat(s.call(arguments)))}},u.isObject=function(e){return e===Object(e)},u}(),window.Messenger.Events=function(){if(window.Backbone&&Backbone.Events)return Backbone.Events;var e=function(){var e=/\s+/,t=function(t,n,s,r){if(!s)return!0;if("object"==typeof s)for(var o in s)t[n].apply(t,[o,s[o]].concat(r));else{if(!e.test(s))return!0;for(var i=s.split(e),a=0,l=i.length;l>a;a++)t[n].apply(t,[i[a]].concat(r))}},n=function(e,t){var n,s=-1,r=e.length;switch(t.length){case 0:for(;r>++s;)(n=e[s]).callback.call(n.ctx);return;case 1:for(;r>++s;)(n=e[s]).callback.call(n.ctx,t[0]);return;case 2:for(;r>++s;)(n=e[s]).callback.call(n.ctx,t[0],t[1]);return;case 3:for(;r>++s;)(n=e[s]).callback.call(n.ctx,t[0],t[1],t[2]);return;default:for(;r>++s;)(n=e[s]).callback.apply(n.ctx,t)}},s={on:function(e,n,s){if(!t(this,"on",e,[n,s])||!n)return this;this._events||(this._events={});var r=this._events[e]||(this._events[e]=[]);return r.push({callback:n,context:s,ctx:s||this}),this},once:function(e,n,s){if(!t(this,"once",e,[n,s])||!n)return this;var r=this,o=_.once(function(){r.off(e,o),n.apply(this,arguments)});return o._callback=n,this.on(e,o,s),this},off:function(e,n,s){var r,o,i,a,l,u,c,h;if(!this._events||!t(this,"off",e,[n,s]))return this;if(!e&&!n&&!s)return this._events={},this;for(a=e?[e]:_.keys(this._events),l=0,u=a.length;u>l;l++)if(e=a[l],r=this._events[e]){if(i=[],n||s)for(c=0,h=r.length;h>c;c++)o=r[c],(n&&n!==o.callback&&n!==o.callback._callback||s&&s!==o.context)&&i.push(o);this._events[e]=i}return this},trigger:function(e){if(!this._events)return this;var s=Array.prototype.slice.call(arguments,1);if(!t(this,"trigger",e,s))return this;var r=this._events[e],o=this._events.all;return r&&n(r,s),o&&n(o,arguments),this},listenTo:function(e,t,n){var s=this._listeners||(this._listeners={}),r=e._listenerId||(e._listenerId=_.uniqueId("l"));return s[r]=e,e.on(t,"object"==typeof t?this:n,this),this},stopListening:function(e,t,n){var s=this._listeners;if(s){if(e)e.off(t,"object"==typeof t?this:n,this),t||n||delete s[e._listenerId];else{"object"==typeof t&&(n=this);for(var r in s)s[r].off(t,n,this);this._listeners={}}return this}}};return s.bind=s.on,s.unbind=s.off,s};return e()}(),function(){var e,t,n,s,r,o,i,a,l,u,c,h={}.hasOwnProperty,p=function(e,t){function n(){this.constructor=e}for(var s in t)h.call(t,s)&&(e[s]=t[s]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},d=[].slice,f=[].indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(t in this&&this[t]===e)return t;return-1};e=jQuery,o=null!=(l=window._)?l:window.Messenger._,s=null!=(u="undefined"!=typeof Backbone&&null!==Backbone?Backbone.Events:void 0)?u:window.Messenger.Events,n=function(){function t(t){e.extend(this,s),o.isObject(t)&&(t.el&&this.setElement(t.el),this.model=t.model),this.initialize.apply(this,arguments)}return t.prototype.setElement=function(t){return this.$el=e(t),this.el=this.$el[0]},t.prototype.delegateEvents=function(e){var t,n,s,r,i,a,l;if(e||(e=o.result(this,"events"))){this.undelegateEvents(),t=/^(\S+)\s*(.*)$/,l=[];for(s in e){if(i=e[s],o.isFunction(i)||(i=this[e[s]]),!i)throw Error('Method "'+e[s]+'" does not exist');r=s.match(t),n=r[1],a=r[2],i=o.bind(i,this),n+=".delegateEvents"+this.cid,""===a?l.push(this.jqon(n,i)):l.push(this.jqon(n,a,i))}return l}},t.prototype.jqon=function(e,t,n){var s;return null!=this.$el.on?(s=this.$el).on.apply(s,arguments):(null==n&&(n=t,t=void 0),null!=t?this.$el.delegate(t,e,n):this.$el.bind(e,n))},t.prototype.jqoff=function(e){var t;return null!=this.$el.off?(t=this.$el).off.apply(t,arguments):(this.$el.undelegate(),this.$el.unbind(e))},t.prototype.undelegateEvents=function(){return this.jqoff(".delegateEvents"+this.cid)},t.prototype.remove=function(){return this.undelegateEvents(),this.$el.remove()},t}(),i=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return p(n,t),n.prototype.defaults={hideAfter:10,scroll:!0,closeButtonText:"&times;"},n.prototype.initialize=function(t){return null==t&&(t={}),this.shown=!1,this.rendered=!1,this.messenger=t.messenger,this.options=e.extend({},this.options,t,this.defaults)},n.prototype.show=function(){var e;return this.rendered||this.render(),this.$message.removeClass("messenger-hidden"),e=this.shown,this.shown=!0,e?void 0:this.trigger("show")},n.prototype.hide=function(){var e;if(this.rendered)return this.$message.addClass("messenger-hidden"),e=this.shown,this.shown=!1,e?this.trigger("hide"):void 0},n.prototype.cancel=function(){return this.hide()},n.prototype.update=function(t){var n,s=this;return o.isString(t)&&(t={message:t}),e.extend(this.options,t),this.lastUpdate=new Date,this.rendered=!1,this.events=null!=(n=this.options.events)?n:{},this.render(),this.actionsToEvents(),this.delegateEvents(),this.checkClickable(),this.options.hideAfter?(this.$message.addClass("messenger-will-hide-after"),null!=this._hideTimeout&&clearTimeout(this._hideTimeout),this._hideTimeout=setTimeout(function(){return s.hide()},1e3*this.options.hideAfter)):this.$message.removeClass("messenger-will-hide-after"),this.options.hideOnNavigate?(this.$message.addClass("messenger-will-hide-on-navigate"),null!=("undefined"!=typeof Backbone&&null!==Backbone?Backbone.history:void 0)&&Backbone.history.on("route",function(){return s.hide()})):this.$message.removeClass("messenger-will-hide-on-navigate"),this.trigger("update",this)},n.prototype.scrollTo=function(){return this.options.scroll?e.scrollTo(this.$el,{duration:400,offset:{left:0,top:-20}}):void 0},n.prototype.timeSinceUpdate=function(){return this.lastUpdate?new Date-this.lastUpdate:null},n.prototype.actionsToEvents=function(){var e,t,n,s,r=this;n=this.options.actions,s=[];for(t in n)e=n[t],s.push(this.events['click [data-action="'+t+'"] a']=function(e){return function(n){return n.preventDefault(),n.stopPropagation(),r.trigger("action:"+t,e,n),e.action.call(r,n,r)}}(e));return s},n.prototype.checkClickable=function(){var e,t,n,s;n=this.events,s=[];for(t in n)e=n[t],"click"===t?s.push(this.$message.addClass("messenger-clickable")):s.push(void 0);return s},n.prototype.undelegateEvents=function(){var e;return n.__super__.undelegateEvents.apply(this,arguments),null!=(e=this.$message)?e.removeClass("messenger-clickable"):void 0},n.prototype.parseActions=function(){var t,n,s,r,o,i;n=[],o=this.options.actions;for(r in o)t=o[r],s=e.extend({},t),s.name=r,null==(i=s.label)&&(s.label=r),n.push(s);return n},n.prototype.template=function(t){var n,s,r,o,i,a,l,u,c,h,p=this;for(i=e("<div class='messenger-message message alert "+t.type+" message-"+t.type+" alert-"+t.type+"'>"),t.showCloseButton&&(r=e('<button type="button" class="messenger-close" data-dismiss="alert">'),r.html(t.closeButtonText),r.click(function(){return p.cancel(),!0}),i.append(r)),a=e('<div class="messenger-message-inner">'+t.message+"</div>"),i.append(a),t.actions.length&&(s=e('<div class="messenger-actions">')),h=t.actions,u=0,c=h.length;c>u;u++)l=h[u],n=e("<span>"),n.attr("data-action",""+l.name),o=e("<a>"),o.html(l.label),n.append(e('<span class="messenger-phrase">')),n.append(o),s.append(n);return i.append(s),i},n.prototype.render=function(){var t;if(!this.rendered)return this._hasSlot||(this.setElement(this.messenger._reserveMessageSlot(this)),this._hasSlot=!0),t=e.extend({},this.options,{actions:this.parseActions()}),this.$message=e(this.template(t)),this.$el.html(this.$message),this.shown=!0,this.rendered=!0,this.trigger("render")},n}(n),r=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return p(t,e),t.prototype.initialize=function(){return t.__super__.initialize.apply(this,arguments),this._timers={}},t.prototype.cancel=function(){return this.clearTimers(),this.hide(),null!=this._actionInstance&&null!=this._actionInstance.abort?this._actionInstance.abort():void 0},t.prototype.clearTimers=function(){var e,t,n,s;n=this._timers;for(e in n)t=n[e],clearTimeout(t);return this._timers={},null!=(s=this.$message)?s.removeClass("messenger-retry-soon messenger-retry-later"):void 0},t.prototype.render=function(){var e,n,s,r;t.__super__.render.apply(this,arguments),this.clearTimers(),s=this.options.actions,r=[];for(n in s)e=s[n],e.auto?r.push(this.startCountdown(n,e)):r.push(void 0);return r},t.prototype.renderPhrase=function(e,t){var n;return n=e.phrase.replace("TIME",this.formatTime(t))},t.prototype.formatTime=function(e){var t;return t=function(e,t){return e=Math.floor(e),1!==e&&(t+="s"),"in "+e+" "+t},0===Math.floor(e)?"now...":60>e?t(e,"second"):(e/=60,60>e?t(e,"minute"):(e/=60,t(e,"hour")))},t.prototype.startCountdown=function(e,t){var n,s,r,o,i=this;if(null==this._timers[e])return n=this.$message.find("[data-action='"+e+"'] .messenger-phrase"),s=null!=(o=t.delay)?o:3,10>=s?(this.$message.removeClass("messenger-retry-later"),this.$message.addClass("messenger-retry-soon")):(this.$message.removeClass("messenger-retry-soon"),this.$message.addClass("messenger-retry-later")),r=function(){var o;return n.text(i.renderPhrase(t,s)),s>0?(o=Math.min(s,1),s-=o,i._timers[e]=setTimeout(r,1e3*o)):(i.$message.removeClass("messenger-retry-soon messenger-retry-later"),delete i._timers[e],t.action())},r()},t}(i),a=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return p(n,t),n.prototype.tagName="ul",n.prototype.className="messenger",n.prototype.messageDefaults={type:"info"},n.prototype.initialize=function(t){return this.options=null!=t?t:{},this.history=[],this.messageDefaults=e.extend({},this.messageDefaults,this.options.messageDefaults)},n.prototype.render=function(){return this.updateMessageSlotClasses()},n.prototype.findById=function(e){return o.filter(this.history,function(t){return t.msg.options.id===e})},n.prototype._reserveMessageSlot=function(t){var n,s,r=this;for(n=e("<li>"),n.addClass("messenger-message-slot"),this.$el.prepend(n),this.history.push({msg:t,$slot:n}),this._enforceIdConstraint(t),t.on("update",function(){return r._enforceIdConstraint(t)});this.options.maxMessages&&this.history.length>this.options.maxMessages;)s=this.history.shift(),s.msg.remove(),s.$slot.remove();return n},n.prototype._enforceIdConstraint=function(e){var t,n,s,r,o;if(null!=e.options.id)for(o=this.history,n=0,s=o.length;s>n;n++)if(t=o[n],r=t.msg,null!=r.options.id&&r.options.id===e.options.id&&e!==r){if(e.options.singleton)return e.hide(),void 0;r.hide()}},n.prototype.newMessage=function(e){var t,n,s,o,a=this;return null==e&&(e={}),e.messenger=this,i=null!=(n=null!=(s=Messenger.themes[null!=(o=e.theme)?o:this.options.theme])?s.Message:void 0)?n:r,t=new i(e),t.on("show",function(){return e.scrollTo&&"fixed"!==a.$el.css("position")?t.scrollTo():void 0}),t.on("hide show render",this.updateMessageSlotClasses,this),t},n.prototype.updateMessageSlotClasses=function(){var e,t,n,s,r,o,i;for(s=!0,t=null,e=!1,i=this.history,r=0,o=i.length;o>r;r++)n=i[r],n.$slot.removeClass("messenger-first messenger-last messenger-shown"),n.msg.shown&&n.msg.rendered&&(n.$slot.addClass("messenger-shown"),e=!0,t=n,s&&(s=!1,n.$slot.addClass("messenger-first")));return null!=t&&t.$slot.addClass("messenger-last"),this.$el[""+(e?"remove":"add")+"Class"]("messenger-empty")},n.prototype.hideAll=function(){var e,t,n,s,r;for(s=this.history,r=[],t=0,n=s.length;n>t;t++)e=s[t],r.push(e.msg.hide());return r},n.prototype.post=function(t){var n;return o.isString(t)&&(t={message:t}),t=e.extend(!0,{},this.messageDefaults,t),n=this.newMessage(t),n.update(t),n},n}(n),t=function(t){function n(){return n.__super__.constructor.apply(this,arguments)}return p(n,t),n.prototype.doDefaults={progressMessage:null,successMessage:null,errorMessage:"Error connecting to the server.",showSuccessWithoutError:!0,retry:{auto:!0,allow:!0},action:e.ajax},n.prototype.hookBackboneAjax=function(t){var n,s=this;if(null==t&&(t={}),null==window.Backbone)throw"Expected Backbone to be defined";return t=o.defaults(t,{id:"BACKBONE_ACTION",errorMessage:!1,successMessage:"Request completed successfully.",showSuccessWithoutError:!1}),n=function(e){var n;return n=o.extend({},t,e.messenger),s["do"](n,e)},null!=Backbone.ajax?(Backbone.ajax._withoutMessenger&&(Backbone.ajax=Backbone.ajax._withoutMessenger),(null==t.action||t.action===this.doDefaults.action)&&(t.action=Backbone.ajax),n._withoutMessenger=Backbone.ajax,Backbone.ajax=n):Backbone.sync=o.wrap(Backbone.sync,function(){var t,s,r;return r=arguments[0],t=arguments.length>=2?d.call(arguments,1):[],s=e.ajax,e.ajax=n,r.call.apply(r,[this].concat(d.call(t))),e.ajax=s})},n.prototype._getHandlerResponse=function(e){return e===!1?!1:e===!0||null==e?!0:e},n.prototype._parseEvents=function(e){var t,n,s,r,o,i,a;null==e&&(e={}),o={};for(r in e)s=e[r],n=r.indexOf(" "),i=r.substring(0,n),t=r.substring(n+1),null==(a=o[i])&&(o[i]={}),o[i][t]=s;return o},n.prototype._normalizeResponse=function(){var e,t,n,s,r,i,a;for(n=arguments.length>=1?d.call(arguments,0):[],s=null,r=null,e=null,i=0,a=n.length;a>i;i++)t=n[i],"success"===t||"timeout"===t||"abort"===t?s=t:null!=(null!=t?t.readyState:void 0)&&null!=(null!=t?t.responseText:void 0)?r=t:o.isObject(t)&&(e=t);return[s,e,r]},n.prototype.run=function(){var t,n,s,r,i,a,l,u,c,h,p,g=this;if(a=arguments[0],c=arguments[1],t=arguments.length>=3?d.call(arguments,2):[],null==c&&(c={}),a=e.extend(!0,{},this.messageDefaults,this.doDefaults,null!=a?a:{}),n=this._parseEvents(a.events),s=function(e,t){var n;return n=a[e+"Message"],o.isFunction(n)?n.call(g,e,t):n},l=null!=(p=a.messageInstance)?p:this.newMessage(a),null!=a.id&&(l.options.id=a.id),null!=a.progressMessage&&l.update(e.extend({},a,{message:s("progress",null),type:"info"})),i={},o.each(["error","success"],function(r){var u;return u=c[r],i[r]=function(){var i,h,p,m,y,v,_,w,b,x,M,C,k,$,E;return v=arguments.length>=1?d.call(arguments,0):[],b=g._normalizeResponse.apply(g,v),y=b[0],i=b[1],w=b[2],"success"===r&&null==l.errorCount&&a.showSuccessWithoutError===!1&&(a.successMessage=null),"error"===r&&(null==(x=a.errorCount)&&(a.errorCount=0),a.errorCount+=1),p=a.returnsPromise?v[0]:"function"==typeof u?u.apply(null,v):void 0,_=g._getHandlerResponse(p),o.isString(_)&&(_={message:_}),"error"!==r||0!==(null!=w?w.status:void 0)&&"abort"!==y?"error"===r&&null!=a.ignoredErrorCodes&&(M=null!=w?w.status:void 0,f.call(a.ignoredErrorCodes,M)>=0)?(l.hide(),void 0):(h={message:s(r,w),type:r,events:null!=(C=n[r])?C:{},hideOnNavigate:"success"===r},m=e.extend({},a,h,_),"number"==typeof(null!=(k=m.retry)?k.allow:void 0)&&m.retry.allow--,"error"===r&&(null!=w?w.status:void 0)>=500&&(null!=($=m.retry)?$.allow:void 0)?(null==m.retry.delay&&(m.retry.delay=4>m.errorCount?10:300),m.hideAfter&&(null==(E=m._hideAfter)&&(m._hideAfter=m.hideAfter),m.hideAfter=m._hideAfter+m.retry.delay),m._retryActions=!0,m.actions={retry:{label:"retry now",phrase:"Retrying TIME",auto:m.retry.auto,delay:m.retry.delay,action:function(){return m.messageInstance=l,setTimeout(function(){return g["do"].apply(g,[m,c].concat(d.call(t)))},0)}},cancel:{action:function(){return l.cancel()}}}):m._retryActions&&(delete m.actions.retry,delete m.actions.cancel,delete a._retryActions),l.update(m),_&&m.message?(Messenger(o.extend({},g.options,{instance:g})),l.show()):l.hide()):(l.hide(),void 0)}}),!a.returnsPromise)for(h in i)r=i[h],u=c[h],c[h]=r;return l._actionInstance=a.action.apply(a,[c].concat(d.call(t))),a.returnsPromise&&l._actionInstance.then(i.success,i.error),l},n.prototype["do"]=n.prototype.run,n.prototype.ajax=function(){var t,n;return n=arguments[0],t=arguments.length>=2?d.call(arguments,1):[],n.action=e.ajax,this.run.apply(this,[n].concat(d.call(t)))},n.prototype.expectPromise=function(e,t){return t=o.extend({},t,{action:e,returnsPromise:!0}),this.run(t)},n.prototype.error=function(e){return null==e&&(e={}),"string"==typeof e&&(e={message:e}),e.type="error",this.post(e)},n.prototype.info=function(e){return null==e&&(e={}),"string"==typeof e&&(e={message:e}),e.type="info",this.post(e)},n.prototype.success=function(e){return null==e&&(e={}),"string"==typeof e&&(e={message:e}),e.type="success",this.post(e)},n}(a),e.fn.messenger=function(){var n,s,r,i,l,u,c,h;return r=arguments[0],s=arguments.length>=2?d.call(arguments,1):[],null==r&&(r={}),n=this,null!=r&&o.isString(r)?(h=n.data("messenger"))[r].apply(h,s):(l=r,null==n.data("messenger")&&(a=null!=(u=null!=(c=Messenger.themes[l.theme])?c.Messenger:void 0)?u:t,n.data("messenger",i=new a(e.extend({el:n},l))),i.render()),n.data("messenger"))},window.Messenger._call=function(t){var n,s,r,o,i,a,l,u,c,h,p;if(a={extraClasses:"messenger-fixed messenger-on-bottom messenger-on-right",theme:"future",maxMessages:9,parentLocations:["body"]},t=e.extend(a,e._messengerDefaults,Messenger.options,t),null!=t.theme&&(t.extraClasses+=" messenger-theme-"+t.theme),l=t.instance||Messenger.instance,null==t.instance){for(c=t.parentLocations,s=null,r=null,h=0,p=c.length;p>h;h++)if(u=c[h],s=e(u),s.length){o=u;break}l?e(l._location).is(e(o))||(l.$el.detach(),s.prepend(l.$el)):(n=e("<ul>"),s.prepend(n),l=n.messenger(t),l._location=o,Messenger.instance=l)}return null!=l._addedClasses&&l.$el.removeClass(l._addedClasses),l.$el.addClass(i=""+l.className+" "+t.extraClasses),l._addedClasses=i,l},e.extend(Messenger,{Message:r,Messenger:t,themes:null!=(c=Messenger.themes)?c:{}}),e.globalMessenger=window.Messenger=Messenger}.call(this);
/*
 * jQuery Reveal Plugin 1.0
 * www.ZURB.com
 * Copyright 2010, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/


(function($) {

/*---------------------------
 Defaults for Reveal
----------------------------*/
	 
/*---------------------------
 Listener for data-reveal-id attributes
----------------------------*/

    $(document).on('click', 'a[data-reveal-id]', function(e) {
		e.preventDefault();
		var modalLocation = $(this).attr('data-reveal-id');
		$('#'+modalLocation).reveal($(this).data());
	});

/*---------------------------
 Extend and Execute
----------------------------*/

    $.fn.reveal = function(options) {
        
        
        var defaults = {  
	    	animation: 'fadeAndPop', //fade, fadeAndPop, none
		    animationspeed: 300, //how fast animtions are
		    closeonbackgroundclick: true, //if you click background will modal close?
		    dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
    	}; 
    	
        //Extend dem' options
        var options = $.extend({}, defaults, options); 
	
        return this.each(function() {
        
/*---------------------------
 Global Variables
----------------------------*/
        	var modal = $(this),
        		topMeasure  = parseInt(modal.css('top')),
				topOffset = modal.height() + topMeasure,
          		locked = false,
				modalBG = $('.reveal-modal-bg');

/*---------------------------
 Create Modal BG
----------------------------*/
			if(modalBG.length == 0) {
				modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
			}		    
     
/*---------------------------
 Open & Close Animations
----------------------------*/
			//Entrance Animations
			modal.bind('reveal:open', function () {
			  modalBG.unbind('click.modalEvent');
				$('.' + options.dismissmodalclass).unbind('click.modalEvent');
				if(!locked) {
					lockModal();
					if(options.animation == "fadeAndPop") {
					    modal.css({ 'top': $(document).scrollTop() - topOffset, 'opacity': 0, 'visibility': 'visible', 'display': '' });
						modalBG.fadeIn(options.animationspeed/2);
						modal.delay(options.animationspeed/2).animate({
							"top": $(document).scrollTop()+topMeasure + 'px',
							"opacity" : 1
						}, options.animationspeed,unlockModal());					
					}
					if(options.animation == "fade") {
					    modal.css({ 'opacity': 0, 'visibility': 'visible', 'top': $(document).scrollTop() + topMeasure, 'display': '' });
						modalBG.fadeIn(options.animationspeed/2);
						modal.delay(options.animationspeed/2).animate({
							"opacity" : 1
						}, options.animationspeed,unlockModal());					
					} 
					if(options.animation == "none") {
					    modal.css({ 'visibility': 'visible', 'top': $(document).scrollTop() + topMeasure, 'display': '' });
						modalBG.css({"display":"block"});	
						unlockModal()				
					}
				}
				modal.unbind('reveal:open');
			}); 	

			//Closing Animation
			modal.bind('reveal:close', function () {
			  if(!locked) {
					lockModal();
					if(options.animation == "fadeAndPop") {
						modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
						modal.animate({
							"top":  $(document).scrollTop()-topOffset + 'px',
							"opacity" : 0
						}, options.animationspeed/2, function() {
						    modal.css({ 'top': topMeasure, 'opacity': 1, 'visibility': 'hidden', 'display': 'none' });
							unlockModal();
						});					
					}  	
					if(options.animation == "fade") {
						modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
						modal.animate({
							"opacity" : 0
						}, options.animationspeed, function() {
						    modal.css({ 'opacity': 1, 'visibility': 'hidden', 'top': topMeasure, 'display': 'none' });
							unlockModal();
						});					
					}  	
					if(options.animation == "none") {
					    modal.css({ 'visibility': 'hidden', 'top': topMeasure, 'display': 'none' });
						modalBG.css({'display' : 'none'});	
					}		
				}
				modal.unbind('reveal:close');
			});     
   	
/*---------------------------
 Open and add Closing Listeners
----------------------------*/
        	//Open Modal Immediately
    	modal.trigger('reveal:open')
			
			//Close Modal Listeners
			var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
			  modal.trigger('reveal:close')
			});
			
			if(options.closeonbackgroundclick) {
				modalBG.css({"cursor":"pointer"})
				modalBG.bind('click.modalEvent', function () {
				  modal.trigger('reveal:close')
				});
			}
			$('body').keyup(function(e) {
        		if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
			});
			
			
/*---------------------------
 Animations Locks
----------------------------*/
			function unlockModal() { 
				locked = false;
			}
			function lockModal() {
				locked = true;
			}	
			
        });//each call
    }//orbit plugin call
})(jQuery);
        

//fgnass.github.com/spin.js#v2.0.0
!function(a,b){"object"==typeof exports?module.exports=b():"function"==typeof define&&define.amd?define(b):a.Spinner=b()}(this,function(){"use strict";function a(a,b){var c,d=document.createElement(a||"div");for(c in b)d[c]=b[c];return d}function b(a){for(var b=1,c=arguments.length;c>b;b++)a.appendChild(arguments[b]);return a}function c(a,b,c,d){var e=["opacity",b,~~(100*a),c,d].join("-"),f=.01+c/d*100,g=Math.max(1-(1-a)/b*(100-f),a),h=j.substring(0,j.indexOf("Animation")).toLowerCase(),i=h&&"-"+h+"-"||"";return l[e]||(m.insertRule("@"+i+"keyframes "+e+"{0%{opacity:"+g+"}"+f+"%{opacity:"+a+"}"+(f+.01)+"%{opacity:1}"+(f+b)%100+"%{opacity:"+a+"}100%{opacity:"+g+"}}",m.cssRules.length),l[e]=1),e}function d(a,b){var c,d,e=a.style;for(b=b.charAt(0).toUpperCase()+b.slice(1),d=0;d<k.length;d++)if(c=k[d]+b,void 0!==e[c])return c;return void 0!==e[b]?b:void 0}function e(a,b){for(var c in b)a.style[d(a,c)||c]=b[c];return a}function f(a){for(var b=1;b<arguments.length;b++){var c=arguments[b];for(var d in c)void 0===a[d]&&(a[d]=c[d])}return a}function g(a,b){return"string"==typeof a?a:a[b%a.length]}function h(a){this.opts=f(a||{},h.defaults,n)}function i(){function c(b,c){return a("<"+b+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',c)}m.addRule(".spin-vml","behavior:url(#default#VML)"),h.prototype.lines=function(a,d){function f(){return e(c("group",{coordsize:k+" "+k,coordorigin:-j+" "+-j}),{width:k,height:k})}function h(a,h,i){b(m,b(e(f(),{rotation:360/d.lines*a+"deg",left:~~h}),b(e(c("roundrect",{arcsize:d.corners}),{width:j,height:d.width,left:d.radius,top:-d.width>>1,filter:i}),c("fill",{color:g(d.color,a),opacity:d.opacity}),c("stroke",{opacity:0}))))}var i,j=d.length+d.width,k=2*j,l=2*-(d.width+d.length)+"px",m=e(f(),{position:"absolute",top:l,left:l});if(d.shadow)for(i=1;i<=d.lines;i++)h(i,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(i=1;i<=d.lines;i++)h(i);return b(a,m)},h.prototype.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}}var j,k=["webkit","Moz","ms","O"],l={},m=function(){var c=a("style",{type:"text/css"});return b(document.getElementsByTagName("head")[0],c),c.sheet||c.styleSheet}(),n={lines:12,length:7,width:5,radius:10,rotate:0,corners:1,color:"#000",direction:1,speed:1,trail:100,opacity:.25,fps:20,zIndex:2e9,className:"spinner",top:"50%",left:"50%",position:"absolute"};h.defaults={},f(h.prototype,{spin:function(b){this.stop();{var c=this,d=c.opts,f=c.el=e(a(0,{className:d.className}),{position:d.position,width:0,zIndex:d.zIndex});d.radius+d.length+d.width}if(b&&(b.insertBefore(f,b.firstChild||null),e(f,{left:d.left,top:d.top})),f.setAttribute("role","progressbar"),c.lines(f,c.opts),!j){var g,h=0,i=(d.lines-1)*(1-d.direction)/2,k=d.fps,l=k/d.speed,m=(1-d.opacity)/(l*d.trail/100),n=l/d.lines;!function o(){h++;for(var a=0;a<d.lines;a++)g=Math.max(1-(h+(d.lines-a)*n)%l*m,d.opacity),c.opacity(f,a*d.direction+i,g,d);c.timeout=c.el&&setTimeout(o,~~(1e3/k))}()}return c},stop:function(){var a=this.el;return a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=void 0),this},lines:function(d,f){function h(b,c){return e(a(),{position:"absolute",width:f.length+f.width+"px",height:f.width+"px",background:b,boxShadow:c,transformOrigin:"left",transform:"rotate("+~~(360/f.lines*k+f.rotate)+"deg) translate("+f.radius+"px,0)",borderRadius:(f.corners*f.width>>1)+"px"})}for(var i,k=0,l=(f.lines-1)*(1-f.direction)/2;k<f.lines;k++)i=e(a(),{position:"absolute",top:1+~(f.width/2)+"px",transform:f.hwaccel?"translate3d(0,0,0)":"",opacity:f.opacity,animation:j&&c(f.opacity,f.trail,l+k*f.direction,f.lines)+" "+1/f.speed+"s linear infinite"}),f.shadow&&b(i,e(h("#000","0 0 4px #000"),{top:"2px"})),b(d,b(i,h(g(f.color,k),"0 0 1px rgba(0,0,0,.1)")));return d},opacity:function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)}});var o=e(a("group"),{behavior:"url(#default#VML)"});return!d(o,"transform")&&o.adj?i():j=d(o,"animation"),h});
(function(){(function(n){var x=this||(0,eval)("this"),u=x.document,M=x.navigator,v=x.jQuery,F=x.JSON;(function(n){"function"===typeof define&&define.amd?define('knockout',["exports","require"],n):"object"===typeof exports&&"object"===typeof module?n(module.exports||exports):n(x.ko={})})(function(N,O){function J(a,c){return null===a||typeof a in T?a===c:!1}function U(b,c){var d;return function(){d||(d=a.a.setTimeout(function(){d=n;b()},c))}}function V(b,c){var d;return function(){clearTimeout(d);d=a.a.setTimeout(b,c)}}function W(a,c){c&&c!==I?"beforeChange"===c?this.Kb(a):this.Ha(a,c):this.Lb(a)}function X(a,c){null!==c&&c.k&&c.k()}function Y(a,c){var d=this.Hc,e=d[s];e.R||(this.lb&&this.Ma[c]?(d.Pb(c,a,this.Ma[c]),this.Ma[c]=null,--this.lb):e.r[c]||d.Pb(c,a,e.s?{ia:a}:d.uc(a)))}function K(b,c,d,e){a.d[b]={init:function(b,g,k,l,m){var h,r;a.m(function(){var q=a.a.c(g()),p=!d!==!q,A=!r;if(A||c||p!==h)A&&a.va.Aa()&&(r=a.a.ua(a.f.childNodes(b),!0)),p?(A||a.f.da(b,a.a.ua(r)),a.eb(e?e(m,q):m,b)):a.f.xa(b),h=p},null,{i:b});return{controlsDescendantBindings:!0}}};a.h.ta[b]=!1;a.f.Z[b]=!0}var a="undefined"!==typeof N?N:{};a.b=function(b,c){for(var d=b.split("."),e=a,f=0;f<d.length-1;f++)e=e[d[f]];e[d[d.length-1]]=c};a.G=function(a,c,d){a[c]=d};a.version="3.4.0";a.b("version",a.version);a.options={deferUpdates:!1,useOnlyNativeEvents:!1};a.a=function(){function b(a,b){for(var c in a)a.hasOwnProperty(c)&&b(c,a[c])}function c(a,b){if(b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function d(a,b){a.__proto__=b;return a}function e(b,c,d,e){var h=b[c].match(r)||[];a.a.q(d.match(r),function(b){a.a.pa(h,b,e)});b[c]=h.join(" ")}var f={__proto__:[]}instanceof Array,g="function"===typeof Symbol,k={},l={};k[M&&/Firefox\/2/i.test(M.userAgent)?"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];k.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");b(k,function(a,b){if(b.length)for(var c=0,d=b.length;c<d;c++)l[b[c]]=a});var m={propertychange:!0},h=u&&function(){for(var a=3,b=u.createElement("div"),c=b.getElementsByTagName("i");b.innerHTML="\x3c!--[if gt IE "+ ++a+"]><i></i><![endif]--\x3e",c[0];);return 4<a?a:n}(),r=/\S+/g;return{cc:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],q:function(a,b){for(var c=0,d=a.length;c<d;c++)b(a[c],c)},o:function(a,b){if("function"==typeof Array.prototype.indexOf)return Array.prototype.indexOf.call(a,b);for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},Sb:function(a,b,c){for(var d=0,e=a.length;d<e;d++)if(b.call(c,a[d],d))return a[d];return null},La:function(b,c){var d=a.a.o(b,c);0<d?b.splice(d,1):0===d&&b.shift()},Tb:function(b){b=b||[];for(var c=[],d=0,e=b.length;d<e;d++)0>a.a.o(c,b[d])&&c.push(b[d]);return c},fb:function(a,b){a=a||[];for(var c=[],d=0,e=a.length;d<e;d++)c.push(b(a[d],d));return c},Ka:function(a,b){a=a||[];for(var c=[],d=0,e=a.length;d<e;d++)b(a[d],d)&&c.push(a[d]);return c},ra:function(a,b){if(b instanceof Array)a.push.apply(a,b);else for(var c=0,d=b.length;c<d;c++)a.push(b[c]);return a},pa:function(b,c,d){var e=a.a.o(a.a.zb(b),c);0>e?d&&b.push(c):d||b.splice(e,1)},ka:f,extend:c,Xa:d,Ya:f?d:c,D:b,Ca:function(a,b){if(!a)return a;var c={},d;for(d in a)a.hasOwnProperty(d)&&(c[d]=b(a[d],d,a));return c},ob:function(b){for(;b.firstChild;)a.removeNode(b.firstChild)},jc:function(b){b=a.a.V(b);for(var c=(b[0]&&b[0].ownerDocument||u).createElement("div"),d=0,e=b.length;d<e;d++)c.appendChild(a.$(b[d]));return c},ua:function(b,c){for(var d=0,e=b.length,h=[];d<e;d++){var m=b[d].cloneNode(!0);h.push(c?a.$(m):m)}return h},da:function(b,c){a.a.ob(b);if(c)for(var d=0,e=c.length;d<e;d++)b.appendChild(c[d])},qc:function(b,c){var d=b.nodeType?[b]:b;if(0<d.length){for(var e=d[0],h=e.parentNode,m=0,l=c.length;m<l;m++)h.insertBefore(c[m],e);m=0;for(l=d.length;m<l;m++)a.removeNode(d[m])}},za:function(a,b){if(a.length){for(b=8===b.nodeType&&b.parentNode||b;a.length&&a[0].parentNode!==b;)a.splice(0,1);for(;1<a.length&&a[a.length-1].parentNode!==b;)a.length--;if(1<a.length){var c=a[0],d=a[a.length-1];for(a.length=0;c!==d;)a.push(c),c=c.nextSibling;a.push(d)}}return a},sc:function(a,b){7>h?a.setAttribute("selected",b):a.selected=b},$a:function(a){return null===a||a===n?"":a.trim?a.trim():a.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},nd:function(a,b){a=a||"";return b.length>a.length?!1:a.substring(0,b.length)===b},Mc:function(a,b){if(a===b)return!0;if(11===a.nodeType)return!1;if(b.contains)return b.contains(3===a.nodeType?a.parentNode:a);if(b.compareDocumentPosition)return 16==(b.compareDocumentPosition(a)&16);for(;a&&a!=b;)a=a.parentNode;return!!a},nb:function(b){return a.a.Mc(b,b.ownerDocument.documentElement)},Qb:function(b){return!!a.a.Sb(b,a.a.nb)},A:function(a){return a&&a.tagName&&a.tagName.toLowerCase()},Wb:function(b){return a.onError?function(){try{return b.apply(this,arguments)}catch(c){throw a.onError&&a.onError(c),c;}}:b},setTimeout:function(b,c){return setTimeout(a.a.Wb(b),c)},$b:function(b){setTimeout(function(){a.onError&&a.onError(b);throw b;},0)},p:function(b,c,d){var e=a.a.Wb(d);d=h&&m[c];if(a.options.useOnlyNativeEvents||d||!v)if(d||"function"!=typeof b.addEventListener)if("undefined"!=typeof b.attachEvent){var l=function(a){e.call(b,a)},f="on"+c;b.attachEvent(f,l);a.a.F.oa(b,function(){b.detachEvent(f,l)})}else throw Error("Browser doesn't support addEventListener or attachEvent");else b.addEventListener(c,e,!1);else v(b).bind(c,e)},Da:function(b,c){if(!b||!b.nodeType)throw Error("element must be a DOM node when calling triggerEvent");var d;"input"===a.a.A(b)&&b.type&&"click"==c.toLowerCase()?(d=b.type,d="checkbox"==d||"radio"==d):d=!1;if(a.options.useOnlyNativeEvents||!v||d)if("function"==typeof u.createEvent)if("function"==typeof b.dispatchEvent)d=u.createEvent(l[c]||"HTMLEvents"),d.initEvent(c,!0,!0,x,0,0,0,0,0,!1,!1,!1,!1,0,b),b.dispatchEvent(d);else throw Error("The supplied element doesn't support dispatchEvent");else if(d&&b.click)b.click();else if("undefined"!=typeof b.fireEvent)b.fireEvent("on"+c);else throw Error("Browser doesn't support triggering events");else v(b).trigger(c)},c:function(b){return a.H(b)?b():b},zb:function(b){return a.H(b)?b.t():b},bb:function(b,c,d){var h;c&&("object"===typeof b.classList?(h=b.classList[d?"add":"remove"],a.a.q(c.match(r),function(a){h.call(b.classList,a)})):"string"===typeof b.className.baseVal?e(b.className,"baseVal",c,d):e(b,"className",c,d))},Za:function(b,c){var d=a.a.c(c);if(null===d||d===n)d="";var e=a.f.firstChild(b);!e||3!=e.nodeType||a.f.nextSibling(e)?a.f.da(b,[b.ownerDocument.createTextNode(d)]):e.data=d;a.a.Rc(b)},rc:function(a,b){a.name=b;if(7>=h)try{a.mergeAttributes(u.createElement("<input name='"+a.name+"'/>"),!1)}catch(c){}},Rc:function(a){9<=h&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},Nc:function(a){if(h){var b=a.style.width;a.style.width=0;a.style.width=b}},hd:function(b,c){b=a.a.c(b);c=a.a.c(c);for(var d=[],e=b;e<=c;e++)d.push(e);return d},V:function(a){for(var b=[],c=0,d=a.length;c<d;c++)b.push(a[c]);return b},Yb:function(a){return g?Symbol(a):a},rd:6===h,sd:7===h,C:h,ec:function(b,c){for(var d=a.a.V(b.getElementsByTagName("input")).concat(a.a.V(b.getElementsByTagName("textarea"))),e="string"==typeof c?function(a){return a.name===c}:function(a){return c.test(a.name)},h=[],m=d.length-1;0<=m;m--)e(d[m])&&h.push(d[m]);return h},ed:function(b){return"string"==typeof b&&(b=a.a.$a(b))?F&&F.parse?F.parse(b):(new Function("return "+b))():null},Eb:function(b,c,d){if(!F||!F.stringify)throw Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");return F.stringify(a.a.c(b),c,d)},fd:function(c,d,e){e=e||{};var h=e.params||{},m=e.includeFields||this.cc,l=c;if("object"==typeof c&&"form"===a.a.A(c))for(var l=c.action,f=m.length-1;0<=f;f--)for(var g=a.a.ec(c,m[f]),k=g.length-1;0<=k;k--)h[g[k].name]=g[k].value;d=a.a.c(d);var r=u.createElement("form");r.style.display="none";r.action=l;r.method="post";for(var n in d)c=u.createElement("input"),c.type="hidden",c.name=n,c.value=a.a.Eb(a.a.c(d[n])),r.appendChild(c);b(h,function(a,b){var c=u.createElement("input");c.type="hidden";c.name=a;c.value=b;r.appendChild(c)});u.body.appendChild(r);e.submitter?e.submitter(r):r.submit();setTimeout(function(){r.parentNode.removeChild(r)},0)}}}();a.b("utils",a.a);a.b("utils.arrayForEach",a.a.q);a.b("utils.arrayFirst",a.a.Sb);a.b("utils.arrayFilter",a.a.Ka);a.b("utils.arrayGetDistinctValues",a.a.Tb);a.b("utils.arrayIndexOf",a.a.o);a.b("utils.arrayMap",a.a.fb);a.b("utils.arrayPushAll",a.a.ra);a.b("utils.arrayRemoveItem",a.a.La);a.b("utils.extend",a.a.extend);a.b("utils.fieldsIncludedWithJsonPost",a.a.cc);a.b("utils.getFormFields",a.a.ec);a.b("utils.peekObservable",a.a.zb);a.b("utils.postJson",a.a.fd);a.b("utils.parseJson",a.a.ed);a.b("utils.registerEventHandler",a.a.p);a.b("utils.stringifyJson",a.a.Eb);a.b("utils.range",a.a.hd);a.b("utils.toggleDomNodeCssClass",a.a.bb);a.b("utils.triggerEvent",a.a.Da);a.b("utils.unwrapObservable",a.a.c);a.b("utils.objectForEach",a.a.D);a.b("utils.addOrRemoveItem",a.a.pa);a.b("utils.setTextContent",a.a.Za);a.b("unwrap",a.a.c);Function.prototype.bind||(Function.prototype.bind=function(a){var c=this;if(1===arguments.length)return function(){return c.apply(a,arguments)};var d=Array.prototype.slice.call(arguments,1);return function(){var e=d.slice(0);e.push.apply(e,arguments);return c.apply(a,e)}});a.a.e=new function(){function a(b,g){var k=b[d];if(!k||"null"===k||!e[k]){if(!g)return n;k=b[d]="ko"+c++;e[k]={}}return e[k]}var c=0,d="__ko__"+(new Date).getTime(),e={};return{get:function(c,d){var e=a(c,!1);return e===n?n:e[d]},set:function(c,d,e){if(e!==n||a(c,!1)!==n)a(c,!0)[d]=e},clear:function(a){var b=a[d];return b?(delete e[b],a[d]=null,!0):!1},I:function(){return c++ +d}}};a.b("utils.domData",a.a.e);a.b("utils.domData.clear",a.a.e.clear);a.a.F=new function(){function b(b,c){var e=a.a.e.get(b,d);e===n&&c&&(e=[],a.a.e.set(b,d,e));return e}function c(d){var e=b(d,!1);if(e)for(var e=e.slice(0),l=0;l<e.length;l++)e[l](d);a.a.e.clear(d);a.a.F.cleanExternalData(d);if(f[d.nodeType])for(e=d.firstChild;d=e;)e=d.nextSibling,8===d.nodeType&&c(d)}var d=a.a.e.I(),e={1:!0,8:!0,9:!0},f={1:!0,9:!0};return{oa:function(a,c){if("function"!=typeof c)throw Error("Callback must be a function");b(a,!0).push(c)},pc:function(c,e){var l=b(c,!1);l&&(a.a.La(l,e),0==l.length&&a.a.e.set(c,d,n))},$:function(b){if(e[b.nodeType]&&(c(b),f[b.nodeType])){var d=[];a.a.ra(d,b.getElementsByTagName("*"));for(var l=0,m=d.length;l<m;l++)c(d[l])}return b},removeNode:function(b){a.$(b);b.parentNode&&b.parentNode.removeChild(b)},cleanExternalData:function(a){v&&"function"==typeof v.cleanData&&v.cleanData([a])}}};a.$=a.a.F.$;a.removeNode=a.a.F.removeNode;a.b("cleanNode",a.$);a.b("removeNode",a.removeNode);a.b("utils.domNodeDisposal",a.a.F);a.b("utils.domNodeDisposal.addDisposeCallback",a.a.F.oa);a.b("utils.domNodeDisposal.removeDisposeCallback",a.a.F.pc);(function(){var b=[0,"",""],c=[1,"<table>","</table>"],d=[3,"<table><tbody><tr>","</tr></tbody></table>"],e=[1,"<select multiple='multiple'>","</select>"],f={thead:c,tbody:c,tfoot:c,tr:[2,"<table><tbody>","</tbody></table>"],td:d,th:d,option:e,optgroup:e},g=8>=a.a.C;a.a.ma=function(c,d){var e;if(v)if(v.parseHTML)e=v.parseHTML(c,d)||[];else{if((e=v.clean([c],d))&&e[0]){for(var h=e[0];h.parentNode&&11!==h.parentNode.nodeType;)h=h.parentNode;h.parentNode&&h.parentNode.removeChild(h)}}else{(e=d)||(e=u);var h=e.parentWindow||e.defaultView||x,r=a.a.$a(c).toLowerCase(),q=e.createElement("div"),p;p=(r=r.match(/^<([a-z]+)[ >]/))&&f[r[1]]||b;r=p[0];p="ignored<div>"+p[1]+c+p[2]+"</div>";"function"==typeof h.innerShiv?q.appendChild(h.innerShiv(p)):(g&&e.appendChild(q),q.innerHTML=p,g&&q.parentNode.removeChild(q));for(;r--;)q=q.lastChild;e=a.a.V(q.lastChild.childNodes)}return e};a.a.Cb=function(b,c){a.a.ob(b);c=a.a.c(c);if(null!==c&&c!==n)if("string"!=typeof c&&(c=c.toString()),v)v(b).html(c);else for(var d=a.a.ma(c,b.ownerDocument),e=0;e<d.length;e++)b.appendChild(d[e])}})();a.b("utils.parseHtmlFragment",a.a.ma);a.b("utils.setHtml",a.a.Cb);a.M=function(){function b(c,e){if(c)if(8==c.nodeType){var f=a.M.lc(c.nodeValue);null!=f&&e.push({Lc:c,cd:f})}else if(1==c.nodeType)for(var f=0,g=c.childNodes,k=g.length;f<k;f++)b(g[f],e)}var c={};return{wb:function(a){if("function"!=typeof a)throw Error("You can only pass a function to ko.memoization.memoize()");var b=(4294967296*(1+Math.random())|0).toString(16).substring(1)+(4294967296*(1+Math.random())|0).toString(16).substring(1);c[b]=a;return"\x3c!--[ko_memo:"+b+"]--\x3e"},xc:function(a,b){var f=c[a];if(f===n)throw Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized.");try{return f.apply(null,b||[]),!0}finally{delete c[a]}},yc:function(c,e){var f=[];b(c,f);for(var g=0,k=f.length;g<k;g++){var l=f[g].Lc,m=[l];e&&a.a.ra(m,e);a.M.xc(f[g].cd,m);l.nodeValue="";l.parentNode&&l.parentNode.removeChild(l)}},lc:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:null}}}();a.b("memoization",a.M);a.b("memoization.memoize",a.M.wb);a.b("memoization.unmemoize",a.M.xc);a.b("memoization.parseMemoText",a.M.lc);a.b("memoization.unmemoizeDomNodeAndDescendants",a.M.yc);a.Y=function(){function b(){if(e)for(var b=e,c=0,m;g<e;)if(m=d[g++]){if(g>b){if(5E3<=++c){g=e;a.a.$b(Error("'Too much recursion' after processing "+c+" task groups."));break}b=e}try{m()}catch(h){a.a.$b(h)}}}function c(){b();g=e=d.length=0}var d=[],e=0,f=1,g=0;return{scheduler:x.MutationObserver?function(a){var b=u.createElement("div");(new MutationObserver(a)).observe(b,{attributes:!0});return function(){b.classList.toggle("foo")}}(c):u&&"onreadystatechange"in u.createElement("script")?function(a){var b=u.createElement("script");b.onreadystatechange=function(){b.onreadystatechange=null;u.documentElement.removeChild(b);b=null;a()};u.documentElement.appendChild(b)}:function(a){setTimeout(a,0)},Wa:function(b){e||a.Y.scheduler(c);d[e++]=b;return f++},cancel:function(a){a-=f-e;a>=g&&a<e&&(d[a]=null)},resetForTesting:function(){var a=e-g;g=e=d.length=0;return a},md:b}}();a.b("tasks",a.Y);a.b("tasks.schedule",a.Y.Wa);a.b("tasks.runEarly",a.Y.md);a.ya={throttle:function(b,c){b.throttleEvaluation=c;var d=null;return a.B({read:b,write:function(e){clearTimeout(d);d=a.a.setTimeout(function(){b(e)},c)}})},rateLimit:function(a,c){var d,e,f;"number"==typeof c?d=c:(d=c.timeout,e=c.method);a.cb=!1;f="notifyWhenChangesStop"==e?V:U;a.Ta(function(a){return f(a,d)})},deferred:function(b,c){if(!0!==c)throw Error("The 'deferred' extender only accepts the value 'true', because it is not supported to turn deferral off once enabled.");b.cb||(b.cb=!0,b.Ta(function(c){var e;return function(){a.Y.cancel(e);e=a.Y.Wa(c);b.notifySubscribers(n,"dirty")}}))},notify:function(a,c){a.equalityComparer="always"==c?null:J}};var T={undefined:1,"boolean":1,number:1,string:1};a.b("extenders",a.ya);a.vc=function(b,c,d){this.ia=b;this.gb=c;this.Kc=d;this.R=!1;a.G(this,"dispose",this.k)};a.vc.prototype.k=function(){this.R=!0;this.Kc()};a.J=function(){a.a.Ya(this,D);D.rb(this)};var I="change",D={rb:function(a){a.K={};a.Nb=1},X:function(b,c,d){var e=this;d=d||I;var f=new a.vc(e,c?b.bind(c):b,function(){a.a.La(e.K[d],f);e.Ia&&e.Ia(d)});e.sa&&e.sa(d);e.K[d]||(e.K[d]=[]);e.K[d].push(f);return f},notifySubscribers:function(b,c){c=c||I;c===I&&this.zc();if(this.Pa(c))try{a.l.Ub();for(var d=this.K[c].slice(0),e=0,f;f=d[e];++e)f.R||f.gb(b)}finally{a.l.end()}},Na:function(){return this.Nb},Uc:function(a){return this.Na()!==a},zc:function(){++this.Nb},Ta:function(b){var c=this,d=a.H(c),e,f,g;c.Ha||(c.Ha=c.notifySubscribers,c.notifySubscribers=W);var k=b(function(){c.Mb=!1;d&&g===c&&(g=c());e=!1;c.tb(f,g)&&c.Ha(f=g)});c.Lb=function(a){c.Mb=e=!0;g=a;k()};c.Kb=function(a){e||(f=a,c.Ha(a,"beforeChange"))}},Pa:function(a){return this.K[a]&&this.K[a].length},Sc:function(b){if(b)return this.K[b]&&this.K[b].length||0;var c=0;a.a.D(this.K,function(a,b){"dirty"!==a&&(c+=b.length)});return c},tb:function(a,c){return!this.equalityComparer||!this.equalityComparer(a,c)},extend:function(b){var c=this;b&&a.a.D(b,function(b,e){var f=a.ya[b];"function"==typeof f&&(c=f(c,e)||c)});return c}};a.G(D,"subscribe",D.X);a.G(D,"extend",D.extend);a.G(D,"getSubscriptionsCount",D.Sc);a.a.ka&&a.a.Xa(D,Function.prototype);a.J.fn=D;a.hc=function(a){return null!=a&&"function"==typeof a.X&&"function"==typeof a.notifySubscribers};a.b("subscribable",a.J);a.b("isSubscribable",a.hc);a.va=a.l=function(){function b(a){d.push(e);e=a}function c(){e=d.pop()}var d=[],e,f=0;return{Ub:b,end:c,oc:function(b){if(e){if(!a.hc(b))throw Error("Only subscribable things can act as dependencies");e.gb.call(e.Gc,b,b.Cc||(b.Cc=++f))}},w:function(a,d,e){try{return b(),a.apply(d,e||[])}finally{c()}},Aa:function(){if(e)return e.m.Aa()},Sa:function(){if(e)return e.Sa}}}();a.b("computedContext",a.va);a.b("computedContext.getDependenciesCount",a.va.Aa);a.b("computedContext.isInitial",a.va.Sa);a.b("ignoreDependencies",a.qd=a.l.w);var E=a.a.Yb("_latestValue");a.N=function(b){function c(){if(0<arguments.length)return c.tb(c[E],arguments[0])&&(c.ga(),c[E]=arguments[0],c.fa()),this;a.l.oc(c);return c[E]}c[E]=b;a.a.ka||a.a.extend(c,a.J.fn);a.J.fn.rb(c);a.a.Ya(c,B);a.options.deferUpdates&&a.ya.deferred(c,!0);return c};var B={equalityComparer:J,t:function(){return this[E]},fa:function(){this.notifySubscribers(this[E])},ga:function(){this.notifySubscribers(this[E],"beforeChange")}};a.a.ka&&a.a.Xa(B,a.J.fn);var H=a.N.gd="__ko_proto__";B[H]=a.N;a.Oa=function(b,c){return null===b||b===n||b[H]===n?!1:b[H]===c?!0:a.Oa(b[H],c)};a.H=function(b){return a.Oa(b,a.N)};a.Ba=function(b){return"function"==typeof b&&b[H]===a.N||"function"==typeof b&&b[H]===a.B&&b.Vc?!0:!1};a.b("observable",a.N);a.b("isObservable",a.H);a.b("isWriteableObservable",a.Ba);a.b("isWritableObservable",a.Ba);a.b("observable.fn",B);a.G(B,"peek",B.t);a.G(B,"valueHasMutated",B.fa);a.G(B,"valueWillMutate",B.ga);a.la=function(b){b=b||[];if("object"!=typeof b||!("length"in b))throw Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");b=a.N(b);a.a.Ya(b,a.la.fn);return b.extend({trackArrayChanges:!0})};a.la.fn={remove:function(b){for(var c=this.t(),d=[],e="function"!=typeof b||a.H(b)?function(a){return a===b}:b,f=0;f<c.length;f++){var g=c[f];e(g)&&(0===d.length&&this.ga(),d.push(g),c.splice(f,1),f--)}d.length&&this.fa();return d},removeAll:function(b){if(b===n){var c=this.t(),d=c.slice(0);this.ga();c.splice(0,c.length);this.fa();return d}return b?this.remove(function(c){return 0<=a.a.o(b,c)}):[]},destroy:function(b){var c=this.t(),d="function"!=typeof b||a.H(b)?function(a){return a===b}:b;this.ga();for(var e=c.length-1;0<=e;e--)d(c[e])&&(c[e]._destroy=!0);this.fa()},destroyAll:function(b){return b===n?this.destroy(function(){return!0}):b?this.destroy(function(c){return 0<=a.a.o(b,c)}):[]},indexOf:function(b){var c=this();return a.a.o(c,b)},replace:function(a,c){var d=this.indexOf(a);0<=d&&(this.ga(),this.t()[d]=c,this.fa())}};a.a.ka&&a.a.Xa(a.la.fn,a.N.fn);a.a.q("pop push reverse shift sort splice unshift".split(" "),function(b){a.la.fn[b]=function(){var a=this.t();this.ga();this.Vb(a,b,arguments);var d=a[b].apply(a,arguments);this.fa();return d===a?this:d}});a.a.q(["slice"],function(b){a.la.fn[b]=function(){var a=this();return a[b].apply(a,arguments)}});a.b("observableArray",a.la);a.ya.trackArrayChanges=function(b,c){function d(){if(!e){e=!0;var c=b.notifySubscribers;b.notifySubscribers=function(a,b){b&&b!==I||++k;return c.apply(this,arguments)};var d=[].concat(b.t()||[]);f=null;g=b.X(function(c){c=[].concat(c||[]);if(b.Pa("arrayChange")){var e;if(!f||1<k)f=a.a.ib(d,c,b.hb);e=f}d=c;f=null;k=0;e&&e.length&&b.notifySubscribers(e,"arrayChange")})}}b.hb={};c&&"object"==typeof c&&a.a.extend(b.hb,c);b.hb.sparse=!0;if(!b.Vb){var e=!1,f=null,g,k=0,l=b.sa,m=b.Ia;b.sa=function(a){l&&l.call(b,a);"arrayChange"===a&&d()};b.Ia=function(a){m&&m.call(b,a);"arrayChange"!==a||b.Pa("arrayChange")||(g.k(),e=!1)};b.Vb=function(b,c,d){function m(a,b,c){return l[l.length]={status:a,value:b,index:c}}if(e&&!k){var l=[],g=b.length,t=d.length,G=0;switch(c){case"push":G=g;case"unshift":for(c=0;c<t;c++)m("added",d[c],G+c);break;case"pop":G=g-1;case"shift":g&&m("deleted",b[G],G);break;case"splice":c=Math.min(Math.max(0,0>d[0]?g+d[0]:d[0]),g);for(var g=1===t?g:Math.min(c+(d[1]||0),g),t=c+t-2,G=Math.max(g,t),P=[],n=[],Q=2;c<G;++c,++Q)c<g&&n.push(m("deleted",b[c],c)),c<t&&P.push(m("added",d[Q],c));a.a.dc(n,P);break;default:return}f=l}}}};var s=a.a.Yb("_state");a.m=a.B=function(b,c,d){function e(){if(0<arguments.length){if("function"===typeof f)f.apply(g.pb,arguments);else throw Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");return this}a.l.oc(e);(g.S||g.s&&e.Qa())&&e.aa();return g.T}"object"===typeof b?d=b:(d=d||{},b&&(d.read=b));if("function"!=typeof d.read)throw Error("Pass a function that returns the value of the ko.computed");var f=d.write,g={T:n,S:!0,Ra:!1,Fb:!1,R:!1,Va:!1,s:!1,jd:d.read,pb:c||d.owner,i:d.disposeWhenNodeIsRemoved||d.i||null,wa:d.disposeWhen||d.wa,mb:null,r:{},L:0,bc:null};e[s]=g;e.Vc="function"===typeof f;a.a.ka||a.a.extend(e,a.J.fn);a.J.fn.rb(e);a.a.Ya(e,z);d.pure?(g.Va=!0,g.s=!0,a.a.extend(e,$)):d.deferEvaluation&&a.a.extend(e,aa);a.options.deferUpdates&&a.ya.deferred(e,!0);g.i&&(g.Fb=!0,g.i.nodeType||(g.i=null));g.s||d.deferEvaluation||e.aa();g.i&&e.ba()&&a.a.F.oa(g.i,g.mb=function(){e.k()});return e};var z={equalityComparer:J,Aa:function(){return this[s].L},Pb:function(a,c,d){if(this[s].Va&&c===this)throw Error("A 'pure' computed must not be called recursively");this[s].r[a]=d;d.Ga=this[s].L++;d.na=c.Na()},Qa:function(){var a,c,d=this[s].r;for(a in d)if(d.hasOwnProperty(a)&&(c=d[a],c.ia.Uc(c.na)))return!0},bd:function(){this.Fa&&!this[s].Ra&&this.Fa()},ba:function(){return this[s].S||0<this[s].L},ld:function(){this.Mb||this.ac()},uc:function(a){if(a.cb&&!this[s].i){var c=a.X(this.bd,this,"dirty"),d=a.X(this.ld,this);return{ia:a,k:function(){c.k();d.k()}}}return a.X(this.ac,this)},ac:function(){var b=this,c=b.throttleEvaluation;c&&0<=c?(clearTimeout(this[s].bc),this[s].bc=a.a.setTimeout(function(){b.aa(!0)},c)):b.Fa?b.Fa():b.aa(!0)},aa:function(b){var c=this[s],d=c.wa;if(!c.Ra&&!c.R){if(c.i&&!a.a.nb(c.i)||d&&d()){if(!c.Fb){this.k();return}}else c.Fb=!1;c.Ra=!0;try{this.Qc(b)}finally{c.Ra=!1}c.L||this.k()}},Qc:function(b){var c=this[s],d=c.Va?n:!c.L,e={Hc:this,Ma:c.r,lb:c.L};a.l.Ub({Gc:e,gb:Y,m:this,Sa:d});c.r={};c.L=0;e=this.Pc(c,e);this.tb(c.T,e)&&(c.s||this.notifySubscribers(c.T,"beforeChange"),c.T=e,c.s?this.zc():b&&this.notifySubscribers(c.T));d&&this.notifySubscribers(c.T,"awake")},Pc:function(b,c){try{var d=b.jd;return b.pb?d.call(b.pb):d()}finally{a.l.end(),c.lb&&!b.s&&a.a.D(c.Ma,X),b.S=!1}},t:function(){var a=this[s];(a.S&&!a.L||a.s&&this.Qa())&&this.aa();return a.T},Ta:function(b){a.J.fn.Ta.call(this,b);this.Fa=function(){this.Kb(this[s].T);this[s].S=!0;this.Lb(this)}},k:function(){var b=this[s];!b.s&&b.r&&a.a.D(b.r,function(a,b){b.k&&b.k()});b.i&&b.mb&&a.a.F.pc(b.i,b.mb);b.r=null;b.L=0;b.R=!0;b.S=!1;b.s=!1;b.i=null}},$={sa:function(b){var c=this,d=c[s];if(!d.R&&d.s&&"change"==b){d.s=!1;if(d.S||c.Qa())d.r=null,d.L=0,d.S=!0,c.aa();else{var e=[];a.a.D(d.r,function(a,b){e[b.Ga]=a});a.a.q(e,function(a,b){var e=d.r[a],l=c.uc(e.ia);l.Ga=b;l.na=e.na;d.r[a]=l})}d.R||c.notifySubscribers(d.T,"awake")}},Ia:function(b){var c=this[s];c.R||"change"!=b||this.Pa("change")||(a.a.D(c.r,function(a,b){b.k&&(c.r[a]={ia:b.ia,Ga:b.Ga,na:b.na},b.k())}),c.s=!0,this.notifySubscribers(n,"asleep"))},Na:function(){var b=this[s];b.s&&(b.S||this.Qa())&&this.aa();return a.J.fn.Na.call(this)}},aa={sa:function(a){"change"!=a&&"beforeChange"!=a||this.t()}};a.a.ka&&a.a.Xa(z,a.J.fn);var R=a.N.gd;a.m[R]=a.N;z[R]=a.m;a.Xc=function(b){return a.Oa(b,a.m)};a.Yc=function(b){return a.Oa(b,a.m)&&b[s]&&b[s].Va};a.b("computed",a.m);a.b("dependentObservable",a.m);a.b("isComputed",a.Xc);a.b("isPureComputed",a.Yc);a.b("computed.fn",z);a.G(z,"peek",z.t);a.G(z,"dispose",z.k);a.G(z,"isActive",z.ba);a.G(z,"getDependenciesCount",z.Aa);a.nc=function(b,c){if("function"===typeof b)return a.m(b,c,{pure:!0});b=a.a.extend({},b);b.pure=!0;return a.m(b,c)};a.b("pureComputed",a.nc);(function(){function b(a,f,g){g=g||new d;a=f(a);if("object"!=typeof a||null===a||a===n||a instanceof RegExp||a instanceof Date||a instanceof String||a instanceof
Number||a instanceof Boolean)return a;var k=a instanceof Array?[]:{};g.save(a,k);c(a,function(c){var d=f(a[c]);switch(typeof d){case"boolean":case"number":case"string":case"function":k[c]=d;break;case"object":case"undefined":var h=g.get(d);k[c]=h!==n?h:b(d,f,g)}});return k}function c(a,b){if(a instanceof Array){for(var c=0;c<a.length;c++)b(c);"function"==typeof a.toJSON&&b("toJSON")}else for(c in a)b(c)}function d(){this.keys=[];this.Ib=[]}a.wc=function(c){if(0==arguments.length)throw Error("When calling ko.toJS, pass the object you want to convert.");return b(c,function(b){for(var c=0;a.H(b)&&10>c;c++)b=b();return b})};a.toJSON=function(b,c,d){b=a.wc(b);return a.a.Eb(b,c,d)};d.prototype={save:function(b,c){var d=a.a.o(this.keys,b);0<=d?this.Ib[d]=c:(this.keys.push(b),this.Ib.push(c))},get:function(b){b=a.a.o(this.keys,b);return 0<=b?this.Ib[b]:n}}})();a.b("toJS",a.wc);a.b("toJSON",a.toJSON);(function(){a.j={u:function(b){switch(a.a.A(b)){case"option":return!0===b.__ko__hasDomDataOptionValue__?a.a.e.get(b,a.d.options.xb):7>=a.a.C?b.getAttributeNode("value")&&b.getAttributeNode("value").specified?b.value:b.text:b.value;case"select":return 0<=b.selectedIndex?a.j.u(b.options[b.selectedIndex]):n;default:return b.value}},ha:function(b,c,d){switch(a.a.A(b)){case"option":switch(typeof c){case"string":a.a.e.set(b,a.d.options.xb,n);"__ko__hasDomDataOptionValue__"in b&&delete b.__ko__hasDomDataOptionValue__;b.value=c;break;default:a.a.e.set(b,a.d.options.xb,c),b.__ko__hasDomDataOptionValue__=!0,b.value="number"===typeof c?c:""}break;case"select":if(""===c||null===c)c=n;for(var e=-1,f=0,g=b.options.length,k;f<g;++f)if(k=a.j.u(b.options[f]),k==c||""==k&&c===n){e=f;break}if(d||0<=e||c===n&&1<b.size)b.selectedIndex=e;break;default:if(null===c||c===n)c="";b.value=c}}}})();a.b("selectExtensions",a.j);a.b("selectExtensions.readValue",a.j.u);a.b("selectExtensions.writeValue",a.j.ha);a.h=function(){function b(b){b=a.a.$a(b);123===b.charCodeAt(0)&&(b=b.slice(1,-1));var c=[],d=b.match(e),r,k=[],p=0;if(d){d.push(",");for(var A=0,y;y=d[A];++A){var t=y.charCodeAt(0);if(44===t){if(0>=p){c.push(r&&k.length?{key:r,value:k.join("")}:{unknown:r||k.join("")});r=p=0;k=[];continue}}else if(58===t){if(!p&&!r&&1===k.length){r=k.pop();continue}}else 47===t&&A&&1<y.length?(t=d[A-1].match(f))&&!g[t[0]]&&(b=b.substr(b.indexOf(y)+1),d=b.match(e),d.push(","),A=-1,y="/"):40===t||123===t||91===t?++p:41===t||125===t||93===t?--p:r||k.length||34!==t&&39!==t||(y=y.slice(1,-1));k.push(y)}}return c}var c=["true","false","null","undefined"],d=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i,e=RegExp("\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|/(?:[^/\\\\]|\\\\.)*/w*|[^\\s:,/][^,\"'{}()/:[\\]]*[^\\s,\"'{}()/:[\\]]|[^\\s]","g"),f=/[\])"'A-Za-z0-9_$]+$/,g={"in":1,"return":1,"typeof":1},k={};return{ta:[],ea:k,yb:b,Ua:function(e,m){function h(b,e){var m;if(!A){var l=a.getBindingHandler(b);if(l&&l.preprocess&&!(e=l.preprocess(e,b,h)))return;if(l=k[b])m=e,0<=a.a.o(c,m)?m=!1:(l=m.match(d),m=null===l?!1:l[1]?"Object("+l[1]+")"+l[2]:m),l=m;l&&g.push("'"+b+"':function(_z){"+m+"=_z}")}p&&(e="function(){return "+e+" }");f.push("'"+b+"':"+e)}m=m||{};var f=[],g=[],p=m.valueAccessors,A=m.bindingParams,y="string"===typeof e?b(e):e;a.a.q(y,function(a){h(a.key||a.unknown,a.value)});g.length&&h("_ko_property_writers","{"+g.join(",")+" }");return f.join(",")},ad:function(a,b){for(var c=0;c<a.length;c++)if(a[c].key==b)return!0;return!1},Ea:function(b,c,d,e,f){if(b&&a.H(b))!a.Ba(b)||f&&b.t()===e||b(e);else if((b=c.get("_ko_property_writers"))&&b[d])b[d](e)}}}();a.b("expressionRewriting",a.h);a.b("expressionRewriting.bindingRewriteValidators",a.h.ta);a.b("expressionRewriting.parseObjectLiteral",a.h.yb);a.b("expressionRewriting.preProcessBindings",a.h.Ua);a.b("expressionRewriting._twoWayBindings",a.h.ea);a.b("jsonExpressionRewriting",a.h);a.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",a.h.Ua);(function(){function b(a){return 8==a.nodeType&&g.test(f?a.text:a.nodeValue)}function c(a){return 8==a.nodeType&&k.test(f?a.text:a.nodeValue)}function d(a,d){for(var e=a,f=1,l=[];e=e.nextSibling;){if(c(e)&&(f--,0===f))return l;l.push(e);b(e)&&f++}if(!d)throw Error("Cannot find closing comment tag to match: "+a.nodeValue);return null}function e(a,b){var c=d(a,b);return c?0<c.length?c[c.length-1].nextSibling:a.nextSibling:null}var f=u&&"\x3c!--test--\x3e"===u.createComment("test").text,g=f?/^\x3c!--\s*ko(?:\s+([\s\S]+))?\s*--\x3e$/:/^\s*ko(?:\s+([\s\S]+))?\s*$/,k=f?/^\x3c!--\s*\/ko\s*--\x3e$/:/^\s*\/ko\s*$/,l={ul:!0,ol:!0};a.f={Z:{},childNodes:function(a){return b(a)?d(a):a.childNodes},xa:function(c){if(b(c)){c=a.f.childNodes(c);for(var d=0,e=c.length;d<e;d++)a.removeNode(c[d])}else a.a.ob(c)},da:function(c,d){if(b(c)){a.f.xa(c);for(var e=c.nextSibling,f=0,l=d.length;f<l;f++)e.parentNode.insertBefore(d[f],e)}else a.a.da(c,d)},mc:function(a,c){b(a)?a.parentNode.insertBefore(c,a.nextSibling):a.firstChild?a.insertBefore(c,a.firstChild):a.appendChild(c)},gc:function(c,d,e){e?b(c)?c.parentNode.insertBefore(d,e.nextSibling):e.nextSibling?c.insertBefore(d,e.nextSibling):c.appendChild(d):a.f.mc(c,d)},firstChild:function(a){return b(a)?!a.nextSibling||c(a.nextSibling)?null:a.nextSibling:a.firstChild},nextSibling:function(a){b(a)&&(a=e(a));return a.nextSibling&&c(a.nextSibling)?null:a.nextSibling},Tc:b,pd:function(a){return(a=(f?a.text:a.nodeValue).match(g))?a[1]:null},kc:function(d){if(l[a.a.A(d)]){var h=d.firstChild;if(h){do if(1===h.nodeType){var f;f=h.firstChild;var g=null;if(f){do if(g)g.push(f);else if(b(f)){var k=e(f,!0);k?f=k:g=[f]}else c(f)&&(g=[f]);while(f=f.nextSibling)}if(f=g)for(g=h.nextSibling,k=0;k<f.length;k++)g?d.insertBefore(f[k],g):d.appendChild(f[k])}while(h=h.nextSibling)}}}}})();a.b("virtualElements",a.f);a.b("virtualElements.allowedBindings",a.f.Z);a.b("virtualElements.emptyNode",a.f.xa);a.b("virtualElements.insertAfter",a.f.gc);a.b("virtualElements.prepend",a.f.mc);a.b("virtualElements.setDomNodeChildren",a.f.da);(function(){a.Q=function(){this.Fc={}};a.a.extend(a.Q.prototype,{nodeHasBindings:function(b){switch(b.nodeType){case 1:return null!=b.getAttribute("data-bind")||a.g.getComponentNameForNode(b);case 8:return a.f.Tc(b);default:return!1}},getBindings:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b):null;return a.g.Ob(d,b,c,!1)},getBindingAccessors:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b,{valueAccessors:!0}):null;return a.g.Ob(d,b,c,!0)},getBindingsString:function(b){switch(b.nodeType){case 1:return b.getAttribute("data-bind");case 8:return a.f.pd(b);default:return null}},parseBindingsString:function(b,c,d,e){try{var f=this.Fc,g=b+(e&&e.valueAccessors||""),k;if(!(k=f[g])){var l,m="with($context){with($data||{}){return{"+a.h.Ua(b,e)+"}}}";l=new Function("$context","$element",m);k=f[g]=l}return k(c,d)}catch(h){throw h.message="Unable to parse bindings.\nBindings value: "+b+"\nMessage: "+h.message,h;}}});a.Q.instance=new a.Q})();a.b("bindingProvider",a.Q);(function(){function b(a){return function(){return a}}function c(a){return a()}function d(b){return a.a.Ca(a.l.w(b),function(a,c){return function(){return b()[c]}})}function e(c,e,h){return"function"===typeof c?d(c.bind(null,e,h)):a.a.Ca(c,b)}function f(a,b){return d(this.getBindings.bind(this,a,b))}function g(b,c,d){var e,h=a.f.firstChild(c),f=a.Q.instance,m=f.preprocessNode;if(m){for(;e=h;)h=a.f.nextSibling(e),m.call(f,e);h=a.f.firstChild(c)}for(;e=h;)h=a.f.nextSibling(e),k(b,e,d)}function k(b,c,d){var e=!0,h=1===c.nodeType;h&&a.f.kc(c);if(h&&d||a.Q.instance.nodeHasBindings(c))e=m(c,null,b,d).shouldBindDescendants;e&&!r[a.a.A(c)]&&g(b,c,!h)}function l(b){var c=[],d={},e=[];a.a.D(b,function Z(h){if(!d[h]){var f=a.getBindingHandler(h);f&&(f.after&&(e.push(h),a.a.q(f.after,function(c){if(b[c]){if(-1!==a.a.o(e,c))throw Error("Cannot combine the following bindings, because they have a cyclic dependency: "+e.join(", "));Z(c)}}),e.length--),c.push({key:h,fc:f}));d[h]=!0}});return c}function m(b,d,e,h){var m=a.a.e.get(b,q);if(!d){if(m)throw Error("You cannot apply bindings multiple times to the same element.");a.a.e.set(b,q,!0)}!m&&h&&a.tc(b,e);var g;if(d&&"function"!==typeof d)g=d;else{var k=a.Q.instance,r=k.getBindingAccessors||f,p=a.B(function(){(g=d?d(e,b):r.call(k,b,e))&&e.P&&e.P();return g},null,{i:b});g&&p.ba()||(p=null)}var u;if(g){var v=p?function(a){return function(){return c(p()[a])}}:function(a){return g[a]},s=function(){return a.a.Ca(p?p():g,c)};s.get=function(a){return g[a]&&c(v(a))};s.has=function(a){return a in g};h=l(g);a.a.q(h,function(c){var d=c.fc.init,h=c.fc.update,f=c.key;if(8===b.nodeType&&!a.f.Z[f])throw Error("The binding '"+f+"' cannot be used with virtual elements");try{"function"==typeof d&&a.l.w(function(){var a=d(b,v(f),s,e.$data,e);if(a&&a.controlsDescendantBindings){if(u!==n)throw Error("Multiple bindings ("+u+" and "+f+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");u=f}}),"function"==typeof h&&a.B(function(){h(b,v(f),s,e.$data,e)},null,{i:b})}catch(m){throw m.message='Unable to process binding "'+f+": "+g[f]+'"\nMessage: '+m.message,m;}})}return{shouldBindDescendants:u===n}}function h(b){return b&&b instanceof a.U?b:new a.U(b)}a.d={};var r={script:!0,textarea:!0,template:!0};a.getBindingHandler=function(b){return a.d[b]};a.U=function(b,c,d,e){var h=this,f="function"==typeof b&&!a.H(b),m,g=a.B(function(){var m=f?b():b,l=a.a.c(m);c?(c.P&&c.P(),a.a.extend(h,c),g&&(h.P=g)):(h.$parents=[],h.$root=l,h.ko=a);h.$rawData=m;h.$data=l;d&&(h[d]=l);e&&e(h,c,l);return h.$data},null,{wa:function(){return m&&!a.a.Qb(m)},i:!0});g.ba()&&(h.P=g,g.equalityComparer=null,m=[],g.Ac=function(b){m.push(b);a.a.F.oa(b,function(b){a.a.La(m,b);m.length||(g.k(),h.P=g=n)})})};a.U.prototype.createChildContext=function(b,c,d){return new a.U(b,this,c,function(a,b){a.$parentContext=b;a.$parent=b.$data;a.$parents=(b.$parents||[]).slice(0);a.$parents.unshift(a.$parent);d&&d(a)})};a.U.prototype.extend=function(b){return new a.U(this.P||this.$data,this,null,function(c,d){c.$rawData=d.$rawData;a.a.extend(c,"function"==typeof b?b():b)})};var q=a.a.e.I(),p=a.a.e.I();a.tc=function(b,c){if(2==arguments.length)a.a.e.set(b,p,c),c.P&&c.P.Ac(b);else return a.a.e.get(b,p)};a.Ja=function(b,c,d){1===b.nodeType&&a.f.kc(b);return m(b,c,h(d),!0)};a.Dc=function(b,c,d){d=h(d);return a.Ja(b,e(c,d,b),d)};a.eb=function(a,b){1!==b.nodeType&&8!==b.nodeType||g(h(a),b,!0)};a.Rb=function(a,b){!v&&x.jQuery&&(v=x.jQuery);if(b&&1!==b.nodeType&&8!==b.nodeType)throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");b=b||x.document.body;k(h(a),b,!0)};a.kb=function(b){switch(b.nodeType){case 1:case 8:var c=a.tc(b);if(c)return c;if(b.parentNode)return a.kb(b.parentNode)}return n};a.Jc=function(b){return(b=a.kb(b))?b.$data:n};a.b("bindingHandlers",a.d);a.b("applyBindings",a.Rb);a.b("applyBindingsToDescendants",a.eb);a.b("applyBindingAccessorsToNode",a.Ja);a.b("applyBindingsToNode",a.Dc);a.b("contextFor",a.kb);a.b("dataFor",a.Jc)})();(function(b){function c(c,e){var m=f.hasOwnProperty(c)?f[c]:b,h;m?m.X(e):(m=f[c]=new a.J,m.X(e),d(c,function(b,d){var e=!(!d||!d.synchronous);g[c]={definition:b,Zc:e};delete f[c];h||e?m.notifySubscribers(b):a.Y.Wa(function(){m.notifySubscribers(b)})}),h=!0)}function d(a,b){e("getConfig",[a],function(c){c?e("loadComponent",[a,c],function(a){b(a,c)}):b(null,null)})}function e(c,d,f,h){h||(h=a.g.loaders.slice(0));var g=h.shift();if(g){var q=g[c];if(q){var p=!1;if(q.apply(g,d.concat(function(a){p?f(null):null!==a?f(a):e(c,d,f,h)}))!==b&&(p=!0,!g.suppressLoaderExceptions))throw Error("Component loaders must supply values by invoking the callback, not by returning values synchronously.");}else e(c,d,f,h)}else f(null)}var f={},g={};a.g={get:function(d,e){var f=g.hasOwnProperty(d)?g[d]:b;f?f.Zc?a.l.w(function(){e(f.definition)}):a.Y.Wa(function(){e(f.definition)}):c(d,e)},Xb:function(a){delete g[a]},Jb:e};a.g.loaders=[];a.b("components",a.g);a.b("components.get",a.g.get);a.b("components.clearCachedDefinition",a.g.Xb)})();(function(){function b(b,c,d,e){function g(){0===--y&&e(k)}var k={},y=2,t=d.template;d=d.viewModel;t?f(c,t,function(c){a.g.Jb("loadTemplate",[b,c],function(a){k.template=a;g()})}):g();d?f(c,d,function(c){a.g.Jb("loadViewModel",[b,c],function(a){k[l]=a;g()})}):g()}function c(a,b,d){if("function"===typeof b)d(function(a){return new b(a)});else if("function"===typeof b[l])d(b[l]);else if("instance"in b){var e=b.instance;d(function(){return e})}else"viewModel"in b?c(a,b.viewModel,d):a("Unknown viewModel value: "+b)}function d(b){switch(a.a.A(b)){case"script":return a.a.ma(b.text);case"textarea":return a.a.ma(b.value);case"template":if(e(b.content))return a.a.ua(b.content.childNodes)}return a.a.ua(b.childNodes)}function e(a){return x.DocumentFragment?a instanceof DocumentFragment:a&&11===a.nodeType}function f(a,b,c){"string"===typeof b.require?O||x.require?(O||x.require)([b.require],c):a("Uses require, but no AMD loader is present"):c(b)}function g(a){return function(b){throw Error("Component '"+a+"': "+b);}}var k={};a.g.register=function(b,c){if(!c)throw Error("Invalid configuration for "+b);if(a.g.ub(b))throw Error("Component "+b+" is already registered");k[b]=c};a.g.ub=function(a){return k.hasOwnProperty(a)};a.g.od=function(b){delete k[b];a.g.Xb(b)};a.g.Zb={getConfig:function(a,b){b(k.hasOwnProperty(a)?k[a]:null)},loadComponent:function(a,c,d){var e=g(a);f(e,c,function(c){b(a,e,c,d)})},loadTemplate:function(b,c,f){b=g(b);if("string"===typeof c)f(a.a.ma(c));else if(c instanceof Array)f(c);else if(e(c))f(a.a.V(c.childNodes));else if(c.element)if(c=c.element,x.HTMLElement?c instanceof HTMLElement:c&&c.tagName&&1===c.nodeType)f(d(c));else if("string"===typeof c){var l=u.getElementById(c);l?f(d(l)):b("Cannot find element with ID "+c)}else b("Unknown element type: "+c);else b("Unknown template value: "+c)},loadViewModel:function(a,b,d){c(g(a),b,d)}};var l="createViewModel";a.b("components.register",a.g.register);a.b("components.isRegistered",a.g.ub);a.b("components.unregister",a.g.od);a.b("components.defaultLoader",a.g.Zb);a.g.loaders.push(a.g.Zb);a.g.Bc=k})();(function(){function b(b,e){var f=b.getAttribute("params");if(f){var f=c.parseBindingsString(f,e,b,{valueAccessors:!0,bindingParams:!0}),f=a.a.Ca(f,function(c){return a.m(c,null,{i:b})}),g=a.a.Ca(f,function(c){var e=c.t();return c.ba()?a.m({read:function(){return a.a.c(c())},write:a.Ba(e)&&function(a){c()(a)},i:b}):e});g.hasOwnProperty("$raw")||(g.$raw=f);return g}return{$raw:{}}}a.g.getComponentNameForNode=function(b){var c=a.a.A(b);if(a.g.ub(c)&&(-1!=c.indexOf("-")||"[object HTMLUnknownElement]"==""+b||8>=a.a.C&&b.tagName===c))return c};a.g.Ob=function(c,e,f,g){if(1===e.nodeType){var k=a.g.getComponentNameForNode(e);if(k){c=c||{};if(c.component)throw Error('Cannot use the "component" binding on a custom element matching a component');var l={name:k,params:b(e,f)};c.component=g?function(){return l}:l}}return c};var c=new a.Q;9>a.a.C&&(a.g.register=function(a){return function(b){u.createElement(b);return a.apply(this,arguments)}}(a.g.register),u.createDocumentFragment=function(b){return function(){var c=b(),f=a.g.Bc,g;for(g in f)f.hasOwnProperty(g)&&c.createElement(g);return c}}(u.createDocumentFragment))})();(function(b){function c(b,c,d){c=c.template;if(!c)throw Error("Component '"+b+"' has no template");b=a.a.ua(c);a.f.da(d,b)}function d(a,b,c,d){var e=a.createViewModel;return e?e.call(a,d,{element:b,templateNodes:c}):d}var e=0;a.d.component={init:function(f,g,k,l,m){function h(){var a=r&&r.dispose;"function"===typeof a&&a.call(r);q=r=null}var r,q,p=a.a.V(a.f.childNodes(f));a.a.F.oa(f,h);a.m(function(){var l=a.a.c(g()),k,t;"string"===typeof l?k=l:(k=a.a.c(l.name),t=a.a.c(l.params));if(!k)throw Error("No component name specified");var n=q=++e;a.g.get(k,function(e){if(q===n){h();if(!e)throw Error("Unknown component '"+k+"'");c(k,e,f);var g=d(e,f,p,t);e=m.createChildContext(g,b,function(a){a.$component=g;a.$componentTemplateNodes=p});r=g;a.eb(e,f)}})},null,{i:f});return{controlsDescendantBindings:!0}}};a.f.Z.component=!0})();var S={"class":"className","for":"htmlFor"};a.d.attr={update:function(b,c){var d=a.a.c(c())||{};a.a.D(d,function(c,d){d=a.a.c(d);var g=!1===d||null===d||d===n;g&&b.removeAttribute(c);8>=a.a.C&&c in S?(c=S[c],g?b.removeAttribute(c):b[c]=d):g||b.setAttribute(c,d.toString());"name"===c&&a.a.rc(b,g?"":d.toString())})}};(function(){a.d.checked={after:["value","attr"],init:function(b,c,d){function e(){var e=b.checked,f=p?g():e;if(!a.va.Sa()&&(!l||e)){var m=a.l.w(c);if(h){var k=r?m.t():m;q!==f?(e&&(a.a.pa(k,f,!0),a.a.pa(k,q,!1)),q=f):a.a.pa(k,f,e);r&&a.Ba(m)&&m(k)}else a.h.Ea(m,d,"checked",f,!0)}}function f(){var d=a.a.c(c());b.checked=h?0<=a.a.o(d,g()):k?d:g()===d}var g=a.nc(function(){return d.has("checkedValue")?a.a.c(d.get("checkedValue")):d.has("value")?a.a.c(d.get("value")):b.value}),k="checkbox"==b.type,l="radio"==b.type;if(k||l){var m=c(),h=k&&a.a.c(m)instanceof Array,r=!(h&&m.push&&m.splice),q=h?g():n,p=l||h;l&&!b.name&&a.d.uniqueName.init(b,function(){return!0});a.m(e,null,{i:b});a.a.p(b,"click",e);a.m(f,null,{i:b});m=n}}};a.h.ea.checked=!0;a.d.checkedValue={update:function(b,c){b.value=a.a.c(c())}}})();a.d.css={update:function(b,c){var d=a.a.c(c());null!==d&&"object"==typeof d?a.a.D(d,function(c,d){d=a.a.c(d);a.a.bb(b,c,d)}):(d=a.a.$a(String(d||"")),a.a.bb(b,b.__ko__cssValue,!1),b.__ko__cssValue=d,a.a.bb(b,d,!0))}};a.d.enable={update:function(b,c){var d=a.a.c(c());d&&b.disabled?b.removeAttribute("disabled"):d||b.disabled||(b.disabled=!0)}};a.d.disable={update:function(b,c){a.d.enable.update(b,function(){return!a.a.c(c())})}};a.d.event={init:function(b,c,d,e,f){var g=c()||{};a.a.D(g,function(g){"string"==typeof g&&a.a.p(b,g,function(b){var m,h=c()[g];if(h){try{var r=a.a.V(arguments);e=f.$data;r.unshift(e);m=h.apply(e,r)}finally{!0!==m&&(b.preventDefault?b.preventDefault():b.returnValue=!1)}!1===d.get(g+"Bubble")&&(b.cancelBubble=!0,b.stopPropagation&&b.stopPropagation())}})})}};a.d.foreach={ic:function(b){return function(){var c=b(),d=a.a.zb(c);if(!d||"number"==typeof d.length)return{foreach:c,templateEngine:a.W.sb};a.a.c(c);return{foreach:d.data,as:d.as,includeDestroyed:d.includeDestroyed,afterAdd:d.afterAdd,beforeRemove:d.beforeRemove,afterRender:d.afterRender,beforeMove:d.beforeMove,afterMove:d.afterMove,templateEngine:a.W.sb}}},init:function(b,c){return a.d.template.init(b,a.d.foreach.ic(c))},update:function(b,c,d,e,f){return a.d.template.update(b,a.d.foreach.ic(c),d,e,f)}};a.h.ta.foreach=!1;a.f.Z.foreach=!0;a.d.hasfocus={init:function(b,c,d){function e(e){b.__ko_hasfocusUpdating=!0;var f=b.ownerDocument;if("activeElement"in f){var g;try{g=f.activeElement}catch(h){g=f.body}e=g===b}f=c();a.h.Ea(f,d,"hasfocus",e,!0);b.__ko_hasfocusLastValue=e;b.__ko_hasfocusUpdating=!1}var f=e.bind(null,!0),g=e.bind(null,!1);a.a.p(b,"focus",f);a.a.p(b,"focusin",f);a.a.p(b,"blur",g);a.a.p(b,"focusout",g)},update:function(b,c){var d=!!a.a.c(c());b.__ko_hasfocusUpdating||b.__ko_hasfocusLastValue===d||(d?b.focus():b.blur(),!d&&b.__ko_hasfocusLastValue&&b.ownerDocument.body.focus(),a.l.w(a.a.Da,null,[b,d?"focusin":"focusout"]))}};a.h.ea.hasfocus=!0;a.d.hasFocus=a.d.hasfocus;a.h.ea.hasFocus=!0;a.d.html={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.Cb(b,c())}};K("if");K("ifnot",!1,!0);K("with",!0,!1,function(a,c){return a.createChildContext(c)});var L={};a.d.options={init:function(b){if("select"!==a.a.A(b))throw Error("options binding applies only to SELECT elements");for(;0<b.length;)b.remove(0);return{controlsDescendantBindings:!0}},update:function(b,c,d){function e(){return a.a.Ka(b.options,function(a){return a.selected})}function f(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c}function g(c,e){if(A&&h)a.j.ha(b,a.a.c(d.get("value")),!0);else if(p.length){var f=0<=a.a.o(p,a.j.u(e[0]));a.a.sc(e[0],f);A&&!f&&a.l.w(a.a.Da,null,[b,"change"])}}var k=b.multiple,l=0!=b.length&&k?b.scrollTop:null,m=a.a.c(c()),h=d.get("valueAllowUnset")&&d.has("value"),r=d.get("optionsIncludeDestroyed");c={};var q,p=[];h||(k?p=a.a.fb(e(),a.j.u):0<=b.selectedIndex&&p.push(a.j.u(b.options[b.selectedIndex])));m&&("undefined"==typeof m.length&&(m=[m]),q=a.a.Ka(m,function(b){return r||b===n||null===b||!a.a.c(b._destroy)}),d.has("optionsCaption")&&(m=a.a.c(d.get("optionsCaption")),null!==m&&m!==n&&q.unshift(L)));var A=!1;c.beforeRemove=function(a){b.removeChild(a)};m=g;d.has("optionsAfterRender")&&"function"==typeof d.get("optionsAfterRender")&&(m=function(b,c){g(0,c);a.l.w(d.get("optionsAfterRender"),null,[c[0],b!==L?b:n])});a.a.Bb(b,q,function(c,e,g){g.length&&(p=!h&&g[0].selected?[a.j.u(g[0])]:[],A=!0);e=b.ownerDocument.createElement("option");c===L?(a.a.Za(e,d.get("optionsCaption")),a.j.ha(e,n)):(g=f(c,d.get("optionsValue"),c),a.j.ha(e,a.a.c(g)),c=f(c,d.get("optionsText"),g),a.a.Za(e,c));return[e]},c,m);a.l.w(function(){h?a.j.ha(b,a.a.c(d.get("value")),!0):(k?p.length&&e().length<p.length:p.length&&0<=b.selectedIndex?a.j.u(b.options[b.selectedIndex])!==p[0]:p.length||0<=b.selectedIndex)&&a.a.Da(b,"change")});a.a.Nc(b);l&&20<Math.abs(l-b.scrollTop)&&(b.scrollTop=l)}};a.d.options.xb=a.a.e.I();a.d.selectedOptions={after:["options","foreach"],init:function(b,c,d){a.a.p(b,"change",function(){var e=c(),f=[];a.a.q(b.getElementsByTagName("option"),function(b){b.selected&&f.push(a.j.u(b))});a.h.Ea(e,d,"selectedOptions",f)})},update:function(b,c){if("select"!=a.a.A(b))throw Error("values binding applies only to SELECT elements");var d=a.a.c(c()),e=b.scrollTop;d&&"number"==typeof d.length&&a.a.q(b.getElementsByTagName("option"),function(b){var c=0<=a.a.o(d,a.j.u(b));b.selected!=c&&a.a.sc(b,c)});b.scrollTop=e}};a.h.ea.selectedOptions=!0;a.d.style={update:function(b,c){var d=a.a.c(c()||{});a.a.D(d,function(c,d){d=a.a.c(d);if(null===d||d===n||!1===d)d="";b.style[c]=d})}};a.d.submit={init:function(b,c,d,e,f){if("function"!=typeof c())throw Error("The value for a submit binding must be a function");a.a.p(b,"submit",function(a){var d,e=c();try{d=e.call(f.$data,b)}finally{!0!==d&&(a.preventDefault?a.preventDefault():a.returnValue=!1)}})}};a.d.text={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.Za(b,c())}};a.f.Z.text=!0;(function(){if(x&&x.navigator)var b=function(a){if(a)return parseFloat(a[1])},c=x.opera&&x.opera.version&&parseInt(x.opera.version()),d=x.navigator.userAgent,e=b(d.match(/^(?:(?!chrome).)*version\/([^ ]*) safari/i)),f=b(d.match(/Firefox\/([^ ]*)/));if(10>a.a.C)var g=a.a.e.I(),k=a.a.e.I(),l=function(b){var c=this.activeElement;(c=c&&a.a.e.get(c,k))&&c(b)},m=function(b,c){var d=b.ownerDocument;a.a.e.get(d,g)||(a.a.e.set(d,g,!0),a.a.p(d,"selectionchange",l));a.a.e.set(b,k,c)};a.d.textInput={init:function(b,d,g){function l(c,d){a.a.p(b,c,d)}function k(){var c=a.a.c(d());if(null===c||c===n)c="";v!==n&&c===v?a.a.setTimeout(k,4):b.value!==c&&(u=c,b.value=c)}function y(){s||(v=b.value,s=a.a.setTimeout(t,4))}function t(){clearTimeout(s);v=s=n;var c=b.value;u!==c&&(u=c,a.h.Ea(d(),g,"textInput",c))}var u=b.value,s,v,x=9==a.a.C?y:t;10>a.a.C?(l("propertychange",function(a){"value"===a.propertyName&&x(a)}),8==a.a.C&&(l("keyup",t),l("keydown",t)),8<=a.a.C&&(m(b,x),l("dragend",y))):(l("input",t),5>e&&"textarea"===a.a.A(b)?(l("keydown",y),l("paste",y),l("cut",y)):11>c?l("keydown",y):4>f&&(l("DOMAutoComplete",t),l("dragdrop",t),l("drop",t)));l("change",t);a.m(k,null,{i:b})}};a.h.ea.textInput=!0;a.d.textinput={preprocess:function(a,b,c){c("textInput",a)}}})();a.d.uniqueName={init:function(b,c){if(c()){var d="ko_unique_"+ ++a.d.uniqueName.Ic;a.a.rc(b,d)}}};a.d.uniqueName.Ic=0;a.d.value={after:["options","foreach"],init:function(b,c,d){if("input"!=b.tagName.toLowerCase()||"checkbox"!=b.type&&"radio"!=b.type){var e=["change"],f=d.get("valueUpdate"),g=!1,k=null;f&&("string"==typeof f&&(f=[f]),a.a.ra(e,f),e=a.a.Tb(e));var l=function(){k=null;g=!1;var e=c(),f=a.j.u(b);a.h.Ea(e,d,"value",f)};!a.a.C||"input"!=b.tagName.toLowerCase()||"text"!=b.type||"off"==b.autocomplete||b.form&&"off"==b.form.autocomplete||-1!=a.a.o(e,"propertychange")||(a.a.p(b,"propertychange",function(){g=!0}),a.a.p(b,"focus",function(){g=!1}),a.a.p(b,"blur",function(){g&&l()}));a.a.q(e,function(c){var d=l;a.a.nd(c,"after")&&(d=function(){k=a.j.u(b);a.a.setTimeout(l,0)},c=c.substring(5));a.a.p(b,c,d)});var m=function(){var e=a.a.c(c()),f=a.j.u(b);if(null!==k&&e===k)a.a.setTimeout(m,0);else if(e!==f)if("select"===a.a.A(b)){var g=d.get("valueAllowUnset"),f=function(){a.j.ha(b,e,g)};f();g||e===a.j.u(b)?a.a.setTimeout(f,0):a.l.w(a.a.Da,null,[b,"change"])}else a.j.ha(b,e)};a.m(m,null,{i:b})}else a.Ja(b,{checkedValue:c})},update:function(){}};a.h.ea.value=!0;a.d.visible={update:function(b,c){var d=a.a.c(c()),e="none"!=b.style.display;d&&!e?b.style.display="":!d&&e&&(b.style.display="none")}};(function(b){a.d[b]={init:function(c,d,e,f,g){return a.d.event.init.call(this,c,function(){var a={};a[b]=d();return a},e,f,g)}}})("click");a.O=function(){};a.O.prototype.renderTemplateSource=function(){throw Error("Override renderTemplateSource");};a.O.prototype.createJavaScriptEvaluatorBlock=function(){throw Error("Override createJavaScriptEvaluatorBlock");};a.O.prototype.makeTemplateSource=function(b,c){if("string"==typeof b){c=c||u;var d=c.getElementById(b);if(!d)throw Error("Cannot find template with ID "+b);return new a.v.n(d)}if(1==b.nodeType||8==b.nodeType)return new a.v.qa(b);throw Error("Unknown template type: "+b);};a.O.prototype.renderTemplate=function(a,c,d,e){a=this.makeTemplateSource(a,e);return this.renderTemplateSource(a,c,d,e)};a.O.prototype.isTemplateRewritten=function(a,c){return!1===this.allowTemplateRewriting?!0:this.makeTemplateSource(a,c).data("isRewritten")};a.O.prototype.rewriteTemplate=function(a,c,d){a=this.makeTemplateSource(a,d);c=c(a.text());a.text(c);a.data("isRewritten",!0)};a.b("templateEngine",a.O);a.Gb=function(){function b(b,c,d,k){b=a.h.yb(b);for(var l=a.h.ta,m=0;m<b.length;m++){var h=b[m].key;if(l.hasOwnProperty(h)){var r=l[h];if("function"===typeof r){if(h=r(b[m].value))throw Error(h);}else if(!r)throw Error("This template engine does not support the '"+h+"' binding within its templates");}}d="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+a.h.Ua(b,{valueAccessors:!0})+" } })()},'"+d.toLowerCase()+"')";return k.createJavaScriptEvaluatorBlock(d)+c}var c=/(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi,d=/\x3c!--\s*ko\b\s*([\s\S]*?)\s*--\x3e/g;return{Oc:function(b,c,d){c.isTemplateRewritten(b,d)||c.rewriteTemplate(b,function(b){return a.Gb.dd(b,c)},d)},dd:function(a,f){return a.replace(c,function(a,c,d,e,h){return b(h,c,d,f)}).replace(d,function(a,c){return b(c,"\x3c!-- ko --\x3e","#comment",f)})},Ec:function(b,c){return a.M.wb(function(d,k){var l=d.nextSibling;l&&l.nodeName.toLowerCase()===c&&a.Ja(l,b,k)})}}}();a.b("__tr_ambtns",a.Gb.Ec);(function(){a.v={};a.v.n=function(b){if(this.n=b){var c=a.a.A(b);this.ab="script"===c?1:"textarea"===c?2:"template"==c&&b.content&&11===b.content.nodeType?3:4}};a.v.n.prototype.text=function(){var b=1===this.ab?"text":2===this.ab?"value":"innerHTML";if(0==arguments.length)return this.n[b];var c=arguments[0];"innerHTML"===b?a.a.Cb(this.n,c):this.n[b]=c};var b=a.a.e.I()+"_";a.v.n.prototype.data=function(c){if(1===arguments.length)return a.a.e.get(this.n,b+c);a.a.e.set(this.n,b+c,arguments[1])};var c=a.a.e.I();a.v.n.prototype.nodes=function(){var b=this.n;if(0==arguments.length)return(a.a.e.get(b,c)||{}).jb||(3===this.ab?b.content:4===this.ab?b:n);a.a.e.set(b,c,{jb:arguments[0]})};a.v.qa=function(a){this.n=a};a.v.qa.prototype=new a.v.n;a.v.qa.prototype.text=function(){if(0==arguments.length){var b=a.a.e.get(this.n,c)||{};b.Hb===n&&b.jb&&(b.Hb=b.jb.innerHTML);return b.Hb}a.a.e.set(this.n,c,{Hb:arguments[0]})};a.b("templateSources",a.v);a.b("templateSources.domElement",a.v.n);a.b("templateSources.anonymousTemplate",a.v.qa)})();(function(){function b(b,c,d){var e;for(c=a.f.nextSibling(c);b&&(e=b)!==c;)b=a.f.nextSibling(e),d(e,b)}function c(c,d){if(c.length){var e=c[0],f=c[c.length-1],g=e.parentNode,k=a.Q.instance,n=k.preprocessNode;if(n){b(e,f,function(a,b){var c=a.previousSibling,d=n.call(k,a);d&&(a===e&&(e=d[0]||b),a===f&&(f=d[d.length-1]||c))});c.length=0;if(!e)return;e===f?c.push(e):(c.push(e,f),a.a.za(c,g))}b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.Rb(d,b)});b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.M.yc(b,[d])});a.a.za(c,g)}}function d(a){return a.nodeType?a:0<a.length?a[0]:null}function e(b,e,f,k,q){q=q||{};var p=(b&&d(b)||f||{}).ownerDocument,n=q.templateEngine||g;a.Gb.Oc(f,n,p);f=n.renderTemplate(f,k,q,p);if("number"!=typeof f.length||0<f.length&&"number"!=typeof f[0].nodeType)throw Error("Template engine must return an array of DOM nodes");p=!1;switch(e){case"replaceChildren":a.f.da(b,f);p=!0;break;case"replaceNode":a.a.qc(b,f);p=!0;break;case"ignoreTargetNode":break;default:throw Error("Unknown renderMode: "+e);}p&&(c(f,k),q.afterRender&&a.l.w(q.afterRender,null,[f,k.$data]));return f}function f(b,c,d){return a.H(b)?b():"function"===typeof b?b(c,d):b}var g;a.Db=function(b){if(b!=n&&!(b instanceof a.O))throw Error("templateEngine must inherit from ko.templateEngine");g=b};a.Ab=function(b,c,h,k,q){h=h||{};if((h.templateEngine||g)==n)throw Error("Set a template engine before calling renderTemplate");q=q||"replaceChildren";if(k){var p=d(k);return a.B(function(){var g=c&&c instanceof a.U?c:new a.U(a.a.c(c)),n=f(b,g.$data,g),g=e(k,q,n,g,h);"replaceNode"==q&&(k=g,p=d(k))},null,{wa:function(){return!p||!a.a.nb(p)},i:p&&"replaceNode"==q?p.parentNode:p})}return a.M.wb(function(d){a.Ab(b,c,h,d,"replaceNode")})};a.kd=function(b,d,g,k,q){function p(a,b){c(b,s);g.afterRender&&g.afterRender(b,a);s=null}function u(a,c){s=q.createChildContext(a,g.as,function(a){a.$index=c});var d=f(b,a,s);return e(null,"ignoreTargetNode",d,s,g)}var s;return a.B(function(){var b=a.a.c(d)||[];"undefined"==typeof b.length&&(b=[b]);b=a.a.Ka(b,function(b){return g.includeDestroyed||b===n||null===b||!a.a.c(b._destroy)});a.l.w(a.a.Bb,null,[k,b,u,g,p])},null,{i:k})};var k=a.a.e.I();a.d.template={init:function(b,c){var d=a.a.c(c());if("string"==typeof d||d.name)a.f.xa(b);else{if("nodes"in d){if(d=d.nodes||[],a.H(d))throw Error('The "nodes" option must be a plain, non-observable array.');}else d=a.f.childNodes(b);d=a.a.jc(d);(new a.v.qa(b)).nodes(d)}return{controlsDescendantBindings:!0}},update:function(b,c,d,e,f){var g=c(),s;c=a.a.c(g);d=!0;e=null;"string"==typeof c?c={}:(g=c.name,"if"in c&&(d=a.a.c(c["if"])),d&&"ifnot"in
c&&(d=!a.a.c(c.ifnot)),s=a.a.c(c.data));"foreach"in c?e=a.kd(g||b,d&&c.foreach||[],c,b,f):d?(f="data"in c?f.createChildContext(s,c.as):f,e=a.Ab(g||b,f,c,b)):a.f.xa(b);f=e;(s=a.a.e.get(b,k))&&"function"==typeof s.k&&s.k();a.a.e.set(b,k,f&&f.ba()?f:n)}};a.h.ta.template=function(b){b=a.h.yb(b);return 1==b.length&&b[0].unknown||a.h.ad(b,"name")?null:"This template engine does not support anonymous templates nested within its templates"};a.f.Z.template=!0})();a.b("setTemplateEngine",a.Db);a.b("renderTemplate",a.Ab);a.a.dc=function(a,c,d){if(a.length&&c.length){var e,f,g,k,l;for(e=f=0;(!d||e<d)&&(k=a[f]);++f){for(g=0;l=c[g];++g)if(k.value===l.value){k.moved=l.index;l.moved=k.index;c.splice(g,1);e=g=0;break}e+=g}}};a.a.ib=function(){function b(b,d,e,f,g){var k=Math.min,l=Math.max,m=[],h,n=b.length,q,p=d.length,s=p-n||1,u=n+p+1,t,v,x;for(h=0;h<=n;h++)for(v=t,m.push(t=[]),x=k(p,h+s),q=l(0,h-1);q<=x;q++)t[q]=q?h?b[h-1]===d[q-1]?v[q-1]:k(v[q]||u,t[q-1]||u)+1:q+1:h+1;k=[];l=[];s=[];h=n;for(q=p;h||q;)p=m[h][q]-1,q&&p===m[h][q-1]?l.push(k[k.length]={status:e,value:d[--q],index:q}):h&&p===m[h-1][q]?s.push(k[k.length]={status:f,value:b[--h],index:h}):(--q,--h,g.sparse||k.push({status:"retained",value:d[q]}));a.a.dc(s,l,!g.dontLimitMoves&&10*n);return k.reverse()}return function(a,d,e){e="boolean"===typeof e?{dontLimitMoves:e}:e||{};a=a||[];d=d||[];return a.length<d.length?b(a,d,"added","deleted",e):b(d,a,"deleted","added",e)}}();a.b("utils.compareArrays",a.a.ib);(function(){function b(b,c,d,k,l){var m=[],h=a.B(function(){var h=c(d,l,a.a.za(m,b))||[];0<m.length&&(a.a.qc(m,h),k&&a.l.w(k,null,[d,h,l]));m.length=0;a.a.ra(m,h)},null,{i:b,wa:function(){return!a.a.Qb(m)}});return{ca:m,B:h.ba()?h:n}}var c=a.a.e.I(),d=a.a.e.I();a.a.Bb=function(e,f,g,k,l){function m(b,c){w=q[c];v!==c&&(D[b]=w);w.qb(v++);a.a.za(w.ca,e);u.push(w);z.push(w)}function h(b,c){if(b)for(var d=0,e=c.length;d<e;d++)c[d]&&a.a.q(c[d].ca,function(a){b(a,d,c[d].ja)})}f=f||[];k=k||{};var r=a.a.e.get(e,c)===n,q=a.a.e.get(e,c)||[],p=a.a.fb(q,function(a){return a.ja}),s=a.a.ib(p,f,k.dontLimitMoves),u=[],t=0,v=0,x=[],z=[];f=[];for(var D=[],p=[],w,C=0,B,E;B=s[C];C++)switch(E=B.moved,B.status){case"deleted":E===n&&(w=q[t],w.B&&(w.B.k(),w.B=n),a.a.za(w.ca,e).length&&(k.beforeRemove&&(u.push(w),z.push(w),w.ja===d?w=null:f[C]=w),w&&x.push.apply(x,w.ca)));t++;break;case"retained":m(C,t++);break;case"added":E!==n?m(C,E):(w={ja:B.value,qb:a.N(v++)},u.push(w),z.push(w),r||(p[C]=w))}a.a.e.set(e,c,u);h(k.beforeMove,D);a.a.q(x,k.beforeRemove?a.$:a.removeNode);for(var C=0,r=a.f.firstChild(e),F;w=z[C];C++){w.ca||a.a.extend(w,b(e,g,w.ja,l,w.qb));for(t=0;s=w.ca[t];r=s.nextSibling,F=s,t++)s!==r&&a.f.gc(e,s,F);!w.Wc&&l&&(l(w.ja,w.ca,w.qb),w.Wc=!0)}h(k.beforeRemove,f);for(C=0;C<f.length;++C)f[C]&&(f[C].ja=d);h(k.afterMove,D);h(k.afterAdd,p)}})();a.b("utils.setDomNodeChildrenFromArrayMapping",a.a.Bb);a.W=function(){this.allowTemplateRewriting=!1};a.W.prototype=new a.O;a.W.prototype.renderTemplateSource=function(b,c,d,e){if(c=(9>a.a.C?0:b.nodes)?b.nodes():null)return a.a.V(c.cloneNode(!0).childNodes);b=b.text();return a.a.ma(b,e)};a.W.sb=new a.W;a.Db(a.W.sb);a.b("nativeTemplateEngine",a.W);(function(){a.vb=function(){var a=this.$c=function(){if(!v||!v.tmpl)return 0;try{if(0<=v.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource=function(b,e,f,g){g=g||u;f=f||{};if(2>a)throw Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");var k=b.data("precompiled");k||(k=b.text()||"",k=v.template(null,"{{ko_with $item.koBindingContext}}"+k+"{{/ko_with}}"),b.data("precompiled",k));b=[e.$data];e=v.extend({koBindingContext:e},f.templateOptions);e=v.tmpl(k,b,e);e.appendTo(g.createElement("div"));v.fragments={};return e};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+a+" })()) }}"};this.addTemplate=function(a,b){u.write("<script type='text/html' id='"+a+"'>"+b+"\x3c/script>")};0<a&&(v.tmpl.tag.ko_code={open:"__.push($1 || '');"},v.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};a.vb.prototype=new a.O;var b=new a.vb;0<b.$c&&a.Db(b);a.b("jqueryTmplTemplateEngine",a.vb)})()})})();})();
/// <reference path="../KOCommonModels/WCCPhotoset.js" />
/// <reference path="../../jquery-1.8.2.js" />
/// <reference path="../../knockout-3.2.0.js" />
(function (factory) {
    if (typeof require === 'function') {
        define('koextensions', [
            'knockout'
        ], factory);
    } else {
        factory(ko);
    }
})(function (ko) {
    ko.bindingHandlers.iCheck = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element);
            eObj.iCheck({
                checkboxClass: 'icheckbox_flat-blue',
                radioClass: 'iradio_flat-blue'
            }).on('ifChecked', function (event) {
                var value = valueAccessor();
                if (allBindings().useValue) {
                    if (allBindings().isMultiple) {
                        value.push(eObj.val());
                    }
                    else {
                        value(eObj.val());
                    }
                }
                else {
                    value(true);
                }
            }).on('ifUnchecked', function (event) {
                var value = valueAccessor();
                if (allBindings().useValue) {
                    if (allBindings().isMultiple) {
                        value.remove(eObj.val());
                    }
                    else {
                        value(null);
                    }
                }
                else {
                    value(false);
                }
            });
        },
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                value = valueAccessor();
            if (allBindings().useValue) {
                if (allBindings().isMultiple && value.indexOf(eObj.val()) > -1 || !allBindings().isMultiple && value() == eObj.val()) {
                    eObj.iCheck('check');
                }
                else {
                    eObj.iCheck('uncheck');
                }
            }
            else {
                if (value()) {
                    eObj.iCheck('check');
                }
                else {
                    eObj.iCheck('uncheck');
                }
            }
        }
    };

    ko.bindingHandlers.iRadio = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element);
            eObj.iCheck({
                checkboxClass: 'icheckbox_flat-blue',
                radioClass: 'iradio_flat-blue'
            }).on('ifChecked', function (event) {
                var value = valueAccessor();
                if (allBindings().isMultiple) {
                    value([eObj.val()]);
                }
                else {
                    value(eObj.val());
                }
            }).on('ifUnchecked', function (event) {
                var value = valueAccessor();
                if (allBindings().isMultiple) {
                    value([]);
                }
                else {
                    value(null);
                }
            });
        },
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                value = valueAccessor();
            if (allBindings().isMultiple && value.indexOf(eObj.val()) > -1 || !allBindings().isMultiple && value() == eObj.val()) {
                eObj.iCheck('check');
            }
            else {
                eObj.iCheck('uncheck');
            }
        }
    };

    ko.bindingHandlers.translate = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var $item = $(element),
                value = ko.unwrap(valueAccessor()) || {},
                x = ko.unwrap(value.x) || 0,
                y = ko.unwrap(value.y) || 0,
                result = 'translate(' + x + 'px, ' + y + 'px)';

            $item.css('transform', result);
        },

        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var $item = $(element),
                value = ko.unwrap(valueAccessor()) || {},
                x = ko.unwrap(value.x) || 0,
                y = ko.unwrap(value.y) || 0,
                result = 'translate(' + x + 'px, ' + y + 'px)';

            $item.css('transform', result);
        }
    }

    ko.bindingHandlers.lazyResize = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var $element = $(element);

            var setHeight = function () {
                var height = _($element.children()).reduce(function (r, child) {
                    return r + $(child).offsetHeight;
                }, 0);

                $element.css({ height: height });
            }

            var observer = new MutationObserver(setHeight);
            observer.observe(element, { attributes: true, childList: true, subtree: true });

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                observer.disconnect();
            });
        }
    }

    ko.bindingHandlers.slideToggle = {
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                value = valueAccessor(),
                doneCallback = allBindings.get('slideToggle-done');

            if (ko.unwrap(value)) {
                eObj.stop(true, true).slideDown({
                    duration: allBindings().slideDuration,
                    start: function () { if (allBindings().showOverflow) { eObj.css('overflow', 'visible'); } },
                    complete: doneCallback
                });
            }
            else {
                eObj.stop(true, true).slideUp({
                    duration: allBindings().slideDuration,
                    complete: doneCallback
                });
            }
        }
    };

    ko.bindingHandlers.fullpage = {
        init: function (element, valuesAccessor, allBindings) {
            var $el = $(element),
                value = ko.unwrap(valuesAccessor()),
                $w = $(window),
                $footer = $("#footer"),
                $header = $("#header");

            var update = _.debounce(function () {
                var topOffset = $el.offset().top,
                    bottomOffset = $footer.outerHeight();

                if (value) {
                    $el.css({ 'min-height': window.innerHeight - topOffset - bottomOffset });
                }
                else {
                    $el.css({ 'height': window.innerHeight - topOffset - bottomOffset });
                }
            }, 0);

            var observer = new MutationObserver(function (mutations) {
                var handle = _(mutations).any(function (m) { return m.target != element && $(m.target).closest(element).length == 0 });

                if (handle) update();
            });

            $w.on('resize', update);

            observer.observe($("body")[0], { attributes: true, childList: true, subtree: true });

            update();

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $w.off('resize', update);
                observer.disconnect();
            });            
        }
    }

    ko.bindingHandlers.slideToggleCSS = (function () {
        var applyTransitions = function ($item) {
            $item.css({
                '-webkit-transition': 'margin .4s ease-in-out',
                '-moz-transition': 'margin .4s ease-in-out',
                '-o-transition': 'margin .4s ease-in-out',
                'transition': 'margin .4s ease-in-out'
            });
        }

        var transitions = {
            "transition": "transitionend",
            "OTransition": "oTransitionEnd",
            "MozTransition": "transitionend",
            "WebkitTransition": "webkitTransitionEnd",
            "MSTransition": "MSTransitionEnd"
        }

        var onTransitionEnd = function (e) {
            $(e.srcElement).parent().css({ 'overflow': 'visible' });
        };

        var func = function (element, valueAccessor) {
            var $item = $(element),
                value = valueAccessor();

            var eventName = _(transitions).find(function (t, key) {
                return element.style[key] !== undefined;
            });

            $item.off('resize');
            $item.off(eventName, onTransitionEnd);

            if (ko.unwrap(value)) {
                if ($item.is(':hidden')) {
                    $item.show();
                    $item.css({ 'margin-top': -element.scrollHeight + 'px' });

                    _.defer(function () {
                        applyTransitions($item);
                    });
                }

                _.defer(function () {
                    $item.css({ 'margin-top': 0 });

                    $item.one(eventName, onTransitionEnd);
                });
            } else {
                $item.parent().css({ 'overflow': 'hidden' });
                $item.css({ 'margin-top': -element.scrollHeight + 'px' });

                $item.on('resize', function () {
                    $item.css({ 'margin-top': -element.scrollHeight + 'px' });
                });
            }
        };

        return {
            init: function (element, valueAccessor) {
                var $item = $(element);

                $item.hide();
                func(element, valueAccessor);
            },

            update: func
        }
    })();

    ko.virtualElements.allowedBindings.wccAfterRender = true;
    ko.bindingHandlers.wccAfterRender = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var callback = valueAccessor();

            if (callback) {
                _.defer(function () {
                    callback(element);
                });
            }
        }
    }

    ko.bindingHandlers.dom = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var val = valueAccessor();

            ko.ignoreDependencies(function () {
                if (ko.isObservable(val) || _(val).isFunction()) {
                    val(element);

                    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                        if (val() == element) {
                            val(null);
                        }
                    });
                } else if (_(val).isArray()) {
                    _(val).each(function (item) {
                        item(element);
                    });

                    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                        _(val).each(function (item) {
                            if (item() == element) {
                                item(null);
                            }
                        });
                    });
                }
            });
        }
    }

    ko.bindingHandlers.smartDropdown = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var $item = $(element),
                offset = 50;

            var update = _.debounce(function () {
                var $dropdown = $item.children('ul').first(),
                    $subMenu = $dropdown.find('.dropdown-submenu .dropdown-menu');

                $item.removeClass('dropup');

                var viewportOffset = element.getBoundingClientRect();

                if (viewportOffset.top < $(window).height() / 2) {
                    $item.addClass('dropdown');
                    $dropdown.removeClass('up');
                }
                else {
                    $item.addClass('dropup');
                    $dropdown.addClass('up');
                }

                if (viewportOffset.right + $dropdown.width() > $(window).width()) {
                    $item.addClass('pull-right');
                } else {
                    $item.removeClass('pull-right');
                }

                if ($subMenu.length && ($item.offset().left + $subMenu.width()) > $(window).width()) {
                    $subMenu.css("left", "-50%");
                }
                else {
                    $subMenu.css("left", "");
                }
            }, 0);

            update();

            $item.click(update);
            $item.hover(update);

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $item.off('click hover', update);
            });
        }
    }

    ko.bindingHandlers.animate = {
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                animateObj = valueAccessor(), //all binding properties are encapsulated inside one object for easy syntax
                value = animateObj.valueProperty, //The KO model property this binding is attached to. Must be boolean
                /*  TimeOuts control the timing of the animation trigger. It has two fields:
                    1. trueTimeOut: The timeout for the animation when the value is true
                    2. falseTimeOut: The timeout for the animation when the value is false  */
                timeOuts = animateObj.timeOuts || {},
                animationProperties = animateObj.animatedProperties,
                animationOptions = animateObj.animationOptions || {
                    duration: 300,
                    easing: 'swing'
                };

            /*The visibility control handles the visibility of the element. For instance, it is needed in cases where we run the animation over 'Opacity' css property. Any control takes full space on the page 
            if the opacity is 0 and so hiding it is needed in most cases. This is just one example for which we can make another binding that can use jQuery's show/hide functions. But I am using it here for 
            the same as it can also be used for other uses and I don't really see a good reason to add another binding unless any issues or seen. */
            if (animateObj.controlVisibility) {
                animationOptions.start = function () {
                    if (value) {
                        eObj.show();
                    }
                };
                animationOptions.complete = function () {
                    if (!value) {
                        eObj.hide();
                    }
                };
            }

            for (var k in animationProperties) { //set multiple properties here
                var propertyValues = animationProperties[k],
                    startValue = 0,
                    endValue = 0;

                if (typeof propertyValues.endValue == 'function') {
                    endValue = propertyValues.endValue();
                }
                else {
                    endValue = propertyValues.endValue;
                }

                if (typeof propertyValues.startValue == 'function') {
                    startValue = propertyValues.startValue();
                }
                else {
                    startValue = propertyValues.startValue;
                }

                if (value) {
                    animationProperties[k] = startValue;
                }
                else {
                    animationProperties[k] = endValue;
                }
            }

            //Assign the main caller function to a variable so it can be called at multiple places without duplicating the code
            var animateFunc = function () { eObj.stop(true, true).animate(animationProperties, animationOptions); };

            if (value) {
                if (timeOuts.trueTimeOut) { //if true timeOut is set, delay the animation
                    setTimeout(animateFunc, timeOuts.trueTimeOut);
                }
                else {
                    animateFunc();
                }
            }
            else {
                if (timeOuts.falseTimeOut) { //if false timeOut is set, delay the animation
                    setTimeout(animateFunc, timeOuts.falseTimeOut);
                }
                else {
                    animateFunc();
                }
            }
        }
    };

    ko.bindingHandlers.loaded = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var $el = $(element),
                value = valueAccessor();

            if (ko.isObservable(value)) {
                $el.load(function () {
                    value(true);
                });
            }
        }
    }

    ko.bindingHandlers.videoLoaded = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var $el = $(element),
                value = valueAccessor();

            if (ko.isObservable(value)) {
                var action = function () {
                    value(true);

                    $el.off('loadeddata', action);
                }

                $el.on('loadeddata', action);

                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    $el.off('loadeddata', action);
                });
            }
        }
    }

    ko.bindingHandlers.imageLoaded = {
        init: function (img, valueAccessor) {
            var val = valueAccessor();

            if (ko.isObservable(val)) {
                val(false);

                WCC
                    .System
                    .waitImage(img)
                    .done(function () { val(true) });
            }

            if (_(val).isObject() && ko.isObservable(val.value) && ko.isObservable(val.src)) {
                var update = function () {
                    val.value(false);

                    WCC
                        .System
                        .waitImage(img)
                        .done(function () { val.value(true) });
                }

                var s = val.src.subscribe(function (src) {
                    if (src != null) { update(); }
                });

                update();

                ko.utils.domNodeDisposal.addDisposeCallback(img, function () {
                    s.dispose();
                });
            }
        }
    }

    ko.bindingHandlers.tooltip = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var value = valueAccessor(),
                data = ko.unwrap(value),
                placement = ko.unwrap(data.placement || "top"),
                force = ko.unwrap(data.force),
                delay = ko.unwrap(data.delay || 0),
                container = ko.unwrap(data.container || null),
                $item = $(element),
                currentPlacement;

            var visibleWrapper = ko.pureComputed(function() {
                var val = ko.unwrap(ko.unwrap(valueAccessor()).visible);

                return val == null ? true : val;
            });

            var createTooltip = function () {
                var message = ko.unwrap(data.message);

                if (message == null) return;

                currentPlacement = getPlacement();

                $item.tooltip({
                    title: ko.unwrap(data.message),
                    delay: delay,
                    placement: currentPlacement,
                    container: container
                });

                if (force) {
                    $item.tooltip('show');
                }

                if (ko.unwrap(data.scrollTo)) {
                    $('html, body').animate({
                        scrollTop: $item.offset().top - 100
                    });
                }
            }

            var getPlacement = function () {
                return placement == 'smart' ?
                    ($item.offset().left > $(window).width() / 2 ? 'left' : 'right') :
                    placement;
            }

            var onHover = function () {
                if (visibleWrapper() && placement != currentPlacement) {
                    _.defer(function () {
                        createTooltip();
                        $item.tooltip('show');
                    });
                }
            }

            $item.on('mouseenter', onHover);

            var subs = visibleWrapper.subscribe(function (visible) {
                $item.tooltip('destroy');
                if (visible) {
                    _.delay(function () { createTooltip() }, 200);
                }
            });

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                subs.dispose();
                $item.tooltip('destroy');
            });
        }
    }

    ko.bindingHandlers.selected = {
        update: function (element, valueAccessor, allBindingsAccessor) {
            var selected = ko.utils.unwrapObservable(valueAccessor());
            if (selected) element.select();
        }
    };

    ko.bindingHandlers.inViewPort = {
        isVisible: function (container, element) {
            if (element == null) return false;

            var w = $(container),
                containerMode = container != window,
                item = $(element);

            var containerBottom = item.is(':last-child') ? w.scrollTop() + w.height() : w.scrollTop() + w.height() - 50,
                containerTop = item.is(':first-child') ? w.scrollTop() : w.scrollTop() + 50,
                itemTop = containerMode ? item.position().top : item.offset().top,
                itemBottom = containerMode ? item.position().top + item.height() : item.offset().top + item.height();

            return itemTop <= containerBottom && itemBottom >= containerTop;
        },

        init: function (element, valueAccessor, allBindingsAccessor) {
            var self = ko.bindingHandlers.inViewPort,
                item = ko.unwrap(allBindingsAccessor.get('inViewPort-element')) || $(element),
                container = ko.unwrap(allBindingsAccessor.get('inViewPort-container')),
                w = container != null ? container : window,
                $w = $(w),
                value = valueAccessor();

            if (ko.observable(value)) {
                var action = _.debounce(function () {
                    if (self.isVisible(w, item)) {
                        value(true);
                    }
                    else {
                        value(false);
                    }
                }, 100);

                $w.on('scroll', action);
                _.defer(action);

                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    $w.off("scroll", action);
                });
            }
        }
    }    

    ko.bindingHandlers.animationComplete = {
        init: function (element, valueAccessor) {
            var item = $(element),
                callback = valueAccessor();

            var animations = {
                "animation": "animationend",
                "OAnimation": "oAnimationEnd",
                "MozAnimation": "animationend",
                "WebkitAnimation": "webkitAnimationEnd",
                "MSAnimation": "MSAnimationEnd"
            }

            var eventName = _(animations).find(function (a, key) {
                return element.style[key] !== undefined;
            });

            if (_(callback).isFunction() && eventName != null) {
                item.on(eventName, callback);

                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    item.off(eventName, callback);
                });
            }
        }
    }

    ko.bindingHandlers.transitionComplete = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var item = $(element),
                callback = valueAccessor(),
                chilrenTransitions = allBindingsAccessor()['transition-children'],
                onlyTargetEvents = chilrenTransitions == null || chilrenTransitions == false;

            var transitions = {
                "transition": "transitionend",
                "OTransition": "oTransitionEnd",
                "MozTransition": "transitionend",
                "WebkitTransition": "webkitTransitionEnd",
                "MSTransition": "MSTransitionEnd"
            }

            var eventName = _(transitions).find(function (t, key) {
                return element.style[key] !== undefined;
            });

            var onEvent = function (e) {
                if (!onlyTargetEvents || e.currentTarget == element) {
                    callback();
                }
            }

            if (_(callback).isFunction() && eventName != null) {
                item.on(eventName, onEvent);

                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    item.off(eventName, onEvent);
                });
            }
        }
    }

    ko.bindingHandlers.shiftUp = {
        init: function (element, valueAccessor) {
            var item = $(element),
                w = $(window),
                value = valueAccessor(),
                height = item.outerHeight(true);

            if (ko.unwrap(value) && w.scrollTop() > 0) {
                w.scrollTop(w.scrollTop() + height);

                _.defer(function () {
                    w.scrollTop(w.scrollTop() + item.outerHeight(true) - height);
                });
            }
        }
    }

    ko.bindingHandlers.cropbox = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var value = valueAccessor(),
                options = ko.unwrap(value);

            value.cropbox = ko.observable(null);

            if (options) {
                value.cropbox($(element).cropbox(options));
            }
        },
        update: function (element, valueAccessor, allBindingsAccessor) {
            var value = valueAccessor(),
                options = ko.unwrap(value),
                cropbox = value.cropbox();

            if (cropbox) {
                cropbox.dispose();
            }

            if (options) {
                cropbox = $(element).cropbox(options);

                cropbox.setImageModified(true);
                value.cropbox(cropbox);
            }
        }
    }

    ko.bindingHandlers.scroll = {
        updating: true,
        init: function (element, valueAccessor, allBindingsAccessor) {
            var self = this
            self.updating = true;
            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $(window).off("scroll.ko.scrollHandler")
                self.updating = false
            });
        },
        update: function (element, valueAccessor, allBindingsAccessor) {
            var props = allBindingsAccessor().scrollOptions
            var offset = props.offset ? props.offset : "0"
            var loadFunc = props.loadFunc
            var load = ko.utils.unwrapObservable(valueAccessor());
            var self = this;

            if (load) {
                element.style.display = "";
                $(window).on("scroll.ko.scrollHandler", function () {
                    if (($(window).scrollTop() >= $(document).height() - offset - 2 * $(window).height())) {
                        if (self.updating) {
                            loadFunc()
                            self.updating = false;
                        }
                    }
                    else {
                        self.updating = true;
                    }
                });
            }
            else {
                element.style.display = "none";
                $(window).off("scroll.ko.scrollHandler")
                self.updating = false
            }
        }
    };

    ko.virtualElements.allowedBindings.lock = true;
    ko.bindingHandlers.lock = {
        init: function () {
            var stack = [],
                timeout = null;

            var process = function () {
                if (stack.length > 0) {
                    stack = _(stack).sortBy('priority');

                    var item = stack.shift();
                    item.func();

                    timeout = _.defer(process);
                } else {
                    timeout = null;
                }
            }

            var start = function () {
                timeout = _.defer(process);
            }

            var add = function (item) {
                stack.push(item);                

                if (timeout == null)
                    start();
            }

            return function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var priority = ko.unwrap(valueAccessor()),
                    children = _(ko.virtualElements.childNodes(element)).clone(),
                    executed = false;

                priority = priority != null ? priority : 10000;

                ko.virtualElements.emptyNode(element);

                var item = {
                    priority: priority,
                    func: function () {
                        ko.virtualElements.setDomNodeChildren(element, children);
                        ko.applyBindingsToDescendants(bindingContext, element);

                        executed = true;
                        $(element).closest('div').trigger('ko-lock-released');
                    }
                }                                

                $(element).closest('div').trigger('ko-lock-init');
                add(item);

                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    if (!executed) {
                        var idx = _(stack).indexOf(item);

                        if (idx != -1) {
                            stack.splice(idx, 1);
                        }
                    }
                });

                return { controlsDescendantBindings: true }
            }
        }()
    }

    ko.virtualElements.allowedBindings.lazyRender = true;
    ko.bindingHandlers.lazyRender = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var children = _(ko.virtualElements.childNodes(element)).clone();

            var val = ko.pureComputed(function () {
                return !!ko.unwrap(valueAccessor());
            });

            ko.virtualElements.emptyNode(element);

            val
                .when()
                .then(function () {
                    ko.virtualElements.setDomNodeChildren(element, children);
                    ko.applyBindingsToDescendants(bindingContext, element);
                }, new Promise(function (resolve) { ko.utils.domNodeDisposal.addDisposeCallback(element, function () { resolve() }) }));

            return { controlsDescendantBindings: true }
        }
    }

    ko.virtualElements.allowedBindings.toContext = true;
    ko.bindingHandlers.toContext = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            function Context () {
                this.$prevContext = bindingContext;
            }

            Context.prototype = valueAccessor();

            var context = new Context();

            ko.applyBindingsToDescendants(context, element);

            return { controlsDescendantBindings: true }
        }
    }

    ko.subscribable.fn.when = function (predicate, disposalPromise) {
        predicate = predicate || _.identity;

        var observable = this;

        return new Promise(function (resolve, reject) {
            var value = observable();

            if (predicate(value) === true) {
                resolve(value);
            } else {
                var sub = observable.subscribe(function (value) {
                    if (predicate(value) === true) {
                        resolve(value);
                        sub.dispose();
                    }
                });

                if (disposalPromise)
                    disposalPromise.then(function () { sub.dispose() });
            }
        });
    }

    ko.subscribable.fn.whenNotNull = function (disposalPromise) {
        return ko.subscribable.fn.when.call(this, function (value) { return value != null }, disposalPromise);
    }

    ko.subscribable.fn.whenChanged = function (disposalPromise) {
        var initial = this();
        return ko.subscribable.fn.when.call(this, function (value) { return value != initial }, disposalPromise);
    }

    ko.bindingHandlers.autogrow = (function () {
        var init = function (element) {
            var $item = $(element);

            if ($item.next(".autogrow-textarea-mirror").length != 0) return;

            $(element).after('<div class="autogrow-textarea-mirror"></div>');

            var $mirror = $item.next(".autogrow-textarea-mirror"),
                mirror = $mirror[0];

            // Style the mirror
            $mirror.css('display', 'none');
            $mirror.css('wordWrap', 'normal');
            $mirror.css('whiteSpace', 'normal');
            $mirror.css('padding', $item.css('padding'));
            $mirror.css('width', $item.css('width'));
            $mirror.css('fontFamily', $item.css('font-family'));
            $mirror.css('fontSize', $item.css('font-size'));
            $mirror.css('lineHeight', $item.css('line-height'));

            // Style the textarea
            $item.css('overflow', "hidden");

            var onChange = function () {
                mirror.innerHTML = String($item.val()).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br />') + ".";
                $mirror.css('width', $item.css('width'));

                var oldHeight = $item.height(),
                    newHeight = Math.ceil($mirror.height());

                if(newHeight != oldHeight)
                    $item.height(newHeight);
            };

            $item.keydown(onChange);
            $item.keyup(onChange);
            $item.on('changed', onChange);

            $item.on('autogrow-dispose', function () {
                $item.off('keydown', onChange);
                $item.off('keyup', onChange);
                $item.off('changed', onChange);

                $mirror.remove();
            });

            onChange();
            _.defer(function () {
                onChange();
            });

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $mirror.remove();
            });
        }

        var dispose = function (element) {
            var $item = $(element);

            $item.trigger('autogrow-dispose');
        }

        return {
            init: function (element, valueAccessor) {
                var val = ko.unwrap(valueAccessor());

                if (val) {
                    init(element);
                }
            },

            update: function (element, valueAccessor) {
                var val = ko.unwrap(valueAccessor());

                if (val) {
                    init(element);
                } else {
                    dispose(element);
                }
            }
        }
    })();

    ko.bindingHandlers.spinner = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var value = ko.unwrap(valueAccessor()),
                spinner = WCC.System.initSpinner(element, allBindingsAccessor().smallSpinner ? { radius: 15, length: 0, width: 3 } : null);
            if (!value) {
                spinner.stop();
            }
            $(element).data('spinner', spinner);
        },
        update: function (element, valueAccessor, allBindingsAccessor) {
            var value = ko.unwrap(valueAccessor());
            if (value) {
                $(element).data('spinner').spin(element);
            }
            else {
                $(element).data('spinner').stop();
            }
        }
    };
    ko.bindingHandlers.log = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            console.log(valueAccessor());
        }
    };
    ko.bindingHandlers.spectrum = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var value = valueAccessor(),
                rgbaMode = allBindingsAccessor()['spectrum-rgba'] || false,
                customClasses = allBindingsAccessor()['spectrum-classes'] || '';

            var format = function (color) { return rgbaMode ? color.toRgbString() : color.toHexString() };

            var test = $(element).spectrum({
                color: "#000",
                showAlpha: rgbaMode,
                showInput: true,
                className: "full-spectrum " + customClasses,
                showInitial: true,
                showPalette: true,
                showSelectionPalette: true,
                maxPaletteSize: 10,
                preferredFormat: "hex",
                localStorageKey: "spectrum.demo",

                hide: function (color) {
                    value(format(color));
                },

                palette: [
                    ["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
                    "rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)"],
                    ["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
                    "rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
                    ["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
                    "rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
                    "rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
                    "rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
                    "rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
                    "rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
                    "rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
                    "rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
                    "rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
                    "rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
                ]
            });

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $(element).spectrum("destroy");
            });
        },
        update: function (element, valueAccessor, allBindingsAccessor) {
            $(element).spectrum("set", valueAccessor()());
        }
    };
    ko.bindingHandlers.iCheckDynamic = {
        init: function (element, valueAccessor, allBindings, bindingContext) {
            var eObj = $(element),
                modelItem = bindingContext;
            eObj.on('change', function (event) {
                var thisCheck = $(this);
                if (thisCheck.is(':checked')) {
                    var value = valueAccessor(),
                        found = false;
                    if (!allBindings().isMultiple || allBindings().isExclusive)
                        value.removeAll();
                    $.each(value(), function (i, v) {
                        if (v.profileQuestionChoiceId == modelItem.profileQuestionChoiceId) {
                            found = true;
                            return false;
                        }
                    });
                    if (!found) {
                        value.push(modelItem);
                    }
                }
                else {
                    var value = valueAccessor();
                    value.remove(modelItem);
                }
            });
        },
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                modelItem = bindingContext.$data,
                selectedChoices = valueAccessor();

            var found = false;
            if (selectedChoices().length > 0) {
                $.each(selectedChoices(), function (i, choice) {
                    if (choice != null) {
                        if (choice.profileQuestionChoiceId == modelItem.profileQuestionChoiceId) {
                            eObj.prop('checked', true);
                            found = true;
                            return false;
                        }
                    }
                });
            }
            if (!found) {
                eObj.prop('checked', false)
            }
        }
    };

    ko.bindingHandlers.errorToggle = (function () {
        var process = function (element, valueAccessor) {
            var eObj = $(element),
                value = valueAccessor();

            if (eObj.hasClass('select2')) {
                eObj = eObj.next('.select2-container');
            }

            if (value.error()) {
                var scroll = false;

                if (typeof value.scrollTo != "undefined")
                    scroll = value.scrollTo();

                WCC.System.markControlAsInvalid(eObj, value.error(), scroll, ko.unwrap(value.container));
            }
            else {
                WCC.System.markControlAsValid(eObj);
            }
        };

        return {
            init: function (element, valueAccessor) {
                var $element = $(element);

                process(element, valueAccessor);

                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    WCC.System.markControlAsValid($element);
                });
            },

            update: process
        };
    })();

    ko.subscribable.fn.trackErrors = function () {
        var self = this;

        this.error = ko.observable('');
        this.scrollTo = ko.observable(false).extend({ notify: 'always' });
        this.hasErrors = ko.pureComputed(function () { return self.error() && self.error().trim() != '' });

        return this;
    };

    //ko extensions
    //wrapper to an observable that requires accept/cancel
    ko.reversibleObservable = function (initialValue) {
        //private variables
        var _actualValue = ko.observable(initialValue),
            _oldValue = initialValue;

        //computed observable that we will return
        var result = ko.computed({
            read: function () {
                return _actualValue();
            },
            write: function (newValue) {
                _actualValue(newValue);
            }
        }).extend({ notify: "always" });

        //update old value to latest
        result.commit = function () {
            _oldValue = _actualValue();
        };

        //force to take original
        result.reset = function () {
            _actualValue(_oldValue);
        };

        //check if the value is changed
        result.isChanged = function () {
            return _oldValue != _actualValue();
        };

        result.trackErrors = ko.observable.fn.trackErrors;
        return result;
    };

    ko.bindingHandlers.dragToggle = {
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                value = valueAccessor();
            try {
                if (ko.unwrap(value)) {
                    eObj.draggable('disable');
                }
                else {
                    eObj.draggable('enable');
                }
            }
            catch (ex) { }
        }
    };

    ko.virtualElements.allowedBindings.hideTemplate = true;
    ko.bindingHandlers.hideTemplate = {
        init: function () {
            return { controlsDescendantBindings: true }
        }
    }

    //This binding is used when we want to set a value on the click of an arbitrary HTML element. Used especially in smart dropdowns
    ko.bindingHandlers.clickSetValue = {
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                value = valueAccessor(),
                baseObj = value.baseObject == null ? viewModel : value.baseObject,
                noPropagation = value.noPropagation;

            var link = $(eObj);
            setTimeout(function () {
                link.on('click', function (e) {
                    var event = e || window.event;

                    if (typeof (baseObj[value.property]) == "function") {//if we have a function then its a ko observable
                        baseObj[value.property](value.valueToSet);//pass it the data value
                    }
                    else {//if its not a function its just a normal property
                        baseObj[value.property] = value.valueToSet;//set the value
                    }

                    // if we don't need bubble efect of this click
                    if (noPropagation === true) {
                        // Normal browsers
                        if (e.stopPropagation) {
                            e.stopPropagation();
                        }
                        //IE8 and Lower
                        else {
                            e.cancelBubble = true;
                        }
                        if (e.preventDefault) {
                            e.preventDefault();
                        }
                    }
                });
            }, 500);
        }
    };

    (function () {//binding handler for the ACE Editor. more info: https://github.com/probonogeek/knockout-ace/blob/master/knockout-ace.js
        var instances_by_id = {} // needed for referencing instances during updates.
        , init_id = 0;           // generated id increment storage

        ko.bindingHandlers.ace = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

                var options = allBindingsAccessor().aceOptions || {};
                var value = ko.utils.unwrapObservable(valueAccessor());

                // Ace attaches to the element by DOM id, so we need to make one for the element if it doesn't have one already.
                if (!element.id) {
                    element.id = 'knockout-ace-' + init_id;
                    init_id = init_id + 1;
                }

                var editor = ace.edit(element.id);

                if (options.theme) editor.setTheme("ace/theme/" + options.theme);
                if (options.mode) editor.getSession().setMode("ace/mode/" + options.mode);
                if (options.readOnly) editor.setReadOnly(true);
                if (options.wrap) editor.setOption('wrap', options.wrap);
                if (options.hideGutter) editor.setOption('showGutter', false);
                if (options.hidePrintMargin) editor.setOption('showPrintMargin', false)

                editor.setValue(value);
                editor.gotoLine(0);

                editor.getSession().on("change", function (delta) {
                    if (ko.isWriteableObservable(valueAccessor())) {
                        valueAccessor()(editor.getValue());
                    }
                });

                instances_by_id[element.id] = editor;

                // destroy the editor instance when the element is removed
                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    editor.destroy();
                    delete instances_by_id[element.id];
                });
            },
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var value = ko.utils.unwrapObservable(valueAccessor());
                var id = element.id;

                //handle programmatic updates to the observable
                // also makes sure it doesn't update it if it's the same.
                // otherwise, it will reload the instance, causing the cursor to jump.
                if (id !== undefined && id !== '' && instances_by_id.hasOwnProperty(id)) {
                    var editor = instances_by_id[id];
                    var content = editor.getValue();
                    if (content !== value) {
                        editor.setValue(value);
                        editor.gotoLine(0);
                    }
                }
            }
        };

        ko.aceEditors = {
            resizeAll: function () {
                for (var id in instances_by_id) {
                    if (!instances_by_id.hasOwnProperty(id)) continue;
                    var editor = instances_by_id[id];
                    editor.resize();
                }
            },
            get: function (id) {
                return instances_by_id[id];
            }
        };
    }());

    (function () {//binding handler for the SimpleMDE Editor. more info: https://simplemde.com/
        var instances_by_id = {} // needed for referencing instances during updates.
        , init_id = 0;           // generated id increment storage

        ko.bindingHandlers.simpleMDE = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

                var options = allBindingsAccessor().editorOptions || {};
                var value = ko.utils.unwrapObservable(valueAccessor());

                // Ace attaches to the element by DOM id, so we need to make one for the element if it doesn't have one already.
                if (!element.id) {
                    element.id = 'knockout-simpleIDE-' + init_id;
                    init_id = init_id + 1;
                }

                var initFunc = function () {
                    var simpleMDEOptions = {
                        element: document.getElementById(element.id),
                        status: ["lines", "words"]
                    };

                    if (options.placeholder) {
                        simpleMDEOptions.placeholder = options.placeholder;
                    }

                    if (options.status === false) {
                        simpleMDEOptions.status = options.status;
                    }
                    
                    if (options.customToolbar !== true && options.showOnlyMergedSymbols != null && options.showOnlyMergedSymbols == true) {
                        simpleMDEOptions.toolbar = ['|'];
                    }
                    else {
                        if (options.customToolbar === true && options.toolbar) {
                            simpleMDEOptions.toolbar = options.toolbar;
                        }
                    }

                    var simpleMDE = new SimpleMDE(simpleMDEOptions);
                    simpleMDE.value(value);

                    simpleMDE.codemirror.on("change", function () {
                        if (ko.isWriteableObservable(valueAccessor())) {
                            valueAccessor()(simpleMDE.value());
                        }
                    });

                    instances_by_id[element.id] = simpleMDE;

                    if (options.customToolbar !== true) {

                        if (WCC.getKOData("MergeSymbols") != null && WCC.getKOData("MergeSymbols").length) { //Render out the merge symbol dropdown
                            var mergeSymbolsSelectId = element.id + '-merge-symbols-select',
                                mergeSymbolsSelectHtml = '<select id="' + mergeSymbolsSelectId + '" style="width: 280px"><option value="">-- Select Integration Symbol --</option>{MERGESYMBOLS}</select>';

                            mergeSymbolsSelectHtml = mergeSymbolsSelectHtml.replace("{MERGESYMBOLS}", WCC.getKOData("MergeSymbols").map(function (m) { return "<option>" + m + "</option>"; }).join(''));
                            var mergeSymbolsSelect = $(mergeSymbolsSelectHtml);
                            $(element).next('.editor-toolbar').append(mergeSymbolsSelect);

                            $('#' + mergeSymbolsSelectId).select2().on('change', function () {
                                var thisRef = $(this);

                                if (WCC.isNullOrEmpty(thisRef.val())) {
                                    return;
                                }
                                var cm = simpleMDE.codemirror,
                                    selectedText = cm.getSelection(),
                                    text = selectedText || thisRef.val();

                                cm.replaceSelection(text);
                            });
                        }
                    }

                    // destroy the editor instance when the element is removed
                    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                        simpleMDE.toTextArea();
                        simpleMDE = null;
                        delete instances_by_id[element.id];
                    });
                };

                if (options.delayInit) {
                    setTimeout(function () {
                        initFunc();
                    }, options.delayInit);
                }
                else {
                    initFunc();
                }
            },
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                var value = ko.utils.unwrapObservable(valueAccessor());
                var id = element.id;

                //handle programmatic updates to the observable
                // also makes sure it doesn't update it if it's the same.
                // otherwise, it will reload the instance, causing the cursor to jump.
                if (id !== undefined && id !== '' && instances_by_id.hasOwnProperty(id)) {
                    var simpleMDE = instances_by_id[id];
                    var content = simpleMDE.value();
                    if (content !== value) {
                        simpleMDE.value(value);
                    }
                }
            }
        }
    }());

    ko.bindingHandlers.datePicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            //initialize datepicker with some optional options
            var options = allBindingsAccessor().datepickerOptions || { format: 'mm/dd/yyyy', inline: false };

            //options.autoclose = true;

            //if (allBindingsAccessor().noMonths) {
            //    options.minView = 4;
            //}
            //else if (allBindingsAccessor().noDays) {
            //    options.minView = 3;
            //}
            //else {
            //    options.minView = 2;
            //}
            //options.startView = options.minView;

            $(element).datetimepicker(options);

            //when a user changes the date, update the view model
            //ko.utils.registerEventHandler(element, "dp.change", function (event) {
            //    var value = valueAccessor();
            //    if (ko.isObservable(value)) {
            //        value(event.date);
            //    }
            //});
        },
        update: function (element, valueAccessor) {
            var widget = $(element).data("DateTimePicker");
            //when the view model is updated, update the widget
            if (widget) {
                var date = ko.utils.unwrapObservable(valueAccessor());
                widget.date(date);
            }
        } 
    };

    ko.bindingHandlers.datePicker332 = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            //initialize datepicker with some optional options
            var options = allBindingsAccessor().datepickerOptions || { format: 'DD/MM/YYYY HH:mm', inline: false };
            $(element).datetimepicker(options);

            //when a user changes the date, update the view model
            ko.utils.registerEventHandler(element, "dp.change", function (event) {
                var value = valueAccessor();
                if (ko.isObservable(value)) {
                    if (event.date) {
                        value(event.date.toDate());
                    }
                    else {
                        value(null);
                    }
                }
            });
        },
        update: function (element, valueAccessor) {
            var widget = $(element).data("DateTimePicker");
            //when the view model is updated, update the widget
            if (widget) {
                var date = ko.utils.unwrapObservable(valueAccessor());
                widget.date(date);
            }
        }
    };

    //This binding is used with time selection control
    ko.bindingHandlers.timeSelection = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var timeSelectionOptions = allBindingsAccessor().timeSelectionOptions,
                value = ko.utils.unwrapObservable(valueAccessor()),
                pOptions = {
                    'timeFormat': 'H:i',
                    'lang': {
                        mins: WCC.Labels.MinutesShort,
                        hr: WCC.Labels.HourShort,
                        hrs: WCC.Labels.HoursShort
                    }
                };

            if (timeSelectionOptions != null) {
                if (timeSelectionOptions.show2400) {
                    pOptions.show2400 = true;
                }
                if (timeSelectionOptions.step) { //Time selection control doesn't work well with null values, hence copy the attributes if not null
                    pOptions.step = timeSelectionOptions.step;
                }
                if (timeSelectionOptions.minTime) {
                    pOptions.minTime = timeSelectionOptions.minTime
                }
                if (timeSelectionOptions.maxTime) {
                    pOptions.maxTime = timeSelectionOptions.maxTime
                }
                else {
                    if (pOptions.show2400) {
                        pOptions.maxTime = "24:00";
                    }
                    else {
                        pOptions.maxTime = "23:59"; //This will automatically round off to the nearest time depending on the allowed range
                    }
                }
                if (timeSelectionOptions.showDuration) {
                    pOptions.showDuration = timeSelectionOptions.showDuration;
                }
            }

            $(element).timepicker(pOptions);

            if (WCC.isNotNullOrEmpty(value)) {
                $(element).timepicker('setTime', value);
            }

            $(element).on('change', function () {
                valueAccessor()($(this).val());
            });

            $(element).on('changeTime', function () {
                valueAccessor()($(this).val());
            });            
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var value = ko.utils.unwrapObservable(valueAccessor());

            if (WCC.isNotNullOrEmpty(value)) {
                $(element).timepicker('setTime', value);
            }
            else {
                $(element).timepicker('setTime', null);
            }
        }
    };

    ko.bindingHandlers.autoNumeric = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $(element).autoNumeric('destroy');
            });

            var formatOptions = allBindingsAccessor().formatOptions,
                nOptions = {
                    decimalCharacter: '.',
                    digitGroupSeparator: '',
                    //decimalPlacesOverride: 2,
                    minimumValue: 0
                };

            if (formatOptions != null) {
                if (formatOptions.langOptions) {
                    if (formatOptions.langOptions.decimalCharacter) {
                        nOptions.decimalCharacter = formatOptions.langOptions.decimalCharacter
                    };
                }
                //if (formatOptions.decimalPlacesOverride) {
                //    nOptions.decimalPlacesOverride = formatOptions.decimalPlacesOverride;
                //}
                if (formatOptions.digits != null) {
                    nOptions.maximumValue = (Math.pow(10, formatOptions.digits) - 1) / Math.pow(10, formatOptions.decimalPlacesOverride == null ? 0 : formatOptions.decimalPlacesOverride);
                }
            }

            $(element).autoNumeric('init', nOptions);
        }
    };
    
    ko.bindingHandlers.sparkline = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            var value = valueAccessor(),
                options = allBindingsAccessor()['sparkline-options'] || {};

            WCC.System.initSparkline($(element), value(), options);
        },
        update: function (element, valueAccessor, allBindingsAccessor) {
            var value = valueAccessor(),
                options = allBindingsAccessor()['sparkline-options'] || {};

            WCC.System.initSparkline($(element), value(), options);
        }
    }

    //This binding is used with time selection control
    ko.bindingHandlers.highcharts = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
            var value = valueAccessor(),
                config = value.highchartsOptions;

            var processor = ko.computed(function () {
                var options = {
                    chart: {
                        type: ko.unwrap(config.chartType)
                    },
                    title: {
                        text: ko.unwrap(config.title),
                        y: 25,
                        widthAdjust: -60
                    },
                    xAxis: {
                        categories: ko.unwrap(config.categories)
                    },
                    yAxis: {
                        min: 0,
                        labels: {
                            overflow: 'justify'
                        }
                    },
                    plotOptions: {
                        bar: {
                            dataLabels: {
                                enabled: true
                            }
                        }
                    },
                    exporting: {
                        buttons: {
                            contextButton: {
                                align: 'left'
                            }
                        }
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -40,
                        y: 80,
                        floating: true,
                        borderWidth: 1,
                        backgroundColor: Highcharts.theme && Highcharts.theme.legendBackgroundColor || '#FFFFFF',
                        shadow: true
                    },
                    series: [{
                        showInLegend: false,
                        data: ko.unwrap(config.data)
                    }],
                    tooltip: ko.unwrap(config.tooltip) || {}
                };

                $(function () {
                    $(element).highcharts(options);
                });
            });   

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                processor.dispose();
            });
        }
    };

    //This binding is used with IntlTelInput
    ko.bindingHandlers.intlTelInput = {
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                value = valueAccessor();

            eObj.blur(function () {
                if ($.trim(eObj.val())) {
                    viewModel[value.isValid] = eObj.intlTelInput("isValidNumber");
                    viewModel[value.value](eObj.intlTelInput("getNumber"));
                }
                else {
                    viewModel[value.value]('');
                }
            });
        }
    };

    //the binding handler for our Ideation Topic 
    ko.bindingHandlers.ideationTopicCanvas = {
        init: function (element, valueAccessor, allBinding, viewModel, bindingContext) {
            var data = valueAccessor()



            var drawIdeationData = function () {
                if (element != null && element.getContext) {
                    //numeric seconds since midnight 1970 (UNIX timestamps)
                    var ideaCreationRangeAfter = data.ideaCreationRangeAfter().getTime();
                    var ideaCreationRangeBefore = data.ideaCreationRangeBefore().getTime();
                    var ideaRankingRangeAfter = data.ideaRankingRangeAfter().getTime();
                    var ideaRankingRangeBefore = data.ideaRankingRangeBefore().getTime();

                    element.width = element.clientWidth;
                    element.height = element.clientHeight;

                    if (element.clientWidth < 50) return;//less than 50px wide don't draw the chart thing

                    var ctx = element.getContext('2d');
                    var radius = 6;
                    var h = 20;//height of all our lines and center of all the circles
                    var c1 = 10;//position of circle 1 - 10px in from the left edge
                    var c2 = element.clientWidth / 2;//position of circle 2 - centre of the box
                    var c3 = element.clientWidth - 10;//position of circle 3 - 10 px in from the right edge
                    var line1Length = c2 - c1 - radius - radius;
                    var line2Length = c3 - c2 - radius - radius;
                    var fullCircle = 2 * Math.PI;
                    var creationText = WCC.getSetting('IdeaCreationText'); //'Idea Creation';
                    var rankingText = WCC.getSetting('IdeaRankingText');//'Idea Ranking';
                    var reviewText = WCC.getSetting('IdeaReviewText');//Idea Review
                    var resultsText = WCC.getSetting('IdeaResultsText'); //Idea Results
                    var textToDraw = 0;//0-Creation, 1-Review, 2-Review

                    //draw black background
                    ctx.beginPath();//start drawing
                    ctx.lineWidth = 3;//make it a fat line
                    ctx.strokeStyle = '#BFBFBF';
                    ctx.arc(c1, h, radius, 0, fullCircle, false);//start with a full circle, leaves cursor 10+radius,10
                    ctx.lineTo(c2 - radius, h);//draw a straight line from the right edge of circle 1 to the left edge of circle 2
                    ctx.moveTo(c2 + radius, h);//move over the circle so we don't fill in the middle with a line
                    ctx.arc(c2, h, radius, 0, fullCircle, false);//draw circle 2, start and finish at 3 o'clock
                    ctx.lineTo(c3 - radius, h);//draw a straight line from the right edge of circle 2 to the left edge of circle 3
                    ctx.moveTo(c3 + radius, h);//move over circle 3 to start drawing at the right edge
                    ctx.arc(c3, h, radius, 0, fullCircle, false);//draw circle 3
                    ctx.stroke();//commit

                    //now we can kick off some kind of animation or something for drawing where we are up to
                    //for now we just draw it out
                    var now = new Date().getTime();

                    if (now > ideaCreationRangeAfter) {//we are after the create start idea - draw our first circle all green
                        ctx.beginPath();//start drawing coloured stuff
                        ctx.lineWidth = 3;//make it a fat line
                        ctx.strokeStyle = '#00F81D';//use our green colour

                        ctx.moveTo(c1 + radius, h);//move to first circle
                        ctx.arc(c1, h, radius, 0, fullCircle, false);//draw it in full in green

                        if (ideaCreationRangeBefore > now) {//we are in the Creation period so we just want to draw our line
                            //work out how far we are in
                            var range = ideaCreationRangeBefore - ideaCreationRangeAfter;
                            var nowRange = now - ideaCreationRangeAfter;

                            var percent = (nowRange / range);

                            ctx.moveTo(c1 + radius, h);
                            ctx.lineTo(c1 + radius + (line1Length * percent), h);
                            textToDraw = 0;//creation stage
                        }
                        else {//we are past the close of the Create period
                            //just because we are past the Create Before date doesn't mean we are into the ranking stage.
                            //draw our first line in full in green.  we definitely need the full first line in green
                            ctx.moveTo(c1 + radius, h);//first circle, right edge
                            ctx.lineTo(c1 + radius + line1Length, h);
                            textToDraw = 1;//review stage

                            if (now > ideaRankingRangeAfter) {//we are into the ranking stage                                
                                //middle circle is green
                                ctx.moveTo(c2 + radius, h);//move so we don't draw
                                ctx.arc(c2, h, radius, 0, fullCircle, false);//draw circle 2 fully in green

                                if (now > ideaRankingRangeBefore) {//we are done: 
                                    textToDraw = 3;//ranking stage
                                    //second line fully in green
                                    ctx.moveTo(c2 + radius, h);
                                    ctx.lineTo(c3 - radius, h);

                                    //draw the last circle green as well.
                                    ctx.moveTo(c3 + radius, h);
                                    ctx.arc(c3, h, radius, 0, fullCircle, false);
                                }
                                else {//we are in the middle of the ranking stage
                                    //work out how far to draw the line
                                    textToDraw = 2;//ranking stage
                                    var range = ideaRankingRangeBefore - ideaRankingRangeAfter;
                                    var nowRange = now - ideaRankingRangeAfter;

                                    var percent = (nowRange / range);

                                    ctx.moveTo(c2 + radius, h);
                                    ctx.lineTo(c2 + radius + (line2Length * percent), h);
                                }
                            }
                        }

                        ctx.stroke();//commit coloured line

                        //now draw our text, we only draw one text string and position it over the stage
                        ctx.font = "14px Helvetica Neue";
                        ctx.fillStyle = '#000000;';
                        ctx.shadowOffsetX = 0;
                        ctx.shadowOffsetY = 0;
                        ctx.shadowBlur = 0;

                        if (textToDraw == 0) {//draw 'Idea Creation' on the left line
                            var textWidth = ctx.measureText(creationText).width;
                            ctx.fillText(creationText, c1 + (line1Length / 2) - (textWidth / 2), 10);
                        } else if (textToDraw == 1) {//draw 'Idea Review' over the middle circle
                            var textWidth = ctx.measureText(reviewText).width;
                            ctx.fillText(reviewText, (element.clientWidth / 2) - (textWidth / 2), 10);
                        } else if (textToDraw == 2) {//draw 'Idea Ranking' over the right line
                            var textWidth = ctx.measureText(rankingText).width;
                            ctx.fillText(rankingText, c2 + (line2Length / 2) - (textWidth / 2), 10);
                        } else if (textToDraw == 3) {
                            var textWidth = ctx.measureText(resultsText).width;
                            ctx.fillText(resultsText, c2 + (line2Length / 2) - (textWidth / 2), 10);
                        }
                    }

                    window.setTimeout(drawIdeationData, 1000);//draw every second
                }//if the element is null we drop out and don't add the timeout again
            };

            drawIdeationData();//start it off

            $(window).on('resize', function () {//also add an on-resize handle
                drawIdeationData();
            });
        }
    };

    //Extend ko objects with underscore functions
    _.extend(ko.subscribable.fn, _.chain(_.prototype).keys().filter(function (key) {
        //add function only if key in fn array is free
        //fn - array of ko objec methods
        return ko.subscribable.fn[key] == null;
    }).map(function (key) {
        var func = function () {
            var observable = this;

            var args = _(arguments).toArray();

            var result = ko.pureComputed(function () {
                var w = _(observable());
                return w[key].apply(w, args);
            });

            return result;
        }

        return [key, func];
    }).object().value());

    var map = function (predicate, context) {
        var observable = this;

        return ko.pureComputed({
            read: function () { return predicate.call(context, observable()) },
            write: function (value) { observable(value) }
        });
    }

    var mapNotNull = function (predicateOrMapping, context) {
        var observable = this;

        var read = _.identity,
            write = function (unwrapped, value) { observable(value) };

        if (_(predicateOrMapping).isFunction()) {
            read = predicateOrMapping;
        } else if (predicateOrMapping != null) {
            if (predicateOrMapping.read != null)
                read = predicateOrMapping.read;

            if (predicateOrMapping.write != null)
                write = predicateOrMapping.write;
        }

        return ko.pureComputed({
            read: function () {
                var val = observable();

                return val == null ? null : read.call(context, val);
            },
            write: function (value) { write.call(context, observable(), value) }
        });
    }

    var not = function () {
        var observable = this;

        return ko.pureComputed(function () {
            return !observable();
        });
    }

    ko.observable.fn.map = map;
    ko.observable.fn.mapSingle = map;
    ko.computed.fn.mapSingle = map;
    ko.observable.fn.mapNotNull = mapNotNull;
    ko.computed.fn.mapNotNull = mapNotNull;
    ko.observable.fn.not = not;
    ko.computed.fn.not = not;

    ko.observableArray.fn.map = function () {
        var observable = this,
            args = _(arguments).toArray();

        var result = ko.pureComputed(function () {
            var w = _(observable());
            return w.map.apply(w, args);
        });

        return result;
    }

    ko.observableArray.fn.concat = function (arr) {
        var observable = this;

        return ko.pureComputed(function () {
            return _(observable()).concat(ko.unwrap(arr));
        });
    }

    ko.subscribable.fn.each = function () {
        var observable = this,
            args = _(arguments).toArray();

        var result = ko.computed(function () {
            var w = _(observable());
            return w.each.apply(w, args);
        });

        return result;
    };

    ko.subscribable.fn.map2 = function (key, predicate, updatePredicate) {
        var items = this,
            cache = [];

        return ko.pureComputed(function () {
            cache = _(items()).map(function (item, idx) {
                var existingItem = _(cache).find(function (i) {
                    return _(key).isFunction() ? key(item, i) : item[key] == i[key];
                });

                if (existingItem != null) {
                    if (updatePredicate)
                        updatePredicate(existingItem, item);

                    return existingItem;
                } else {
                    return predicate(item, idx);
                };
            });

            return cache;
        });
    }

    ko.subscribable.fn.toFlag = function (delay) {
        var observable = this;

        var value = ko.observable(false);

        var result = observable.mapSingle(function (v) {
            if (v) value(v);

            return value();
        });

        if (_(delay).isNumber())
            result.extend({ rateLimit: delay });

        result.reset = function () {
            value(false);
        }

        return result;
    }

    ko.subscribable.fn.is = function (predicate) {
        var observable = this;

        var result = ko.pureComputed(function () {
            return predicate(observable());
        });

        return result;
    }

    ko.subscribable.fn.readOnly = function () {
        var observable = this;

        return ko.pureComputed(function () {
            return observable();
        });
    }

    ko.subscribable.fn.default = function (defaultValue) {
        var observable = this;

        var get = function (value) {
            return defaultValue !== undefined && (value == null || value == -Infinity) ?
                ko.unwrap(defaultValue) :
                value;
        };

        return ko.pureComputed({
            read: function () { return get(observable()) },
            write: function (value) { observable(value) }
        });
    }

    ko.subscribable.fn.attachTo = function (mainObservable) {
        var observable = this;

        return ko.computed(function () {
            observable(mainObservable());
        });
    }

    ko.subscribable.fn.unwrap = function () {
        var observable = this;

        return ko.pureComputed(function () {
            return ko.unwrap(observable());
        });
    }

    ko.subscribable.fn.unwrapPromise = function () {
        var observable = this,
            result = ko.observable(null);

        return ko.pureComputed(function () {
            var value = observable();

            if (value.done) {
                value.done(function (val) { result(val); })
            } else {
                result(value);
            }

            return result;
        });
    }

    ko.subscribable.fn.toPOJO = function () {
        return ko.unwrap(this);
    }

    var guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
    ko.subscribable.fn.isGuid = function () {
        var observable = this;

        return ko.pureComputed(function () {
            var v = observable();

            return _(v).isString() && guidRegex.test(v);
        });
    }

    ko.extenders.notifyIfChanged = function (target, val) {
        if (val) {
            target["equalityComparer"] = function (a, b) { return a === b; }
        }
        else {
            target["equalityComparer"] = ko.observable.fn.equalityComparer;
        }
    }

    //model.name.extend({
    //    validate: function (name) {
    //        if (ko.unwrap(showErrors)) {
    //            var result = null;

    //            name = $.trim(name);

    //            result = name.length == 0 ? messages.WidgetNameCantBeEmpty : null;
    //            result = result || (name.length < 3 ? messages.WidgetNameTooSmall : null);

    //            return result;
    //        }

    //        return null;
    //    }
    //});

    ko.extenders.validate = function (target, predicate) {
        target.error = target.mapSingle(function (val) {
            return predicate(val);
        });

        target.isValid = target.error.mapSingle(function (err) { return err == null || err == '' });
        target.hasError = target.isValid.mapSingle(function (v) { return !v });
        target.scrollTo = ko.observable(false);

        return target;
    }

    ko.extenders.hasErrors = function (target) {
        target.error = ko.observable(null);
        target.isValid = target.error.mapSingle(function (err) { return err == null });
        target.hasError = target.isValid.not();
        target.scrollTo = ko.observable(false);
    }

    ko.extenders.moment = function (target) {
        //create a writable computed observable to intercept writes to our observable
        var result = ko.pureComputed({
            read: target,  //always return the original observables value
            write: function (newValue) {
                var current = target(),
                    valueToWrite = moment(newValue);

                //only write if it changed
                if (valueToWrite !== current) {
                    target(valueToWrite);
                }
            }
        }).extend({ notify: 'always' });

        //initialize with current value to make sure it is rounded appropriately
        result(target());

        //return the new computed observable
        return result;
    };

    ko.subscribable.fn.shortcut = function (length, hard, fullwords) {
        var observable = this;

        hard = hard || false;
        fullwords = fullwords || false;

        return ko.pureComputed(function () {
            var originalContent = observable();

            if (_(originalContent).isString()) {
                if (originalContent.length <= length) {
                    return originalContent.trim();
                } else {
                    var words = originalContent.split(' ');

                    var content = _.chain(words).first(length).reduce(function (result, word) {
                        return result.length >= length ? result : result + " " + (fullwords ? word : word.substr(0, hard ? length - result.length : length).trim());
                    }, "").value();

                    return content.length < originalContent.length ? content.trim() + "..." : content.trim();
                }
            } else {
                return '';
            }
        });
    }

    ko.groups = function () {
        var groups = {}

        var Group = function (name) {
            var self = this,
                items = [];

            self.items = function () {
                var addItem = function (item) {
                    if (!_(items).contains(item)) {
                        items.push(item);
                    }
                }

                return {
                    add: addItem
                }
            }();

            self.dispose = function () {
                _(items).each(function (i) {
                    if (i.dispose != null) { i.dispose(); }
                });

                items = [];
            }
        }

        var getGroup = function (name, createIfNotExists) {
            var createIfNotExists = createIfNotExists != null ? createIfNotExists : true;

            if (groups[name] == null && createIfNotExists) {
                groups[name] = new Group(name);
            }

            return groups[name];
        }

        return {
            get: getGroup
        }
    }();

    ko.utils.disposeGroup = function (name) {
        var group = ko.groups.get(name, false);

        if (group != null) {
            group.dispose();
        }
    }

    var _subscribe = ko.subscribable.fn.subscribe;
    ko.subscribable.fn.subscribe = function () {
        var s = _subscribe.apply(this, arguments);

        s.register = function (name) {
            if (_(name).isArray()) {
                name.push(s);
            } else {
                ko.groups.get(name).items.add(s);
            }

            return this;
        }

        return s;
    }

    ko.subscribable.fn.register = function (name) {
        if (_(name).isArray()) {
            name.push(this);
        } else {
            ko.groups.get(name).items.add(this);
        }

        return this;
    }    

    ko.subscribable.fn.toPx = function (allowNull) {
        var observable = this;

        return ko.pureComputed(function () {
            if (_(observable()).isNumber()) {
                return observable() + 'px';
            } else if (_(observable()).isString()) {
                return observable();
            } else {
                return allowNull ? null : 'auto';
            }
        });
    }

    ko.subscribable.fn.toUrl = function () {
        var observable = this;

        return ko.pureComputed(function () {
            var val = observable();

            return val ? 'url("' + val + '")' : '';
        });
    }

    ko.bindingHandlers.select2 = {
        //
        // NOTE: you must use at least select2-4.0.5 for this binding
        //
        init: function (el, valueAccessor, allBindingsAccessor, viewModel) {
            ko.utils.domNodeDisposal.addDisposeCallback(el, function () {
                $(el).select2('destroy');
            });

            var allBindings = allBindingsAccessor(),
                select2 = ko.utils.unwrapObservable(allBindings.select2);

            $(el).select2(select2);
        },
        update: function (el, valueAccessor, allBindingsAccessor, viewModel) {
            var allBindings = allBindingsAccessor();

            if ("value" in allBindings) {
                if (allBindings.select2.multiple && allBindings.value() && allBindings.value().constructor != Array) {
                    $(el).val(allBindings.value().split(","));
                }
                else {
                    $(el).val(allBindings.value());
                }
                $(el).trigger('change');
            } else if ("selectedOptions" in allBindings) {
                var converted = [];
                //var textAccessor = function (value) { return value; };
                //if ("optionsText" in allBindings) {
                //    textAccessor = function (value) {
                //        var valueAccessor = function (item) { return item; }
                //        if ("optionsValue" in allBindings) {
                //            valueAccessor = function (item) { return item[allBindings.optionsValue]; }
                //        }
                //        var items = $.grep(allBindings.options(), function (e) { return valueAccessor(e) == value });
                //        if (items.length == 0 || items.length > 1) {
                //            return "UNKNOWN";
                //        }
                //        return items[0][allBindings.optionsText];
                //    }
                //}
                $.each(allBindings.selectedOptions(), function (key, value) {
                    converted.push(value);
                });

                $(el).val(converted);
                $(el).trigger('change');
            }
        }
    };

    ko.bindingHandlers.ChoiceQuestionOptions = {
        processNewChoices: function (value) {
            //new magic now supports inserting choices.
            var numberValuesNeeded = false;

            return value.split('\n').map(function (s, i) {

                if (!s || s.length <= 0) {
                    return null;
                }

                var ret = {};

                if (s.indexOf('[') > -1 && s.indexOf(']') > -1) {
                    var bStart = s.indexOf('['),
                        bEnd = s.indexOf(']');
                    if (bEnd - bStart > 1) {
                        ret.choiceImage = s.substr(bStart + 1, bEnd - bStart - 1);
                        s = s.replace('[' + ret.choiceImage + ']', '');
                    }
                }

                var parts = s.split('|');
                var sLower = s.toLowerCase();

                //these two should really always be there and they MUST be first
                if (parts.length == 1) {
                    ret.choiceText = parts[0];
                }
                else if (parts.length > 1) {
                    var startsWithOldValueMatches = /^[\d]+\|/.exec(s); //if we are editing choices, the old value must be there in the beginning

                    if (startsWithOldValueMatches != null && startsWithOldValueMatches.length >= 1) {
                        ret.oldValue = parts[0];
                        ret.choiceText = parts[1];
                    }
                    else {
                        ret.choiceText = parts[0];
                    }
                }
                else {
                    ret.choiceText = '';
                }

                var valueMatches = /\(?(\d+)\)/g.exec(ret.choiceText);

                if (valueMatches != null && valueMatches.length >= 2) {
                    ret.choiceValue = valueMatches[1];

                    if (isNaN(ret.choiceValue)) {
                        throw "The data contains invalid choice values. Choices values must be numeric";
                        return;
                    }

                    ret.choiceText = ret.choiceText.replace("(" + ret.choiceValue + ")", ""); //strip number value

                    if (i == 0) { //if it's first value, set validNumberValues to true
                        numberValuesNeeded = true;
                    }
                }
                else {
                    ret.choiceValue = i + 1;

                    if (i == 0) { //if it's first value, set validNumberValues to true
                        numberValuesNeeded = false;
                    }
                }

                if (i > 0) {
                    if ((numberValuesNeeded == true && (valueMatches == null || valueMatches.length == 0)) || (numberValuesNeeded == false && (valueMatches != null && valueMatches.length > 0))) {
                        throw "You can't have some choices with values and some without values";
                        return;
                    }
                }

                //now check the other options
                ret.isExclusive = /((?!\d+)[^|]+)\|exclusive/.test(sLower); //Make sure that "3|Exclusive choice' is not treated as an exclusive type and only '3|Exclusive choice|exclusive' is treated as an exclusive choice
                ret.isDefault = /((?!\d+)[^|]+)\|default/.test(sLower); //Make sure that "3|Default choice' is not treated as default choice type and only '3|Default choice|default' is treated as a default choice
                ret.isHidden = /((?!\d+)[^|]+)\|hidden/.test(sLower); //Make sure that "3|Hidden choice' is not treated as hidden choice type and only '3|Hidden choice|other' is treated as a hidden choice
                ret.isPinned = /((?!\d+)[^|]+)\|pinned/.test(sLower); //Make sure that "3|Pinned choice' is not treated as pinned choice type and only '3|Pinned choice|pinned' is treated as other choice
                ret.isOther = /((?!\d+)[^|]+)\|other/.test(sLower); //Make sure that "3|other choice' is not treated as other choice type and only '3|other choice|other' is treated as other choice

                if (ret.choiceText.indexOf('##') != -1 && WCC.Tag) { //we have tag here
                    var isAppliedOnThread = ret.choiceText.indexOf('###') != -1; //'###' means the tag is applied both on person as well as thread

                    var choiceTextParts = ret.choiceText.split(isAppliedOnThread ? '###' : '##');
                    ret.choiceText = choiceTextParts.length >= 1 ? choiceTextParts[0] : '';
                    ret.dataTag = {
                        TagValue: choiceTextParts[1],
                        Visibility: WCC.Enums.ContentTagVisibilityType.AdministratorsOnly.value,
                        SpecialType: isAppliedOnThread ? WCC.Enums.ContentTagSpecialType.ChoiceTagForThread.value : WCC.Enums.ContentTagSpecialType.None.value
                    };
                }
                ret.choiceText = WCC.System.generateStringWithBasicFormattingTags(ret.choiceText); //strip html other than bold, italics and underlines
                return ret;
            }).filter(function (i) { return i != null; });//clean out any blank lines
        },

        init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
            $(element).on('blur', function () {
                var allBindings = allBindingsAccessor();
                if(viewModel.showChoicesInTextArea != null) {
                    viewModel.showChoicesInTextArea = false;
                }
                allBindings.ChoicesError(false);
                allBindings.ChoicesError.error('');

                var processedChoices = [];//these are the new choices in order that have been processed and should replace whatever we originally had in our question choices array

                //old/original choices as an array:
                var oldChoices = context.$data.choices();

                try {
                    //turn whatever they typed in into a nice object            
                    var newChoices = ko.bindingHandlers.ChoiceQuestionOptions.processNewChoices(element.value);
                }
                catch (err) {
                    allBindings.ChoicesError(true);
                    allBindings.ChoicesError.error(err);
                    return;
                }

                //go through everything they entered in one by one and match it up with what we used to have OR create a new one
                for (var iChoice = 0; iChoice < newChoices.length; iChoice++) {
                    var c = newChoices[iChoice];

                    //update their choice order to their new index/position
                    c.choiceOrder = iChoice;//keep this starting at 0 cause you always send them all, no need to be tricky

                    //check to see if there was already a choice with a matching value (compare against my old choice value in case it is being changed now)
                    var originalChoice = $.grep(oldChoices, function (e) { return e.choiceValue == c.oldValue; });

                    if (originalChoice && originalChoice.length == 1) {//we found one that matches
                        originalChoice = originalChoice[0];//get our choice out.  we really only want this for its id because we are updating it.

                        c.profileQuestionChoiceId = originalChoice.profileQuestionChoiceId;//steal its id
                    }

                    c = new ApiProfileQuestionChoice(c, context.$data);

                    if (c.choiceValue === null) {//no choice value, make sure this stays NULL after 
                        c.choiceValue = null;
                    }

                    processedChoices.push(c);
                }

                if (processedChoices && processedChoices.length > 0) {
                    //now process any NEW choice values if they have not been set somehow (either by the user or by linking to existing choices as an update)

                    //first get the biggest numeric value we have
                    var nextChoiceValue = processedChoices.map(function (c) { return parseInt(c.choiceValue, 10); }).filter(function (c) { return !isNaN(parseInt(c, 10)); }).sort();

                    if (nextChoiceValue && nextChoiceValue.length > 0) {//we found at least one value that is real
                        nextChoiceValue = nextChoiceValue[nextChoiceValue.length - 1] + 1;
                    }
                    else {
                        nextChoiceValue = 1;//we didnt find any values, they must ALL be new, start our values at 1
                    }

                    //now go  through each question and set their value if they dont have one
                    for (var iChoice = 0; iChoice < processedChoices.length; iChoice++) {
                        var c = processedChoices[iChoice];

                        if (c.choiceValue === null) {//choice value SHOULD be a number, if it is empty string then then are trying to add a new choice and didnt give it a value, fix it
                            c.choiceValue = nextChoiceValue;
                            nextChoiceValue++;
                        }
                    }
                }

                //now replace the choices array with this new processed one and we are done.
                context.$data.choices(processedChoices);//pass this new value (array) into the observable array to swap all its elements                
            });
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            if (viewModel.showChoicesInTextArea != null && viewModel.showChoicesInTextArea == false) { //don't update choices live in the editor
                viewModel.showChoicesInTextArea = true;
            }
            else {
                var choices = ko.unwrap(valueAccessor());//get our data (get the value not the observable)

                //process each choice turning it into a line of text.
                //add them all up
                //stuff them in the text box (element)
                if ($.isArray(choices)) {
                    var newText = choices.map(function (i) {
                        return i.toUserEditString();
                    }).join('\n');

                    $(element).val(newText);
                }
            }
        }
    };

    ko.bindingHandlers.limitCharacters = {
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            element.value = element.value.substr(0, valueAccessor());
            allBindingsAccessor().value(element.value.substr(0, valueAccessor()));
        }
    };

    ko.bindingHandlers.enterkey = {
        init: function (element, valueAccessor, allBindings, viewModel) {
            var callback = valueAccessor();
            $(element).keypress(function (event) {
                var keyCode = (event.which ? event.which : event.keyCode);
                if (keyCode === 13) {
                    callback.call(viewModel);
                    return false;
                }
                return true;
            });
        }
    };

    ko.bindingHandlers.kohtml = {
        init: function (element, valueAccessor) {
            var $element = $(element),
                data = valueAccessor();

            var value,
                model;

            if (data != null && !_(data).isFunction() && data.value != null) {
                value = data.value;
                model = data.data || {};
            } else {
                value = data;
                model = {};
            }

            var sub = ko.computed(function () { $element.html(ko.unwrap(value)) });
            ko.applyBindingsToDescendants(model, element);

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () { sub.dispose() });

            return { controlsDescendantBindings: true };
        }
    };

    ko.bindingHandlers.maskedInput = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                options = allBindings().maskOptions || {},
                mask = options.mask || '';

            eObj.on('blur', function (event) {
                valueAccessor()(eObj.val()/*.replace('$ ', '')*/);
            });
            eObj.inputmask(mask);
        },
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                value = valueAccessor();
            eObj.val(value());
        }
    };

    ko.extenders.numeric = function (target, options) {
        //create a writable computed observable to intercept writes to our observable
        var result = ko.pureComputed({
            read: target,  //always return the original observables value
            write: function (newValue) {
                var current = target(),
                    roundingMultiplier = Math.pow(10, options.precision),
                    newValueAsNum = isNaN(newValue) ? 0 : +newValue,
                    valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;

                if (typeof options.min != 'undefined' && valueToWrite < options.min) {
                    valueToWrite = options.min;
                }
                if (typeof options.max != 'undefined' && valueToWrite > options.max) {
                    valueToWrite = options.max;
                }

                //only write if it changed
                if (valueToWrite !== current) {
                    target(valueToWrite);
                } else {
                    //if the rounded value is the same, but a different value was written, force a notification for the current field
                    if (newValue !== current) {
                        target.notifySubscribers(valueToWrite);
                    }
                }
            }
        }).extend({ notify: 'always' });

        //initialize with current value to make sure it is rounded appropriately
        result(target());

        //return the new computed observable
        return result;
    };

    ko.bindingHandlers.rangeSlider = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                options = allBindings().rangeOptions || {},
                sliderValues = options.values;

            var sliderOptions = {
                type: options.toValue ? 'double' : 'single',
                step: options.step || 1,
                grid: options.grid === undefined ? true : options.grid,
                hide_min_max: options.hide_min_max || false,
                hide_from_to: options.hide_from_to || false
            };

            if (sliderValues && sliderValues.length) { //we may add support for two sliders for WCCRangleSliderModel
                if (options.usesRangleSliderModel) {
                    sliderOptions.values = sliderValues.map(function (i) { return i.value(); });

                    sliderOptions.prettify_enabled = true;
                    sliderOptions.prettify = function (num) {
                        var obj = _.find(sliderValues, function (e) { return e.value() == num; });
                        if (obj == null || !obj.isLabelVisible()) {
                            return "";
                        }
                        return obj.value();
                    };
                    sliderOptions.current_label = function (num) {
                        var obj = _.find(sliderValues, function (e) { return e.value() == num; });
                        if (obj == null) {
                            return "";
                        }
                        return obj.label();
                    };
                }
                else {
                    sliderOptions.values = sliderValues;
                }
            }
            else {
                $.extend(sliderOptions, {
                    min: options.min || 0,
                    max: options.max || 20,
                    from: options.from,
                    from_min: options.from_min || options.min
                });

                if (options.toValue) {
                    $.extend(sliderOptions, {
                        to: options.to,
                        to_max: options.to_max || options.max
                    });
                }
            }

            sliderOptions.onFinish = function (obj) {
                var value = valueAccessor(),
                    fromValToPush = null,
                    toValToPush = null;

                if (options.usesRangleSliderModel) {
                    var item = _.find(sliderValues, function (e) { return e.value() == obj.from_value; });

                    if (item != null) {
                        fromValToPush = item.originalItem();
                    }

                    if (options.toValue) {
                        var toItem = _.find(sliderValues, function (e) { return e.value() == obj.to_value; });

                        if (toItem != null) {
                            toValToPush = toItem.originalItem();
                        }
                    }
                }
                else {
                    if (obj.from_value != null) {
                        fromValToPush = obj.from_value;
                    } else if (obj.from != null) {
                        fromValToPush = obj.from;
                    }                 

                    if (options.toValue && obj.to_value != null) {
                        toValToPush = obj.to_value;
                    }
                }

                if (fromValToPush != null) {
                    if (Array.isArray(value())) {
                        value.removeAll();
                        value.push(fromValToPush);
                    }
                    else {
                        value(fromValToPush);
                    }
                }
                if (toValToPush != null) {
                    if (Array.isArray(options.toValue)) {
                        options.toValue.removeAll();
                        options.toValue.push(toValToPush);
                    }
                    else {
                        options.toValue(toValToPush);
                    }
                }
            };

            eObj.ionRangeSlider(sliderOptions);

            var slider = eObj.data("ionRangeSlider");

            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                slider.destroy();
            });
        },
        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            var eObj = $(element),
                slider = eObj.data("ionRangeSlider"),
                options = allBindings().rangeOptions || {},
                value = valueAccessor(),
                sliderValues = options.values;

            if (sliderValues && sliderValues.length) {
                var selectedItem = null;
                if (options.usesRangleSliderModel) {
                    selectedItem = sliderValues.find(function (i) { return i.originalItem() == (Array.isArray(value()) && value().length > 0 ? value()[0] : value); });
                }
                else {
                    selectedItem = sliderValues.find(function (i) { return i == (Array.isArray(value()) && value().length > 0 ? value()[0] : value); });
                }
                if (selectedItem) {
                    _.defer(function () {
                        slider.update({
                            from: sliderValues.indexOf(selectedItem)
                        });
                    });
                }
            }
            else {
                slider.update({
                    from: ko.unwrap(value)
                });

                if (options.toValue) {
                    slider.update({
                        to: options.toValue()
                    });
                }
            }
        }
    };
});
WCC.Settings = {
    maxUserContentImageSize: 512000,
    allowedUploadImageExtensions: ['gif', 'jpeg', 'jpg', 'png'],
};
