Plugin Directory

Changeset 1355844


Ignore:
Timestamp:
02/22/2016 04:04:42 PM (10 years ago)
Author:
clinked
Message:

fix for Navbar not showing under some installations

Location:
clinked-client-portal/trunk
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • clinked-client-portal/trunk/app/clinked-portal.js

    r1209039 r1355844  
    1 (function($,undef){"use strict";var debug=false;window.FileUpload_Debug=function(){if(debug&&console.log)if($.browser.msie){var output="Log: ";$.each(arguments,function(){output+=this});console.log(output)}else console.log.apply(console,arguments)};window.FileUpload_ToJSONIfPossible=function(responseText){if(responseText)try{return $.parseJSON(responseText)}catch(e){window.FileUpload_Debug(e)}return responseText}})(jQuery,"undefined");(function($,undef,debug){"use strict";var default_options={chunkEndpoint:"",finalEndpoint:"",beforeFinalSend:function(){},multipartEndpoint:"",completeRetries:300,defaultDataType:"json",defaultContentType:"application/x-www-form-urlencoded; charset=UTF-8",numberOfSimultaneousFileUploads:2,serializeFormData:true,chunkSize:5242880,maxFileSize:4294967296,runtimes:["HTMLRuntime","FlashRuntime","FrameRuntime"],autoUpload:false,deleteOnFailure:false,flashPath:"../swf/",ajaxLoader:"../img/ajax-loader.gif",fileLoading:"Loading file",fileComplete:"Complete",fileSize:"File too large"};function assert(expr,exception){if(expr)throw exception}function FileUpload(element,options){assert(element.nodeName.toLowerCase()!=="form","Invalid element, expected form nodeName");this.options=$.extend({},default_options,options||{});this.element=$(element);this.runtime=this.createRuntime();assert(!this.runtime,"No runtime supported");if(this.options.layout){this.element.addClass("layout-"+this.options.layout.toLowerCase());this.layout=new FileUpload.Layout[this.options.layout](this);this.layout.create()}this.runtime.create(this)}FileUpload.defaultOptions=default_options;FileUpload.hasSupport=function(runtimes){try{return new FileUpload(document.createElement("form"),{runtimes:runtimes||["HTMLRuntime","FlashRuntime"]})!==null}catch(e){return false}};FileUpload.formatBytes=function(bytes){var output=bytes/1024;if(output<1024)return output.toFixed(2)+"KB";output=output/1024;if(output<1024)return output.toFixed(2)+"MB";return(output/1024).toFixed(2)+"GB"};FileUpload.prototype.createRuntime=function(){var runtimeIndex,runtimes=this.options.runtimes;for(runtimeIndex=0;runtimeIndex<runtimes.length;runtimeIndex++){var runtimeName=runtimes[runtimeIndex];var Runtime=FileUpload.Runtime[runtimeName];if(Runtime.supports()){this.runtimeName=runtimeName;return new Runtime(this)}}return null};FileUpload.prototype.triggerEvent=function(eventName){if($.isFunction(this.options[eventName]))this.options[eventName].apply(this,$.makeArray(arguments).slice(1));this.element.trigger("FileUpload_"+eventName,$.makeArray(arguments).slice(1))};FileUpload.prototype.on=function(eventName,handler){var eventNames=$.map(eventName.split(" "),function(value){return"FileUpload_"+value+".FileUpload"}).join(" ");this.element.on(eventNames,handler)};$.each(["send","abort","remove"],function(){var functionName=this;FileUpload.prototype[functionName]=function(){this.runtime[functionName].apply(this.runtime,arguments)}});FileUpload.prototype.finalizeSend=function(file,success,responseHandler){responseHandler=responseHandler||$.noop;var submitData=$.extend({},{FileUploadId:file.fuid,FileUploadName:encodeURIComponent(file.name),FileUploadType:file.type,FileUploadSuccess:success,FileUploadSize:file.size},this.options.data||{});if(this.options.serializeFormData)$.each(this.element.serializeArray(),function(i,item){submitData[item.name]=item.value});var self=this;$.ajax(this.options.finalEndpoint,{beforeSend:this.options.beforeFinalSend,type:"post",dataType:this.options.defaultDataType,data:submitData,contentType:this.options.defaultContentType,success:function(response){responseHandler(false,response);self.triggerEvent("filefinish",file,success,false,response)},error:function(xhr){var text=window.FileUpload_ToJSONIfPossible(xhr.responseText);responseHandler(true,text);self.triggerEvent("filefinish",file,success,true,text)},file:file})};FileUpload.prototype.destroy=function(){if(this.layout){this.element.removeClass("layout-"+this.options.layout.toLowerCase());this.layout.destroy(this);delete this.layout}this.runtime.destroy(this);delete this.runtime;this.element.unbind(".FileUpload")};window.FileUpload=FileUpload})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.File=function(fuid,name,size,type){this.fuid=fuid||0;this.name=name||"unknown";this.size=size||0;this.type=type||"application/octet-stream"}})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";function Runtime(){}Runtime.create=function(name,runtimeCode){var runtime=function(fileUpload){this.fileUpload=fileUpload};$.extend(runtime.prototype,Runtime.prototype,runtimeCode);FileUpload.Runtime[name]=runtime;FileUpload.Runtime[name].supports=runtimeCode.supports};$.each(["create","destroy","send","abort","supports","remove","uploading"],function(){Runtime.prototype[this]=$.noop});Runtime.prototype.abort=function(fileId){if(fileId&&this.files[fileId]){debug("Aborting file id:",fileId);this.files[fileId].abort()}else if(!fileId){this.fileUpload.triggerEvent("abort");debug("Aborting all file uploads");this.fileStack=[];$.each(this.files,function(){this.abort()})}};Runtime.prototype.remove=function(fileId){if(fileId&&this.files[fileId]){var file=this.files[fileId];if(file.isUploading())throw"Abort or complete in order to remove";file.destroy();delete this.files[fileId]}else if(!fileId){if(this.uploading())throw"Abort or complete in order to remove";$.each(this.files,function(){this.destroy()});this.files={}}};FileUpload.Runtime=Runtime})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";function Layout(){}Layout.create=function(name,layoutCode){var layout=function(fileUpload){this.fileUpload=fileUpload};$.extend(layout.prototype,Layout.prototype,layoutCode);window.FileUpload.Layout[name]=layout};Layout.prototype.create=Layout.prototype.destroy=$.noop;FileUpload.Layout=Layout})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.Runtime.create("HTMLRuntime",{create:function(){this.filesUploading=0;this.files={};this.counter=0;var self=this,HTMLFile=FileUpload.Runtime.HTMLRuntime.File;this.fileUpload.element.on("change.FileUpload",":file",function(e){var target=e.target,newFiles=[];$.each(target.files,function(){var htmlFile=new HTMLFile(this,self.createFileOptions(self.counter));if(this.size>self.fileUpload.options.maxFileSize)self.fileUpload.triggerEvent("filesizeerror",htmlFile.info);else{self.files[self.counter]=new HTMLFile(this,self.createFileOptions(self.counter));newFiles.push(self.files[self.counter].info);self.counter++}});self.fileUpload.triggerEvent("select",newFiles);if(self.fileUpload.options.autoUpload)self.fileUpload.send();if(self.fileUpload.options.clearInputOnChange)target.value=""})},destroy:function(){if(this.timer)clearTimeout(this.timer);$.each(this.files,function(){this.destroy()});this.files=this.fileStack=null},createFileOptions:function(counter){var self=this,options=$.extend({},this.fileUpload.options,{finalize:function(success){var innerSelf=this;self.fileUpload.finalizeSend(this.info,success,function(isError,response,onComplete){if(!isError&&success){if(!innerSelf.aborted){debug("Deleting file with counter",innerSelf.options.counter);delete self.files[innerSelf.options.counter]}}else if(self.fileUpload.options.deleteOnFailure)delete self.files[innerSelf.options.counter]});self.filesUploading--},progress:function(percentage,bytesLoaded,progressEvent,xhrOptions){self.percentLoaded[this.info.fuid]=percentage;var percentTotal=0;$.each(self.percentLoaded,function(){percentTotal+=this});self.fileUpload.triggerEvent("totalprogress",Math.min(100,Math.ceil(percentTotal/self.stackCount)));self.fileUpload.triggerEvent("fileprogress",this.info,percentage)},counter:counter});var defaultEventHandler=function(eventName){return function(chunk){self.fileUpload.triggerEvent(eventName,this.info,chunk)}};$.each(["beforeStart","beforeSend","success","error"],function(){options[this]=defaultEventHandler("file"+this.toLowerCase())});return options},uploading:function(){return!!this.timeout},send:function(fileId){if(!this.uploading()){this.stackLoaded=0;this.percentLoaded={};this.stackSize=0;this.stackCount=0;this.fileStack=[]}var self=this;if(!fileId){$.each(this.files,function(counter){if($.inArray(counter,self.fileStack)===-1&&!self.files[counter].isUploading()){self.fileStack.push(counter);self.stackSize+=this.file.size;self.stackCount++}})}else if(this.files[fileId]&&!this.files[fileId].isUploading()){this.fileStack.push(fileId);this.stackSize+=this.files[fileId].file.size;this.stackCount++}debug("Total stack size: ",this.stackSize);this.fileUpload.triggerEvent("beforestart",{fileStack:this.fileStack,stackSize:this.stackSize,fileId:fileId,running:this.uploading()});this.fileStack=this.fileStack.reverse();if(!this.uploading())this.timeout=setInterval(function(){if(self.fileStack.length===0){clearInterval(self.timeout);self.timeout=null}else if(self.filesUploading<self.fileUpload.options.numberOfSimultaneousFileUploads){var counter=self.fileStack.pop();if(self.files[counter]){debug("Uploading file: ",counter,self.fileStack,self.files);self.files[counter].upload();self.filesUploading++}}},500)},supports:function(){if(typeof File===undef||typeof Blob===undef)return false;var isFn=$.isFunction;return isFn(Blob.prototype.webkitSlice)||isFn(Blob.prototype.mozSlice)||isFn(Blob.prototype.slice)}});$.ajaxPrefilter(function(options){options.xhr=function createStandardXhrWithUpload(){var xhr=$.ajaxSettings.xhr();if(xhr.upload)$.each(options.upload||{},function(event,listener){var optionsWrapper=function(e){return listener.call(this,e,options)};xhr.upload.addEventListener(event,optionsWrapper,false)});return xhr}})})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";var default_options={method:"post",chunkEndpoint:"",dataType:"html",numberOfSimultaneousChunkUploads:1,numberOfRetriesBeforeFailure:1e3,chunkSize:5242880,beforeStart:$.noop,beforeSend:$.noop,success:$.noop,error:$.noop,finalize:$.noop,progress:$.noop};function File(file,options){this.options=$.extend({},default_options,options||{});this.file=file;this.info=new FileUpload.File(this.options.counter,file.name,file.size,file.type);this.totalChunks=Math.ceil(file.size/this.options.chunkSize);this.chunksUploading=0;this.chunksUploaded=0}File.prototype.destroy=function(){if(this.timer)clearTimeout(this.timer);this.chunks=this.xhr=null};File.prototype.slice=function(start,end){if(this.file.slice)return this.file.slice(start,end);if(this.file.mozSlice)return this.file.mozSlice(start,end);return this.file.webkitSlice(start,end)};File.prototype.isUploading=function(){return!!this.timeout};File.prototype.upload=function(){debug("Starting upload process for file");if(this.isUploading()){debug("File is in uploading state, exit");return false}this.chunks=[];this.chunksLoaded=[];this.xhr={};this.uploaded=0;var startPosition=0,endPosition=this.options.chunkSize,index=0;while(startPosition<this.file.size){if(endPosition>this.file.size)endPosition=this.file.size;this.chunks.push({id:index,start:startPosition,end:endPosition,failures:0});index++;startPosition=endPosition;endPosition+=this.options.chunkSize}this.chunks=this.chunks.reverse();this.options.beforeStart.call(this);var self=this;this.percentage=0;this.aborted=false;this.timeout=setInterval(function(){if(self.chunks.length===0&&self.chunksUploading===0){clearInterval(self.timeout);self.timeout=null;self.finalize(self.chunksUploaded===self.totalChunks)}else if(!self.aborted)if(self.chunksUploading<self.options.numberOfSimultaneousChunkUploads&&self.chunks.length!==0)self.send()},500);return true};File.prototype.progressHandler=function(e,options){var self=this;setTimeout(function(){var bytesLoaded=0;$.each(self.chunksLoaded,function(){bytesLoaded+=this.end-this.start});bytesLoaded+=e.loaded;self.percentage=Math.max(self.percentage,Math.min(100,Math.ceil(bytesLoaded/self.file.size*100)));self.options.progress.call(self,self.percentage,bytesLoaded,e,options);debug("File progress: ",self.file.name," = ",self.percentage,"% (chunk:",options.chunk.id,")")},0)};File.prototype.send=function(){var chunk=this.chunks.pop(),blob=this.slice(chunk.start,chunk.end);debug("Sending a new file chunk",chunk);var options=this.options,self=this;var ajaxOptions={dataType:options.dataType,type:options.method,data:blob,timeout:3e4*(chunk.failures+1),contentType:"application/octet-stream",processData:false,chunk:chunk,upload:{progress:$.proxy(this.progressHandler,this),load:$.proxy(this.progressHandler,this)},beforeSend:function(xhr,settings){xhr.setRequestHeader("X-File-Chunk",settings.chunk.id);xhr.setRequestHeader("X-File-Start",settings.chunk.start);xhr.setRequestHeader("X-File-End",settings.chunk.end);xhr.setRequestHeader("X-File-Id",self.info.fuid);xhr.setRequestHeader("X-File-Name",encodeURIComponent(self.info.name));xhr.setRequestHeader("X-File-Size",self.info.size);xhr.setRequestHeader("X-File-Type",self.info.type);self.xhr[settings.chunk.id]=xhr;self.options.beforeSend.apply(self,$.merge([this.chunk],arguments))},success:function(){self.chunksUploaded++;self.chunksUploading--;self.chunksLoaded.push(this.chunk);delete self.xhr[this.chunk.id];self.options.success.apply(self,$.merge([this.chunk],arguments))},error:function(e,statusText){var errorChunk=this.chunk;debug("Failed to upload chunk",errorChunk,statusText);if(statusText!=="abort"&&errorChunk.failures<options.numberOfRetriesBeforeFailure){errorChunk.failures++;self.chunks.push(errorChunk);debug("Retrying to upload chunk",errorChunk)}self.chunksUploading--;delete self.xhr[errorChunk.id];self.options.error.apply(self,$.merge([this.chunk],arguments))}};$.ajax(options.chunkEndpoint,ajaxOptions);this.chunksUploading++};File.prototype.abort=function(){debug("Aborting file upload");this.aborted=true;this.chunks=[];this.chunksUploaded=0;$.each(this.xhr||[],function(){this.abort()})};File.prototype.finalize=function(success){debug("Finalizing file upload, success state: ",success);this.chunksUploading=0;this.options.finalize.apply(this,arguments)};window.FileUpload.Runtime.HTMLRuntime.File=File})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";var instanceCounter=0;var instances={};FileUpload.Runtime.create("FlashRuntime",{create:function(){var instanceId=this.instanceId=++instanceCounter;var options=this.fileUpload.options;this.fileUpload.options.numberOfRetriesBeforeFailure=1e3;var wrapElement=this.wrapElement=this.fileUpload.element.find(options.flashWrapper||":file");$("<div />").attr("id","runtime_"+this.instanceId).insertAfter(wrapElement);$(window).on("resize.FileUpload scroll.FileUpload DOMNodeInserted.FileUpload",$.proxy(this.positionAndResize,this));instances[instanceId]=this;this.embedSWF()},destroy:function(){this.getMovieObject().remove();$(window).unbind(".FileUpload")},init:function(){this.getMovie().setOptions(this.fileUpload.options);this.positionAndResize()},send:function(fileId){this.getMovie().upload(fileId||-1)},abort:function(fileId){this.getMovie().abort(fileId||-1)},remove:function(fileId){this.getMovie().remove(fileId||-1)},uploading:function(){return this.getMovie().uploading()},embedSWF:function(){var flashPath=this.fileUpload.options.flashPath;var flashvars={id:this.instanceId};var params={menu:"false",scale:"noScale",allowFullscreen:"true",allowNetworking:"all",allowScriptAccess:"always",bgcolor:"",wmode:"transparent"};var attributes={id:"flash_runtime_"+this.instanceId};swfobject.embedSWF(flashPath+"fileupload.swf","runtime_"+this.instanceId,"100%","100%","11.1.0",flashPath+"expressInstall.swf",flashvars,params,attributes)},handleFlashEvent:function(eventName,eventArgs){if(eventName==="filefinish"){var self=this;this.fileUpload.finalizeSend.call(this.fileUpload,eventArgs[0],eventArgs[1],function(isError,response,onComplete){if(eventArgs[1]&&!isError||self.fileUpload.options.deleteOnFailure)self.getMovie().deleteFile(eventArgs[0].fuid)})}else this.fileUpload.triggerEvent.apply(this.fileUpload,$.merge([eventName],eventArgs))},positionAndResize:function(){this.getMovieObject().css($.extend(this.wrapElement.position(),{position:"absolute",outline:0})).width(this.wrapElement.outerWidth()).height(this.wrapElement.outerHeight())},getMovieObject:function(){return $("#flash_runtime_"+this.instanceId)},getMovie:function(){var name="flash_runtime_"+this.instanceId;return document[name]||window[name]},supports:function(){return swfobject.hasFlashPlayerVersion("10")}});FileUpload.Runtime.FlashRuntime.EventHandler=function(instanceId,args){var instance=instances[instanceId],safeCall="handleFlashEvent";var eventName=args[0],eventArgs=[];if(args.length>1)eventArgs=args.slice(1);debug("Flash event:",eventName,eventArgs);if(eventName!=="abort")if($.isFunction(instance[eventName]))instance[eventName].apply(instance,eventArgs);else if($.isFunction(instance[safeCall]))instance[safeCall].call(instance,eventName,eventArgs)}})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.Runtime.create("FrameRuntime",{create:function(){if(!this.fileUpload.options.multipartEndpoint)throw"Unable to use FrameRuntime, define multipartEndpoint in options";this.filesUploading=0;this.counter=0;this.files={};this.percentLoaded={};var self=this,FrameFile=FileUpload.Runtime.FrameRuntime.File;this.fileUpload.element.on("change.FileUpload",":file",function(e){var target=$(e.target);target.clone(true).insertBefore(target).val("");var file=new FrameFile(target,self.createFileOptions(self.counter));self.files[self.counter]=file;self.counter++;self.fileUpload.triggerEvent("select",[file.info]);if(self.fileUpload.options.autoUpload)self.fileUpload.send()})},destroy:function(){if(this.timer)clearTimeout(this.timer);$.each(this.files,function(){this.destroy()});this.files=null},send:function(fileId){if(!this.uploading()){this.fileStack=[];this.stackComplete=0;this.stackCount=0;this.percentLoaded={}}var self=this;if(!fileId){$.each(this.files,function(counter){if($.inArray(counter,self.fileStack)===-1&&!self.files[counter].isUploading()){self.fileStack.push(counter);self.stackCount++}})}else if(this.files[fileId]){this.fileStack.push(fileId);this.stackCount++}debug("Total stack count: ",this.stackCount);this.fileUpload.triggerEvent("beforestart",{fileStack:this.fileStack,stackSize:0,fileId:fileId,running:this.uploading()});this.fileStack=this.fileStack.reverse();if(!this.uploading())this.timeout=setInterval(function(){if(self.fileStack.length===0){clearInterval(self.timeout);self.timeout=null}else if(self.filesUploading<self.fileUpload.options.numberOfSimultaneousFileUploads){var counter=self.fileStack.pop();debug("Uploading file: ",counter,self.fileStack,self.files);self.files[counter].upload();self.filesUploading++}},500)},uploading:function(){return!!this.timeout},createFileOptions:function(counter){var self=this;function handleSuccessOrError(success){return function(){var innerSelf=this;self.fileUpload.finalizeSend(this.info,success,function(isError,response,onComplete){if(!isError&&success){var c=innerSelf.options.counter;debug("Deleting file with counter",c);self.files[c].destroy();delete self.files[c]}});self.filesUploading--;self.stackComplete++}}return $.extend({},this.fileUpload.options,{counter:counter,beforeStart:function(){self.fileUpload.triggerEvent("filebeforestart",this.info)},progress:function(percentage){self.percentLoaded[this.info.fuid]=percentage;var percentTotal=0;$.each(self.percentLoaded,function(){percentTotal+=this});self.fileUpload.triggerEvent("totalprogress",Math.min(100,Math.ceil(percentTotal/self.stackCount)));self.fileUpload.triggerEvent("fileprogress",this.info,percentage)},success:handleSuccessOrError(true),error:handleSuccessOrError(false)})},supports:function(){return true}})})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";var default_options={beforeStart:$.noop,success:$.noop,progress:$.noop};function File(fileElement,options){this.options=$.extend({},default_options,options);var path=fileElement.val(),tokens=path.split(/\\|\//),name=tokens[tokens.length-1];this.info=new FileUpload.File(this.options.counter,name);this.createFormWrapper(fileElement);this.uploading=false}File.prototype.upload=function(){if(this.isUploading()){debug("File already in upload state");return false}this.options.beforeStart.call(this);this.uploading=true;this.frameElement.removeClass("abort");this.formElement.submit();return true};File.prototype.isUploading=function(){return false};File.prototype.abort=function(){this.frameElement.attr("src","about:blank").addClass("abort")};File.prototype.destroy=function(){this.frameElement.add(this.formElement).remove()};File.prototype.handleFrameComplete=function(){try{var response=this.frameElement[0].contentWindow.document.body.innerHTML,type="success";debug("Frame Loaded");debug(response);try{response=$.parseJSON($("<span />").append(response).text())||{}}catch(e){debug("Failed to parse JSON response",e.message);type="error";response={}}if(response.error||response.exception||this.frameElement.hasClass("abort"))type="error";if(response.request){this.info.size=response.request.fileSize;this.info.type=response.request.fileType}this.options.progress.call(this,100);this.options[type].call(this,response)}catch(ad){debug("Failed to get frame contents (Access Denied?): ",ad)}this.uploading=false};File.prototype.createFormWrapper=function(domElement){var hash="Form_"+Math.round(Math.random()*1e5);var endpoint=this.options.multipartEndpoint;var form=this.formElement=$("<form />").append(domElement).attr({action:endpoint,enctype:"multipart/form-data",method:"post",id:hash,target:hash}).addClass("fileupload-frame");form.insertBefore("body").hide();form.append($('<input type="text" name="X-File-Id" />').val(this.info.fuid));form.append($('<input type="text" name="X-File-Name" />').val(this.info.name));form.append($('<input type="text" name="X-File-Type" />').val(this.info.type));form.append($('<input type="text" name="X-File-Size" />').val(this.info.size));var frame=this.frameElement=$('<iframe src="javascript:;" name="'+hash+'" />').on("load",$.proxy(this.handleFrameComplete,this)).attr({id:"IFrame_"+hash}).hide().insertBefore(form)};window.FileUpload.Runtime.FrameRuntime.File=File})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.Layout.create("Simple",{create:function(){this.progressBar=$("<div />").insertAfter(this.fileUpload.element.find(":file")).addClass("progress").append($("<div/>").addClass("progress-bar progress-bar-striped"));if(this.fileUpload.runtimeName==="FlashRuntime"){this.flashContainer=this.fileUpload.element.find("#simple-flash-wrapper");if(this.flashContainer.size()!==0){this.fileUpload.options.flashWrapper="#simple-flash-wrapper :button";this.fileUpload.element.find(":file").hide();this.flashContainer.show()}}var self=this;this.fileUpload.element.on("submit.FileUpload",function(e){e.preventDefault();self.progressBar.find(".progress-bar").text("");self.fileUpload.send()});this.fileUpload.on("select",function(e,files){if(self.flashContainer){var fileArray=[];$.each(files,function(){fileArray.push(this.name)});self.flashContainer.find(".selection").text(fileArray.join(", "))}});this.fileUpload.on("filebebeforeloading",function(){self.appendLoadingIfNotPresent()});this.fileUpload.on("fileloading",function(e,file,percentage){var bar=self.progressBar.find(".progress-bar").text(self.fileUpload.options.fileLoading+" ("+percentage+"%)");if(bar.width()<120)bar.width(120)});this.fileUpload.on("filesizeerror",function(e,file){self.progressBar.find(".progress-bar").addClass("progress-bar-danger").removeClass("active").width("100%").text(self.fileUpload.options.fileSize)});this.fileUpload.on("beforestart totalprogress",function(e,ui){var isStart=e.type==="FileUpload_beforestart";if(isStart){self.stackFileFailures=0;self.stackFileCount=0;self.stackSizeCount=ui.fileStack.length;if(self.stackSizeCount>0){self.appendLoadingIfNotPresent();self.fileUpload.element.find(":submit").addClass("disabled")}}self.handleProgress(isStart?0:ui)});this.fileUpload.on("filefinish",$.proxy(this.handleFileFinalize,this));this.fileUpload.on("abort",$.proxy(this.handleAbort,this));this.fileUpload.element.find("button.abort, input.abort").on("click.FileUpload",function(){self.fileUpload.element.find(":submit").removeClass("disabled");self.fileUpload.abort()})},destroy:function(){this.progressBar.remove();if(this.flashContainer&&this.flashContainer.size()!==0){this.flashContainer.hide();this.fileUpload.element.find(":file").show()}this.fileUpload.element.find("button.abort, input.abort").unbind(".FileUpload")},handleProgress:function(width){this.width=Math.max(this.width||0,width);var bar=this.progressBar.find(".progress-bar").width(width+"%");if(width===0)bar.addClass("active").removeClass("progress-bar-danger progress-bar-warning progress-bar-success");else bar.text(width+"%")},handleAbort:function(){this.progressBar.find(".progress-bar").addClass("progress-bar-danger").removeClass("active")},handleFileFinalize:function(e,file,success,isError,response){this.progressBar.removeClass("active");if(!success)this.stackFileFailures++;this.stackFileCount++;if(this.stackFileCount===this.stackSizeCount){this.fileUpload.element.find(".ajax-loading").remove();this.fileUpload.element.find(":submit").removeClass("disabled");var className="progress-bar-success";if(isError||this.stackFileFailures===this.stackSizeCount)className="progress-bar-danger";else if(this.stackFileFailures>0)className="progress-bar-warning";this.progressBar.find(".progress-bar").text(this.fileUpload.options.fileComplete).addClass(className).removeClass("active")}},appendLoadingIfNotPresent:function(){var loader=$("<img />").addClass("ajax-loading").attr("src",this.fileUpload.options.ajaxLoader);if(this.flashContainer&&this.flashContainer.size()!==0&&this.flashContainer.find(".ajax-loading").size()===0)loader.appendTo(this.flashContainer);else if(this.fileUpload.element.find(".ajax-loading").size()===0)loader.insertAfter(this.fileUpload.element.find(":file"))}})})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.Layout.create("Complex",{create:function(){if(this.fileUpload.runtimeName==="FlashRuntime"){this.fileUpload.options.flashWrapper="#complex-flash-wrapper";this.fileUpload.element.find(":file").hide()}this.table=this.fileUpload.element.find("table");this.tbody=this.table.find("tbody");this.fileUpload.on("select",$.proxy(this.handleFileSelect,this));this.fileUpload.on("filebebeforeloading",$.proxy(this.handleFileStart,this));this.fileUpload.on("filebeforestart",$.proxy(this.handleFileStart,this));this.fileUpload.on("filefinish",$.proxy(this.handleFileComplete,this));this.fileUpload.on("fileprogress",$.proxy(this.handleFileProgress,this));this.fileUpload.on("fileloading",$.proxy(this.handleFileLoading,this));this.fileUpload.on("filesizeerror",$.proxy(this.handleFileSizeError,this));var self=this;this.table.on("click.FileUpload",".btn",function(e){var target=$(e.target),row=target.parents("tr:first"),id=row.attr("id").substring(5);if(target.hasClass("submit")||target.hasClass("retry")){debug("Uploading new file: ",id);self.fileUpload.send(id)}if(target.hasClass("cancel"))self.fileUpload.abort(id);if(target.hasClass("remove")){self.fileUpload.remove(id);row.fadeOut("fast",function(){row.remove()})}});this.fileUpload.element.find(".upload-all").on("click.FileUpload",function(){self.fileUpload.send()});this.fileUpload.element.find(".cancel-all").on("click.FileUpload",function(){self.fileUpload.abort()})},destroy:function(){this.fileUpload.element.find(".upload-all, .cancel-all").unbind(".FileUpload");this.table.unbind(".FileUpload");this.table.find("tr").not(".template").remove();if(this.fileUpload.runtimeName==="FlashRuntime")this.fileUpload.element.find(":file").show()},getFileRow:function(file,selector){var row=this.tbody.find("#file_"+file.fuid);if(selector)return row.find(selector);return row},handleFileSelect:function(e,files){var template=this.fileUpload.element.find(".template"),i;for(i=0;i<files.length;i++){var file=files[i],newTemplate=template.clone();newTemplate.removeClass("template").attr("id","file_"+file.fuid);newTemplate.find(".name").html(file.name);newTemplate.find(".size").html(FileUpload.formatBytes(file.size));newTemplate.appendTo(this.tbody);newTemplate.find(".submit, .remove").show()}},handleFileProgress:function(e,file,progress){this.getFileRow(file,".progress .progress-bar").data("progress",progress).width(progress+"%").text(progress+"%")},handleFileBeforeLoad:function(e,file){this.appendLoadingIfNotPresent(file)},handleFileLoading:function(e,file,percentage){var tableRow=this.getFileRow(file);var msg=this.fileUpload.options.fileLoading+" ("+percentage+"%)";var bar=this.getFileRow(file,".progress .progress-bar").text(msg);if(bar.width()<120)bar.width(120)},handleFileStart:function(e,file){var tableRow=this.getFileRow(file);var selector=".submit, .retry";if(e.type!=="FileUpload_filebeforestart")selector+=", .cancel";else tableRow.find(".cancel").removeClass("disabled");var buttons=tableRow.find(selector);setTimeout(function(){buttons.addClass("disabled")},0);tableRow.find(".remove").hide();tableRow.find(".cancel").show();this.appendLoadingIfNotPresent(file);tableRow.find(".progress-bar").removeClass("progress-bar-success progress-bar-danger").addClass("active");tableRow.addClass("is-loading")},handleFileComplete:function(e,file,success,isError){var tableRow=this.getFileRow(file);var failure=isError||!success,bar=tableRow.find(".progress .progress-bar");if(failure){tableRow.find(".retry").button("reset").removeClass("disabled").show();tableRow.find(".submit").button("reset").hide()}else bar.text(this.fileUpload.options.fileComplete);tableRow.find(".cancel").hide();tableRow.find(".remove").show();tableRow.find(".progress-bar").addClass(!failure?"progress-bar-success":"progress-bar-danger").removeClass("active");tableRow.find(".ajax-loading").remove();tableRow.removeClass("is-loading error").addClass("complete")},handleFileSizeError:function(e,info){$("<div />").addClass("alert alert-error").text(info.name+" "+this.fileUpload.options.fileSize).prepend($('<button type="button" class="close" data-dismiss="alert">×</button>')).prependTo(this.fileUpload.element)},appendLoadingIfNotPresent:function(file){var tableRow=this.getFileRow(file);var loader=$("<img />").addClass("ajax-loading").attr("src",this.fileUpload.options.ajaxLoader);if(tableRow.find(".ajax-loading").size()===0)tableRow.find("td:last").append(loader)}})})(jQuery,"undefined",FileUpload_Debug);(function($,undef){"use strict";var default_options={layout:"Simple"};$.fn.extend({fileupload:function(options){var args=Array.prototype.slice.call(arguments);return $.each(this,function(){var element=$(this),instance=element.data("fileupload");if(instance){if(typeof options==="string"&&$.isFunction(instance[options])){instance[options].apply(instance,args.slice(1));if(options==="destroy")element.removeData("fileupload")}}else element.data("fileupload",new FileUpload(this,$.extend({},default_options,options||{})))})}})})(jQuery,"undefined");(function($){$.timeago=function(timestamp){if(timestamp instanceof Date)return inWords(timestamp);else if(typeof timestamp=="string")return inWords($.timeago.parse(timestamp));else return inWords($.timeago.datetime(timestamp))};var $t=$.timeago;$.extend($.timeago,{settings:{refreshMillis:6e4,allowFuture:false,strings:{prefixAgo:null,prefixFromNow:null,suffixAgo:"ago",suffixFromNow:"from now",seconds:"less than a minute",minute:"about a minute",minutes:"%d minutes",hour:"about an hour",hours:"about %d hours",day:"a day",days:"%d days",month:"about a month",months:"%d months",year:"about a year",years:"%d years",numbers:[]}},inWords:function(distanceMillis){var $l=this.settings.strings;var prefix=$l.prefixAgo;var suffix=$l.suffixAgo;if(this.settings.allowFuture){if(distanceMillis<0){prefix=$l.prefixFromNow;
    2 suffix=$l.suffixFromNow}distanceMillis=Math.abs(distanceMillis)}var seconds=distanceMillis/1e3;var minutes=seconds/60;var hours=minutes/60;var days=hours/24;var years=days/365;function substitute(stringOrFunction,number){var string=$.isFunction(stringOrFunction)?stringOrFunction(number,distanceMillis):stringOrFunction;var value=$l.numbers&&$l.numbers[number]||number;return string.replace(/%d/i,value)}var words=seconds<45&&substitute($l.seconds,Math.round(seconds))||seconds<90&&substitute($l.minute,1)||minutes<45&&substitute($l.minutes,Math.round(minutes))||minutes<90&&substitute($l.hour,1)||hours<24&&substitute($l.hours,Math.round(hours))||hours<48&&substitute($l.day,1)||days<30&&substitute($l.days,Math.floor(days))||days<60&&substitute($l.month,1)||days<365&&substitute($l.months,Math.floor(days/30))||years<2&&substitute($l.year,1)||substitute($l.years,Math.floor(years));return $.trim([prefix,words,suffix].join(" "))},parse:function(iso8601){var s=$.trim(iso8601);s=s.replace(/\.\d\d\d+/,"");s=s.replace(/-/,"/").replace(/-/,"/");s=s.replace(/T/," ").replace(/Z/," UTC");s=s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2");return new Date(s)},datetime:function(elem){var isTime=$(elem).get(0).tagName.toLowerCase()=="time";var iso8601=isTime?$(elem).attr("datetime"):$(elem).attr("title");return $t.parse(iso8601)}});$.fn.timeago=function(){var self=this;self.each(refresh);var $s=$t.settings;if($s.refreshMillis>0){setInterval(function(){self.each(refresh)},$s.refreshMillis)}return self};function refresh(){var data=prepareData(this);if(!isNaN(data.datetime)){$(this).text(inWords(data.datetime))}return this}function prepareData(element){element=$(element);if(!element.data("timeago")){element.data("timeago",{datetime:$t.datetime(element)});var text=$.trim(element.text());if(text.length>0)element.attr("title",text)}return element.data("timeago")}function inWords(date){return $t.inWords(distance(date))}function distance(date){return(new Date).getTime()-date.getTime()}document.createElement("abbr");document.createElement("time")})(jQuery);(function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,s){var n,a,o,r=t.nodeName.toLowerCase();return"area"===r?(n=t.parentNode,a=n.name,t.href&&a&&"map"===n.nodeName.toLowerCase()?(o=e("img[usemap='#"+a+"']")[0],!!o&&i(o)):!1):(/^(input|select|textarea|button|object)$/.test(r)?!t.disabled:"a"===r?t.href||s:s)&&i(t)}function i(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(t){var i=this.css("position"),s="absolute"===i,n=t?/(auto|scroll|hidden)/:/(auto|scroll)/,a=this.parents().filter(function(){var t=e(this);return s&&"static"===t.css("position")?!1:n.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==i&&a.length?a:e(this[0].ownerDocument||document)},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(i){return t(i,!isNaN(e.attr(i,"tabindex")))},tabbable:function(i){var s=e.attr(i,"tabindex"),n=isNaN(s);return(n||s>=0)&&t(i,!n)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,i){function s(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],a=i.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+i]=function(t){return void 0===t?o["inner"+i].call(this):this.each(function(){e(this).css(a,s(this,t)+"px")})},e.fn["outer"+i]=function(t,n){return"number"!=typeof t?o["outer"+i].call(this,t):this.each(function(){e(this).css(a,s(this,t,!0,n)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(void 0!==t)return this.css("zIndex",t);if(this.length)for(var i,s,n=e(this[0]);n.length&&n[0]!==document;){if(i=n.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(n.css("zIndex"),10),!isNaN(s)&&0!==s))return s;n=n.parent()}return 0}}),e.ui.plugin={add:function(t,i,s){var n,a=e.ui[t].prototype;for(n in s)a.plugins[n]=a.plugins[n]||[],a.plugins[n].push([i,s[n]])},call:function(e,t,i,s){var n,a=e.plugins[t];if(a&&(s||e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType))for(n=0;a.length>n;n++)e.options[a[n][0]]&&a[n][1].apply(e.element,i)}};var s=0,n=Array.prototype.slice;e.cleanData=function(t){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=e._data(n,"events"),s&&s.remove&&e(n).triggerHandler("remove")}catch(o){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var n,a,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],n=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[l]=e[l]||{},a=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,a,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},n=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,a=this._superApply;return this._super=e,this._superApply=n,t=s.apply(this,arguments),this._super=i,this._superApply=a,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:a?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:n}),a?(e.each(a._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete a._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var i,s,a=n.call(arguments,1),o=0,r=a.length;r>o;o++)for(i in a[o])s=a[o][i],a[o].hasOwnProperty(i)&&void 0!==s&&(t[i]=e.isPlainObject(s)?e.isPlainObject(t[i])?e.widget.extend({},t[i],s):e.widget.extend({},s):s);return t},e.widget.bridge=function(t,i){var s=i.prototype.widgetFullName||t;e.fn[t]=function(a){var o="string"==typeof a,r=n.call(arguments,1),h=this;return o?this.each(function(){var i,n=e.data(this,s);return"instance"===a?(h=n,!1):n?e.isFunction(n[a])&&"_"!==a.charAt(0)?(i=n[a].apply(n,r),i!==n&&void 0!==i?(h=i&&i.jquery?h.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+a+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+a+"'")}):(r.length&&(a=e.widget.extend.apply(null,[a].concat(r))),this.each(function(){var t=e.data(this,s);t?(t.option(a||{}),t._init&&t._init()):e.data(this,s,new i(a,this))})),h}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,i){i=e(i||this.defaultElement||this)[0],this.element=e(i),this.uuid=s++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),i!==this&&(e.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===i&&this.destroy()}}),this.document=e(i.style?i.ownerDocument:i.document||i),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(t,i){var s,n,a,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(n=o[t]=e.widget.extend({},this.options[t]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(t=s.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var n,a=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=n=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),e.each(s,function(s,o){function r(){return t||a.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.delegate(u,l,r):i.bind(l,r)})},_off:function(t,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(i).undelegate(i),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var o,r=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),o=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&e.effects&&e.effects.effect[r]?s[t](n):r!==t&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}}),e.widget,function(){function t(e,t,i){return[parseFloat(e[0])*(p.test(e[0])?t/100:1),parseFloat(e[1])*(p.test(e[1])?i/100:1)]}function i(t,i){return parseInt(e.css(t,i),10)||0}function s(t){var i=t[0];return 9===i.nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(i)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var n,a,o=Math.max,r=Math.abs,h=Math.round,l=/left|center|right/,u=/top|center|bottom/,d=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,p=/%$/,f=e.fn.position;e.position={scrollbarWidth:function(){if(void 0!==n)return n;var t,i,s=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),a=s.children()[0];return e("body").append(s),t=a.offsetWidth,s.css("overflow","scroll"),i=a.offsetWidth,t===i&&(i=s[0].clientWidth),s.remove(),n=t-i},getScrollInfo:function(t){var i=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),s=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),n="scroll"===i||"auto"===i&&t.width<t.element[0].scrollWidth,a="scroll"===s||"auto"===s&&t.height<t.element[0].scrollHeight;return{width:a?e.position.scrollbarWidth():0,height:n?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var i=e(t||window),s=e.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s||n?i.width():i.outerWidth(),height:s||n?i.height():i.outerHeight()}}},e.fn.position=function(n){if(!n||!n.of)return f.apply(this,arguments);n=e.extend({},n);var p,m,g,v,y,b,_=e(n.of),x=e.position.getWithinInfo(n.within),w=e.position.getScrollInfo(x),k=(n.collision||"flip").split(" "),T={};return b=s(_),_[0].preventDefault&&(n.at="left top"),m=b.width,g=b.height,v=b.offset,y=e.extend({},v),e.each(["my","at"],function(){var e,t,i=(n[this]||"").split(" ");1===i.length&&(i=l.test(i[0])?i.concat(["center"]):u.test(i[0])?["center"].concat(i):["center","center"]),i[0]=l.test(i[0])?i[0]:"center",i[1]=u.test(i[1])?i[1]:"center",e=d.exec(i[0]),t=d.exec(i[1]),T[this]=[e?e[0]:0,t?t[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===k.length&&(k[1]=k[0]),"right"===n.at[0]?y.left+=m:"center"===n.at[0]&&(y.left+=m/2),"bottom"===n.at[1]?y.top+=g:"center"===n.at[1]&&(y.top+=g/2),p=t(T.at,m,g),y.left+=p[0],y.top+=p[1],this.each(function(){var s,l,u=e(this),d=u.outerWidth(),c=u.outerHeight(),f=i(this,"marginLeft"),b=i(this,"marginTop"),D=d+f+i(this,"marginRight")+w.width,S=c+b+i(this,"marginBottom")+w.height,N=e.extend({},y),M=t(T.my,u.outerWidth(),u.outerHeight());"right"===n.my[0]?N.left-=d:"center"===n.my[0]&&(N.left-=d/2),"bottom"===n.my[1]?N.top-=c:"center"===n.my[1]&&(N.top-=c/2),N.left+=M[0],N.top+=M[1],a||(N.left=h(N.left),N.top=h(N.top)),s={marginLeft:f,marginTop:b},e.each(["left","top"],function(t,i){e.ui.position[k[t]]&&e.ui.position[k[t]][i](N,{targetWidth:m,targetHeight:g,elemWidth:d,elemHeight:c,collisionPosition:s,collisionWidth:D,collisionHeight:S,offset:[p[0]+M[0],p[1]+M[1]],my:n.my,at:n.at,within:x,elem:u})}),n.using&&(l=function(e){var t=v.left-N.left,i=t+m-d,s=v.top-N.top,a=s+g-c,h={target:{element:_,left:v.left,top:v.top,width:m,height:g},element:{element:u,left:N.left,top:N.top,width:d,height:c},horizontal:0>i?"left":t>0?"right":"center",vertical:0>a?"top":s>0?"bottom":"middle"};d>m&&m>r(t+i)&&(h.horizontal="center"),c>g&&g>r(s+a)&&(h.vertical="middle"),h.important=o(r(t),r(i))>o(r(s),r(a))?"horizontal":"vertical",n.using.call(this,e,h)}),u.offset(e.extend(N,{using:l}))})},e.ui.position={fit:{left:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=e.left-t.collisionPosition.marginLeft,h=n-r,l=r+t.collisionWidth-a-n;t.collisionWidth>a?h>0&&0>=l?(i=e.left+h+t.collisionWidth-a-n,e.left+=h-i):e.left=l>0&&0>=h?n:h>l?n+a-t.collisionWidth:n:h>0?e.left+=h:l>0?e.left-=l:e.left=o(e.left-r,e.left)},top:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollTop:s.offset.top,a=t.within.height,r=e.top-t.collisionPosition.marginTop,h=n-r,l=r+t.collisionHeight-a-n;t.collisionHeight>a?h>0&&0>=l?(i=e.top+h+t.collisionHeight-a-n,e.top+=h-i):e.top=l>0&&0>=h?n:h>l?n+a-t.collisionHeight:n:h>0?e.top+=h:l>0?e.top-=l:e.top=o(e.top-r,e.top)}},flip:{left:function(e,t){var i,s,n=t.within,a=n.offset.left+n.scrollLeft,o=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=e.left-t.collisionPosition.marginLeft,u=l-h,d=l+t.collisionWidth-o-h,c="left"===t.my[0]?-t.elemWidth:"right"===t.my[0]?t.elemWidth:0,p="left"===t.at[0]?t.targetWidth:"right"===t.at[0]?-t.targetWidth:0,f=-2*t.offset[0];0>u?(i=e.left+c+p+f+t.collisionWidth-o-a,(0>i||r(u)>i)&&(e.left+=c+p+f)):d>0&&(s=e.left-t.collisionPosition.marginLeft+c+p+f-h,(s>0||d>r(s))&&(e.left+=c+p+f))},top:function(e,t){var i,s,n=t.within,a=n.offset.top+n.scrollTop,o=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=e.top-t.collisionPosition.marginTop,u=l-h,d=l+t.collisionHeight-o-h,c="top"===t.my[1],p=c?-t.elemHeight:"bottom"===t.my[1]?t.elemHeight:0,f="top"===t.at[1]?t.targetHeight:"bottom"===t.at[1]?-t.targetHeight:0,m=-2*t.offset[1];0>u?(s=e.top+p+f+m+t.collisionHeight-o-a,(0>s||r(u)>s)&&(e.top+=p+f+m)):d>0&&(i=e.top-t.collisionPosition.marginTop+p+f+m-h,(i>0||d>r(i))&&(e.top+=p+f+m))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,i,s,n,o,r=document.getElementsByTagName("body")[0],h=document.createElement("div");t=document.createElement(r?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},r&&e.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in s)t.style[o]=s[o];t.appendChild(h),i=r||document.documentElement,i.insertBefore(t,i.firstChild),h.style.cssText="position: absolute; left: 10.7432222px;",n=e(h).offset().left,a=n>10&&11>n,t.innerHTML="",i.removeChild(t)}()}(),e.ui.position,e.widget("ui.menu",{version:"1.11.4",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},items:"> *",menus:"ul",position:{my:"left-1 top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item":function(e){e.preventDefault()},"click .ui-menu-item":function(t){var i=e(t.target);!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&e(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){if(!this.previousFilter){var i=e(t.currentTarget);i.siblings(".ui-state-active").removeClass("ui-state-active"),this.focus(t,i)}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var i=this.active||this.element.find(this.options.items).eq(0);t||this.focus(e,i)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){this._closeOnDocumentClick(e)&&this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-menu-icons ui-front").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").removeUniqueId().removeClass("ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){var i,s,n,a,o=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:o=!1,s=this.previousFilter||"",n=String.fromCharCode(t.keyCode),a=!1,clearTimeout(this.filterTimer),n===s?a=!0:n=s+n,i=this._filterMenuItems(n),i=a&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(t.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(t,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}o&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.is("[aria-haspopup='true']")?this.expand(e):this.select(e))},refresh:function(){var t,i,s=this,n=this.options.icons.submenu,a=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),a.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-front").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=e(this),i=t.parent(),s=e("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);i.attr("aria-haspopup","true").prepend(s),t.attr("aria-labelledby",i.attr("id"))}),t=a.add(this.element),i=t.find(this.options.items),i.not(".ui-menu-item").each(function(){var t=e(this);s._isDivider(t)&&t.addClass("ui-widget-content ui-menu-divider")}),i.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(e,t){"icons"===e&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu),"disabled"===e&&this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this._super(e,t)},focus:function(e,t){var i,s;this.blur(e,e&&"focus"===e.type),this._scrollIntoView(t),this.active=t.first(),s=this.active.addClass("ui-state-focus").removeClass("ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"),e&&"keydown"===e.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=t.children(".ui-menu"),i.length&&e&&/^mouse/.test(e.type)&&this._startOpening(i),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,n=t.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=t.outerHeight(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(e,t){t||clearTimeout(this.timer),this.active&&(this.active.removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active}))},_startOpening:function(e){clearTimeout(this.timer),"true"===e.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(e)},this.delay))},_open:function(t){var i=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(t,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(t),this.activeMenu=s},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find(".ui-state-active").not(".ui-state-focus").removeClass("ui-state-active")},_closeOnDocumentClick:function(t){return!e(t.target).closest(".ui-menu").length},_isDivider:function(e){return!/[^\-\u2014\u2013\s]/.test(e.text())},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,i){var s;this.active&&(s="first"===e||"last"===e?this.active["first"===e?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[e+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[t]()),this.focus(i,s)},nextPage:function(t){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=e(this),0>i.offset().top-s-n}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(t),void 0)},previousPage:function(t){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=e(this),i.offset().top-s+n>0}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items).first())),void 0):(this.next(t),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,i)},_filterMenuItems:function(t){var i=t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(e.trim(e(this).text()))})}}),e.widget("ui.autocomplete",{version:"1.11.4",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var t,i,s,n=this.element[0].nodeName.toLowerCase(),a="textarea"===n,o="input"===n;this.isMultiLine=a?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[a||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return t=!0,s=!0,i=!0,void 0;t=!1,s=!1,i=!1;var a=e.ui.keyCode;switch(n.keyCode){case a.PAGE_UP:t=!0,this._move("previousPage",n);break;case a.PAGE_DOWN:t=!0,this._move("nextPage",n);break;case a.UP:t=!0,this._keyEvent("previous",n);break;case a.DOWN:t=!0,this._keyEvent("next",n);break;case a.ENTER:this.menu.active&&(t=!0,n.preventDefault(),this.menu.select(n));break;case a.TAB:this.menu.active&&this.menu.select(n);break;case a.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(t)return t=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=e.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(e){return s?(s=!1,e.preventDefault(),void 0):(this._searchTimeout(e),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(e),this._change(e),void 0)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(s){s.target===t.element[0]||s.target===i||e.contains(i,s.target)||t.close()})})},menufocus:function(t,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",t,{item:n})&&t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&e.trim(s).length&&(this.liveRegion.children().hide(),e("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,t){var i=t.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",e,{item:i})&&this._value(i.value),this.term=this._value(),this.close(e),this.selectedItem=i}}),this.liveRegion=e("<span>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),"source"===e&&this._initSource(),"appendTo"===e&&this.menu.element.appendTo(this._appendTo()),"disabled"===e&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t&&t[0]||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_initSource:function(){var t,i,s=this;
    3 e.isArray(this.options.source)?(t=this.options.source,this.source=function(i,s){s(e.ui.autocomplete.filter(t,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(t,n){s.xhr&&s.xhr.abort(),s.xhr=e.ajax({url:i,data:t,dataType:"json",success:function(e){n(e)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){var t=this.term===this._value(),i=this.menu.element.is(":visible"),s=e.altKey||e.ctrlKey||e.metaKey||e.shiftKey;(!t||t&&!i&&!s)&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){return e=null!=e?e:this._value(),this.term=this._value(),e.length<this.options.minLength?this.close(t):this._trigger("search",t)!==!1?this._search(e):void 0},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var t=++this.requestIndex;return e.proxy(function(e){t===this.requestIndex&&this.__response(e),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return"string"==typeof t?{label:t,value:t}:e.extend({},t,{label:t.label||t.value,value:t.value||t.label})})},_suggest:function(t){var i=this.menu.element.empty();this._renderMenu(i,t),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,i){var s=this;e.each(i,function(e,i){s._renderItemData(t,i)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,i){return e("<li>").text(i.label).appendTo(t)},_move:function(e,t){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[e](t),void 0):(this.search(null,t),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(e,t),t.preventDefault())}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,i){var s=RegExp(e.ui.autocomplete.escapeRegex(i),"i");return e.grep(t,function(e){return s.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(t){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=t&&t.length?this.options.messages.results(t.length):this.options.messages.noResults,this.liveRegion.children().hide(),e("<div>").text(i).appendTo(this.liveRegion))}}),e.ui.autocomplete});(function($){$.timeago.regional={};$.timeago.regional["es"]={prefixAgo:"hace",prefixFromNow:"dentro de",suffixAgo:"",suffixFromNow:"",seconds:"menos de un minuto",minute:"un minuto",minutes:"unos %d minutos",hour:"una hora",hours:"%d horas",day:"un día",days:"%d días",month:"un mes",months:"%d meses",year:"un año",years:"%d años"};$.timeago.regional["fr"]={prefixAgo:"il y a",prefixFromNow:"d'ici",seconds:"moins d'une minute",minute:"environ une minute",minutes:"environ %d minutes",hour:"environ une heure",hours:"environ %d heures",day:"environ un jour",days:"environ %d jours",month:"environ un mois",months:"environ %d mois",year:"un an",years:"%d ans"};$.timeago.regional["pt"]={suffixAgo:"atrás",suffixFromNow:"a partir de agora",seconds:"menos de um minuto",minute:"cerca de um minuto",minutes:"%d minutos",hour:"cerca de uma hora",hours:"cerca de %d horas",day:"um dia",days:"%d dias",month:"cerca de um mês",months:"%d meses",year:"cerca de um ano",years:"%d anos"};$.timeago.regional["sv"]={prefixAgo:"för",prefixFromNow:"om",suffixAgo:"sedan",suffixFromNow:"",seconds:"mindre än en minut",minute:"ungefär en minut",minutes:"%d minuter",hour:"ungefär en timme",hours:"ungefär %d timmar",day:"en dag",days:"%d dagar",month:"ungefär en månad",months:"%d månader",year:"ungefär ett år",years:"%d år"};$.timeago.regional["zh"]={prefixAgo:null,prefixFromNow:"从现在开始",suffixAgo:"之前",suffixFromNow:null,seconds:"不到 1 分钟",minute:"大约 1 分钟",minutes:"%d 分钟",hour:"大约 1 小时",hours:"大约 %d 小时",day:"1 天",days:"%d 天",month:"大约 1 个月",months:"%d 月",year:"大约 1 年",years:"%d 年",numbers:[]};$.timeago.regional["ja"]={prefixAgo:"",prefixFromNow:"今から",suffixAgo:"前",suffixFromNow:"後",seconds:"ほんの数秒",minute:"約一分",minutes:"%d 分",hour:"大体一時間",hours:"大体 %d 時間位",day:"一日",days:"%d 日ほど",month:"大体一ヶ月",months:"%d ヶ月ほど",year:"丁度一年(虎舞流w)",years:"%d 年"};function numpf(n,f,s,t){var n10=n%10;if(n10==1&&(n==1||n>20)){return f}else if(n10>1&&n10<5&&(n>20||n<10)){return s}else{return t}}$.timeago.regional["ru"]={prefixAgo:null,prefixFromNow:"через",suffixAgo:"назад",suffixFromNow:null,seconds:"меньше минуты",minute:"минуту",minutes:function(value){return numpf(value,"%d минута","%d минуты","%d минут")},hour:"час",hours:function(value){return numpf(value,"%d час","%d часа","%d часов")},day:"день",days:function(value){return numpf(value,"%d день","%d дня","%d дней")},month:"месяц",months:function(value){return numpf(value,"%d месяц","%d месяца","%d месяцев")},year:"год",years:function(value){return numpf(value,"%d год","%d года","%d лет")}};$.timeago.regional["tr"]={suffixAgo:"önce",suffixFromNow:null,seconds:"1 dakikadan",minute:"1 dakika",minutes:"%d dakika",hour:"1 saat",hours:"%d saat",day:"1 gün",days:"%d gün",month:"1 ay",months:"%d ay",year:"1 yıl",years:"%d yıl"};$.timeago.regional["ca"]={prefixAgo:"fa",prefixFromNow:"d'aqui a",suffixAgo:null,suffixFromNow:null,seconds:"menys d'un minut",minute:"un minut",minutes:"uns %d minuts",hour:"una hora",hours:"unes %d hores",day:"1 dia",days:"%d dies",month:"aproximadament un mes",months:"%d mesos",year:"aproximadament un any",years:"%d anys"};$.timeago.regional["de"]={prefixAgo:"vor",prefixFromNow:"in",suffixAgo:"",suffixFromNow:"",seconds:"wenigen Sekunden",minute:"etwa einer Minute",minutes:"%d Minuten",hour:"etwa einer Stunde",hours:"%d Stunden",day:"etwa einem Tag",days:"%d Tagen",month:"etwa einem Monat",months:"%d Monaten",year:"etwa einem Jahr",years:"%d Jahren"}})(jQuery);(function(c){function p(){var d,a={height:h.innerHeight,width:h.innerWidth};if(!a.height&&((d=i.compatMode)||!c.support.boxModel))d=d==="CSS1Compat"?k:i.body,a={height:d.clientHeight,width:d.clientWidth};return a}var m={},e,a,i=document,h=window,k=i.documentElement,j=c.expando;c.event.special.inview={add:function(a){m[a.guid+"-"+this[j]]={data:a,$element:c(this)}},remove:function(a){try{delete m[a.guid+"-"+this[j]]}catch(c){}}};c(h).bind("scroll resize",function(){e=a=null});setInterval(function(){var d=c(),j,l=0;c.each(m,function(a,b){var c=b.data.selector,e=b.$element;d=d.add(c?e.find(c):e)});if(j=d.length){e=e||p();for(a=a||{top:h.pageYOffset||k.scrollTop||i.body.scrollTop,left:h.pageXOffset||k.scrollLeft||i.body.scrollLeft};l<j;l++)if(c.contains(k,d[l])){var g=c(d[l]),f={height:g.height(),width:g.width()},b=g.offset(),n=g.data("inview"),o;if(!a||!e)break;b.top+f.height>a.top&&b.top<a.top+e.height&&b.left+f.width>a.left&&b.left<a.left+e.width?(o=a.left>b.left?"right":a.left+e.width<b.left+f.width?"left":"both",f=a.top>b.top?"bottom":a.top+e.height<b.top+f.height?"top":"both",b=o+"-"+f,(!n||n!==b)&&g.data("inview",b).trigger("inview",[!0,o,f])):n&&g.data("inview",!1).trigger("inview",[!1])}}},250)})(jQuery);(function($){var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a256="",r64=[256],r256=[256],i=0;var UTF8={encode:function(strUni){var strUtf=strUni.replace(/[\u0080-\u07ff]/g,function(c){var cc=c.charCodeAt(0);return String.fromCharCode(192|cc>>6,128|cc&63)}).replace(/[\u0800-\uffff]/g,function(c){var cc=c.charCodeAt(0);return String.fromCharCode(224|cc>>12,128|cc>>6&63,128|cc&63)});return strUtf},decode:function(strUtf){var strUni=strUtf.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g,function(c){var cc=(c.charCodeAt(0)&15)<<12|(c.charCodeAt(1)&63)<<6|c.charCodeAt(2)&63;return String.fromCharCode(cc)}).replace(/[\u00c0-\u00df][\u0080-\u00bf]/g,function(c){var cc=(c.charCodeAt(0)&31)<<6|c.charCodeAt(1)&63;return String.fromCharCode(cc)});return strUni}};while(i<256){var c=String.fromCharCode(i);a256+=c;r256[i]=i;r64[i]=b64.indexOf(c);++i}function code(s,discard,alpha,beta,w1,w2){s=String(s);var buffer=0,i=0,length=s.length,result="",bitsInBuffer=0;while(i<length){var c=s.charCodeAt(i);c=c<256?alpha[c]:-1;buffer=(buffer<<w1)+c;bitsInBuffer+=w1;while(bitsInBuffer>=w2){bitsInBuffer-=w2;var tmp=buffer>>bitsInBuffer;result+=beta.charAt(tmp);buffer^=tmp<<bitsInBuffer}++i}if(!discard&&bitsInBuffer>0)result+=beta.charAt(buffer<<w2-bitsInBuffer);return result}var Plugin=$.base64=function(dir,input,encode){return input?Plugin[dir](input,encode):dir?null:this};Plugin.btoa=Plugin.encode=function(plain,utf8encode){plain=Plugin.raw===false||Plugin.utf8encode||utf8encode?UTF8.encode(plain):plain;plain=code(plain,false,r256,b64,8,6);return plain+"====".slice(plain.length%4||4)};Plugin.atob=Plugin.decode=function(coded,utf8decode){coded=String(coded).split("=");var i=coded.length;do{--i;coded[i]=code(coded[i],true,r64,a256,6,8)}while(i>0);coded=coded.join("");return Plugin.raw===false||Plugin.utf8decode||utf8decode?UTF8.decode(coded):coded}})(jQuery);+function($){"use strict";var Modal=function(element,options){this.options=options;this.$body=$(document.body);this.$element=$(element);this.$backdrop=this.isShown=null;this.scrollbarWidth=0;if(this.options.remote){this.$element.find("#clinked-portal .modal-content").load(this.options.remote,$.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))}};Modal.VERSION="3.3.2";Modal.TRANSITION_DURATION=300;Modal.BACKDROP_TRANSITION_DURATION=150;Modal.DEFAULTS={backdrop:true,keyboard:true,show:true};Modal.prototype.toggle=function(_relatedTarget){return this.isShown?this.hide():this.show(_relatedTarget)};Modal.prototype.show=function(_relatedTarget){var that=this;var e=$.Event("show.bs.modal",{relatedTarget:_relatedTarget});this.$element.trigger(e);if(this.isShown||e.isDefaultPrevented())return;this.isShown=true;this.checkScrollbar();this.setScrollbar();this.$body.addClass("modal-open");this.escape();this.resize();this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',$.proxy(this.hide,this));this.backdrop(function(){var transition=$.support.transition&&that.$element.hasClass("fade");if(!that.$element.parent().length){that.$element.appendTo(that.$body)}that.$element.show().scrollTop(0);if(that.options.backdrop)that.adjustBackdrop();that.adjustDialog();if(transition){that.$element[0].offsetWidth}that.$element.addClass("in").attr("aria-hidden",false);that.enforceFocus();var e=$.Event("shown.bs.modal",{relatedTarget:_relatedTarget});transition?that.$element.find("#clinked-portal .modal-dialog").one("bsTransitionEnd",function(){that.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(Modal.TRANSITION_DURATION):that.$element.trigger("focus").trigger(e)})};Modal.prototype.hide=function(e){if(e)e.preventDefault();e=$.Event("hide.bs.modal");this.$element.trigger(e);if(!this.isShown||e.isDefaultPrevented())return;this.isShown=false;this.escape();this.resize();$(document).off("focusin.bs.modal");this.$element.removeClass("in").attr("aria-hidden",true).off("click.dismiss.bs.modal");$.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",$.proxy(this.hideModal,this)).emulateTransitionEnd(Modal.TRANSITION_DURATION):this.hideModal()};Modal.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){if(this.$element[0]!==e.target&&!this.$element.has(e.target).length){this.$element.trigger("focus")}},this))};Modal.prototype.escape=function(){if(this.isShown&&this.options.keyboard){this.$element.on("keydown.dismiss.bs.modal",$.proxy(function(e){e.which==27&&this.hide()},this))}else if(!this.isShown){this.$element.off("keydown.dismiss.bs.modal")}};Modal.prototype.resize=function(){if(this.isShown){$(window).on("resize.bs.modal",$.proxy(this.handleUpdate,this))}else{$(window).off("resize.bs.modal")}};Modal.prototype.hideModal=function(){var that=this;this.$element.hide();this.backdrop(function(){that.$body.removeClass("modal-open");that.resetAdjustments();that.resetScrollbar();that.$element.trigger("hidden.bs.modal")})};Modal.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove();this.$backdrop=null};Modal.prototype.backdrop=function(callback){var that=this;var animate=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var doAnimate=$.support.transition&&animate;this.$backdrop=$('<div class="modal-backdrop '+animate+'" />').prependTo(this.$element).on("click.dismiss.bs.modal",$.proxy(function(e){if(e.target!==e.currentTarget)return;this.options.backdrop=="static"?this.$element[0].focus.call(this.$element[0]):this.hide.call(this)},this));if(doAnimate)this.$backdrop[0].offsetWidth;this.$backdrop.addClass("in");if(!callback)return;doAnimate?this.$backdrop.one("bsTransitionEnd",callback).emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION):callback()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var callbackRemove=function(){that.removeBackdrop();callback&&callback()};$.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",callbackRemove).emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION):callbackRemove()}else if(callback){callback()}};Modal.prototype.handleUpdate=function(){if(this.options.backdrop)this.adjustBackdrop();this.adjustDialog()};Modal.prototype.adjustBackdrop=function(){this.$backdrop.css("height",0).css("height",this.$element[0].scrollHeight)};Modal.prototype.adjustDialog=function(){var modalIsOverflowing=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&modalIsOverflowing?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!modalIsOverflowing?this.scrollbarWidth:""})};Modal.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})};Modal.prototype.checkScrollbar=function(){this.bodyIsOverflowing=document.body.scrollHeight>document.documentElement.clientHeight;this.scrollbarWidth=this.measureScrollbar()};Modal.prototype.setScrollbar=function(){var bodyPad=parseInt(this.$body.css("padding-right")||0,10);if(this.bodyIsOverflowing)this.$body.css("padding-right",bodyPad+this.scrollbarWidth)};Modal.prototype.resetScrollbar=function(){this.$body.css("padding-right","")};Modal.prototype.measureScrollbar=function(){var scrollDiv=document.createElement("div");scrollDiv.className="modal-scrollbar-measure";this.$body.append(scrollDiv);var scrollbarWidth=scrollDiv.offsetWidth-scrollDiv.clientWidth;this.$body[0].removeChild(scrollDiv);return scrollbarWidth};function Plugin(option,_relatedTarget){return this.each(function(){var $this=$(this);var data=$this.data("bs.modal");var options=$.extend({},Modal.DEFAULTS,$this.data(),typeof option=="object"&&option);if(!data)$this.data("bs.modal",data=new Modal(this,options));if(typeof option=="string")data[option](_relatedTarget);else if(options.show)data.show(_relatedTarget)})}var old=$.fn.modal;$.fn.modal=Plugin;$.fn.modal.Constructor=Modal;$.fn.modal.noConflict=function(){$.fn.modal=old;return this};$(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(e){var $this=$(this);var href=$this.attr("href");var $target=$($this.attr("data-target")||href&&href.replace(/.*(?=#[^\s]+$)/,""));var option=$target.data("bs.modal")?"toggle":$.extend({remote:!/#/.test(href)&&href},$target.data(),$this.data());if($this.is("a"))e.preventDefault();$target.one("show.bs.modal",function(showEvent){if(showEvent.isDefaultPrevented())return;$target.one("hidden.bs.modal",function(){$this.is(":visible")&&$this.trigger("focus")})});Plugin.call($target,option,this)})}(jQuery);(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,w=Object.keys,_=i.bind,j=function(n){return n instanceof j?n:this instanceof j?void(this._wrapped=n):new j(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=j),exports._=j):n._=j,j.VERSION="1.6.0";var A=j.each=j.forEach=function(n,t,e){if(null==n)return n;if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a=j.keys(n),u=0,i=a.length;i>u;u++)if(t.call(e,n[a[u]],a[u],n)===r)return;return n};j.map=j.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e.push(t.call(r,n,u,i))}),e)};var O="Reduce of empty array with no initial value";j.reduce=j.foldl=j.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=j.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},j.reduceRight=j.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=j.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=j.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},j.find=j.detect=function(n,t,r){var e;return k(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},j.filter=j.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&e.push(n)}),e)},j.reject=function(n,t,r){return j.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},j.every=j.all=function(n,t,e){t||(t=j.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var k=j.some=j.any=function(n,t,e){t||(t=j.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};j.contains=j.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:k(n,function(n){return n===t})},j.invoke=function(n,t){var r=o.call(arguments,2),e=j.isFunction(t);return j.map(n,function(n){return(e?t:n[t]).apply(n,r)})},j.pluck=function(n,t){return j.map(n,j.property(t))},j.where=function(n,t){return j.filter(n,j.matches(t))},j.findWhere=function(n,t){return j.find(n,j.matches(t))},j.max=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.max.apply(Math,n);var e=-1/0,u=-1/0;return A(n,function(n,i,a){var o=t?t.call(r,n,i,a):n;o>u&&(e=n,u=o)}),e},j.min=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.min.apply(Math,n);var e=1/0,u=1/0;return A(n,function(n,i,a){var o=t?t.call(r,n,i,a):n;u>o&&(e=n,u=o)}),e},j.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=j.random(r++),e[r-1]=e[t],e[t]=n}),e},j.sample=function(n,t,r){return null==t||r?(n.length!==+n.length&&(n=j.values(n)),n[j.random(n.length-1)]):j.shuffle(n).slice(0,Math.max(0,t))};var E=function(n){return null==n?j.identity:j.isFunction(n)?n:j.property(n)};j.sortBy=function(n,t,r){return t=E(t),j.pluck(j.map(n,function(n,e,u){return{value:n,index:e,criteria:t.call(r,n,e,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=E(r),A(t,function(i,a){var o=r.call(e,i,a,t);n(u,o,i)}),u}};j.groupBy=F(function(n,t,r){j.has(n,t)?n[t].push(r):n[t]=[r]}),j.indexBy=F(function(n,t,r){n[t]=r}),j.countBy=F(function(n,t){j.has(n,t)?n[t]++:n[t]=1}),j.sortedIndex=function(n,t,r,e){r=E(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;r.call(e,n[o])<u?i=o+1:a=o}return i},j.toArray=function(n){return n?j.isArray(n)?o.call(n):n.length===+n.length?j.map(n,j.identity):j.values(n):[]},j.size=function(n){return null==n?0:n.length===+n.length?n.length:j.keys(n).length},j.first=j.head=j.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:0>t?[]:o.call(n,0,t)},j.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},j.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},j.rest=j.tail=j.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},j.compact=function(n){return j.filter(n,j.identity)};var M=function(n,t,r){return t&&j.every(n,j.isArray)?c.apply(r,n):(A(n,function(n){j.isArray(n)||j.isArguments(n)?t?a.apply(r,n):M(n,t,r):r.push(n)}),r)};j.flatten=function(n,t){return M(n,t,[])},j.without=function(n){return j.difference(n,o.call(arguments,1))},j.partition=function(n,t){var r=[],e=[];return A(n,function(n){(t(n)?r:e).push(n)}),[r,e]},j.uniq=j.unique=function(n,t,r,e){j.isFunction(t)&&(e=r,r=t,t=!1);var u=r?j.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:j.contains(a,r))||(a.push(r),i.push(n[e]))}),i},j.union=function(){return j.uniq(j.flatten(arguments,!0))},j.intersection=function(n){var t=o.call(arguments,1);return j.filter(j.uniq(n),function(n){return j.every(t,function(t){return j.contains(t,n)})})},j.difference=function(n){var t=c.apply(e,o.call(arguments,1));return j.filter(n,function(n){return!j.contains(t,n)})},j.zip=function(){for(var n=j.max(j.pluck(arguments,"length").concat(0)),t=new Array(n),r=0;n>r;r++)t[r]=j.pluck(arguments,""+r);return t},j.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},j.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=j.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},j.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},j.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=new Array(e);e>u;)i[u++]=n,n+=r;return i};var R=function(){};j.bind=function(n,t){var r,e;if(_&&n.bind===_)return _.apply(n,o.call(arguments,1));if(!j.isFunction(n))throw new TypeError;return r=o.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(o.call(arguments)));R.prototype=n.prototype;var u=new R;R.prototype=null;var i=n.apply(u,r.concat(o.call(arguments)));return Object(i)===i?i:u}},j.partial=function(n){var t=o.call(arguments,1);return function(){for(var r=0,e=t.slice(),u=0,i=e.length;i>u;u++)e[u]===j&&(e[u]=arguments[r++]);for(;r<arguments.length;)e.push(arguments[r++]);return n.apply(this,e)}},j.bindAll=function(n){var t=o.call(arguments,1);if(0===t.length)throw new Error("bindAll must be passed function names");return A(t,function(t){n[t]=j.bind(n[t],n)}),n},j.memoize=function(n,t){var r={};return t||(t=j.identity),function(){var e=t.apply(this,arguments);return j.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},j.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},j.defer=function(n){return j.delay.apply(j,[n,1].concat(o.call(arguments,1)))},j.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var c=function(){o=r.leading===!1?0:j.now(),a=null,i=n.apply(e,u),e=u=null};return function(){var l=j.now();o||r.leading!==!1||(o=l);var f=t-(l-o);return e=this,u=arguments,0>=f?(clearTimeout(a),a=null,o=l,i=n.apply(e,u),e=u=null):a||r.trailing===!1||(a=setTimeout(c,f)),i}},j.debounce=function(n,t,r){var e,u,i,a,o,c=function(){var l=j.now()-a;t>l?e=setTimeout(c,t-l):(e=null,r||(o=n.apply(i,u),i=u=null))};return function(){i=this,u=arguments,a=j.now();var l=r&&!e;return e||(e=setTimeout(c,t)),l&&(o=n.apply(i,u),i=u=null),o}},j.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},j.wrap=function(n,t){return j.partial(t,n)},j.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},j.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},j.keys=function(n){if(!j.isObject(n))return[];if(w)return w(n);var t=[];for(var r in n)j.has(n,r)&&t.push(r);return t},j.values=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},j.pairs=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},j.invert=function(n){for(var t={},r=j.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},j.functions=j.methods=function(n){var t=[];for(var r in n)j.isFunction(n[r])&&t.push(r);return t.sort()},j.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},j.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},j.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)j.contains(r,u)||(t[u]=n[u]);return t},j.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]===void 0&&(n[r]=t[r])}),n},j.clone=function(n){return j.isObject(n)?j.isArray(n)?n.slice():j.extend({},n):n},j.tap=function(n,t){return t(n),n};var S=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof j&&(n=n._wrapped),t instanceof j&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==String(t);case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;var a=n.constructor,o=t.constructor;if(a!==o&&!(j.isFunction(a)&&a instanceof a&&j.isFunction(o)&&o instanceof o)&&"constructor"in n&&"constructor"in t)return!1;r.push(n),e.push(t);var c=0,f=!0;if("[object Array]"==u){if(c=n.length,f=c==t.length)for(;c--&&(f=S(n[c],t[c],r,e)););}else{for(var s in n)if(j.has(n,s)&&(c++,!(f=j.has(t,s)&&S(n[s],t[s],r,e))))break;if(f){for(s in t)if(j.has(t,s)&&!c--)break;f=!c}}return r.pop(),e.pop(),f};j.isEqual=function(n,t){return S(n,t,[],[])},j.isEmpty=function(n){if(null==n)return!0;if(j.isArray(n)||j.isString(n))return 0===n.length;for(var t in n)if(j.has(n,t))return!1;return!0},j.isElement=function(n){return!(!n||1!==n.nodeType)},j.isArray=x||function(n){return"[object Array]"==l.call(n)},j.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){j["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),j.isArguments(arguments)||(j.isArguments=function(n){return!(!n||!j.has(n,"callee"))}),"function"!=typeof/./&&(j.isFunction=function(n){return"function"==typeof n}),j.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},j.isNaN=function(n){return j.isNumber(n)&&n!=+n},j.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},j.isNull=function(n){return null===n},j.isUndefined=function(n){return n===void 0},j.has=function(n,t){return f.call(n,t)},j.noConflict=function(){return n._=t,this},j.identity=function(n){return n},j.constant=function(n){return function(){return n}},j.property=function(n){return function(t){return t[n]}},j.matches=function(n){return function(t){if(t===n)return!0;for(var r in n)if(n[r]!==t[r])return!1;return!0}},j.times=function(n,t,r){for(var e=Array(Math.max(0,n)),u=0;n>u;u++)e[u]=t.call(r,u);return e},j.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},j.now=Date.now||function(){return(new Date).getTime()};var T={escape:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"}};T.unescape=j.invert(T.escape);var I={escape:new RegExp("["+j.keys(T.escape).join("")+"]","g"),unescape:new RegExp("("+j.keys(T.unescape).join("|")+")","g")};j.each(["escape","unescape"],function(n){j[n]=function(t){return null==t?"":(""+t).replace(I[n],function(t){return T[n][t]})}}),j.result=function(n,t){if(null==n)return void 0;var r=n[t];return j.isFunction(r)?r.call(n):r},j.mixin=function(n){A(j.functions(n),function(t){var r=j[t]=n[t];j.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),z.call(this,r.apply(j,n))}})};var N=0;j.uniqueId=function(n){var t=++N+"";return n?n+t:t},j.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var q=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\t|\u2028|\u2029/g;j.template=function(n,t,r){var e;r=j.defaults({},r,j.templateSettings);var u=new RegExp([(r.escape||q).source,(r.interpolate||q).source,(r.evaluate||q).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(D,function(n){return"\\"+B[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=new Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,j);var c=function(n){return e.call(this,n,j)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},j.chain=function(n){return j(n).chain()};var z=function(n){return this._chain?j(n).chain():n};j.mixin(j),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];j.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],z.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];j.prototype[n]=function(){return z.call(this,t.apply(this._wrapped,arguments))}}),j.extend(j.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}}),"function"==typeof define&&define.amd&&define("underscore",[],function(){return j})}).call(this);(function(root,factory){if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(_,$,exports){root.Backbone=factory(root,exports,_,$)})}else if(typeof exports!=="undefined"){var _=require("underscore");factory(root,exports,_)}else{root.Backbone=factory(root,{},root._,root.jQuery||root.Zepto||root.ender||root.$)}})(this,function(root,Backbone,_,$){var previousBackbone=root.Backbone;var array=[];var push=array.push;var slice=array.slice;var splice=array.splice;Backbone.VERSION="1.1.2";Backbone.$=$;Backbone.noConflict=function(){root.Backbone=previousBackbone;return this};
    4 Backbone.emulateHTTP=false;Backbone.emulateJSON=false;var Events=Backbone.Events={on:function(name,callback,context){if(!eventsApi(this,"on",name,[callback,context])||!callback)return this;this._events||(this._events={});var events=this._events[name]||(this._events[name]=[]);events.push({callback:callback,context:context,ctx:context||this});return this},once:function(name,callback,context){if(!eventsApi(this,"once",name,[callback,context])||!callback)return this;var self=this;var once=_.once(function(){self.off(name,once);callback.apply(this,arguments)});once._callback=callback;return this.on(name,once,context)},off:function(name,callback,context){var retain,ev,events,names,i,l,j,k;if(!this._events||!eventsApi(this,"off",name,[callback,context]))return this;if(!name&&!callback&&!context){this._events=void 0;return this}names=name?[name]:_.keys(this._events);for(i=0,l=names.length;i<l;i++){name=names[i];if(events=this._events[name]){this._events[name]=retain=[];if(callback||context){for(j=0,k=events.length;j<k;j++){ev=events[j];if(callback&&callback!==ev.callback&&callback!==ev.callback._callback||context&&context!==ev.context){retain.push(ev)}}}if(!retain.length)delete this._events[name]}}return this},trigger:function(name){if(!this._events)return this;var args=slice.call(arguments,1);if(!eventsApi(this,"trigger",name,args))return this;var events=this._events[name];var allEvents=this._events.all;if(events)triggerEvents(events,args);if(allEvents)triggerEvents(allEvents,arguments);return this},stopListening:function(obj,name,callback){var listeningTo=this._listeningTo;if(!listeningTo)return this;var remove=!name&&!callback;if(!callback&&typeof name==="object")callback=this;if(obj)(listeningTo={})[obj._listenId]=obj;for(var id in listeningTo){obj=listeningTo[id];obj.off(name,callback,this);if(remove||_.isEmpty(obj._events))delete this._listeningTo[id]}return this}};var eventSplitter=/\s+/;var eventsApi=function(obj,action,name,rest){if(!name)return true;if(typeof name==="object"){for(var key in name){obj[action].apply(obj,[key,name[key]].concat(rest))}return false}if(eventSplitter.test(name)){var names=name.split(eventSplitter);for(var i=0,l=names.length;i<l;i++){obj[action].apply(obj,[names[i]].concat(rest))}return false}return true};var triggerEvents=function(events,args){var ev,i=-1,l=events.length,a1=args[0],a2=args[1],a3=args[2];switch(args.length){case 0:while(++i<l)(ev=events[i]).callback.call(ev.ctx);return;case 1:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1);return;case 2:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2);return;case 3:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2,a3);return;default:while(++i<l)(ev=events[i]).callback.apply(ev.ctx,args);return}};var listenMethods={listenTo:"on",listenToOnce:"once"};_.each(listenMethods,function(implementation,method){Events[method]=function(obj,name,callback){var listeningTo=this._listeningTo||(this._listeningTo={});var id=obj._listenId||(obj._listenId=_.uniqueId("l"));listeningTo[id]=obj;if(!callback&&typeof name==="object")callback=this;obj[implementation](name,callback,this);return this}});Events.bind=Events.on;Events.unbind=Events.off;_.extend(Backbone,Events);var Model=Backbone.Model=function(attributes,options){var attrs=attributes||{};options||(options={});this.cid=_.uniqueId("c");this.attributes={};if(options.collection)this.collection=options.collection;if(options.parse)attrs=this.parse(attrs,options)||{};attrs=_.defaults({},attrs,_.result(this,"defaults"));this.set(attrs,options);this.changed={};this.initialize.apply(this,arguments)};_.extend(Model.prototype,Events,{changed:null,validationError:null,idAttribute:"id",initialize:function(){},toJSON:function(options){return _.clone(this.attributes)},sync:function(){return Backbone.sync.apply(this,arguments)},get:function(attr){return this.attributes[attr]},escape:function(attr){return _.escape(this.get(attr))},has:function(attr){return this.get(attr)!=null},set:function(key,val,options){var attr,attrs,unset,changes,silent,changing,prev,current;if(key==null)return this;if(typeof key==="object"){attrs=key;options=val}else{(attrs={})[key]=val}options||(options={});if(!this._validate(attrs,options))return false;unset=options.unset;silent=options.silent;changes=[];changing=this._changing;this._changing=true;if(!changing){this._previousAttributes=_.clone(this.attributes);this.changed={}}current=this.attributes,prev=this._previousAttributes;if(this.idAttribute in attrs)this.id=attrs[this.idAttribute];for(attr in attrs){val=attrs[attr];if(!_.isEqual(current[attr],val))changes.push(attr);if(!_.isEqual(prev[attr],val)){this.changed[attr]=val}else{delete this.changed[attr]}unset?delete current[attr]:current[attr]=val}if(!silent){if(changes.length)this._pending=options;for(var i=0,l=changes.length;i<l;i++){this.trigger("change:"+changes[i],this,current[changes[i]],options)}}if(changing)return this;if(!silent){while(this._pending){options=this._pending;this._pending=false;this.trigger("change",this,options)}}this._pending=false;this._changing=false;return this},unset:function(attr,options){return this.set(attr,void 0,_.extend({},options,{unset:true}))},clear:function(options){var attrs={};for(var key in this.attributes)attrs[key]=void 0;return this.set(attrs,_.extend({},options,{unset:true}))},hasChanged:function(attr){if(attr==null)return!_.isEmpty(this.changed);return _.has(this.changed,attr)},changedAttributes:function(diff){if(!diff)return this.hasChanged()?_.clone(this.changed):false;var val,changed=false;var old=this._changing?this._previousAttributes:this.attributes;for(var attr in diff){if(_.isEqual(old[attr],val=diff[attr]))continue;(changed||(changed={}))[attr]=val}return changed},previous:function(attr){if(attr==null||!this._previousAttributes)return null;return this._previousAttributes[attr]},previousAttributes:function(){return _.clone(this._previousAttributes)},fetch:function(options){options=options?_.clone(options):{};if(options.parse===void 0)options.parse=true;var model=this;var success=options.success;options.success=function(resp){if(!model.set(model.parse(resp,options),options))return false;if(success)success(model,resp,options);model.trigger("sync",model,resp,options)};wrapError(this,options);return this.sync("read",this,options)},save:function(key,val,options){var attrs,method,xhr,attributes=this.attributes;if(key==null||typeof key==="object"){attrs=key;options=val}else{(attrs={})[key]=val}options=_.extend({validate:true},options);if(attrs&&!options.wait){if(!this.set(attrs,options))return false}else{if(!this._validate(attrs,options))return false}if(attrs&&options.wait){this.attributes=_.extend({},attributes,attrs)}if(options.parse===void 0)options.parse=true;var model=this;var success=options.success;options.success=function(resp){model.attributes=attributes;var serverAttrs=model.parse(resp,options);if(options.wait)serverAttrs=_.extend(attrs||{},serverAttrs);if(_.isObject(serverAttrs)&&!model.set(serverAttrs,options)){return false}if(success)success(model,resp,options);model.trigger("sync",model,resp,options)};wrapError(this,options);method=this.isNew()?"create":options.patch?"patch":"update";if(method==="patch")options.attrs=attrs;xhr=this.sync(method,this,options);if(attrs&&options.wait)this.attributes=attributes;return xhr},destroy:function(options){options=options?_.clone(options):{};var model=this;var success=options.success;var destroy=function(){model.trigger("destroy",model,model.collection,options)};options.success=function(resp){if(options.wait||model.isNew())destroy();if(success)success(model,resp,options);if(!model.isNew())model.trigger("sync",model,resp,options)};if(this.isNew()){options.success();return false}wrapError(this,options);var xhr=this.sync("delete",this,options);if(!options.wait)destroy();return xhr},url:function(){var base=_.result(this,"urlRoot")||_.result(this.collection,"url")||urlError();if(this.isNew())return base;return base.replace(/([^\/])$/,"$1/")+encodeURIComponent(this.id)},parse:function(resp,options){return resp},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.has(this.idAttribute)},isValid:function(options){return this._validate({},_.extend(options||{},{validate:true}))},_validate:function(attrs,options){if(!options.validate||!this.validate)return true;attrs=_.extend({},this.attributes,attrs);var error=this.validationError=this.validate(attrs,options)||null;if(!error)return true;this.trigger("invalid",this,error,_.extend(options,{validationError:error}));return false}});var modelMethods=["keys","values","pairs","invert","pick","omit"];_.each(modelMethods,function(method){Model.prototype[method]=function(){var args=slice.call(arguments);args.unshift(this.attributes);return _[method].apply(_,args)}});var Collection=Backbone.Collection=function(models,options){options||(options={});if(options.model)this.model=options.model;if(options.comparator!==void 0)this.comparator=options.comparator;this._reset();this.initialize.apply(this,arguments);if(models)this.reset(models,_.extend({silent:true},options))};var setOptions={add:true,remove:true,merge:true};var addOptions={add:true,remove:false};_.extend(Collection.prototype,Events,{model:Model,initialize:function(){},toJSON:function(options){return this.map(function(model){return model.toJSON(options)})},sync:function(){return Backbone.sync.apply(this,arguments)},add:function(models,options){return this.set(models,_.extend({merge:false},options,addOptions))},remove:function(models,options){var singular=!_.isArray(models);models=singular?[models]:_.clone(models);options||(options={});var i,l,index,model;for(i=0,l=models.length;i<l;i++){model=models[i]=this.get(models[i]);if(!model)continue;delete this._byId[model.id];delete this._byId[model.cid];index=this.indexOf(model);this.models.splice(index,1);this.length--;if(!options.silent){options.index=index;model.trigger("remove",model,this,options)}this._removeReference(model,options)}return singular?models[0]:models},set:function(models,options){options=_.defaults({},options,setOptions);if(options.parse)models=this.parse(models,options);var singular=!_.isArray(models);models=singular?models?[models]:[]:_.clone(models);var i,l,id,model,attrs,existing,sort;var at=options.at;var targetModel=this.model;var sortable=this.comparator&&at==null&&options.sort!==false;var sortAttr=_.isString(this.comparator)?this.comparator:null;var toAdd=[],toRemove=[],modelMap={};var add=options.add,merge=options.merge,remove=options.remove;var order=!sortable&&add&&remove?[]:false;for(i=0,l=models.length;i<l;i++){attrs=models[i]||{};if(attrs instanceof Model){id=model=attrs}else{id=attrs[targetModel.prototype.idAttribute||"id"]}if(existing=this.get(id)){if(remove)modelMap[existing.cid]=true;if(merge){attrs=attrs===model?model.attributes:attrs;if(options.parse)attrs=existing.parse(attrs,options);existing.set(attrs,options);if(sortable&&!sort&&existing.hasChanged(sortAttr))sort=true}models[i]=existing}else if(add){model=models[i]=this._prepareModel(attrs,options);if(!model)continue;toAdd.push(model);this._addReference(model,options)}model=existing||model;if(order&&(model.isNew()||!modelMap[model.id]))order.push(model);modelMap[model.id]=true}if(remove){for(i=0,l=this.length;i<l;++i){if(!modelMap[(model=this.models[i]).cid])toRemove.push(model)}if(toRemove.length)this.remove(toRemove,options)}if(toAdd.length||order&&order.length){if(sortable)sort=true;this.length+=toAdd.length;if(at!=null){for(i=0,l=toAdd.length;i<l;i++){this.models.splice(at+i,0,toAdd[i])}}else{if(order)this.models.length=0;var orderedModels=order||toAdd;for(i=0,l=orderedModels.length;i<l;i++){this.models.push(orderedModels[i])}}}if(sort)this.sort({silent:true});if(!options.silent){for(i=0,l=toAdd.length;i<l;i++){(model=toAdd[i]).trigger("add",model,this,options)}if(sort||order&&order.length)this.trigger("sort",this,options)}return singular?models[0]:models},reset:function(models,options){options||(options={});for(var i=0,l=this.models.length;i<l;i++){this._removeReference(this.models[i],options)}options.previousModels=this.models;this._reset();models=this.add(models,_.extend({silent:true},options));if(!options.silent)this.trigger("reset",this,options);return models},push:function(model,options){return this.add(model,_.extend({at:this.length},options))},pop:function(options){var model=this.at(this.length-1);this.remove(model,options);return model},unshift:function(model,options){return this.add(model,_.extend({at:0},options))},shift:function(options){var model=this.at(0);this.remove(model,options);return model},slice:function(){return slice.apply(this.models,arguments)},get:function(obj){if(obj==null)return void 0;return this._byId[obj]||this._byId[obj.id]||this._byId[obj.cid]},at:function(index){return this.models[index]},where:function(attrs,first){if(_.isEmpty(attrs))return first?void 0:[];return this[first?"find":"filter"](function(model){for(var key in attrs){if(attrs[key]!==model.get(key))return false}return true})},findWhere:function(attrs){return this.where(attrs,true)},sort:function(options){if(!this.comparator)throw new Error("Cannot sort a set without a comparator");options||(options={});if(_.isString(this.comparator)||this.comparator.length===1){this.models=this.sortBy(this.comparator,this)}else{this.models.sort(_.bind(this.comparator,this))}if(!options.silent)this.trigger("sort",this,options);return this},pluck:function(attr){return _.invoke(this.models,"get",attr)},fetch:function(options){options=options?_.clone(options):{};if(options.parse===void 0)options.parse=true;var success=options.success;var collection=this;options.success=function(resp){var method=options.reset?"reset":"set";collection[method](resp,options);if(success)success(collection,resp,options);collection.trigger("sync",collection,resp,options)};wrapError(this,options);return this.sync("read",this,options)},create:function(model,options){options=options?_.clone(options):{};if(!(model=this._prepareModel(model,options)))return false;if(!options.wait)this.add(model,options);var collection=this;var success=options.success;options.success=function(model,resp){if(options.wait)collection.add(model,options);if(success)success(model,resp,options)};model.save(null,options);return model},parse:function(resp,options){return resp},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(attrs,options){if(attrs instanceof Model)return attrs;options=options?_.clone(options):{};options.collection=this;var model=new this.model(attrs,options);if(!model.validationError)return model;this.trigger("invalid",this,model.validationError,options);return false},_addReference:function(model,options){this._byId[model.cid]=model;if(model.id!=null)this._byId[model.id]=model;if(!model.collection)model.collection=this;model.on("all",this._onModelEvent,this)},_removeReference:function(model,options){if(this===model.collection)delete model.collection;model.off("all",this._onModelEvent,this)},_onModelEvent:function(event,model,collection,options){if((event==="add"||event==="remove")&&collection!==this)return;if(event==="destroy")this.remove(model,options);if(model&&event==="change:"+model.idAttribute){delete this._byId[model.previous(model.idAttribute)];if(model.id!=null)this._byId[model.id]=model}this.trigger.apply(this,arguments)}});var methods=["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","difference","indexOf","shuffle","lastIndexOf","isEmpty","chain","sample"];_.each(methods,function(method){Collection.prototype[method]=function(){var args=slice.call(arguments);args.unshift(this.models);return _[method].apply(_,args)}});var attributeMethods=["groupBy","countBy","sortBy","indexBy"];_.each(attributeMethods,function(method){Collection.prototype[method]=function(value,context){var iterator=_.isFunction(value)?value:function(model){return model.get(value)};return _[method](this.models,iterator,context)}});var View=Backbone.View=function(options){this.cid=_.uniqueId("view");options||(options={});_.extend(this,_.pick(options,viewOptions));this._ensureElement();this.initialize.apply(this,arguments);this.delegateEvents()};var delegateEventSplitter=/^(\S+)\s*(.*)$/;var viewOptions=["model","collection","el","id","attributes","className","tagName","events"];_.extend(View.prototype,Events,{tagName:"div",$:function(selector){return this.$el.find(selector)},initialize:function(){},render:function(){return this},remove:function(){this.$el.remove();this.stopListening();return this},setElement:function(element,delegate){if(this.$el)this.undelegateEvents();this.$el=element instanceof Backbone.$?element:Backbone.$(element);this.el=this.$el[0];if(delegate!==false)this.delegateEvents();return this},delegateEvents:function(events){if(!(events||(events=_.result(this,"events"))))return this;this.undelegateEvents();for(var key in events){var method=events[key];if(!_.isFunction(method))method=this[events[key]];if(!method)continue;var match=key.match(delegateEventSplitter);var eventName=match[1],selector=match[2];method=_.bind(method,this);eventName+=".delegateEvents"+this.cid;if(selector===""){this.$el.on(eventName,method)}else{this.$el.on(eventName,selector,method)}}return this},undelegateEvents:function(){this.$el.off(".delegateEvents"+this.cid);return this},_ensureElement:function(){if(!this.el){var attrs=_.extend({},_.result(this,"attributes"));if(this.id)attrs.id=_.result(this,"id");if(this.className)attrs["class"]=_.result(this,"className");var $el=Backbone.$("<"+_.result(this,"tagName")+">").attr(attrs);this.setElement($el,false)}else{this.setElement(_.result(this,"el"),false)}}});Backbone.sync=function(method,model,options){var type=methodMap[method];_.defaults(options||(options={}),{emulateHTTP:Backbone.emulateHTTP,emulateJSON:Backbone.emulateJSON});var params={type:type,dataType:"json"};if(!options.url){params.url=_.result(model,"url")||urlError()}if(options.data==null&&model&&(method==="create"||method==="update"||method==="patch")){params.contentType="application/json";params.data=JSON.stringify(options.attrs||model.toJSON(options))}if(options.emulateJSON){params.contentType="application/x-www-form-urlencoded";params.data=params.data?{model:params.data}:{}}if(options.emulateHTTP&&(type==="PUT"||type==="DELETE"||type==="PATCH")){params.type="POST";if(options.emulateJSON)params.data._method=type;var beforeSend=options.beforeSend;options.beforeSend=function(xhr){xhr.setRequestHeader("X-HTTP-Method-Override",type);if(beforeSend)return beforeSend.apply(this,arguments)}}if(params.type!=="GET"&&!options.emulateJSON){params.processData=false}if(params.type==="PATCH"&&noXhrPatch){params.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}var xhr=options.xhr=Backbone.ajax(_.extend(params,options));model.trigger("request",model,xhr,options);return xhr};var noXhrPatch=typeof window!=="undefined"&&!!window.ActiveXObject&&!(window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent);var methodMap={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};Backbone.ajax=function(){return Backbone.$.ajax.apply(Backbone.$,arguments)};var Router=Backbone.Router=function(options){options||(options={});if(options.routes)this.routes=options.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var optionalParam=/\((.*?)\)/g;var namedParam=/(\(\?)?:\w+/g;var splatParam=/\*\w+/g;var escapeRegExp=/[\-{}\[\]+?.,\\\^$|#\s]/g;_.extend(Router.prototype,Events,{initialize:function(){},route:function(route,name,callback){if(!_.isRegExp(route))route=this._routeToRegExp(route);if(_.isFunction(name)){callback=name;name=""}if(!callback)callback=this[name];var router=this;Backbone.history.route(route,function(fragment){var args=router._extractParameters(route,fragment);router.execute(callback,args);router.trigger.apply(router,["route:"+name].concat(args));router.trigger("route",name,args);Backbone.history.trigger("route",router,name,args)});return this},execute:function(callback,args){if(callback)callback.apply(this,args)},navigate:function(fragment,options){Backbone.history.navigate(fragment,options);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=_.result(this,"routes");var route,routes=_.keys(this.routes);while((route=routes.pop())!=null){this.route(route,this.routes[route])}},_routeToRegExp:function(route){route=route.replace(escapeRegExp,"\\$&").replace(optionalParam,"(?:$1)?").replace(namedParam,function(match,optional){return optional?match:"([^/?]+)"}).replace(splatParam,"([^?]*?)");return new RegExp("^"+route+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(route,fragment){var params=route.exec(fragment).slice(1);return _.map(params,function(param,i){if(i===params.length-1)return param||null;return param?decodeURIComponent(param):null})}});var History=Backbone.History=function(){this.handlers=[];_.bindAll(this,"checkUrl");if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var routeStripper=/^[#\/]|\s+$/g;var rootStripper=/^\/+|\/+$/g;var isExplorer=/msie [\w.]+/;var trailingSlash=/\/$/;var pathStripper=/#.*$/;History.started=false;_.extend(History.prototype,Events,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root},getHash:function(window){var match=(window||this).location.href.match(/#(.*)$/);return match?match[1]:""},getFragment:function(fragment,forcePushState){if(fragment==null){if(this._hasPushState||!this._wantsHashChange||forcePushState){fragment=decodeURI(this.location.pathname+this.location.search);var root=this.root.replace(trailingSlash,"");if(!fragment.indexOf(root))fragment=fragment.slice(root.length)}else{fragment=this.getHash()}}return fragment.replace(routeStripper,"")},start:function(options){if(History.started)throw new Error("Backbone.history has already been started");History.started=true;this.options=_.extend({root:"/"},this.options,options);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var fragment=this.getFragment();var docMode=document.documentMode;var oldIE=isExplorer.exec(navigator.userAgent.toLowerCase())&&(!docMode||docMode<=7);this.root=("/"+this.root+"/").replace(rootStripper,"/");if(oldIE&&this._wantsHashChange){var frame=Backbone.$('<iframe src="javascript:0" tabindex="-1">');this.iframe=frame.hide().appendTo("body")[0].contentWindow;this.navigate(fragment)}if(this._hasPushState){Backbone.$(window).on("popstate",this.checkUrl)}else if(this._wantsHashChange&&"onhashchange"in window&&!oldIE){Backbone.$(window).on("hashchange",this.checkUrl)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}this.fragment=fragment;var loc=this.location;if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){this.fragment=this.getFragment(null,true);this.location.replace(this.root+"#"+this.fragment);return true}else if(this._hasPushState&&this.atRoot()&&loc.hash){this.fragment=this.getHash().replace(routeStripper,"");this.history.replaceState({},document.title,this.root+this.fragment)}}if(!this.options.silent)return this.loadUrl()},stop:function(){Backbone.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl);if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);History.started=false},route:function(route,callback){this.handlers.unshift({route:route,callback:callback})},checkUrl:function(e){var current=this.getFragment();if(current===this.fragment&&this.iframe){current=this.getFragment(this.getHash(this.iframe))}if(current===this.fragment)return false;if(this.iframe)this.navigate(current);this.loadUrl()},loadUrl:function(fragment){fragment=this.fragment=this.getFragment(fragment);return _.any(this.handlers,function(handler){if(handler.route.test(fragment)){handler.callback(fragment);return true}})},navigate:function(fragment,options){if(!History.started)return false;if(!options||options===true)options={trigger:!!options};var url=this.root+(fragment=this.getFragment(fragment||""));fragment=fragment.replace(pathStripper,"");if(this.fragment===fragment)return;this.fragment=fragment;if(fragment===""&&url!=="/")url=url.slice(0,-1);if(this._hasPushState){this.history[options.replace?"replaceState":"pushState"]({},document.title,url)}else if(this._wantsHashChange){this._updateHash(this.location,fragment,options.replace);if(this.iframe&&fragment!==this.getFragment(this.getHash(this.iframe))){if(!options.replace)this.iframe.document.open().close();this._updateHash(this.iframe.location,fragment,options.replace)}}else{return this.location.assign(url)}if(options.trigger)return this.loadUrl(fragment)},_updateHash:function(location,fragment,replace){if(replace){var href=location.href.replace(/(javascript:|#).*$/,"");location.replace(href+"#"+fragment)}else{location.hash="#"+fragment}}});Backbone.history=new History;var extend=function(protoProps,staticProps){var parent=this;var child;if(protoProps&&_.has(protoProps,"constructor")){child=protoProps.constructor}else{child=function(){return parent.apply(this,arguments)}}_.extend(child,parent,staticProps);var Surrogate=function(){this.constructor=child};Surrogate.prototype=parent.prototype;child.prototype=new Surrogate;if(protoProps)_.extend(child.prototype,protoProps);child.__super__=parent.prototype;return child};Model.extend=Collection.extend=Router.extend=View.extend=History.extend=extend;var urlError=function(){throw new Error('A "url" property or function must be specified')};var wrapError=function(model,options){var error=options.error;options.error=function(resp){if(error)error(model,resp,options);model.trigger("error",model,resp,options)}};return Backbone});var requirejs,require,define;(function(ba){function G(b){return"[object Function]"===K.call(b)}function H(b){return"[object Array]"===K.call(b)}function v(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function T(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));d-=1);}}function t(b,c){return fa.call(b,c)}function m(b,c){return t(b,c)&&b[c]}function B(b,c){for(var d in b)if(t(b,d)&&c(b[d],d))break}function U(b,c,d,e){c&&B(c,function(c,g){if(d||!t(b,g))e&&"object"===typeof c&&c&&!H(c)&&!G(c)&&!(c instanceof RegExp)?(b[g]||(b[g]={}),U(b[g],c,d,e)):b[g]=c});return b}function u(b,c){return function(){return c.apply(b,arguments)}}function ca(b){throw b}function da(b){if(!b)return b;var c=ba;v(b.split("."),function(b){c=c[b]});return c}function C(b,c,d,e){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=e;d&&(c.originalError=d);return c}function ga(b){function c(a,k,b){var f,l,c,d,e,g,i,p,k=k&&k.split("/"),h=j.map,n=h&&h["*"];if(a){a=a.split("/");l=a.length-1;j.nodeIdCompat&&Q.test(a[l])&&(a[l]=a[l].replace(Q,""));"."===a[0].charAt(0)&&k&&(l=k.slice(0,k.length-1),a=l.concat(a));l=a;for(c=0;c<l.length;c++)if(d=l[c],"."===d)l.splice(c,1),c-=1;else if(".."===d&&!(0===c||1==c&&".."===l[2]||".."===l[c-1])&&0<c)l.splice(c-1,2),c-=2;a=a.join("/")}if(b&&h&&(k||n)){l=a.split("/");c=l.length;a:for(;0<c;c-=1){e=l.slice(0,c).join("/");if(k)for(d=k.length;0<d;d-=1)if(b=m(h,k.slice(0,d).join("/")))if(b=m(b,e)){f=b;g=c;break a}!i&&(n&&m(n,e))&&(i=m(n,e),p=c)}!f&&i&&(f=i,g=p);f&&(l.splice(0,g,f),a=l.join("/"))}return(f=m(j.pkgs,a))?f:a}function d(a){z&&v(document.getElementsByTagName("script"),function(k){if(k.getAttribute("data-requiremodule")===a&&k.getAttribute("data-requirecontext")===i.contextName)return k.parentNode.removeChild(k),!0})}function e(a){var k=m(j.paths,a);if(k&&H(k)&&1<k.length)return k.shift(),i.require.undef(a),i.makeRequire(null,{skipMap:!0})([a]),!0}function n(a){var k,c=a?a.indexOf("!"):-1;-1<c&&(k=a.substring(0,c),a=a.substring(c+1,a.length));return[k,a]}function p(a,k,b,f){var l,d,e=null,g=k?k.name:null,j=a,p=!0,h="";a||(p=!1,a="_@r"+(K+=1));a=n(a);e=a[0];a=a[1];e&&(e=c(e,g,f),d=m(r,e));a&&(e?h=d&&d.normalize?d.normalize(a,function(a){return c(a,g,f)}):-1===a.indexOf("!")?c(a,g,f):a:(h=c(a,g,f),a=n(h),e=a[0],h=a[1],b=!0,l=i.nameToUrl(h)));b=e&&!d&&!b?"_unnormalized"+(O+=1):"";return{prefix:e,name:h,parentMap:k,unnormalized:!!b,url:l,originalName:j,isDefine:p,id:(e?e+"!"+h:h)+b}}function s(a){var k=a.id,b=m(h,k);b||(b=h[k]=new i.Module(a));return b}function q(a,k,b){var f=a.id,c=m(h,f);if(t(r,f)&&(!c||c.defineEmitComplete))"defined"===k&&b(r[f]);else if(c=s(a),c.error&&"error"===k)b(c.error);else c.on(k,b)}function w(a,b){var c=a.requireModules,f=!1;if(b)b(a);else if(v(c,function(b){if(b=m(h,b))b.error=a,b.events.error&&(f=!0,b.emit("error",a))}),!f)g.onError(a)}function x(){R.length&&(ha.apply(A,[A.length,0].concat(R)),R=[])}function y(a){delete h[a];delete V[a]}function F(a,b,c){var f=a.map.id;a.error?a.emit("error",a.error):(b[f]=!0,v(a.depMaps,function(f,d){var e=f.id,g=m(h,e);g&&(!a.depMatched[d]&&!c[e])&&(m(b,e)?(a.defineDep(d,r[e]),a.check()):F(g,b,c))}),c[f]=!0)}function D(){var a,b,c=(a=1e3*j.waitSeconds)&&i.startTime+a<(new Date).getTime(),f=[],l=[],g=!1,h=!0;if(!W){W=!0;B(V,function(a){var i=a.map,j=i.id;if(a.enabled&&(i.isDefine||l.push(a),!a.error))if(!a.inited&&c)e(j)?g=b=!0:(f.push(j),d(j));else if(!a.inited&&(a.fetched&&i.isDefine)&&(g=!0,!i.prefix))return h=!1});if(c&&f.length)return a=C("timeout","Load timeout for modules: "+f,null,f),a.contextName=i.contextName,w(a);h&&v(l,function(a){F(a,{},{})});if((!c||b)&&g)if((z||ea)&&!X)X=setTimeout(function(){X=0;D()},50);W=!1}}function E(a){t(r,a[0])||s(p(a[0],null,!0)).init(a[1],a[2])}function I(a){var a=a.currentTarget||a.srcElement,b=i.onScriptLoad;a.detachEvent&&!Y?a.detachEvent("onreadystatechange",b):a.removeEventListener("load",b,!1);b=i.onScriptError;(!a.detachEvent||Y)&&a.removeEventListener("error",b,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function J(){var a;for(x();A.length;){a=A.shift();if(null===a[0])return w(C("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));E(a)}}var W,Z,i,L,X,j={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},h={},V={},$={},A=[],r={},S={},aa={},K=1,O=1;L={require:function(a){return a.require?a.require:a.require=i.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports?r[a.map.id]=a.exports:a.exports=r[a.map.id]={}},module:function(a){return a.module?a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){return m(j.config,a.map.id)||{}},exports:a.exports||(a.exports={})}}};Z=function(a){this.events=m($,a.id)||{};this.map=a;this.shim=m(j.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};Z.prototype={init:function(a,b,c,f){f=f||{};if(!this.inited){this.factory=b;if(c)this.on("error",c);else this.events.error&&(c=u(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=c;this.inited=!0;this.ignore=f.ignore;f.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,b){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=b)},fetch:function(){if(!this.fetched){this.fetched=!0;i.startTime=(new Date).getTime();var a=this.map;if(this.shim)i.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],u(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=this.map.url;S[a]||(S[a]=!0,i.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,b,c=this.map.id;b=this.depExports;var f=this.exports,l=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;
    5 if(1>this.depCount&&!this.defined){if(G(l)){if(this.events.error&&this.map.isDefine||g.onError!==ca)try{f=i.execCb(c,l,b,f)}catch(d){a=d}else f=i.execCb(c,l,b,f);this.map.isDefine&&void 0===f&&((b=this.module)?f=b.exports:this.usingExports&&(f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=l;this.exports=f;if(this.map.isDefine&&!this.ignore&&(r[c]=f,g.onResourceLoad))g.onResourceLoad(i,this.map,this.depMaps);y(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=p(a.prefix);this.depMaps.push(d);q(d,"defined",u(this,function(f){var l,d;d=m(aa,this.map.id);var e=this.map.name,P=this.map.parentMap?this.map.parentMap.name:null,n=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(e=f.normalize(e,function(a){return c(a,P,!0)})||""),f=p(a.prefix+"!"+e,this.map.parentMap),q(f,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),d=m(h,f.id)){this.depMaps.push(f);if(this.events.error)d.on("error",u(this,function(a){this.emit("error",a)}));d.enable()}}else d?(this.map.url=i.nameToUrl(d),this.load()):(l=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),l.error=u(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(h,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),l.fromText=u(this,function(f,c){var d=a.name,e=p(d),P=M;c&&(f=c);P&&(M=!1);s(e);t(j.config,b)&&(j.config[d]=j.config[b]);try{g.exec(f)}catch(h){return w(C("fromtexteval","fromText eval for "+b+" failed: "+h,h,[b]))}P&&(M=!0);this.depMaps.push(e);i.completeLoad(d);n([d],l)}),f.load(a.name,n,l,j))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){V[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,u(this,function(a,b){var c,f;if("string"===typeof a){a=p(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=m(L,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;q(a,"defined",u(this,function(a){this.defineDep(b,a);this.check()}));this.errback&&q(a,"error",u(this,this.errback))}c=a.id;f=h[c];!t(L,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,u(this,function(a){var b=m(h,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:j,contextName:b,registry:h,defined:r,urlFetched:S,defQueue:A,Module:Z,makeModuleMap:p,nextTick:g.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=j.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(j[b]||(j[b]={}),U(j[b],a,!0,!0)):j[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(aa[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);b[c]=a}),j.shim=b);a.packages&&v(a.packages,function(a){var b,a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(j.paths[b]=a.location);j.pkgs[b]=a.name+"/"+(a.main||"main").replace(ia,"").replace(Q,"")});B(h,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=p(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ba,arguments));return b||a.exports&&da(a.exports)}},makeRequire:function(a,e){function j(c,d,m){var n,q;e.enableBuildCallback&&(d&&G(d))&&(d.__requireJsBuild=!0);if("string"===typeof c){if(G(d))return w(C("requireargs","Invalid require call"),m);if(a&&t(L,c))return L[c](h[a.id]);if(g.get)return g.get(i,c,a,j);n=p(c,a,!1,!0);n=n.id;return!t(r,n)?w(C("notloaded",'Module name "'+n+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[n]}J();i.nextTick(function(){J();q=s(p(null,a));q.skipMap=e.skipMap;q.init(c,d,m,{enabled:!0});D()});return j}e=e||{};U(j,{isBrowser:z,toUrl:function(b){var d,e=b.lastIndexOf("."),k=b.split("/")[0];if(-1!==e&&(!("."===k||".."===k)||1<e))d=b.substring(e,b.length),b=b.substring(0,e);return i.nameToUrl(c(b,a&&a.id,!0),d,!0)},defined:function(b){return t(r,p(b,a,!1,!0).id)},specified:function(b){b=p(b,a,!1,!0).id;return t(r,b)||t(h,b)}});a||(j.undef=function(b){x();var c=p(b,a,!0),e=m(h,b);d(b);delete r[b];delete S[c.url];delete $[b];T(A,function(a,c){a[0]===b&&A.splice(c,1)});e&&(e.events.defined&&($[b]=e.events),y(b))});return j},enable:function(a){m(h,a.id)&&s(a).enable()},completeLoad:function(a){var b,c,d=m(j.shim,a)||{},g=d.exports;for(x();A.length;){c=A.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);E(c)}c=m(h,a);if(!b&&!t(r,a)&&c&&!c.inited){if(j.enforceDefine&&(!g||!da(g)))return e(a)?void 0:w(C("nodefine","No define call for "+a,null,[a]));E([a,d.deps||[],d.exportsFn])}D()},nameToUrl:function(a,b,c){var d,e,h;(d=m(j.pkgs,a))&&(a=d);if(d=m(aa,a))return i.nameToUrl(d,b,c);if(g.jsExtRegExp.test(a))d=a+(b||"");else{d=j.paths;a=a.split("/");for(e=a.length;0<e;e-=1)if(h=a.slice(0,e).join("/"),h=m(d,h)){H(h)&&(h=h[0]);a.splice(0,e,h);break}d=a.join("/");d+=b||(/^data\:|\?/.test(d)||c?"":".js");d=("/"===d.charAt(0)||d.match(/^[\w\+\.\-]+:/)?"":j.baseUrl)+d}return j.urlArgs?d+((-1===d.indexOf("?")?"?":"&")+j.urlArgs):d},load:function(a,b){g.load(i,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if("load"===a.type||ja.test((a.currentTarget||a.srcElement).readyState))N=null,a=I(a),i.completeLoad(a.id)},onScriptError:function(a){var b=I(a);if(!e(b.id))return w(C("scripterror","Script error for: "+b.id,a,[b.id]))}};i.require=i.makeRequire();return i}var g,x,y,D,I,E,N,J,s,O,ka=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm,la=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,Q=/\.js$/,ia=/^\.\//;x=Object.prototype;var K=x.toString,fa=x.hasOwnProperty,ha=Array.prototype.splice,z=!!("undefined"!==typeof window&&"undefined"!==typeof navigator&&window.document),ea=!z&&"undefined"!==typeof importScripts,ja=z&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,Y="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),F={},q={},R=[],M=!1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(G(requirejs))return;q=requirejs;requirejs=void 0}"undefined"!==typeof require&&!G(require)&&(q=require,require=void 0);g=requirejs=function(b,c,d,e){var n,p="_";!H(b)&&"string"!==typeof b&&(n=b,H(c)?(b=c,c=d,d=e):b=[]);n&&n.context&&(p=n.context);(e=m(F,p))||(e=F[p]=g.s.newContext(p));n&&e.configure(n);return e.require(b,c,d)};g.config=function(b){return g(b)};g.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b,4)}:function(b){b()};require||(require=g);g.version="2.1.15";g.jsExtRegExp=/^\/|:|\?|\.js$/;g.isBrowser=z;x=g.s={contexts:F,newContext:ga};g({});v(["toUrl","undef","defined","specified"],function(b){g[b]=function(){var c=F._;return c.require[b].apply(c,arguments)}});if(z&&(y=x.head=document.getElementsByTagName("head")[0],D=document.getElementsByTagName("base")[0]))y=x.head=D.parentNode;g.onError=ca;g.createNode=function(b){var c=b.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");c.type=b.scriptType||"text/javascript";c.charset="utf-8";c.async=!0;return c};g.load=function(b,c,d){var e=b&&b.config||{};if(z)return e=g.createNode(e,c,d),e.setAttribute("data-requirecontext",b.contextName),e.setAttribute("data-requiremodule",c),e.attachEvent&&!(e.attachEvent.toString&&0>e.attachEvent.toString().indexOf("[native code"))&&!Y?(M=!0,e.attachEvent("onreadystatechange",b.onScriptLoad)):(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)),e.src=d,J=e,D?y.insertBefore(e,D):y.appendChild(e),J=null,e;if(ea)try{importScripts(d),b.completeLoad(c)}catch(m){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,m,[c]))}};z&&!q.skipDataMain&&T(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(I=b.getAttribute("data-main"))return s=I,q.baseUrl||(E=s.split("/"),s=E.pop(),O=E.length?E.join("/")+"/":"./",q.baseUrl=O),s=s.replace(Q,""),g.jsExtRegExp.test(s)&&(s=I),q.deps=q.deps?q.deps.concat(s):[s],!0});define=function(b,c,d){var e,g;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(ka,"").replace(la,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(M){if(!(e=J))N&&"interactive"===N.readyState||T(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return N=b}),e=N;e&&(b||(b=e.getAttribute("data-requiremodule")),g=F[e.getAttribute("data-requirecontext")])}(g?g.defQueue:R).push([b,c,d])};define.amd={jQuery:!0};g.exec=function(b){return eval(b)};g(q)}})(this);!function(root,String){var nativeTrim=String.prototype.trim;var nativeTrimRight=String.prototype.trimRight;var nativeTrimLeft=String.prototype.trimLeft;var parseNumber=function(source){return source*1||0};var strRepeat=function(str,qty){if(qty<1)return"";var result="";while(qty>0){if(qty&1)result+=str;qty>>=1,str+=str}return result};var slice=[].slice;var defaultToWhiteSpace=function(characters){if(characters==null)return"\\s";else if(characters.source)return characters.source;else return"["+_s.escapeRegExp(characters)+"]"};var escapeChars={lt:"<",gt:">",quot:'"',amp:"&",apos:"'"};var reversedEscapeChars={};for(var key in escapeChars)reversedEscapeChars[escapeChars[key]]=key;reversedEscapeChars["'"]="#39";var sprintf=function(){function get_type(variable){return Object.prototype.toString.call(variable).slice(8,-1).toLowerCase()}var str_repeat=strRepeat;var str_format=function(){if(!str_format.cache.hasOwnProperty(arguments[0])){str_format.cache[arguments[0]]=str_format.parse(arguments[0])}return str_format.format.call(null,str_format.cache[arguments[0]],arguments)};str_format.format=function(parse_tree,argv){var cursor=1,tree_length=parse_tree.length,node_type="",arg,output=[],i,k,match,pad,pad_character,pad_length;for(i=0;i<tree_length;i++){node_type=get_type(parse_tree[i]);if(node_type==="string"){output.push(parse_tree[i])}else if(node_type==="array"){match=parse_tree[i];if(match[2]){arg=argv[cursor];for(k=0;k<match[2].length;k++){if(!arg.hasOwnProperty(match[2][k])){throw new Error(sprintf('[_.sprintf] property "%s" does not exist',match[2][k]))}arg=arg[match[2][k]]}}else if(match[1]){arg=argv[match[1]]}else{arg=argv[cursor++]}if(/[^s]/.test(match[8])&&get_type(arg)!="number"){throw new Error(sprintf("[_.sprintf] expecting number but found %s",get_type(arg)))}switch(match[8]){case"b":arg=arg.toString(2);break;case"c":arg=String.fromCharCode(arg);break;case"d":arg=parseInt(arg,10);break;case"e":arg=match[7]?arg.toExponential(match[7]):arg.toExponential();break;case"f":arg=match[7]?parseFloat(arg).toFixed(match[7]):parseFloat(arg);break;case"o":arg=arg.toString(8);break;case"s":arg=(arg=String(arg))&&match[7]?arg.substring(0,match[7]):arg;break;case"u":arg=Math.abs(arg);break;case"x":arg=arg.toString(16);break;case"X":arg=arg.toString(16).toUpperCase();break}arg=/[def]/.test(match[8])&&match[3]&&arg>=0?"+"+arg:arg;pad_character=match[4]?match[4]=="0"?"0":match[4].charAt(1):" ";pad_length=match[6]-String(arg).length;pad=match[6]?str_repeat(pad_character,pad_length):"";output.push(match[5]?arg+pad:pad+arg)}}return output.join("")};str_format.cache={};str_format.parse=function(fmt){var _fmt=fmt,match=[],parse_tree=[],arg_names=0;while(_fmt){if((match=/^[^\x25]+/.exec(_fmt))!==null){parse_tree.push(match[0])}else if((match=/^\x25{2}/.exec(_fmt))!==null){parse_tree.push("%")}else if((match=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt))!==null){if(match[2]){arg_names|=1;var field_list=[],replacement_field=match[2],field_match=[];if((field_match=/^([a-z_][a-z_\d]*)/i.exec(replacement_field))!==null){field_list.push(field_match[1]);while((replacement_field=replacement_field.substring(field_match[0].length))!==""){if((field_match=/^\.([a-z_][a-z_\d]*)/i.exec(replacement_field))!==null){field_list.push(field_match[1])}else if((field_match=/^\[(\d+)\]/.exec(replacement_field))!==null){field_list.push(field_match[1])}else{throw new Error("[_.sprintf] huh?")}}}else{throw new Error("[_.sprintf] huh?")}match[2]=field_list}else{arg_names|=2}if(arg_names===3){throw new Error("[_.sprintf] mixing positional and named placeholders is not (yet) supported")}parse_tree.push(match)}else{throw new Error("[_.sprintf] huh?")}_fmt=_fmt.substring(match[0].length)}return parse_tree};return str_format}();var _s={VERSION:"2.3.0",isBlank:function(str){if(str==null)str="";return/^\s*$/.test(str)},stripTags:function(str){if(str==null)return"";return String(str).replace(/<\/?[^>]+>/g,"")},capitalize:function(str){str=str==null?"":String(str);return str.charAt(0).toUpperCase()+str.slice(1)},chop:function(str,step){if(str==null)return[];str=String(str);step=~~step;return step>0?str.match(new RegExp(".{1,"+step+"}","g")):[str]},clean:function(str){return _s.strip(str).replace(/\s+/g," ")},count:function(str,substr){if(str==null||substr==null)return 0;str=String(str);substr=String(substr);var count=0,pos=0,length=substr.length;while(true){pos=str.indexOf(substr,pos);if(pos===-1)break;count++;pos+=length}return count},chars:function(str){if(str==null)return[];return String(str).split("")},swapCase:function(str){if(str==null)return"";return String(str).replace(/\S/g,function(c){return c===c.toUpperCase()?c.toLowerCase():c.toUpperCase()})},escapeHTML:function(str){if(str==null)return"";return String(str).replace(/[&<>"']/g,function(m){return"&"+reversedEscapeChars[m]+";"})},unescapeHTML:function(str){if(str==null)return"";return String(str).replace(/\&([^;]+);/g,function(entity,entityCode){var match;if(entityCode in escapeChars){return escapeChars[entityCode]}else if(match=entityCode.match(/^#x([\da-fA-F]+)$/)){return String.fromCharCode(parseInt(match[1],16))}else if(match=entityCode.match(/^#(\d+)$/)){return String.fromCharCode(~~match[1])}else{return entity}})},escapeRegExp:function(str){if(str==null)return"";return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")},splice:function(str,i,howmany,substr){var arr=_s.chars(str);arr.splice(~~i,~~howmany,substr);return arr.join("")},insert:function(str,i,substr){return _s.splice(str,i,0,substr)},include:function(str,needle){if(needle==="")return true;if(str==null)return false;return String(str).indexOf(needle)!==-1},join:function(){var args=slice.call(arguments),separator=args.shift();if(separator==null)separator="";return args.join(separator)},lines:function(str){if(str==null)return[];return String(str).split("\n")},reverse:function(str){return _s.chars(str).reverse().join("")},startsWith:function(str,starts){if(starts==="")return true;if(str==null||starts==null)return false;str=String(str);starts=String(starts);return str.length>=starts.length&&str.slice(0,starts.length)===starts},endsWith:function(str,ends){if(ends==="")return true;if(str==null||ends==null)return false;str=String(str);ends=String(ends);return str.length>=ends.length&&str.slice(str.length-ends.length)===ends},succ:function(str){if(str==null)return"";str=String(str);return str.slice(0,-1)+String.fromCharCode(str.charCodeAt(str.length-1)+1)},titleize:function(str){if(str==null)return"";return String(str).replace(/(?:^|\s)\S/g,function(c){return c.toUpperCase()})},camelize:function(str){return _s.trim(str).replace(/[-_\s]+(.)?/g,function(match,c){return c.toUpperCase()})},underscored:function(str){return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},dasherize:function(str){return _s.trim(str).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},classify:function(str){return _s.titleize(String(str).replace(/_/g," ")).replace(/\s/g,"")},humanize:function(str){return _s.capitalize(_s.underscored(str).replace(/_id$/,"").replace(/_/g," "))},trim:function(str,characters){if(str==null)return"";if(!characters&&nativeTrim)return nativeTrim.call(str);characters=defaultToWhiteSpace(characters);return String(str).replace(new RegExp("^"+characters+"+|"+characters+"+$","g"),"")},ltrim:function(str,characters){if(str==null)return"";if(!characters&&nativeTrimLeft)return nativeTrimLeft.call(str);characters=defaultToWhiteSpace(characters);return String(str).replace(new RegExp("^"+characters+"+"),"")},rtrim:function(str,characters){if(str==null)return"";if(!characters&&nativeTrimRight)return nativeTrimRight.call(str);characters=defaultToWhiteSpace(characters);return String(str).replace(new RegExp(characters+"+$"),"")},truncate:function(str,length,truncateStr){if(str==null)return"";str=String(str);truncateStr=truncateStr||"...";length=~~length;return str.length>length?str.slice(0,length)+truncateStr:str},prune:function(str,length,pruneStr){if(str==null)return"";str=String(str);length=~~length;pruneStr=pruneStr!=null?String(pruneStr):"...";if(str.length<=length)return str;var tmpl=function(c){return c.toUpperCase()!==c.toLowerCase()?"A":" "},template=str.slice(0,length+1).replace(/.(?=\W*\w*$)/g,tmpl);if(template.slice(template.length-2).match(/\w\w/))template=template.replace(/\s*\S+$/,"");else template=_s.rtrim(template.slice(0,template.length-1));return(template+pruneStr).length>str.length?str:str.slice(0,template.length)+pruneStr},words:function(str,delimiter){if(_s.isBlank(str))return[];return _s.trim(str,delimiter).split(delimiter||/\s+/)},pad:function(str,length,padStr,type){str=str==null?"":String(str);length=~~length;var padlen=0;if(!padStr)padStr=" ";else if(padStr.length>1)padStr=padStr.charAt(0);switch(type){case"right":padlen=length-str.length;return str+strRepeat(padStr,padlen);case"both":padlen=length-str.length;return strRepeat(padStr,Math.ceil(padlen/2))+str+strRepeat(padStr,Math.floor(padlen/2));default:padlen=length-str.length;return strRepeat(padStr,padlen)+str}},lpad:function(str,length,padStr){return _s.pad(str,length,padStr)},rpad:function(str,length,padStr){return _s.pad(str,length,padStr,"right")},lrpad:function(str,length,padStr){return _s.pad(str,length,padStr,"both")},sprintf:sprintf,vsprintf:function(fmt,argv){argv.unshift(fmt);return sprintf.apply(null,argv)},toNumber:function(str,decimals){if(!str)return 0;str=_s.trim(str);if(!str.match(/^-?\d+(?:\.\d+)?$/))return NaN;return parseNumber(parseNumber(str).toFixed(~~decimals))},numberFormat:function(number,dec,dsep,tsep){if(isNaN(number)||number==null)return"";number=number.toFixed(~~dec);tsep=typeof tsep=="string"?tsep:",";var parts=number.split("."),fnums=parts[0],decimals=parts[1]?(dsep||".")+parts[1]:"";return fnums.replace(/(\d)(?=(?:\d{3})+$)/g,"$1"+tsep)+decimals},strRight:function(str,sep){if(str==null)return"";str=String(str);sep=sep!=null?String(sep):sep;var pos=!sep?-1:str.indexOf(sep);return~pos?str.slice(pos+sep.length,str.length):str},strRightBack:function(str,sep){if(str==null)return"";str=String(str);sep=sep!=null?String(sep):sep;var pos=!sep?-1:str.lastIndexOf(sep);return~pos?str.slice(pos+sep.length,str.length):str},strLeft:function(str,sep){if(str==null)return"";str=String(str);sep=sep!=null?String(sep):sep;var pos=!sep?-1:str.indexOf(sep);return~pos?str.slice(0,pos):str},strLeftBack:function(str,sep){if(str==null)return"";str+="";sep=sep!=null?""+sep:sep;var pos=str.lastIndexOf(sep);return~pos?str.slice(0,pos):str},toSentence:function(array,separator,lastSeparator,serial){separator=separator||", ";lastSeparator=lastSeparator||" and ";var a=array.slice(),lastMember=a.pop();if(array.length>2&&serial)lastSeparator=_s.rtrim(separator)+lastSeparator;return a.length?a.join(separator)+lastSeparator+lastMember:lastMember},toSentenceSerial:function(){var args=slice.call(arguments);args[3]=true;return _s.toSentence.apply(_s,args)},slugify:function(str){if(str==null)return"";var from="ąàáäâãåæćęèéëêìíïîłńòóöôõøùúüûñçżź",to="aaaaaaaaceeeeeiiiilnoooooouuuunczz",regex=new RegExp(defaultToWhiteSpace(from),"g");str=String(str).toLowerCase().replace(regex,function(c){var index=from.indexOf(c);return to.charAt(index)||"-"});return _s.dasherize(str.replace(/[^\w\s-]/g,""))},surround:function(str,wrapper){return[wrapper,str,wrapper].join("")},quote:function(str){return _s.surround(str,'"')},exports:function(){var result={};for(var prop in this){if(!this.hasOwnProperty(prop)||prop.match(/^(?:include|contains|reverse)$/))continue;result[prop]=this[prop]}return result},repeat:function(str,qty,separator){if(str==null)return"";qty=~~qty;if(separator==null)return strRepeat(String(str),qty);for(var repeat=[];qty>0;repeat[--qty]=str){}return repeat.join(separator)},levenshtein:function(str1,str2){if(str1==null&&str2==null)return 0;if(str1==null)return String(str2).length;if(str2==null)return String(str1).length;str1=String(str1);str2=String(str2);var current=[],prev,value;for(var i=0;i<=str2.length;i++)for(var j=0;j<=str1.length;j++){if(i&&j)if(str1.charAt(j-1)===str2.charAt(i-1))value=prev;else value=Math.min(current[j],current[j-1],prev)+1;else value=i+j;prev=current[j];current[j]=value}return current.pop()}};_s.strip=_s.trim;_s.lstrip=_s.ltrim;_s.rstrip=_s.rtrim;_s.center=_s.lrpad;_s.rjust=_s.lpad;_s.ljust=_s.rpad;_s.contains=_s.include;_s.q=_s.quote;if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)module.exports=_s;exports._s=_s}if(typeof define==="function"&&define.amd)define("underscore.string",[],function(){return _s});root._=root._||{};root._.string=root._.str=_s}(this,String);define("ext/underscore",["underscore.string"],function(_s){var self=_;_.mixin(_s.exports());_.mixin({assert:function(outcome,description){if(!outcome){throw description||"assertion failed"}},getProperty:function(object,property){if(object&&object[property]){if(self.isFunction(object[property])){return object[property].apply(object)}return object[property]}return null},bindToMethods:function(obj){var funcs=self.functions(obj);self.each(funcs,function(f){obj[f]=self.bind(obj[f],obj)});return obj}});return _.noConflict()});define("jquery",[],function(){return jQuery});!function(a){"function"==typeof define&&define.amd?define("picker",["jquery"],a):"object"==typeof exports?module.exports=a(require("jquery")):this.Picker=a(jQuery)}(function(a){function b(f,g,i,m){function n(){return b._.node("div",b._.node("div",b._.node("div",b._.node("div",B.component.nodes(w.open),y.box),y.wrap),y.frame),y.holder,'tabindex="-1"')}function o(){z.data(g,B).addClass(y.input).val(z.data("value")?B.get("select",x.format):f.value),x.editable||z.on("focus."+w.id+" click."+w.id,function(a){a.preventDefault(),B.open()}).on("keydown."+w.id,u),e(f,{haspopup:!0,expanded:!1,readonly:!1,owns:f.id+"_root"})}function p(){e(B.$root[0],"hidden",!0)}function q(){B.$holder.on({keydown:u,"focus.toOpen":t,blur:function(){z.removeClass(y.target)},focusin:function(a){B.$root.removeClass(y.focused),a.stopPropagation()},"mousedown click":function(b){var c=b.target;c!=B.$holder[0]&&(b.stopPropagation(),"mousedown"!=b.type||a(c).is("input, select, textarea, button, option")||(b.preventDefault(),B.$holder[0].focus()))}}).on("click","[data-pick], [data-nav], [data-clear], [data-close]",function(){var b=a(this),c=b.data(),d=b.hasClass(y.navDisabled)||b.hasClass(y.disabled),e=h();e=e&&(e.type||e.href),(d||e&&!a.contains(B.$root[0],e))&&B.$holder[0].focus(),!d&&c.nav?B.set("highlight",B.component.item.highlight,{nav:c.nav}):!d&&"pick"in c?(B.set("select",c.pick),x.closeOnSelect&&B.close(!0)):c.clear?(B.clear(),x.closeOnClear&&B.close(!0)):c.close&&B.close(!0)})}function r(){var b;x.hiddenName===!0?(b=f.name,f.name=""):(b=["string"==typeof x.hiddenPrefix?x.hiddenPrefix:"","string"==typeof x.hiddenSuffix?x.hiddenSuffix:"_submit"],b=b[0]+f.name+b[1]),B._hidden=a('<input type=hidden name="'+b+'"'+(z.data("value")||f.value?' value="'+B.get("select",x.formatSubmit)+'"':"")+">")[0],z.on("change."+w.id,function(){B._hidden.value=f.value?B.get("select",x.formatSubmit):""})}function s(){v&&l?B.$holder.find("."+y.frame).one("transitionend",function(){B.$holder[0].focus()}):B.$holder[0].focus()}function t(a){a.stopPropagation(),z.addClass(y.target),B.$root.addClass(y.focused),B.open()}function u(a){var b=a.keyCode,c=/^(8|46)$/.test(b);return 27==b?(B.close(!0),!1):void((32==b||c||!w.open&&B.component.key[b])&&(a.preventDefault(),a.stopPropagation(),c?B.clear().close():B.open()))}if(!f)return b;var v=!1,w={id:f.id||"P"+Math.abs(~~(Math.random()*new Date))},x=i?a.extend(!0,{},i.defaults,m):m||{},y=a.extend({},b.klasses(),x.klass),z=a(f),A=function(){return this.start()},B=A.prototype={constructor:A,$node:z,start:function(){return w&&w.start?B:(w.methods={},w.start=!0,w.open=!1,w.type=f.type,f.autofocus=f==h(),f.readOnly=!x.editable,f.id=f.id||w.id,"text"!=f.type&&(f.type="text"),B.component=new i(B,x),B.$root=a('<div class="'+y.picker+'" id="'+f.id+'_root" />'),p(),B.$holder=a(n()).appendTo(B.$root),q(),x.formatSubmit&&r(),o(),x.containerHidden?a(x.containerHidden).append(B._hidden):z.after(B._hidden),x.container?a(x.container).append(B.$root):z.after(B.$root),B.on({start:B.component.onStart,render:B.component.onRender,stop:B.component.onStop,open:B.component.onOpen,close:B.component.onClose,set:B.component.onSet}).on({start:x.onStart,render:x.onRender,stop:x.onStop,open:x.onOpen,close:x.onClose,set:x.onSet}),v=c(B.$holder[0]),f.autofocus&&B.open(),B.trigger("start").trigger("render"))},render:function(a){return a?(B.$holder=n(),B.$root.html(B.$holder)):B.$root.find("."+y.box).html(B.component.nodes(w.open)),B.trigger("render")},stop:function(){return w.start?(B.close(),B._hidden&&B._hidden.parentNode.removeChild(B._hidden),B.$root.remove(),z.removeClass(y.input).removeData(g),setTimeout(function(){z.off("."+w.id)},0),f.type=w.type,f.readOnly=!1,B.trigger("stop"),w.methods={},w.start=!1,B):B},open:function(c){return w.open?B:(z.addClass(y.active),e(f,"expanded",!0),setTimeout(function(){B.$root.addClass(y.opened),e(B.$root[0],"hidden",!1)},0),c!==!1&&(w.open=!0,v&&k.css("overflow","hidden").css("padding-right","+="+d()),s(),j.on("click."+w.id+" focusin."+w.id,function(a){var b=a.target;b!=f&&b!=document&&3!=a.which&&B.close(b===B.$holder[0])}).on("keydown."+w.id,function(c){var d=c.keyCode,e=B.component.key[d],f=c.target;27==d?B.close(!0):f!=B.$holder[0]||!e&&13!=d?a.contains(B.$root[0],f)&&13==d&&(c.preventDefault(),f.click()):(c.preventDefault(),e?b._.trigger(B.component.key.go,B,[b._.trigger(e)]):B.$root.find("."+y.highlighted).hasClass(y.disabled)||(B.set("select",B.component.item.highlight),x.closeOnSelect&&B.close(!0)))})),B.trigger("open"))},close:function(a){return a&&(x.editable?f.focus():(B.$holder.off("focus.toOpen").focus(),setTimeout(function(){B.$holder.on("focus.toOpen",t)},0))),z.removeClass(y.active),e(f,"expanded",!1),setTimeout(function(){B.$root.removeClass(y.opened+" "+y.focused),e(B.$root[0],"hidden",!0)},0),w.open?(w.open=!1,v&&k.css("overflow","").css("padding-right","-="+d()),j.off("."+w.id),B.trigger("close")):B},clear:function(a){return B.set("clear",null,a)},set:function(b,c,d){var e,f,g=a.isPlainObject(b),h=g?b:{};if(d=g&&a.isPlainObject(c)?c:d||{},b){g||(h[b]=c);for(e in h)f=h[e],e in B.component.item&&(void 0===f&&(f=null),B.component.set(e,f,d)),("select"==e||"clear"==e)&&z.val("clear"==e?"":B.get(e,x.format)).trigger("change");B.render()}return d.muted?B:B.trigger("set",h)},get:function(a,c){if(a=a||"value",null!=w[a])return w[a];if("valueSubmit"==a){if(B._hidden)return B._hidden.value;a="value"}if("value"==a)return f.value;if(a in B.component.item){if("string"==typeof c){var d=B.component.get(a);return d?b._.trigger(B.component.formats.toString,B.component,[c,d]):""}return B.component.get(a)}},on:function(b,c,d){var e,f,g=a.isPlainObject(b),h=g?b:{};if(b){g||(h[b]=c);for(e in h)f=h[e],d&&(e="_"+e),w.methods[e]=w.methods[e]||[],w.methods[e].push(f)}return B},off:function(){var a,b,c=arguments;for(a=0,namesCount=c.length;a<namesCount;a+=1)b=c[a],b in w.methods&&delete w.methods[b];return B},trigger:function(a,c){var d=function(a){var d=w.methods[a];d&&d.map(function(a){b._.trigger(a,B,[c])})};return d("_"+a),d(a),B}};return new A}function c(a){var b,c="position";return a.currentStyle?b=a.currentStyle[c]:window.getComputedStyle&&(b=getComputedStyle(a)[c]),"fixed"==b}function d(){if(k.height()<=i.height())return 0;var b=a('<div style="visibility:hidden;width:100px" />').appendTo("body"),c=b[0].offsetWidth;b.css("overflow","scroll");var d=a('<div style="width:100%" />').appendTo(b),e=d[0].offsetWidth;return b.remove(),c-e}function e(b,c,d){if(a.isPlainObject(c))for(var e in c)f(b,e,c[e]);else f(b,c,d)}function f(a,b,c){a.setAttribute(("role"==b?"":"aria-")+b,c)}function g(b,c){a.isPlainObject(b)||(b={attribute:c}),c="";for(var d in b){var e=("role"==d?"":"aria-")+d,f=b[d];c+=null==f?"":e+'="'+b[d]+'"'}return c}function h(){try{return document.activeElement}catch(a){}}var i=a(window),j=a(document),k=a(document.documentElement),l=null!=document.body.style.transition;return b.klasses=function(a){return a=a||"picker",{picker:a,opened:a+"--opened",focused:a+"--focused",input:a+"__input",active:a+"__input--active",target:a+"__input--target",holder:a+"__holder",frame:a+"__frame",wrap:a+"__wrap",box:a+"__box"}},b._={group:function(a){for(var c,d="",e=b._.trigger(a.min,a);e<=b._.trigger(a.max,a,[e]);e+=a.i)c=b._.trigger(a.item,a,[e]),d+=b._.node(a.node,c[0],c[1],c[2]);return d},node:function(b,c,d,e){return c?(c=a.isArray(c)?c.join(""):c,d=d?' class="'+d+'"':"",e=e?" "+e:"","<"+b+d+e+">"+c+"</"+b+">"):""},lead:function(a){return(10>a?"0":"")+a},trigger:function(a,b,c){return"function"==typeof a?a.apply(b,c||[]):a},digits:function(a){return/\d/.test(a[1])?2:1},isDate:function(a){return{}.toString.call(a).indexOf("Date")>-1&&this.isInteger(a.getDate())},isInteger:function(a){return{}.toString.call(a).indexOf("Number")>-1&&a%1===0},ariaAttr:g},b.extend=function(c,d){a.fn[c]=function(e,f){var g=this.data(c);return"picker"==e?g:g&&"string"==typeof e?b._.trigger(g[e],g,[f]):this.each(function(){var f=a(this);f.data(c)||new b(this,c,d,e)})},a.fn[c].defaults=d.defaults},b});!function(a){"function"==typeof define&&define.amd?define("lib/pickadate.min",["picker","jquery"],a):"object"==typeof exports?module.exports=a(require("./picker.js"),require("jquery")):a(Picker,jQuery)}(function(a,b){function c(a,b){var c=this,d=a.$node[0],e=d.value,f=a.$node.data("value"),g=f||e,h=f?b.formatSubmit:b.format,i=function(){return d.currentStyle?"rtl"==d.currentStyle.direction:"rtl"==getComputedStyle(a.$root[0]).direction};c.settings=b,c.$node=a.$node,c.queue={min:"measure create",max:"measure create",now:"now create",select:"parse create validate",highlight:"parse navigate create validate",view:"parse create validate viewset",disable:"deactivate",enable:"activate"},c.item={},c.item.clear=null,c.item.disable=(b.disable||[]).slice(0),c.item.enable=-function(a){return a[0]===!0?a.shift():-1}(c.item.disable),c.set("min",b.min).set("max",b.max).set("now"),g?c.set("select",g,{format:h,defaultValue:!0}):c.set("select",null).set("highlight",c.item.now),c.key={40:7,38:-7,39:function(){return i()?-1:1},37:function(){return i()?1:-1},go:function(a){var b=c.item.highlight,d=new Date(b.year,b.month,b.date+a);c.set("highlight",d,{interval:a}),this.render()}},a.on("render",function(){a.$root.find("."+b.klass.selectMonth).on("change",function(){var c=this.value;c&&(a.set("highlight",[a.get("view").year,c,a.get("highlight").date]),a.$root.find("."+b.klass.selectMonth).trigger("focus"))}),a.$root.find("."+b.klass.selectYear).on("change",function(){var c=this.value;c&&(a.set("highlight",[c,a.get("view").month,a.get("highlight").date]),a.$root.find("."+b.klass.selectYear).trigger("focus"))})},1).on("open",function(){var d="";
    6 c.disabled(c.get("now"))&&(d=":not(."+b.klass.buttonToday+")"),a.$root.find("button"+d+", select").attr("disabled",!1)},1).on("close",function(){a.$root.find("button, select").attr("disabled",!0)},1)}var d=7,e=6,f=a._;c.prototype.set=function(a,b,c){var d=this,e=d.item;return null===b?("clear"==a&&(a="select"),e[a]=b,d):(e["enable"==a?"disable":"flip"==a?"enable":a]=d.queue[a].split(" ").map(function(e){return b=d[e](a,b,c)}).pop(),"select"==a?d.set("highlight",e.select,c):"highlight"==a?d.set("view",e.highlight,c):a.match(/^(flip|min|max|disable|enable)$/)&&(e.select&&d.disabled(e.select)&&d.set("select",e.select,c),e.highlight&&d.disabled(e.highlight)&&d.set("highlight",e.highlight,c)),d)},c.prototype.get=function(a){return this.item[a]},c.prototype.create=function(a,c,d){var e,g=this;return c=void 0===c?a:c,c==-1/0||1/0==c?e=c:b.isPlainObject(c)&&f.isInteger(c.pick)?c=c.obj:b.isArray(c)?(c=new Date(c[0],c[1],c[2]),c=f.isDate(c)?c:g.create().obj):c=f.isInteger(c)||f.isDate(c)?g.normalize(new Date(c),d):g.now(a,c,d),{year:e||c.getFullYear(),month:e||c.getMonth(),date:e||c.getDate(),day:e||c.getDay(),obj:e||c,pick:e||c.getTime()}},c.prototype.createRange=function(a,c){var d=this,e=function(a){return a===!0||b.isArray(a)||f.isDate(a)?d.create(a):a};return f.isInteger(a)||(a=e(a)),f.isInteger(c)||(c=e(c)),f.isInteger(a)&&b.isPlainObject(c)?a=[c.year,c.month,c.date+a]:f.isInteger(c)&&b.isPlainObject(a)&&(c=[a.year,a.month,a.date+c]),{from:e(a),to:e(c)}},c.prototype.withinRange=function(a,b){return a=this.createRange(a.from,a.to),b.pick>=a.from.pick&&b.pick<=a.to.pick},c.prototype.overlapRanges=function(a,b){var c=this;return a=c.createRange(a.from,a.to),b=c.createRange(b.from,b.to),c.withinRange(a,b.from)||c.withinRange(a,b.to)||c.withinRange(b,a.from)||c.withinRange(b,a.to)},c.prototype.now=function(a,b,c){return b=new Date,c&&c.rel&&b.setDate(b.getDate()+c.rel),this.normalize(b,c)},c.prototype.navigate=function(a,c,d){var e,f,g,h,i=b.isArray(c),j=b.isPlainObject(c),k=this.item.view;if(i||j){for(j?(f=c.year,g=c.month,h=c.date):(f=+c[0],g=+c[1],h=+c[2]),d&&d.nav&&k&&k.month!==g&&(f=k.year,g=k.month),e=new Date(f,g+(d&&d.nav?d.nav:0),1),f=e.getFullYear(),g=e.getMonth();new Date(f,g,h).getMonth()!==g;)h-=1;c=[f,g,h]}return c},c.prototype.normalize=function(a){return a.setHours(0,0,0,0),a},c.prototype.measure=function(a,b){var c=this;return b?"string"==typeof b?b=c.parse(a,b):f.isInteger(b)&&(b=c.now(a,b,{rel:b})):b="min"==a?-1/0:1/0,b},c.prototype.viewset=function(a,b){return this.create([b.year,b.month,1])},c.prototype.validate=function(a,c,d){var e,g,h,i,j=this,k=c,l=d&&d.interval?d.interval:1,m=-1===j.item.enable,n=j.item.min,o=j.item.max,p=m&&j.item.disable.filter(function(a){if(b.isArray(a)){var d=j.create(a).pick;d<c.pick?e=!0:d>c.pick&&(g=!0)}return f.isInteger(a)}).length;if((!d||!d.nav&&!d.defaultValue)&&(!m&&j.disabled(c)||m&&j.disabled(c)&&(p||e||g)||!m&&(c.pick<=n.pick||c.pick>=o.pick)))for(m&&!p&&(!g&&l>0||!e&&0>l)&&(l*=-1);j.disabled(c)&&(Math.abs(l)>1&&(c.month<k.month||c.month>k.month)&&(c=k,l=l>0?1:-1),c.pick<=n.pick?(h=!0,l=1,c=j.create([n.year,n.month,n.date+(c.pick===n.pick?0:-1)])):c.pick>=o.pick&&(i=!0,l=-1,c=j.create([o.year,o.month,o.date+(c.pick===o.pick?0:1)])),!h||!i);)c=j.create([c.year,c.month,c.date+l]);return c},c.prototype.disabled=function(a){var c=this,d=c.item.disable.filter(function(d){return f.isInteger(d)?a.day===(c.settings.firstDay?d:d-1)%7:b.isArray(d)||f.isDate(d)?a.pick===c.create(d).pick:b.isPlainObject(d)?c.withinRange(d,a):void 0});return d=d.length&&!d.filter(function(a){return b.isArray(a)&&"inverted"==a[3]||b.isPlainObject(a)&&a.inverted}).length,-1===c.item.enable?!d:d||a.pick<c.item.min.pick||a.pick>c.item.max.pick},c.prototype.parse=function(a,b,c){var d=this,e={};return b&&"string"==typeof b?(c&&c.format||(c=c||{},c.format=d.settings.format),d.formats.toArray(c.format).map(function(a){var c=d.formats[a],g=c?f.trigger(c,d,[b,e]):a.replace(/^!/,"").length;c&&(e[a]=b.substr(0,g)),b=b.substr(g)}),[e.yyyy||e.yy,+(e.mm||e.m)-1,e.dd||e.d]):b},c.prototype.formats=function(){function a(a,b,c){var d=a.match(/[^\x00-\x7F]+|\w+/)[0];return c.mm||c.m||(c.m=b.indexOf(d)+1),d.length}function b(a){return a.match(/\w+/)[0].length}return{d:function(a,b){return a?f.digits(a):b.date},dd:function(a,b){return a?2:f.lead(b.date)},ddd:function(a,c){return a?b(a):this.settings.weekdaysShort[c.day]},dddd:function(a,c){return a?b(a):this.settings.weekdaysFull[c.day]},m:function(a,b){return a?f.digits(a):b.month+1},mm:function(a,b){return a?2:f.lead(b.month+1)},mmm:function(b,c){var d=this.settings.monthsShort;return b?a(b,d,c):d[c.month]},mmmm:function(b,c){var d=this.settings.monthsFull;return b?a(b,d,c):d[c.month]},yy:function(a,b){return a?2:(""+b.year).slice(2)},yyyy:function(a,b){return a?4:b.year},toArray:function(a){return a.split(/(d{1,4}|m{1,4}|y{4}|yy|!.)/g)},toString:function(a,b){var c=this;return c.formats.toArray(a).map(function(a){return f.trigger(c.formats[a],c,[0,b])||a.replace(/^!/,"")}).join("")}}}(),c.prototype.isDateExact=function(a,c){var d=this;return f.isInteger(a)&&f.isInteger(c)||"boolean"==typeof a&&"boolean"==typeof c?a===c:(f.isDate(a)||b.isArray(a))&&(f.isDate(c)||b.isArray(c))?d.create(a).pick===d.create(c).pick:b.isPlainObject(a)&&b.isPlainObject(c)?d.isDateExact(a.from,c.from)&&d.isDateExact(a.to,c.to):!1},c.prototype.isDateOverlap=function(a,c){var d=this,e=d.settings.firstDay?1:0;return f.isInteger(a)&&(f.isDate(c)||b.isArray(c))?(a=a%7+e,a===d.create(c).day+1):f.isInteger(c)&&(f.isDate(a)||b.isArray(a))?(c=c%7+e,c===d.create(a).day+1):b.isPlainObject(a)&&b.isPlainObject(c)?d.overlapRanges(a,c):!1},c.prototype.flipEnable=function(a){var b=this.item;b.enable=a||(-1==b.enable?1:-1)},c.prototype.deactivate=function(a,c){var d=this,e=d.item.disable.slice(0);return"flip"==c?d.flipEnable():c===!1?(d.flipEnable(1),e=[]):c===!0?(d.flipEnable(-1),e=[]):c.map(function(a){for(var c,g=0;g<e.length;g+=1)if(d.isDateExact(a,e[g])){c=!0;break}c||(f.isInteger(a)||f.isDate(a)||b.isArray(a)||b.isPlainObject(a)&&a.from&&a.to)&&e.push(a)}),e},c.prototype.activate=function(a,c){var d=this,e=d.item.disable,g=e.length;return"flip"==c?d.flipEnable():c===!0?(d.flipEnable(1),e=[]):c===!1?(d.flipEnable(-1),e=[]):c.map(function(a){var c,h,i,j;for(i=0;g>i;i+=1){if(h=e[i],d.isDateExact(h,a)){c=e[i]=null,j=!0;break}if(d.isDateOverlap(h,a)){b.isPlainObject(a)?(a.inverted=!0,c=a):b.isArray(a)?(c=a,c[3]||c.push("inverted")):f.isDate(a)&&(c=[a.getFullYear(),a.getMonth(),a.getDate(),"inverted"]);break}}if(c)for(i=0;g>i;i+=1)if(d.isDateExact(e[i],a)){e[i]=null;break}if(j)for(i=0;g>i;i+=1)if(d.isDateOverlap(e[i],a)){e[i]=null;break}c&&e.push(c)}),e.filter(function(a){return null!=a})},c.prototype.nodes=function(a){var b=this,c=b.settings,g=b.item,h=g.now,i=g.select,j=g.highlight,k=g.view,l=g.disable,m=g.min,n=g.max,o=function(a,b){return c.firstDay&&(a.push(a.shift()),b.push(b.shift())),f.node("thead",f.node("tr",f.group({min:0,max:d-1,i:1,node:"th",item:function(d){return[a[d],c.klass.weekdays,'scope=col title="'+b[d]+'"']}})))}((c.showWeekdaysFull?c.weekdaysFull:c.weekdaysShort).slice(0),c.weekdaysFull.slice(0)),p=function(a){return f.node("div"," ",c.klass["nav"+(a?"Next":"Prev")]+(a&&k.year>=n.year&&k.month>=n.month||!a&&k.year<=m.year&&k.month<=m.month?" "+c.klass.navDisabled:""),"data-nav="+(a||-1)+" "+f.ariaAttr({role:"button",controls:b.$node[0].id+"_table"})+' title="'+(a?c.labelMonthNext:c.labelMonthPrev)+'"')},q=function(){var d=c.showMonthsShort?c.monthsShort:c.monthsFull;return c.selectMonths?f.node("select",f.group({min:0,max:11,i:1,node:"option",item:function(a){return[d[a],0,"value="+a+(k.month==a?" selected":"")+(k.year==m.year&&a<m.month||k.year==n.year&&a>n.month?" disabled":"")]}}),c.klass.selectMonth,(a?"":"disabled")+" "+f.ariaAttr({controls:b.$node[0].id+"_table"})+' title="'+c.labelMonthSelect+'"'):f.node("div",d[k.month],c.klass.month)},r=function(){var d=k.year,e=c.selectYears===!0?5:~~(c.selectYears/2);if(e){var g=m.year,h=n.year,i=d-e,j=d+e;if(g>i&&(j+=g-i,i=g),j>h){var l=i-g,o=j-h;i-=l>o?o:l,j=h}return f.node("select",f.group({min:i,max:j,i:1,node:"option",item:function(a){return[a,0,"value="+a+(d==a?" selected":"")]}}),c.klass.selectYear,(a?"":"disabled")+" "+f.ariaAttr({controls:b.$node[0].id+"_table"})+' title="'+c.labelYearSelect+'"')}return f.node("div",d,c.klass.year)};return f.node("div",(c.selectYears?r()+q():q()+r())+p()+p(1),c.klass.header)+f.node("table",o+f.node("tbody",f.group({min:0,max:e-1,i:1,node:"tr",item:function(a){var e=c.firstDay&&0===b.create([k.year,k.month,1]).day?-7:0;return[f.group({min:d*a-k.day+e+1,max:function(){return this.min+d-1},i:1,node:"td",item:function(a){a=b.create([k.year,k.month,a+(c.firstDay?1:0)]);var d=i&&i.pick==a.pick,e=j&&j.pick==a.pick,g=l&&b.disabled(a)||a.pick<m.pick||a.pick>n.pick,o=f.trigger(b.formats.toString,b,[c.format,a]);return[f.node("div",a.date,function(b){return b.push(k.month==a.month?c.klass.infocus:c.klass.outfocus),h.pick==a.pick&&b.push(c.klass.now),d&&b.push(c.klass.selected),e&&b.push(c.klass.highlighted),g&&b.push(c.klass.disabled),b.join(" ")}([c.klass.day]),"data-pick="+a.pick+" "+f.ariaAttr({role:"gridcell",label:o,selected:d&&b.$node.val()===o?!0:null,activedescendant:e?!0:null,disabled:g?!0:null})),"",f.ariaAttr({role:"presentation"})]}})]}})),c.klass.table,'id="'+b.$node[0].id+'_table" '+f.ariaAttr({role:"grid",controls:b.$node[0].id,readonly:!0}))+f.node("div",f.node("button",c.today,c.klass.buttonToday,"type=button data-pick="+h.pick+(a&&!b.disabled(h)?"":" disabled")+" "+f.ariaAttr({controls:b.$node[0].id}))+f.node("button",c.clear,c.klass.buttonClear,"type=button data-clear=1"+(a?"":" disabled")+" "+f.ariaAttr({controls:b.$node[0].id}))+f.node("button",c.close,c.klass.buttonClose,"type=button data-close=true "+(a?"":" disabled")+" "+f.ariaAttr({controls:b.$node[0].id})),c.klass.footer)},c.defaults=function(a){return{labelMonthNext:"Next month",labelMonthPrev:"Previous month",labelMonthSelect:"Select a month",labelYearSelect:"Select a year",monthsFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],weekdaysFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],weekdaysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],today:"Today",clear:"Clear",close:"Close",closeOnSelect:!0,closeOnClear:!0,format:"d mmmm, yyyy",klass:{table:a+"table",header:a+"header",navPrev:a+"nav--prev",navNext:a+"nav--next",navDisabled:a+"nav--disabled",month:a+"month",year:a+"year",selectMonth:a+"select--month",selectYear:a+"select--year",weekdays:a+"weekday",day:a+"day",disabled:a+"day--disabled",selected:a+"day--selected",highlighted:a+"day--highlighted",now:a+"day--today",infocus:a+"day--infocus",outfocus:a+"day--outfocus",footer:a+"footer",buttonClear:a+"button--clear",buttonToday:a+"button--today",buttonClose:a+"button--close"}}}(a.klasses().picker+"__"),a.extend("pickadate",c)});define("native",["ext/underscore","lib/pickadate.min"],function(_,pickadate){var $=jQuery;var $root=$("#clinked-portal");var _native={popupPreview:true,searchBarAdjust:0,navigate:function(hash){Backbone.history.loadUrl(hash);window.localStorage.setItem("native_location",hash)},height:function(){return $root.height()},width:function(){return $root.width()},start:function(callback){var options=_.extend({location:window.localStorage.getItem("native_location")},$root.data());callback(options)},online:function(callback){callback(true)},preview:function(link){$(".loader").addClass("hidden");var $iframe=$("<iframe>").css({margin:"0 auto",display:"block",height:"600px"}).attr("src",link);$(".modal-dialog").css("width","800px");$(".modal-title").html("Document Preview");$(".modal-body").html($iframe);$(".modal").modal("show");$(".modal-dialog").css("margin-left",function(){return($(window).width()-$(this).width())/2})},setHeader:function(options){var message=_.pick(options,"title","nosearch");if(options.back){message.back=_.pick(options.back,"text","link")}message.actions=[];_.each(options.actions,function(action){message.actions.push(_.pick(action,"text","icon","link","target"))});handleHeader(message)},list:true,datepicker:function($el){$(".date",$el).pickadate({format:"dd mmm, yyyy",today:"",klass:{buttonClear:"btn",buttonClose:"btn"},onSet:function(context){var $dueTime=$(".time",$el);if(context.select){$dueTime.attr("disabled",false)}else{$dueTime.attr("disabled",true).val("")}}})}};var createLink=function(data){var a=$("<a>").attr("href","javascript:void(0);").data("target",data);if(data.icon){a.addClass("glyphicon glyphicon-"+data.icon).attr("title",data.text)}else{a.html(data.text)}return a};var $header=$(">.header",$root).removeClass("hidden").on("click","a",function(e){e.preventDefault();var data=$(this).data("target");if(data.target){$(data.target).trigger("action")}else if(data.link){_native.navigate(data.link)}else{$buttons.addClass("hidden");$search.removeClass("hidden").focus()}});var $buttons=$("span",$header);var $search=$("input",$header).keyup(function(e){if(e.keyCode==27){$buttons.removeClass("hidden");$search.addClass("hidden")}else if(e.keyCode==13){_native.navigate("#search/"+encodeURIComponent($search.val()));$buttons.removeClass("hidden");$search.addClass("hidden").val("")}});var handleHeader=function(options){var $left=$(".left",$header).empty();if(options.back){createLink(options.back).appendTo($left)}$left.append("<strong>"+options.title+"</strong>");var $action=$(".right",$header).empty();_.each(options.actions,function(action){createLink(action).appendTo($action)});if(!options.nosearch){createLink({text:"Search",icon:"search"}).appendTo($action)}};$root.on("click","a",function(e){if(this.href!="javascript:void(0)"&&!_.isBlank(this.hash)){e.preventDefault();_native.navigate(this.hash)}});$(">.wrapper",$root).data("marginals",1).height(_native.height()-44);return _native});define("messages",["ext/underscore"],function(_){var messages={m_last_updated:"Last updated",m_said:"said",m_comments:"Comments",m_comment:"Comment",m_share:"Share",m_shares:"Shared With",m_share_contact:"Share With Contact",m_new:"New",m_reply:"Reply",m_back:"Back",m_cancel:"Cancel",m_file:"File",m_page:"Note",m_discussion:"Discussion",m_event:"Event",m_task:"Task",m_edit:"Edit",m_post:"Post",m_save:"Save",m_preview:"Preview",m_download:"Download",m_search:"Search",m_on:"On",m_by:"by",m_all_day:"All day",m_to:"to",m_at:"at",m_version:"Version",m_size:"Size",m_today:"Today",m_tomorrow:"Tomorrow",m_assign:"Assign",m_mention:"Mention",m_mention_title:"Select A Person",m_make_comment:"Make A Comment",m_create_reply:"Create A Reply",m_create_discussion:"Create A Discussion",m_discussion_topic:"Enter Discussion Topic",m_discussion_first:"Enter First Comment",m_create_task:"Create A Task",m_update_task:"Update Task",m_task_title:"Enter Task Title",m_task_description:"Enter Task Description",m_task_duedate:"Select Due Date and Time, if applicable",m_task_status_NOT_STARTED:"Not Started",m_task_status_IN_PROGRESS:"In Progress",m_task_status_DEFERRED:"Deferred",m_task_status_WAITING:"Waiting",m_task_status_COMPLETED:"Complete",m_create_event:"Create An Event",m_update_event:"Update Event",m_event_title:"Enter Event Title",m_event_location:"Enter Event Location",m_event_startdate:"Select Start Date and Time, if applicable",m_event_enddate:"Select End Date and Time, if applicable",m_event_description:"Enter Event Description",m_actions_filter:"Filter",m_actions_sort:"Sort",m_actions_upload:"Upload",m_btn_context:"Groups",m_btn_updates:"Activity",m_btn_files:"Files",m_btn_notes:"Notes",m_btn_discussions:"Disc..",m_btn_events:"Events",m_btn_tasks:"Tasks",m_context_select_header:"Select group or account",m_context_signout:"Sign out",m_context_dashboard:"Dashboard",m_context_personal:"Personal",m_page_loading:"Loading..",m_updates_nothing:"Nothing yet..",m_files_nothing:"No files",m_notes_nothing:"No Notes",m_discussions_nothing:"No Discussions",m_events_nothing:"No Events",m_tasks_nothing:"No Tasks",m_comments_nothing:"No Comments",m_share_tokens_nothing:"Not Shared",m_share_input:"Start typing the email or name of your contact",m_email_input_error:"This is not a valid email address",m_search_nothing:"No Results",m_search_suggestions:"Did you mean",m_type_here:"Start typing here",m_file_uploader:"Uploaded by",m_file_preview_waiting:"Preview Generating ..",m_file_preview_failed:"No Preview Available",m_file_upload_header:"Upload A File",m_file_upload_failure:"Failed",m_file_upload_success:"Complete!",m_file_upload_add:"Add Files...",m_file_upload_start:"Start Upload",m_file_upload_cancel:"Cancel",m_file_upload_upload:"Upload",m_file_upload_retry:"Retry",m_file_upload_stop:"Stop",m_file_upload_remove:"Remove",m_file_native_header:"Select A File",m_file_native_failure:"There has been an error. Click to retry.",m_file_native_success:" has been uploaded",m_no_groups:"You do not have any groups",m_actions_sort_header:"Choose Sorting Option",m_actions_sort_latest:"Sort by most recent",m_actions_sort_name:"Sort by name",m_update_unknown:"Unknown Message",m_tasks_actions_header:"Choose Task Filter",m_tasks_actions_tbc:"Uncompleted",m_tasks_actions_all:"All Tasks",m_tasks_overdue:"Overdue",m_tasks_no_due_date:"No due date",m_tasks_requested_by:"Requested by",m_signin_title:"Sign in to Clinked",m_signin_domain:"Private Cloud Users Click Here",m_signin_username:"Enter username or email",m_signin_password:"Enter password",m_signin_signin:"Sign in",m_signin_linkedin:"Sign in using LinkedIn",m_signin_google:"Sign in using Google",m_signin_forgotten:"Forgotten Password?",m_signin_invalid:"Invalid username or password. Please try again.",m_signup_header:"Sign up to Clinked",m_signup_signup:"Sign up",m_reset_header:"Reset your Password",m_reset_reset:"Reset",m_input_signup:"Sign up",m_input_name:"Enter full name",m_input_error_name:"Please provide your full name",m_input_username:"Enter username",m_input_error_username:"Provide username",m_input_error_taken:"Username is taken, please choose again",m_input_password:"Enter password",m_input_error_password:"Provide password",m_input_error_minimum_6:"Minimum password length is 6 characters",m_input_confirm:"Re-enter password",m_input_error_mismatch:"Passwords do not match",m_input_error_confirm:"Confirm your password",m_input_telephone:"Enter phone number",m_input_organisation:"Enter organisation name",m_error_title:"Error",m_error_unexpected:"An unexpected error has occurred.",m_error_not_found:"The requested resource cannot be found.",m_error_dashboard:"Go To Dashboard",m_error_retry:"Retry",m_error_network:"Check your connection and try again.",m_error_invite:"This invitation has not been recognised.",m_error_startdate:"A start date must be given.",m_error_enddate:"An end date must be given.",m_error_time:"The time should be between 00:00 and 23:59.",m_error_date_range:'The date must be after "{0}"',m_domain_title:"Change Domain",m_domain_value:"Enter new domain",m_domain_change:"Change",m_domain_reset:"Reset",m_forgotten_title:"Forgotten Password Request",m_forgotten_email:"Please enter your email address",m_forgotten_request:"Request",m_forgotten_request_sent:"Password reset instructions have been sent to your email address.",m_forgotten_request_fail:"Sorry, there is no account registered with that email address.",m_list_pull_to_refresh:"Pull and release to refresh",m_event_location:"Location",m_event_places:"Places Taken",m_event_of:"out of",m_event_DECLINE:"Not attending",m_event_MAYBE:"Maybe attending",m_event_ACCEPT:"Attending",m_task_due:"Due",m_task_no_due:"No due date",m_task_progress:"Progress",m_task_REJECT:"Reject",m_task_ACCEPT:"Accept",m_request_event_NONE:"Awaiting reply",m_request_event_DECLINE:"Not attending",m_request_event_MAYBE:"Maybe attending",m_request_event_ACCEPT:"Attending",m_request_task_NONE:"Awaiting reply",m_request_task_REJECT:"Rejected",m_request_task_ACCEPT:"Accepted",m_message_placeholder:"Enter message","update.organisation.create":"{0} created account {1}","update.organisation.disable":"{0} disabled account {1}","update.organisation.enabled":"{0} enabled account {1}","update.user.private":"{0} said","update.user.profile":"{0} said to {4}","update.organisation.private":"{0} in {1} said","update.organisation.join":"{0} joined {1}","update.space.private":"{0} in {2} said","update.following.start":"{0} started following {3} in {2}","update.following.stop":"{0} stopped following {3} in {2}","update.discussion.create":"{0} created new discussion {3} in {2}","update.discussion.update":"{0} updated discussion {3} in {2}","update.discussion.createreply":"{0} replied to discussion {3} in {2}","update.space.create":"{0} created a new group {2}","update.space.join":"{0} joined {2} group","update.trash.remove":"{0} deleted group {2}","update.trash.restore":"{0} restored group {2}","update.trash.delete":"{0} deleted group {2} from {1} trash","update.filestore.create":"{0} uploaded file {3} in {2}","update.filestore.update":"{0} updated file {3} in {2}","update.filestore.folder":"{0} created folder {3} in {2}","update.filestore.rename":'{0} renamed folder "{5}" to {3} in {2}',"update.filestore.move":'{0} moved {3} to "{5}" in {2}',"update.filestore.copy":'{0} copied {3} to "{5}" in {2}',"update.filestore.approval.accept":"{0} approved file {3} in {2}","update.filestore.approval.reject":"{0} rejected file {3} in {2} ","update.event.create":"{0} created event {3} in {2}","update.event.createandassign":"{0} created event {3} in {2}","update.event.update":"{0} updated event {3} in {2}","update.event.updateandassign":"{0} updated event {3} in {2}","update.task.create":"{0} created task {3} in {2}","update.task.createandassign":"{0} created task {3} in {2}","update.task.update":"{0} updated task {3} in {2}","update.task.updateandassign":"{0} updated task {3} in {2}","update.task.complete":"{0} completed task {3} in {2}","update.task.reopen":"{0} marked task {3} as incomplete in {2}","update.attachment.create":"{0} attached file {5} to {3} in {2}","update.attachment.update":"{0} updated attachment {5} in {3}","update.comment.create":"{0} commented on {3} in {2}","update.comment.delete":"{0} deleted comment from {3} in {2}","update.comment.reply":"{0} replied on {3} in {2}","update.page.create":"{0} created new page {3} in {2}","update.page.update":"{0} updated page {3} in {2}","update.page.restore":"{0} restored page {3} version {5} in {2}","update.page.renameandupdate":"{0} moved page {5} to {3} in {2}","update.space.trash.filerecord.create":"{0} deleted file {3} in {2}","update.space.trash.filerecord.attemptRestore":"{0} restored file {3} in {2}","update.space.trash.filerecord.delete":"{0} permanently deleted file {3} from {2} trash","update.space.trash.page.create":"{0} deleted page {3} in {2}","update.space.trash.page.attemptRestore":"{0} restored page {3} in {2}","update.space.trash.page.delete":"{0} permanently deleted page {3} from {2} trash","update.space.trash.discussion.create":"{0} deleted discussion {3} in {2}","update.space.trash.discussion.attemptRestore":"{0} restored discussion {3} in {2}","update.space.trash.discussion.delete":"{0} permanently deleted discussion {3} from {2} trash","update.space.trash.event.create":"{0} deleted event {3} in {2}","update.space.trash.event.attemptRestore":"{0} restored event {3} in {2}","update.space.trash.event.delete":"{0} permanently deleted event {3} from {2} trash","update.space.trash.task.create":"{0} deleted task {3} in {2}","update.space.trash.task.attemptRestore":"{0} restored task {3} in {2}","update.space.trash.task.delete":"{0} permanently deleted task {3} from {2} trash","update.space.rename":"{0} renamed group {5} to {2}","update.space.move":"{0} moved group {2} from {3}","update.space.remove":"{0} removed group {2}","update.space.restore":"{0} restored group {2} from trash","update.attachment.create.notify":"{0} attached the file {2} to {1} ","update.attachment.update.notify":"{0} updated the attachment {2} to {1}","update.discussion.createreply.notify":"{0} replied to discussion {1}","update.event.update.notify":"{0} edited the event {1}","update.event.updateandassign.notify":"{0} edited the event {1}","update.filestore.update.notify":"{0} edited the file {1}","update.filestore.folder.notify":"{0} created folder {1}","update.filestore.create.notify":"{0} created a new file {1}","update.page.update.notify":"{0} changed the page {1} ","update.page.renameandupdate.notify":"{0} changed the page {1}","update.space.trash.discussion.create.notify":"{0} deleted the discussion {1}","update.space.trash.event.create.notify":"{0} deleted the event {1}","update.space.trash.filerecord.create.notify":"{0} deleted the file {1}","update.space.trash.page.create.notify":"{0} deleted the page {1}","update.space.trash.task.create.notify":"{0} deleted the task {1}","update.space.trash.discussion.attemptRestore.notify":"{0} restored the discussion {1}","update.space.trash.event.attemptRestore.notify":"{0} restored the event {1}","update.space.trash.filerecord.attemptRestore.notify":"{0} restored the file {1}","update.space.trash.page.attemptRestore.notify":"{0} restored the page {1}","update.space.trash.task.attemptRestore.notify":"{0} restored the task {1}","update.task.complete.notify":"{0} completed the task {1}","update.task.reopen.notify":"{0} marked the task {1} as uncompleted ","update.task.update.notify":"{0} changed the task {1}","update.task.updateandassign.notify":"{0} changed the task {1}","update.comment.create.notify":"{0} commented on {1}","update.comment.reply.notify":"{0} commented on {1}"};var regional={};regional["tr"]={"update.user.private":"{0} söyledi","update.user.profile":"{0} {4} 'e söyledi","update.organisation.private":"{0} {1}'da söyledi","update.organisation.join":"{0} {1}'e katıldı","update.space.private":"{0} {2} grubunda söyledi","update.discussion.create":"{0} {2} grubunda {3} tartışmasını yarattı","update.discussion.update":"{0} {2} grubunda {3} tartışmasını güncelledi","update.discussion.createreply":"{0} {2} grubunda {3} tartışmasına yanıt verdi","update.space.create":"{0} {2} grubunu yarattı","update.space.join":"{0} {2} grubuna katıldı","update.trash.remove":"{0} {2} grubunu sildi","update.trash.restore":"{0} {2} grubunu geri getirdi","update.trash.delete":"{0} {2} grubunu {1} 'den sildi","update.filestore.create":"{0} {2} grubuna {3} dosyasını yükledi","update.filestore.update":"{0} {2} grubuna {3} dosyasını güncelledi","update.filestore.approval.accept":"{0} {2} grubunda {3} dosyasını onayladı","update.filestore.approval.reject":"{0} {2} grubunda {3} dosyasını reddetti ","update.event.create":"{0} {2} grubunda {3} etkinliğini yarattı","update.event.createandassign":"{0} {2} grubunda {3} etkinliğini yarattı","update.event.update":"{0} {2} grubunda {3} etkinliğini güncelledi","update.event.updateandassign":"{0} {2} grubunda {3} etkinliğini güncelledi","update.task.create":"{0} {2} grubunda {3} görevini yarattı","update.task.createandassign":"{0} {2} grubunda {3} görevini yarattı","update.task.update":"{0} {2} grubunda {3} görevini güncelledi","update.task.updateandassign":"{0} {2} grubunda {3} görevini güncelledi","update.task.complete":"{0} {2} grubunda {3} görevini tamamladı","update.task.reopen":"{0} {2} grubunda {3} görevini tamamladı","update.attachment.create":"{0} {5} dosyasını {2} grubunda {3} sayfasına ekledi ","update.attachment.update":"{0} {5} dosyasını {3}'de güncelledi","update.comment.create":"{0} {2} grubunda {3} sayfasına yorum yazdı ","update.comment.reply":"{0} {2} grubunda {3} yorumunu yanıtladı","update.page.create":"{0} {2} grubunda {3} sayfasını yarattı","update.page.update":"{0} {2} grubundaki {3} sayfasını güncelledi","update.page.restore":"{0} {2} grubundaki {3} sayfasının {5}. sürümünü geri yükledi","update.page.renameandupdate":"{0} {2} grubundaki {5} sayfasını {3} olarak değiştirdi","update.space.trash.filerecord.create":"{0} {3} dosyasını {2} grubundan sildi ","update.space.trash.filerecord.attemptRestore":"{0} {3} dosyasını {2} grubuna geri getirdi ","update.space.trash.filerecord.delete":"{0} {2} grubunda {3} dosyasını çöp kutusundan kalıcı olarak sildi","update.space.trash.page.create":"{0} {2} grubunda {3} sayfasını sildi","update.space.trash.page.attemptRestore":"{0} {2} grubunda {3} sayfasını geri getirdi ","update.space.trash.page.delete":"{0} {2} grubunda {3} sayfasını çöp kutusundan kalıcı olarak sildi","update.space.trash.discussion.create":"{0} {2} grubunda {3} tartışmasını sildi","update.space.trash.discussion.attemptRestore":"{0} {2} grubunda {3} tartışmasını geri getirdi","update.space.trash.discussion.delete":"{0} {2} grubunda {3} tartışmasını çöp kutusundan kalıcı olarak sildi","update.space.trash.event.create":"{0} {2} grubunda {3} etkinliğini sildi","update.space.trash.event.attemptRestore":"{0} {2} grubunda {3} etkinliğini geri getirdi","update.space.trash.event.delete":"{0} {2} grubunda {3} etkinliğini çöp kutusundan kalıcı olarak sildi","update.space.trash.task.create":"{0} {2} grubunda {3} görevini sildi","update.space.trash.task.attemptRestore":"{0} {2} grubunda {3} görevini geri getirdi","update.space.trash.task.delete":"{0} {2} grubunda {3} görevini çöp kutusundan kalıcı olarak sildi"};regional["ru"]={"update.user.private":"{0}сказал","update.user.profile":"{0}сказал{4}","update.organisation.private":"{0}в{1} указанном","update.organisation.join":"{0}регистрация {1}","update.space.private":"{0}в{2} указанном","update.discussion.create":"создал новую дискуссию {3} в","update.discussion.update":"обновление обсуждения {3} в {2}","update.discussion.createreply":"{0} ответил на обсуждении {3} в {2}","update.space.create":"{0} создана новая группа {2}","update.space.join":"{0} присоединился к {2} группе","update.trash.remove":"{0} удален из группы {2}","update.trash.restore":"{0} восстановлено группы {2}","update.trash.delete":"{0} удален группы {2} из {1} корзины","update.filestore.create":"{0} загруженный файл {3} в {2}","update.filestore.update":"{0} обновленный файл {3} в {2}","update.filestore.approval.accept":"утвержденный файл {3} в {2}","update.filestore.approval.reject":"{0} отклонил файл {3} в {2} ","update.event.create":"{0} создано событие {3} в {2}","update.event.createandassign":"{0} создано событие {3} в {2}","update.event.update":"{0} обновленно событие {3} в {2}","update.event.updateandassign":"обновленно событие {3} в {2}","update.task.create":"{0} созданной задачи {3} в {2}","update.task.createandassign":"{0} созданной задачи {3} в {2}","update.task.update":"обновленно задачи {3} в {2}","update.task.updateandassign":"обновленно задачи {3} в {2}","update.task.complete":"выполненная задача {3} в {2}","update.task.reopen":"отмечены задачи {3}, как неполное в {2}","update.attachment.create":"{0} прикрепленный файл {5} до {3} в {2}","update.attachment.update":"{0} обновленно вложение {5} в {3}","update.comment.create":"{0} прокомментировал {3} в {2}","update.comment.reply":"{0} ответил на {3} в {2}","update.page.create":"{0} создана новая страница {3} в {2}","update.page.update":"{0} обновленна страница {3} в {2}","update.page.restore":"{0} восстановлена страница {3} версии {5} в {2}","update.page.renameandupdate":"{0} переехала страница {5} в {3} в {2}","update.space.trash.filerecord.create":"{0} удаленный файл {3} в {2}","update.space.trash.filerecord.attemptRestore":"{0} восстановленный файл {3} в {2}","update.space.trash.filerecord.delete":"{0} постоянно удаляется файл {3} из {2} корзины","update.space.trash.page.create":"{0} удаленная страница {3} в {2}","update.space.trash.page.attemptRestore":"{0} восстановлена страница {3} в {2}","update.space.trash.page.delete":"{0} удалена страница {3} из {2} корзины","update.space.trash.discussion.create":"{0} удалена страница {3} из {2} корзины","update.space.trash.discussion.attemptRestore":"{0} восстановлено обсуждение {3} в {2}","update.space.trash.discussion.delete":"{0} постоянно удалено обсуждение {3} из {2} корзины","update.space.trash.event.create":"{0} удалено событие {3} в {2}","update.space.trash.event.attemptRestore":"{0} восстановлено событие {3} в {2}","update.space.trash.event.delete":"{0} постоянно удалено событие {3} из {2} корзины","update.space.trash.task.create":"удалена задача {3} в {2}","update.space.trash.task.attemptRestore":"{0} восстановлена задача {3} в {2}","update.space.trash.task.delete":"{0} постоянно удалена задача {3} из {2} корзины"};
    7 regional["it"]={"update.attachment.create":"{0} file allegati {5} di {3} in {2}","update.attachment.create.notify":"{0} ha allegato il file {2} di {1}","update.attachment.update":"{0} aggiornato file {5} di {3}","update.attachment.update.notify":"{0} aggiornato file {5} di {2}","update.comment.create":"{0} ha commentato su {3} di {2}","update.comment.create.notify":"{0} ha commentato su {1}","update.comment.delete":"{0} cancella commenti da {3} in {2}","update.comment.reply":"{0} risposte a {3} di {2}","update.comment.reply.notify":"{0} commenti su {1}","update.discussion.create":"{0} ha creato una nuova discussion {3} in {2}","update.discussion.createreply":"{0} ha risposto alla discussion {3} in {2}","update.discussion.createreply.notify":"{0} ha risposto alla discussion {1}","update.discussion.update":"{0} ha aggiornato la discussion {3} di {2}","update.event.create":"{0} ha creato l` event {3} in {2}","update.event.createandassign":"{0} {0} ha creato l` event {3} in {2}","update.event.update":"{0} event aggiornato {3} in {2}","update.event.update.notify":"{0} event modificati {1}","update.event.updateandassign":"{0} event aggiornato {3} in {2}","update.event.updateandassign.notify":"{0} event modificati {1}","update.filestore.approval.accept":"{0} file approvati {3} in {2}","update.filestore.approval.reject":"{0} file rifiutati {3} in {2}","update.filestore.copy":'{0} copiati {3} da "{5}" in {2}',"update.filestore.create":"{0} file caricati {3} in {2}","update.filestore.create.notify":"{0} nuovi file creati {3} in {2}","update.filestore.folder":"{0} cartelle create {3} in {2}","update.filestore.folder.notify":"{0} cartelle create {1}","update.filestore.move":'{0} spostato {3} da "{5}" a {2}',"update.filestore.rename":'{0} cartella rinominata "{5}" da {3} in {2}',"update.filestore.update":"{0} file caricati {3} in {2}","update.filestore.update.notify":"{0} modifca i file {1}","update.following.start":"{0} comincia a seguire {3} in {2}","update.following.stop":"{0} smette di seguire {3} in {2}","update.organisation.create":"{0} ha creato l`account {1} ","update.organisation.disable":"{0} ha disabilitato l`account {1}","update.organisation.enabled":"{0} ha abilitato l`account {1}","update.organisation.join":"{0} partecipa {1}","update.organisation.private":"{0} ha detto in {1} ","update.page.create":"{0} nuove page create {3} in {2}","update.page.renameandupdate":"{0} page spostate {5} da {3} in {2}","update.page.renameandupdate.notify":"{0} page cambiate {1}","update.page.restore":"{0} page aggiornate {3} in {2}","update.page.update":"{0} page aggiornate {3} in {2}","update.page.update.notify":"{0} page cambiate {1}","update.space.create":"{0} ha creato un nuovo gruppo {2}","update.space.join":"{0} si è unito al {2} gruppo","update.space.move":"{0} ha spostato il gruppo {2} da {3}","update.space.private":"{0} ha detto in {2}","update.space.remove":"{0} ha rimosso il gruppo {2}","update.space.rename":"{0} ha rinominato il gruppo {5} a {2}","update.space.restore":"{0} ha ripristinato il gruppo {2} dal cestino","update.space.trash.discussion.attemptRestore":"{0} ha ripristinato discussion  {3} in {2}","update.space.trash.discussion.attemptRestore.notify":"{0} ha ripristinato discussion  {1}","update.space.trash.discussion.create":"{0} ha cancellato la discussion {3} in {2}","update.space.trash.discussion.create.notify":"{0} ha cancellato la discussion {3} da {2} cestino","update.space.trash.discussion.delete":"{0} ha cancellato permanentemente la discussion {3} da {2} cestino","update.space.trash.event.attemptRestore":"{0} ha rispristinato event {3} di {2}","update.space.trash.event.attemptRestore.notify":"{0} ha ripristinato l` event {3} in {2}","update.space.trash.event.create":"{0} event ha cancellato {3} in {2}","update.space.trash.event.create.notify":"{0} ha cancellato l` event {1}","update.space.trash.event.delete":"{0} ha cancellato permanentemente event {3} da {2} cestino","update.space.trash.filerecord.attemptRestore":"{0} ha ripristinato file {3} in {2} ","update.space.trash.filerecord.attemptRestore.notify":"{0} ha ripristinato il file {1}","update.space.trash.filerecord.create":"{0} ha cancellato file {3} in {2}","update.space.trash.filerecord.create.notify":"{0} ha cancellato il file {1}","update.space.trash.filerecord.delete":"{0} ha cancellato permanentemente il/i file {3} da {2} cestino","update.space.trash.page.attemptRestore":"{0} ha ripristinato la/le page  {3} in {2}","update.space.trash.page.attemptRestore.notify":"{0} ha ripristinato la page {1}","update.space.trash.page.create":"{0} ha cancellato le page {3} in {2}","update.space.trash.page.create.notify":"{0} ha cancellato la page {1}","update.space.trash.page.delete":"{0} ha cancellato permanentemente le page {3} da {2} cestino","update.space.trash.task.attemptRestore":"{0} task ripristinato {3} in {2}","update.space.trash.task.attemptRestore.notify":"{0} ha ripristinato il compito task {1}","update.space.trash.task.create":"{0} task cancellati {3} in {2}","update.space.trash.task.create.notify":"{0} ha cancellato il compito task {1}","update.space.trash.task.delete":"{0} Cancellato permanentemente task {3} da {2}","update.task.complete":"{0} task completato {3} in {2}","update.task.complete.notify":"{0} completato il task {1}","update.task.create":"{0} task creati {3} in {2}","update.task.createandassign":"{0} task creati {3} in {2}","update.task.reopen":"{0} task segnati {3} come incompleti in {2}","update.task.reopen.notify":"{0} segnato il task come incompleto {1}","update.task.update":"{0} task aggiornati {3} in {2}","update.task.update.notify":"{0} ha cambiato il compito task {1}","update.task.updateandassign":"{0} task aggiornati {3} in {2}","update.task.updateandassign.notify":"{0} ha cambiato il compito task {1}","update.trash.delete":"{0} ha cancellato il gruppo {2} da {1} cestino","update.trash.remove":"{0} ha cancellato gruppo {2} da {1} cestino","update.trash.restore":"{0} ha cancellato gruppo {2}","update.user.private":"{0} ha detto","update.user.profile":"{0} ha detto a {4}"};regional["voxns"]={m_signin_title:"Sign in to VOXNS CXP",m_signup_header:"Sign up to VOXNS CXP"};regional["ruralco"]={m_signin_title:"Sign in to RuralcoLink",m_signup_header:"Sign up to RuralcoLink"};return{messages:messages,template:function(template,data){return _.template(template,_.extend({},data,messages))},setLocale:function(locale){var regionalMessages=regional[locale];if(regionalMessages){this.messages=_.extend(messages,regionalMessages)}else{this.messages=messages}}}});define("app-context",["ext/underscore","native","messages"],function(_,_native,messages){var $=jQuery;var _credentials=null;var $root=$("#clinked-portal");var _getAppUrl=function(){return $root.data("appurl")};var appContext=_.extend({version:6,defaultThumb:_getAppUrl()+"/styles/images/default_thumbnail.png",environments:{prod:["https://api-p1.clinked.com","https://app.clinked.com","https://pubsub.clinked.com"],test:["https://test-api.clinked.com","https://test-app.clinked.com","https://test-pubsub.clinked.com"],dev:["http://localhost:18080/ROOT","http://localhost.localdomain:8080/ROOT","http://localhost:2222"],ip:["http://192.168.126.12:18080/ROOT","http://192.168.126.12:8080/ROOT","http://192.168.126.12:2222"],variants:{ruralco:{prod:["https://api.ruralcolink.com.au","https://ruralcolink.com.au","https://pubsub.ruralcolink.com.au"],test:["https://api-test.ruralcolink.com.au","https://test.ruralcolink.com.au","https://pubsub-test.ruralcolink.com.au"]}}},clientId:"clinked-mobile",pageSize:25,notificationUrls:{},getAppUrl:_getAppUrl,setStartOptions:function(options){this.startOptions=options;if(options.variant){$root.addClass(options.variant);messages.setLocale(options.variant);if(this.environments.variants[options.variant]){this.environments=_.extend(this.environments,this.environments.variants[options.variant])}_native.thirdPartySignin=false}_updateConfig()},getCredentials:function(callback){return _credentials},setCredentials:function(credentials){_credentials=credentials},removeCredentials:function(){_credentials=null},setAccessToken:function(token){if(token.expires_in){token.expires=(new Date).getTime()+token.expires_in*1e3}window.localStorage.setItem("accessToken",JSON.stringify(token));this.trigger("accessToken")},getAccessToken:function(){var json=window.localStorage.getItem("accessToken");if(json){var token=JSON.parse(json);var now=(new Date).getTime();if(!token.expires||token.expires>now){return token}}return null},removeAccessToken:function(){window.localStorage.removeItem("accessToken")},setTaskCompletedFilter:function(completed){window.localStorage.setItem("taskCompletedFilter",completed)},getTaskCompletedFilter:function(){return window.localStorage.getItem("taskCompletedFilter")=="true"},setFileSort:function(field){window.localStorage.setItem("fileSortField",field)},getFileSort:function(){var field=window.localStorage.getItem("fileSortField");return field?field:"lastModified"},setNoteSort:function(field){window.localStorage.setItem("noteSortField",field)},getNoteSort:function(){var field=window.localStorage.getItem("noteSortField");return field?field:"lastModified"},setPrinciple:function(principle){window.localStorage.setItem("me",JSON.stringify(principle));_updateLocale(principle.locale)},getPrinciple:function(){var principle=window.localStorage.getItem("me");if(principle){return JSON.parse(principle)}return null},removePrinciple:function(){window.localStorage.removeItem("me")},setDashboard:function(dashboard){window.localStorage.setItem("dashboard",dashboard)},getDashboard:function(){var dashboard=window.localStorage.getItem("dashboard");if(dashboard&&dashboard.indexOf(":@")==-1){dashboard=dashboard.replace(":",":@")}return dashboard},removeDashboard:function(){window.localStorage.removeItem("dashboard")},setEnvironment:function(environment){if(environment in this.environments){window.localStorage.setItem("environment",environment);_updateConfig()}},getEnvironment:function(){var environment=window.localStorage.getItem("environment");return environment?environment:_.keys(this.environments)[0]},resolveEndPoint:function(){return this.environments[this.getEnvironment()][0]},resolveAppEndPoint:function(){return this.environments[this.getEnvironment()][1]},resolvePubsubEndPoint:function(){return this.environments[this.getEnvironment()][2]},fullUrl:function(path){path+="?version="+this.version;var token=this.getAccessToken();if(token){path+="&access_token="+token.access_token}return this.resolveEndPoint()+path},preview:function(file,sessionNeeded){this.loading("show");if(sessionNeeded){$.get(this.fullUrl(file.url()+"session"),function(url){_native.preview(url,"text/html")})}else{_native.preview(this.fullUrl(file.url()+"preview"),file.get("contentType"),file.id+"."+file.get("versions"))}},loading:function(action){var $loader=$(".loader",$root);if(action=="show"){$loader.removeClass("hidden")}else if(action=="hide"){$loader.addClass("hidden")}},setHeader:function(options){if(options.back){options.back.text=messages.messages[options.back.code]}if(!options.actions){options.actions=[]}if(options.action){options.actions.push(options.action)}_.each(options.actions,function(action){action.text=messages.messages[action.code]});_native.setHeader(options)},navigate:function(hash,force){if(window.location.hash==hash){force&&Backbone.history.loadUrl(hash)}else if(_native.navigate){_native.navigate(hash)}else{window.location.hash=hash}},addNotification:function(url){this.notificationUrls[url]=true;$(".notifications",$root).removeClass("hidden").find("span").html(_.keys(this.notificationUrls).length)}},Backbone.Events);$(".notifications",$root).off().click(function(e){e.preventDefault();var keys=_.keys(appContext.notificationUrls);var nextUrl=keys.pop();delete appContext.notificationUrls[nextUrl];appContext.navigate(nextUrl,true);var $notifications=$(".notifications",$root);if(keys.length==0){$notifications.addClass("hidden")}else{$notifications.find("span").html(keys.length)}});var _updateLocale=function(locale){messages.setLocale(locale);var timeagoStrings=$.timeago.regional[locale];if(timeagoStrings){$.timeago.settings.strings=timeagoStrings}};var principle=appContext.getPrinciple();if(principle){_updateLocale(principle.locale)}var _updateConfig=function(){$.ajax({url:appContext.fullUrl("/config"),success:function(config){_.extend(appContext,config)},error:function(){appContext.navigate("#error",true)}})};return appContext});define("router/base",["ext/underscore"],function(_){return Backbone.Router.extend({initialize:function(){_.bindToMethods(this)}})});define("api/cache",["ext/underscore"],function(_){return{defaultExpireIn:10,cache:{},putModel:function(model,expireIn){model._expiry=this.calcExpiry(expireIn);this.cache[model.getKey()]=model},calcExpiry:function(expireIn){if(!expireIn){expireIn=this.defaultExpireIn}return(new Date).getTime()+expireIn*6e4},get:function(contextKey){var model=this.cache[contextKey];if(model&&model._expiry>(new Date).getTime()){return model}return null},getFrom:function(model){var cached=this.get(model.getKey());return cached?cached:model},clear:function(pattern){if(pattern){_.each(_.keys(this.cache),function(key){if(key.indexOf(pattern)==0){delete this.cache[key]}},this)}else{this.cache={}}},put2:function(key,object){this.cache[key]={expiry:this.calcExpiry(),object:object}},get2:function(contextKey){var entry=this.cache[contextKey];if(entry&&entry.expiry>(new Date).getTime()){return entry.object}return null}}});define("api/sync",["ext/underscore","app-context"],function(_,appContext){var $=jQuery;var ajax=function(request){appContext.loading("show");var token=appContext.getAccessToken();if(token){request["headers"]={Authorization:"Bearer "+token.access_token}}var jqXHR=$.ajax(request);jqXHR.request=request};var requestTokenAndRetry=function(credentials,request){var grantType=credentials.session?"session":credentials.password?"password":"refresh_token";$.ajax({type:"POST",url:appContext.resolveEndPoint()+"/oauth/token?grant_type="+grantType+"&client_id="+appContext.clientId,data:credentials,success:function(data,textStatus,jqXHR){appContext.setAccessToken(data);ajax(request)},error:function(jqXHR,textStatus,errorThrown){console.log(JSON.stringify(jqXHR));console.log(JSON.stringify(textStatus));console.log(JSON.stringify(errorThrown));appContext.removeCredentials();appContext.navigate("#public/signin/m_signin_invalid",true)}})};var getCredentials=function(){var credentials=appContext.getCredentials();if(credentials){return credentials}else{var token=appContext.getAccessToken();if(token&&token.refresh_token){return{refresh_token:token.refresh_token}}}return null};var error=function(_error,jqXHR,textStatus,errorThrown){appContext.loading("hide");if(errorThrown=="Unauthorized"){var credentials=getCredentials();if(credentials){requestTokenAndRetry(credentials,jqXHR.request)}else{appContext.navigate("#public/signin",true)}}else{_error(jqXHR,textStatus,errorThrown);appContext.navigate("#error",true)}};var success=function(_success,data,textStatus,jqXHR){appContext.loading("hide");_success(data,textStatus,jqXHR)};var methodMap={create:"POST",update:"PUT","delete":"DELETE",read:"GET"};return{getKey:function(){var key=_.result(this,"url").replace(/\//g,":").substr(1);return this._getKey?this._getKey(key):key},sync:function(method,model,options){var params={type:methodMap[method],dataType:"json",cache:false,url:appContext.resolveEndPoint()+_.getProperty(model,"url")+"?version="+appContext.version};options.success=_.wrap(options.success,success);options.error=_.wrap(options.error,error);if(model.params){params.url+="&"+$.param(model.params,true)}if(model&&(method=="create"||method=="update")){params.contentType="application/json";params.data=JSON.stringify(model.toJSON())}if(params.type!=="GET"){params.processData=false}ajax(_.extend(params,options))}}});define("api/collection/base",["api/sync"],function(sync){return Backbone.Collection.extend(sync)});define("api/model/base",["ext/underscore","api/sync"],function(_,sync){return Backbone.Model.extend(sync)});define("api/model/user",["api/model/base"],function(BaseModel){return BaseModel.extend({})});define("api/collection/users",["api/collection/base","api/model/user"],function(BaseCollection,User){return BaseCollection.extend({model:User,url:"/users",initialize:function(models,options){this.context=options.context;this.params={};this.params[this.context.type+"Id"]=this.context.id;this.params["allowSelf"]=options.allowSelf},_getKey:function(key){return key+":"+this.context.getKey()}})});define("api/model/account",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(){this.type="account"},url:function(){return"/accounts/@"+this.id},isUser:function(){return this.get("name").indexOf("@")==0}})});define("api/collection/accounts",["api/collection/base","api/model/account"],function(BaseCollection,Account){return BaseCollection.extend({model:Account,url:"/accounts"})});define("api/model/group",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(){this.type="group"},url:function(){var id=this.id?"@"+this.id:this.get("name");return"/groups/"+id}})});define("api/collection/groups",["api/collection/base","api/model/group"],function(BaseCollection,Group){return BaseCollection.extend({model:Group,url:"/groups"})});define("api/collection/search",["ext/underscore","api/collection/base"],function(_,BaseCollection){return BaseCollection.extend({url:function(){return"/search/@"+this.account.id},initialize:function(models,options){options&&_.extend(this,options)},parse:function(response){if(response.suggestions.length>0){var suggestions=[];_.each(response.suggestions,function(suggestion){suggestions.push({suggestion:suggestion})});this.suggestions=true;return suggestions}this.more=response.nextPage;return response.page}})});define("api/model/principle",["api/model/user"],function(User){return User.extend({url:"/me"})});define("api/service/general",["ext/underscore","app-context","api/cache","api/collection/users","api/collection/accounts","api/collection/groups","api/collection/search","api/model/principle","api/model/account","api/model/group"],function(_,appContext,cache,Users,Accounts,Groups,Search,Principle,Account,Group){var $=jQuery;var _cacheIfNew=function(model){if(!model._expiry){cache.putModel(model)}};var _attachGroupsToAccounts=function(handler,accounts,groups){var catchall=new Account;accounts.unshift(catchall);var accountMap={};_cacheIfNew(accounts);accounts.each(function(account){_cacheIfNew(account);accountMap[account.getKey()]=account;account.groups=[]},this);_cacheIfNew(groups);groups.each(function(group){_cacheIfNew(group);var account=new Account(group.get("account"));account=accountMap[account.getKey()];if(!account){account=catchall}account.groups.push(group)},this);handler(accounts)};var _getSearchResults=function(account,query,page,handler){var search=new Search([],{account:account,search2:appContext.search2,params:{page:page,pageSize:appContext.pageSize,query:query}});search.once("sync",handler);search.fetch()};return{getUsers:function(context,handler,allowSelf){var users=cache.getFrom(new Users([],{context:context,allowSelf:allowSelf}));if(users._expiry){handler(users);return}users.once("sync",function(){cache.putModel(users);handler(users)});users.fetch()},fetchPrinciple:function(handler){var principle=new Principle;principle.once("change",function(){handler(principle)});principle.fetch()},getSearchResults:function(account,query,handler){_getSearchResults(account,query,1,handler)},getNextSearchResults:function(search,handler){_getSearchResults(search.account,search.params.query,search.params.page+1,function(next){search.add(next.models);search.params.page=next.params.page;search.more=next.more;handler(next)})},getAccountsWithGroups:function(handler){var accounts=cache.getFrom(new Accounts);var groups=cache.getFrom(new Groups);var attachGroupsToAccounts=_.bind(_.after(2,_attachGroupsToAccounts),this,handler,accounts,groups);if(accounts._expiry){attachGroupsToAccounts()}else{accounts.once("sync",attachGroupsToAccounts);accounts.fetch()}if(groups._expiry){attachGroupsToAccounts()}else{groups.once("sync",attachGroupsToAccounts);groups.fetch()}},getContext:function(contextKey,handler){var parts=contextKey.split(":@");var id=parseInt(parts[1]);if(parts[0]=="groups"){this.getGroup(id,handler)}else{this.getAccount(id,handler)}},getAccount:function(id,handler){var account=cache.getFrom(new Account({id:id}));if(account._expiry){handler(account)}else{account.once("change",function(){cache.putModel(account);handler(account)});account.fetch()}},getGroup:function(id,handler){var group=cache.getFrom(new Group({id:id}));if(group._expiry&&group.get("components")){handler(group)}else{group.once("change",function(){cache.putModel(group);handler(group)});group.fetch()}},getEmailFromInviteKey:function(inviteKey,handler){$.ajax({url:appContext.resolveAppEndPoint()+"/signup/invited",data:{inviteKey:inviteKey},success:function(response){if(response.form){handler(response.form.user.email)}else{handler()}},error:function(){handler()},dataType:"json"})},isUsernameTaken:function(username,handler){$.get(appContext.resolveAppEndPoint()+"/signup/taken",{username:username},function(response){handler(response.status)},"json")},createUser:function(user,handler){appContext.loading("show");$.ajax({type:"POST",url:appContext.resolveAppEndPoint()+"/signup/invited",data:user,success:function(){appContext.loading("hide");handler(true)},error:function(){appContext.loading("hide");handler(false)},dataType:"json"})},requestPasswordReset:function(email,handler){appContext.loading("show");$.ajax({type:"POST",url:appContext.resolveAppEndPoint()+"/password/forgotten",data:{email:email},success:function(response){appContext.loading("hide");handler(response._viewName=="organisation/password_forgotten_success")},error:function(){appContext.loading("hide");handler(false)},dataType:"json"})},resetPassword:function(username,tokenKey,password,handler){appContext.loading("show");$.ajax({type:"POST",url:appContext.resolveAppEndPoint()+"/password/reset/"+username+"/"+tokenKey,data:password,success:function(response){appContext.loading("hide");handler(true)},error:function(){appContext.loading("hide");handler(false)},dataType:"json"})},deleteModel:function(model,handler){model.destroy({wait:true});model.once("destroy",handler)}}});define("api/model/request",["api/model/base"],function(BaseModel){return BaseModel.extend({url:function(){var id="";if(this.id){id="/"+this.id}if(this.collection){return this.collection.url()+id}return"/requests"+id}})});!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define("moment",b):a.moment=b()}(this,function(){function a(){return Dc.apply(null,arguments)}function b(a){Dc=a}function c(a){return"[object Array]"===Object.prototype.toString.call(a)}function d(a){return a instanceof Date||"[object Date]"===Object.prototype.toString.call(a)}function e(a,b){var c,d=[];for(c=0;c<a.length;++c)d.push(b(a[c],c));return d}function f(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function g(a,b){for(var c in b)f(b,c)&&(a[c]=b[c]);return f(b,"toString")&&(a.toString=b.toString),f(b,"valueOf")&&(a.valueOf=b.valueOf),a}function h(a,b,c,d){return za(a,b,c,d,!0).utc()}function i(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function j(a){return null==a._pf&&(a._pf=i()),a._pf}function k(a){if(null==a._isValid){var b=j(a);a._isValid=!isNaN(a._d.getTime())&&b.overflow<0&&!b.empty&&!b.invalidMonth&&!b.nullInput&&!b.invalidFormat&&!b.userInvalidated,a._strict&&(a._isValid=a._isValid&&0===b.charsLeftOver&&0===b.unusedTokens.length&&void 0===b.bigHour)}return a._isValid}function l(a){var b=h(0/0);return null!=a?g(j(b),a):j(b).userInvalidated=!0,b}function m(a,b){var c,d,e;if("undefined"!=typeof b._isAMomentObject&&(a._isAMomentObject=b._isAMomentObject),"undefined"!=typeof b._i&&(a._i=b._i),"undefined"!=typeof b._f&&(a._f=b._f),"undefined"!=typeof b._l&&(a._l=b._l),"undefined"!=typeof b._strict&&(a._strict=b._strict),"undefined"!=typeof b._tzm&&(a._tzm=b._tzm),"undefined"!=typeof b._isUTC&&(a._isUTC=b._isUTC),"undefined"!=typeof b._offset&&(a._offset=b._offset),"undefined"!=typeof b._pf&&(a._pf=j(b)),"undefined"!=typeof b._locale&&(a._locale=b._locale),Fc.length>0)for(c in Fc)d=Fc[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function n(b){m(this,b),this._d=new Date(+b._d),Gc===!1&&(Gc=!0,a.updateOffset(this),Gc=!1)}function o(a){return a instanceof n||null!=a&&null!=a._isAMomentObject}function p(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function q(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&p(a[d])!==p(b[d]))&&g++;return g+f}function r(){}function s(a){return a?a.toLowerCase().replace("_","-"):a}function t(a){for(var b,c,d,e,f=0;f<a.length;){for(e=s(a[f]).split("-"),b=e.length,c=s(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=u(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&q(e,c,!0)>=b-1)break;b--}f++}return null}function u(a){var b=null;if(!Hc[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=Ec._abbr,require("./locale/"+a),v(b)}catch(c){}return Hc[a]}function v(a,b){var c;return a&&(c="undefined"==typeof b?x(a):w(a,b),c&&(Ec=c)),Ec._abbr}function w(a,b){return null!==b?(b.abbr=a,Hc[a]||(Hc[a]=new r),Hc[a].set(b),v(a),Hc[a]):(delete Hc[a],null)}function x(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return Ec;if(!c(a)){if(b=u(a))return b;a=[a]}return t(a)}function y(a,b){var c=a.toLowerCase();Ic[c]=Ic[c+"s"]=Ic[b]=a}function z(a){return"string"==typeof a?Ic[a]||Ic[a.toLowerCase()]:void 0}function A(a){var b,c,d={};for(c in a)f(a,c)&&(b=z(c),b&&(d[b]=a[c]));return d}function B(b,c){return function(d){return null!=d?(D(this,b,d),a.updateOffset(this,c),this):C(this,b)}}function C(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function D(a,b,c){return a._d["set"+(a._isUTC?"UTC":"")+b](c)}function E(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=z(a),"function"==typeof this[a])return this[a](b);return this}function F(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.length<b;)d="0"+d;return(e?c?"+":"":"-")+d}function G(a,b,c,d){var e=d;"string"==typeof d&&(e=function(){return this[d]()}),a&&(Mc[a]=e),b&&(Mc[b[0]]=function(){return F(e.apply(this,arguments),b[1],b[2])}),c&&(Mc[c]=function(){return this.localeData().ordinal(e.apply(this,arguments),a)})}function H(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function I(a){var b,c,d=a.match(Jc);for(b=0,c=d.length;c>b;b++)Mc[d[b]]?d[b]=Mc[d[b]]:d[b]=H(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function J(a,b){return a.isValid()?(b=K(b,a.localeData()),Lc[b]||(Lc[b]=I(b)),Lc[b](a)):a.localeData().invalidDate()}function K(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Kc.lastIndex=0;d>=0&&Kc.test(a);)a=a.replace(Kc,c),Kc.lastIndex=0,d-=1;return a}function L(a,b,c){_c[a]="function"==typeof b?b:function(a){return a&&c?c:b}}function M(a,b){return f(_c,a)?_c[a](b._strict,b._locale):new RegExp(N(a))}function N(a){return a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function O(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=p(a)}),c=0;c<a.length;c++)ad[a[c]]=d}function P(a,b){O(a,function(a,c,d,e){d._w=d._w||{},b(a,d._w,d,e)})}function Q(a,b,c){null!=b&&f(ad,a)&&ad[a](b,c._a,c,a)}function R(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function S(a){return this._months[a.month()]}function T(a){return this._monthsShort[a.month()]}function U(a,b,c){var d,e,f;for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),d=0;12>d;d++){if(e=h([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function V(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),R(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function W(b){return null!=b?(V(this,b),a.updateOffset(this,!0),this):C(this,"Month")}function X(){return R(this.year(),this.month())}function Y(a){var b,c=a._a;return c&&-2===j(a).overflow&&(b=c[cd]<0||c[cd]>11?cd:c[dd]<1||c[dd]>R(c[bd],c[cd])?dd:c[ed]<0||c[ed]>24||24===c[ed]&&(0!==c[fd]||0!==c[gd]||0!==c[hd])?ed:c[fd]<0||c[fd]>59?fd:c[gd]<0||c[gd]>59?gd:c[hd]<0||c[hd]>999?hd:-1,j(a)._overflowDayOfYear&&(bd>b||b>dd)&&(b=dd),j(a).overflow=b),a}function Z(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function $(a,b){var c=!0,d=a+"\n"+(new Error).stack;return g(function(){return c&&(Z(d),c=!1),b.apply(this,arguments)},b)}function _(a,b){kd[a]||(Z(b),kd[a]=!0)}function aa(a){var b,c,d=a._i,e=ld.exec(d);if(e){for(j(a).iso=!0,b=0,c=md.length;c>b;b++)if(md[b][1].exec(d)){a._f=md[b][0]+(e[6]||" ");break}for(b=0,c=nd.length;c>b;b++)if(nd[b][1].exec(d)){a._f+=nd[b][0];break}d.match(Yc)&&(a._f+="Z"),ta(a)}else a._isValid=!1}function ba(b){var c=od.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(aa(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function ca(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function da(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function ea(a){return fa(a)?366:365}function fa(a){return a%4===0&&a%100!==0||a%400===0}function ga(){return fa(this.year())}function ha(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=Aa(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function ia(a){return ha(a,this._week.dow,this._week.doy).week}function ja(){return this._week.dow}function ka(){return this._week.doy}function la(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function ma(a){var b=ha(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function na(a,b,c,d,e){var f,g,h=da(a,0,1).getUTCDay();return h=0===h?7:h,c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:ea(a-1)+g}}function oa(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function pa(a,b,c){return null!=a?a:null!=b?b:c}function qa(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function ra(a){var b,c,d,e,f=[];if(!a._d){for(d=qa(a),a._w&&null==a._a[dd]&&null==a._a[cd]&&sa(a),a._dayOfYear&&(e=pa(a._a[bd],d[bd]),a._dayOfYear>ea(e)&&(j(a)._overflowDayOfYear=!0),c=da(e,0,a._dayOfYear),a._a[cd]=c.getUTCMonth(),a._a[dd]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[ed]&&0===a._a[fd]&&0===a._a[gd]&&0===a._a[hd]&&(a._nextDay=!0,a._a[ed]=0),a._d=(a._useUTC?da:ca).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[ed]=24)}}function sa(a){var b,c,d,e,f,g,h;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=pa(b.GG,a._a[bd],ha(Aa(),1,4).year),d=pa(b.W,1),e=pa(b.E,1)):(f=a._locale._week.dow,g=a._locale._week.doy,c=pa(b.gg,a._a[bd],ha(Aa(),f,g).year),d=pa(b.w,1),null!=b.d?(e=b.d,f>e&&++d):e=null!=b.e?b.e+f:f),h=na(c,d,e,g,f),a._a[bd]=h.year,a._dayOfYear=h.dayOfYear
    8 }function ta(b){if(b._f===a.ISO_8601)return void aa(b);b._a=[],j(b).empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,k=0;for(e=K(b._f,b._locale).match(Jc)||[],c=0;c<e.length;c++)f=e[c],d=(h.match(M(f,b))||[])[0],d&&(g=h.substr(0,h.indexOf(d)),g.length>0&&j(b).unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),k+=d.length),Mc[f]?(d?j(b).empty=!1:j(b).unusedTokens.push(f),Q(f,d,b)):b._strict&&!d&&j(b).unusedTokens.push(f);j(b).charsLeftOver=i-k,h.length>0&&j(b).unusedInput.push(h),j(b).bigHour===!0&&b._a[ed]<=12&&b._a[ed]>0&&(j(b).bigHour=void 0),b._a[ed]=ua(b._locale,b._a[ed],b._meridiem),ra(b),Y(b)}function ua(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function va(a){var b,c,d,e,f;if(0===a._f.length)return j(a).invalidFormat=!0,void(a._d=new Date(0/0));for(e=0;e<a._f.length;e++)f=0,b=m({},a),null!=a._useUTC&&(b._useUTC=a._useUTC),b._f=a._f[e],ta(b),k(b)&&(f+=j(b).charsLeftOver,f+=10*j(b).unusedTokens.length,j(b).score=f,(null==d||d>f)&&(d=f,c=b));g(a,c||b)}function wa(a){if(!a._d){var b=A(a._i);a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],ra(a)}}function xa(a){var b,e=a._i,f=a._f;return a._locale=a._locale||x(a._l),null===e||void 0===f&&""===e?l({nullInput:!0}):("string"==typeof e&&(a._i=e=a._locale.preparse(e)),o(e)?new n(Y(e)):(c(f)?va(a):f?ta(a):d(e)?a._d=e:ya(a),b=new n(Y(a)),b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b))}function ya(b){var f=b._i;void 0===f?b._d=new Date:d(f)?b._d=new Date(+f):"string"==typeof f?ba(b):c(f)?(b._a=e(f.slice(0),function(a){return parseInt(a,10)}),ra(b)):"object"==typeof f?wa(b):"number"==typeof f?b._d=new Date(f):a.createFromInputFallback(b)}function za(a,b,c,d,e){var f={};return"boolean"==typeof c&&(d=c,c=void 0),f._isAMomentObject=!0,f._useUTC=f._isUTC=e,f._l=c,f._i=a,f._f=b,f._strict=d,xa(f)}function Aa(a,b,c,d){return za(a,b,c,d,!1)}function Ba(a,b){var d,e;if(1===b.length&&c(b[0])&&(b=b[0]),!b.length)return Aa();for(d=b[0],e=1;e<b.length;++e)b[e][a](d)&&(d=b[e]);return d}function Ca(){var a=[].slice.call(arguments,0);return Ba("isBefore",a)}function Da(){var a=[].slice.call(arguments,0);return Ba("isAfter",a)}function Ea(a){var b=A(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+36e5*h,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=x(),this._bubble()}function Fa(a){return a instanceof Ea}function Ga(a,b){G(a,0,0,function(){var a=this.utcOffset(),c="+";return 0>a&&(a=-a,c="-"),c+F(~~(a/60),2)+b+F(~~a%60,2)})}function Ha(a){var b=(a||"").match(Yc)||[],c=b[b.length-1]||[],d=(c+"").match(td)||["-",0,0],e=+(60*d[1])+p(d[2]);return"+"===d[0]?e:-e}function Ia(b,c){var e,f;return c._isUTC?(e=c.clone(),f=(o(b)||d(b)?+b:+Aa(b))-+e,e._d.setTime(+e._d+f),a.updateOffset(e,!1),e):Aa(b).local();return c._isUTC?Aa(b).zone(c._offset||0):Aa(b).local()}function Ja(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Ka(b,c){var d,e=this._offset||0;return null!=b?("string"==typeof b&&(b=Ha(b)),Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ja(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?$a(this,Va(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ja(this)}function La(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function Ma(a){return this.utcOffset(0,a)}function Na(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ja(this),"m")),this}function Oa(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ha(this._i)),this}function Pa(a){return a=a?Aa(a).utcOffset():0,(this.utcOffset()-a)%60===0}function Qa(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Ra(){if(this._a){var a=this._isUTC?h(this._a):Aa(this._a);return this.isValid()&&q(this._a,a.toArray())>0}return!1}function Sa(){return!this._isUTC}function Ta(){return this._isUTC}function Ua(){return this._isUTC&&0===this._offset}function Va(a,b){var c,d,e,g=a,h=null;return Fa(a)?g={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(g={},b?g[b]=a:g.milliseconds=a):(h=ud.exec(a))?(c="-"===h[1]?-1:1,g={y:0,d:p(h[dd])*c,h:p(h[ed])*c,m:p(h[fd])*c,s:p(h[gd])*c,ms:p(h[hd])*c}):(h=vd.exec(a))?(c="-"===h[1]?-1:1,g={y:Wa(h[2],c),M:Wa(h[3],c),d:Wa(h[4],c),h:Wa(h[5],c),m:Wa(h[6],c),s:Wa(h[7],c),w:Wa(h[8],c)}):null==g?g={}:"object"==typeof g&&("from"in g||"to"in g)&&(e=Ya(Aa(g.from),Aa(g.to)),g={},g.ms=e.milliseconds,g.M=e.months),d=new Ea(g),Fa(a)&&f(a,"_locale")&&(d._locale=a._locale),d}function Wa(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function Xa(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function Ya(a,b){var c;return b=Ia(b,a),a.isBefore(b)?c=Xa(a,b):(c=Xa(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function Za(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(_(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Va(c,d),$a(this,e,a),this}}function $a(b,c,d,e){var f=c._milliseconds,g=c._days,h=c._months;e=null==e?!0:e,f&&b._d.setTime(+b._d+f*d),g&&D(b,"Date",C(b,"Date")+g*d),h&&V(b,C(b,"Month")+h*d),e&&a.updateOffset(b,g||h)}function _a(a){var b=a||Aa(),c=Ia(b,this).startOf("day"),d=this.diff(c,"days",!0),e=-6>d?"sameElse":-1>d?"lastWeek":0>d?"lastDay":1>d?"sameDay":2>d?"nextDay":7>d?"nextWeek":"sameElse";return this.format(this.localeData().calendar(e,this,Aa(b)))}function ab(){return new n(this)}function bb(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+this>+a):(c=o(a)?+a:+Aa(a),c<+this.clone().startOf(b))}function cb(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+a>+this):(c=o(a)?+a:+Aa(a),+this.clone().endOf(b)<c)}function db(a,b,c){return this.isAfter(a,c)&&this.isBefore(b,c)}function eb(a,b){var c;return b=z(b||"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+this===+a):(c=+Aa(a),+this.clone().startOf(b)<=c&&c<=+this.clone().endOf(b))}function fb(a){return 0>a?Math.ceil(a):Math.floor(a)}function gb(a,b,c){var d,e,f=Ia(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=z(b),"year"===b||"month"===b||"quarter"===b?(e=hb(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:fb(e)}function hb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function ib(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function jb(){var a=this.clone().utc();return 0<a.year()&&a.year()<=9999?"function"==typeof Date.prototype.toISOString?this.toDate().toISOString():J(a,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):J(a,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function kb(b){var c=J(this,b||a.defaultFormat);return this.localeData().postformat(c)}function lb(a,b){return this.isValid()?Va({to:this,from:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function mb(a){return this.from(Aa(),a)}function nb(a,b){return this.isValid()?Va({from:this,to:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function ob(a){return this.to(Aa(),a)}function pb(a){var b;return void 0===a?this._locale._abbr:(b=x(a),null!=b&&(this._locale=b),this)}function qb(){return this._locale}function rb(a){switch(a=z(a)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===a&&this.weekday(0),"isoWeek"===a&&this.isoWeekday(1),"quarter"===a&&this.month(3*Math.floor(this.month()/3)),this}function sb(a){return a=z(a),void 0===a||"millisecond"===a?this:this.startOf(a).add(1,"isoWeek"===a?"week":a).subtract(1,"ms")}function tb(){return+this._d-6e4*(this._offset||0)}function ub(){return Math.floor(+this/1e3)}function vb(){return this._offset?new Date(+this):this._d}function wb(){var a=this;return[a.year(),a.month(),a.date(),a.hour(),a.minute(),a.second(),a.millisecond()]}function xb(){return k(this)}function yb(){return g({},j(this))}function zb(){return j(this).overflow}function Ab(a,b){G(0,[a,a.length],0,b)}function Bb(a,b,c){return ha(Aa([a,11,31+b-c]),b,c).week}function Cb(a){var b=ha(this,this.localeData()._week.dow,this.localeData()._week.doy).year;return null==a?b:this.add(a-b,"y")}function Db(a){var b=ha(this,1,4).year;return null==a?b:this.add(a-b,"y")}function Eb(){return Bb(this.year(),1,4)}function Fb(){var a=this.localeData()._week;return Bb(this.year(),a.dow,a.doy)}function Gb(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)}function Hb(a,b){if("string"==typeof a)if(isNaN(a)){if(a=b.weekdaysParse(a),"number"!=typeof a)return null}else a=parseInt(a,10);return a}function Ib(a){return this._weekdays[a.day()]}function Jb(a){return this._weekdaysShort[a.day()]}function Kb(a){return this._weekdaysMin[a.day()]}function Lb(a){var b,c,d;for(this._weekdaysParse||(this._weekdaysParse=[]),b=0;7>b;b++)if(this._weekdaysParse[b]||(c=Aa([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b}function Mb(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Hb(a,this.localeData()),this.add(a-b,"d")):b}function Nb(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Ob(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)}function Pb(a,b){G(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function Qb(a,b){return b._meridiemParse}function Rb(a){return"p"===(a+"").toLowerCase().charAt(0)}function Sb(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Tb(a){G(0,[a,3],0,"millisecond")}function Ub(){return this._isUTC?"UTC":""}function Vb(){return this._isUTC?"Coordinated Universal Time":""}function Wb(a){return Aa(1e3*a)}function Xb(){return Aa.apply(null,arguments).parseZone()}function Yb(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.call(b,c):d}function Zb(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b}function $b(){return this._invalidDate}function _b(a){return this._ordinal.replace("%d",a)}function ac(a){return a}function bc(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)}function cc(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)}function dc(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function ec(a,b,c,d){var e=x(),f=h().set(d,b);return e[c](f,a)}function fc(a,b,c,d,e){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return ec(a,b,c,e);var f,g=[];for(f=0;d>f;f++)g[f]=ec(a,f,c,e);return g}function gc(a,b){return fc(a,b,"months",12,"month")}function hc(a,b){return fc(a,b,"monthsShort",12,"month")}function ic(a,b){return fc(a,b,"weekdays",7,"day")}function jc(a,b){return fc(a,b,"weekdaysShort",7,"day")}function kc(a,b){return fc(a,b,"weekdaysMin",7,"day")}function lc(){var a=this._data;return this._milliseconds=Rd(this._milliseconds),this._days=Rd(this._days),this._months=Rd(this._months),a.milliseconds=Rd(a.milliseconds),a.seconds=Rd(a.seconds),a.minutes=Rd(a.minutes),a.hours=Rd(a.hours),a.months=Rd(a.months),a.years=Rd(a.years),this}function mc(a,b,c,d){var e=Va(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function nc(a,b){return mc(this,a,b,1)}function oc(a,b){return mc(this,a,b,-1)}function pc(){var a,b,c,d=this._milliseconds,e=this._days,f=this._months,g=this._data,h=0;return g.milliseconds=d%1e3,a=fb(d/1e3),g.seconds=a%60,b=fb(a/60),g.minutes=b%60,c=fb(b/60),g.hours=c%24,e+=fb(c/24),h=fb(qc(e)),e-=fb(rc(h)),f+=fb(e/30),e%=30,h+=fb(f/12),f%=12,g.days=e,g.months=f,g.years=h,this}function qc(a){return 400*a/146097}function rc(a){return 146097*a/400}function sc(a){var b,c,d=this._milliseconds;if(a=z(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+12*qc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(rc(this._months/12)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 1440*b+d/6e4;case"second":return 86400*b+d/1e3;case"millisecond":return Math.floor(864e5*b)+d;default:throw new Error("Unknown unit "+a)}}function tc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*p(this._months/12)}function uc(a){return function(){return this.as(a)}}function vc(a){return a=z(a),this[a+"s"]()}function wc(a){return function(){return this._data[a]}}function xc(){return fb(this.days()/7)}function yc(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function zc(a,b,c){var d=Va(a).abs(),e=fe(d.as("s")),f=fe(d.as("m")),g=fe(d.as("h")),h=fe(d.as("d")),i=fe(d.as("M")),j=fe(d.as("y")),k=e<ge.s&&["s",e]||1===f&&["m"]||f<ge.m&&["mm",f]||1===g&&["h"]||g<ge.h&&["hh",g]||1===h&&["d"]||h<ge.d&&["dd",h]||1===i&&["M"]||i<ge.M&&["MM",i]||1===j&&["y"]||["yy",j];return k[2]=b,k[3]=+a>0,k[4]=c,yc.apply(null,k)}function Ac(a,b){return void 0===ge[a]?!1:void 0===b?ge[a]:(ge[a]=b,!0)}function Bc(a){var b=this.localeData(),c=zc(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function Cc(){var a=he(this.years()),b=he(this.months()),c=he(this.days()),d=he(this.hours()),e=he(this.minutes()),f=he(this.seconds()+this.milliseconds()/1e3),g=this.asSeconds();return g?(0>g?"-":"")+"P"+(a?a+"Y":"")+(b?b+"M":"")+(c?c+"D":"")+(d||e||f?"T":"")+(d?d+"H":"")+(e?e+"M":"")+(f?f+"S":""):"P0D"}var Dc,Ec,Fc=a.momentProperties=[],Gc=!1,Hc={},Ic={},Jc=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Kc=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Lc={},Mc={},Nc=/\d/,Oc=/\d\d/,Pc=/\d{3}/,Qc=/\d{4}/,Rc=/[+-]?\d{6}/,Sc=/\d\d?/,Tc=/\d{1,3}/,Uc=/\d{1,4}/,Vc=/[+-]?\d{1,6}/,Wc=/\d+/,Xc=/[+-]?\d+/,Yc=/Z|[+-]\d\d:?\d\d/gi,Zc=/[+-]?\d+(\.\d{1,3})?/,$c=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,_c={},ad={},bd=0,cd=1,dd=2,ed=3,fd=4,gd=5,hd=6;G("M",["MM",2],"Mo",function(){return this.month()+1}),G("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),G("MMMM",0,0,function(a){return this.localeData().months(this,a)}),y("month","M"),L("M",Sc),L("MM",Sc,Oc),L("MMM",$c),L("MMMM",$c),O(["M","MM"],function(a,b){b[cd]=p(a)-1}),O(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[cd]=e:j(c).invalidMonth=a});var id="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),jd="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),kd={};a.suppressDeprecationWarnings=!1;var ld=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,md=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],nd=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],od=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=$("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),G(0,["YY",2],0,function(){return this.year()%100}),G(0,["YYYY",4],0,"year"),G(0,["YYYYY",5],0,"year"),G(0,["YYYYYY",6,!0],0,"year"),y("year","y"),L("Y",Xc),L("YY",Sc,Oc),L("YYYY",Uc,Qc),L("YYYYY",Vc,Rc),L("YYYYYY",Vc,Rc),O(["YYYY","YYYYY","YYYYYY"],bd),O("YY",function(b,c){c[bd]=a.parseTwoDigitYear(b)}),a.parseTwoDigitYear=function(a){return p(a)+(p(a)>68?1900:2e3)};var pd=B("FullYear",!1);G("w",["ww",2],"wo","week"),G("W",["WW",2],"Wo","isoWeek"),y("week","w"),y("isoWeek","W"),L("w",Sc),L("ww",Sc,Oc),L("W",Sc),L("WW",Sc,Oc),P(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=p(a)});var qd={dow:0,doy:6};G("DDD",["DDDD",3],"DDDo","dayOfYear"),y("dayOfYear","DDD"),L("DDD",Tc),L("DDDD",Pc),O(["DDD","DDDD"],function(a,b,c){c._dayOfYear=p(a)}),a.ISO_8601=function(){};var rd=$("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=Aa.apply(null,arguments);return this>a?this:a}),sd=$("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=Aa.apply(null,arguments);return a>this?this:a});Ga("Z",":"),Ga("ZZ",""),L("Z",Yc),L("ZZ",Yc),O(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ha(a)});var td=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var ud=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,vd=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Va.fn=Ea.prototype;var wd=Za(1,"add"),xd=Za(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var yd=$("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});G(0,["gg",2],0,function(){return this.weekYear()%100}),G(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Ab("gggg","weekYear"),Ab("ggggg","weekYear"),Ab("GGGG","isoWeekYear"),Ab("GGGGG","isoWeekYear"),y("weekYear","gg"),y("isoWeekYear","GG"),L("G",Xc),L("g",Xc),L("GG",Sc,Oc),L("gg",Sc,Oc),L("GGGG",Uc,Qc),L("gggg",Uc,Qc),L("GGGGG",Vc,Rc),L("ggggg",Vc,Rc),P(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=p(a)}),P(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),G("Q",0,0,"quarter"),y("quarter","Q"),L("Q",Nc),O("Q",function(a,b){b[cd]=3*(p(a)-1)}),G("D",["DD",2],"Do","date"),y("date","D"),L("D",Sc),L("DD",Sc,Oc),L("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),O(["D","DD"],dd),O("Do",function(a,b){b[dd]=p(a.match(Sc)[0],10)});var zd=B("Date",!0);G("d",0,"do","day"),G("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),G("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),G("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),G("e",0,0,"weekday"),G("E",0,0,"isoWeekday"),y("day","d"),y("weekday","e"),y("isoWeekday","E"),L("d",Sc),L("e",Sc),L("E",Sc),L("dd",$c),L("ddd",$c),L("dddd",$c),P(["dd","ddd","dddd"],function(a,b,c){var d=c._locale.weekdaysParse(a);null!=d?b.d=d:j(c).invalidWeekday=a}),P(["d","e","E"],function(a,b,c,d){b[d]=p(a)});var Ad="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Bd="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Cd="Su_Mo_Tu_We_Th_Fr_Sa".split("_");G("H",["HH",2],0,"hour"),G("h",["hh",2],0,function(){return this.hours()%12||12}),Pb("a",!0),Pb("A",!1),y("hour","h"),L("a",Qb),L("A",Qb),L("H",Sc),L("h",Sc),L("HH",Sc,Oc),L("hh",Sc,Oc),O(["H","HH"],ed),O(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),O(["h","hh"],function(a,b,c){b[ed]=p(a),j(c).bigHour=!0});var Dd=/[ap]\.?m?\.?/i,Ed=B("Hours",!0);G("m",["mm",2],0,"minute"),y("minute","m"),L("m",Sc),L("mm",Sc,Oc),O(["m","mm"],fd);var Fd=B("Minutes",!1);G("s",["ss",2],0,"second"),y("second","s"),L("s",Sc),L("ss",Sc,Oc),O(["s","ss"],gd);var Gd=B("Seconds",!1);G("S",0,0,function(){return~~(this.millisecond()/100)}),G(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Tb("SSS"),Tb("SSSS"),y("millisecond","ms"),L("S",Tc,Nc),L("SS",Tc,Oc),L("SSS",Tc,Pc),L("SSSS",Wc),O(["S","SS","SSS","SSSS"],function(a,b){b[hd]=p(1e3*("0."+a))});var Hd=B("Milliseconds",!1);G("z",0,0,"zoneAbbr"),G("zz",0,0,"zoneName");var Id=n.prototype;Id.add=wd,Id.calendar=_a,Id.clone=ab,Id.diff=gb,Id.endOf=sb,Id.format=kb,Id.from=lb,Id.fromNow=mb,Id.to=nb,Id.toNow=ob,Id.get=E,Id.invalidAt=zb,Id.isAfter=bb,Id.isBefore=cb,Id.isBetween=db,Id.isSame=eb,Id.isValid=xb,Id.lang=yd,Id.locale=pb,Id.localeData=qb,Id.max=sd,Id.min=rd,Id.parsingFlags=yb,Id.set=E,Id.startOf=rb,Id.subtract=xd,Id.toArray=wb,Id.toDate=vb,Id.toISOString=jb,Id.toJSON=jb,Id.toString=ib,Id.unix=ub,Id.valueOf=tb,Id.year=pd,Id.isLeapYear=ga,Id.weekYear=Cb,Id.isoWeekYear=Db,Id.quarter=Id.quarters=Gb,Id.month=W,Id.daysInMonth=X,Id.week=Id.weeks=la,Id.isoWeek=Id.isoWeeks=ma,Id.weeksInYear=Fb,Id.isoWeeksInYear=Eb,Id.date=zd,Id.day=Id.days=Mb,Id.weekday=Nb,Id.isoWeekday=Ob,Id.dayOfYear=oa,Id.hour=Id.hours=Ed,Id.minute=Id.minutes=Fd,Id.second=Id.seconds=Gd,Id.millisecond=Id.milliseconds=Hd,Id.utcOffset=Ka,Id.utc=Ma,Id.local=Na,Id.parseZone=Oa,Id.hasAlignedHourOffset=Pa,Id.isDST=Qa,Id.isDSTShifted=Ra,Id.isLocal=Sa,Id.isUtcOffset=Ta,Id.isUtc=Ua,Id.isUTC=Ua,Id.zoneAbbr=Ub,Id.zoneName=Vb,Id.dates=$("dates accessor is deprecated. Use date instead.",zd),Id.months=$("months accessor is deprecated. Use month instead",W),Id.years=$("years accessor is deprecated. Use year instead",pd),Id.zone=$("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",La);var Jd=Id,Kd={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Ld={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},Md="Invalid date",Nd="%d",Od=/\d{1,2}/,Pd={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Qd=r.prototype;Qd._calendar=Kd,Qd.calendar=Yb,Qd._longDateFormat=Ld,Qd.longDateFormat=Zb,Qd._invalidDate=Md,Qd.invalidDate=$b,Qd._ordinal=Nd,Qd.ordinal=_b,Qd._ordinalParse=Od,Qd.preparse=ac,Qd.postformat=ac,Qd._relativeTime=Pd,Qd.relativeTime=bc,Qd.pastFuture=cc,Qd.set=dc,Qd.months=S,Qd._months=id,Qd.monthsShort=T,Qd._monthsShort=jd,Qd.monthsParse=U,Qd.week=ia,Qd._week=qd,Qd.firstDayOfYear=ka,Qd.firstDayOfWeek=ja,Qd.weekdays=Ib,Qd._weekdays=Ad,Qd.weekdaysMin=Kb,Qd._weekdaysMin=Cd,Qd.weekdaysShort=Jb,Qd._weekdaysShort=Bd,Qd.weekdaysParse=Lb,Qd.isPM=Rb,Qd._meridiemParse=Dd,Qd.meridiem=Sb,v("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===p(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=$("moment.lang is deprecated. Use moment.locale instead.",v),a.langData=$("moment.langData is deprecated. Use moment.localeData instead.",x);var Rd=Math.abs,Sd=uc("ms"),Td=uc("s"),Ud=uc("m"),Vd=uc("h"),Wd=uc("d"),Xd=uc("w"),Yd=uc("M"),Zd=uc("y"),$d=wc("milliseconds"),_d=wc("seconds"),ae=wc("minutes"),be=wc("hours"),ce=wc("days"),de=wc("months"),ee=wc("years"),fe=Math.round,ge={s:45,m:45,h:22,d:26,M:11},he=Math.abs,ie=Ea.prototype;ie.abs=lc,ie.add=nc,ie.subtract=oc,ie.as=sc,ie.asMilliseconds=Sd,ie.asSeconds=Td,ie.asMinutes=Ud,ie.asHours=Vd,ie.asDays=Wd,ie.asWeeks=Xd,ie.asMonths=Yd,ie.asYears=Zd,ie.valueOf=tc,ie._bubble=pc,ie.get=vc,ie.milliseconds=$d,ie.seconds=_d,ie.minutes=ae,ie.hours=be,ie.days=ce,ie.weeks=xc,ie.months=de,ie.years=ee,ie.humanize=Bc,ie.toISOString=Cc,ie.toString=Cc,ie.toJSON=Cc,ie.locale=pb,ie.localeData=qb,ie.toIsoString=$("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Cc),ie.lang=yd,G("X",0,0,"unix"),G("x",0,0,"valueOf"),L("x",Xc),L("X",Zc),O("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),O("x",function(a,b,c){c._d=new Date(p(a))}),a.version="2.10.3",b(Aa),a.fn=Jd,a.min=Ca,a.max=Da,a.utc=h,a.unix=Wb,a.months=gc,a.isDate=d,a.locale=v,a.invalid=l,a.duration=Va,a.isMoment=o,a.weekdays=ic,a.parseZone=Xb,a.localeData=x,a.isDuration=Fa,a.monthsShort=hc,a.weekdaysMin=kc,a.defineLocale=w,a.weekdaysShort=jc,a.normalizeUnits=z,a.relativeTimeThreshold=Ac;var je=a;return je});define("view/base",["ext/underscore","app-context","messages"],function(_,appContext,messages){var _message=function(code,args){var message=messages.messages[code];if(args){if(args.constructor!==Array){args=[args]}var parts=message.split(/[\{\}]+/);for(var i=1;i<parts.length;i+=2){parts[i]=args[parseInt(parts[i])]}return parts.join("")}return message};return Backbone.View.extend({initialize:function(options){_.bindToMethods(this);this.options=options},template:function(template,data){},template:function(template,data){if(data){var args=_.extend({messages:messages.messages,$:jQuery,appurl:appContext.getAppUrl()},data,messages.messages);return _.template(template,args)}return _.template(template,messages.messages)},message:_message},{message:_message})});define("lib/pull",["ext/underscore"],function(_){var $=jQuery;var $wrapper,viewStartY,startY,track=false,refresh=false;return{clear:function(settings){if($wrapper){$wrapper.off("touchstart touchmove touchend");$(">.refresh",$wrapper).empty()}},init:function(settings){var success=settings.success?settings.success:function(){};var top=settings.top?settings.top:0;$wrapper=settings.$wrapper?settings.$wrapper:$();var $refresh=$(">.refresh",$wrapper);var threshold=$refresh.height();settings.text&&$refresh.html(settings.text);var $view=$(">.view",$wrapper);var $pullable=$("ul.list-unstyled",$view);$wrapper.on("touchstart",function(e){viewStartY=-$pullable.position().top;startY=e.originalEvent.touches[0].screenY});$wrapper.on("touchend",function(e){if(refresh||track){$view.css("top",top+"px");if(refresh){success();refresh=false}track=false}});$wrapper.on("touchmove",function(e){var moveTo=viewStartY+(startY-e.originalEvent.targetTouches[0].screenY);if(moveTo<0){track=true;e.preventDefault();$view.css("top",top-moveTo+"px")}if(moveTo<-threshold){refresh=true}else{refresh=false}})}}});define("view/page",["ext/underscore","view/base","lib/pull","native","app-context","api/service/general"],function(_,BaseView,PULL,_native,appContext,service){var $=jQuery;var views={};return BaseView.extend({title:"Clinked",initialize:function(options){_.bindToMethods(this);this.options=options;this.$root=$("#clinked-portal");this.$wrapper=$(">.wrapper",this.$root)},render:function(){PULL.clear();var id=(new Date).getTime();views[id]=this;this.$view=$("<div>").addClass("view").attr("id",id).append(this.el);var $current=$(".view",this.$root);var viewId=$current.attr("id");if(viewId){views[viewId].remove();views[viewId]=null}$current.replaceWith(this.$view);if(this.navbar){this.$navigation=$("<div>").addClass("navigation");var self=this;this.navbar(function(navbar){self.$navigation.html(navbar.render().el);self.addFooter(self.$navigation)})}if(appContext.alert){this.$alert=$("<div>").addClass("alert alert-warning").html(appContext.alert);self.addHeader(this.$alert)}if(_native.refreshable&&this.handleRefresh){PULL.init({text:this.message("m_list_pull_to_refresh"),$wrapper:this.$wrapper,success:this.handleRefresh})}if(this.action&&!this.action.link){this.action.target="#"+this.$view.attr("id");this.$view.on("action",this.action.view.doAction)}appContext.setHeader(this);return this},remove:function(){BaseView.prototype.remove.apply(this,arguments);if(this.$navigation){this.removeMarginal(this.$navigation)}if(this.$alert){this.removeMarginal(this.$alert)}},scroll:function(position){this.$view.animate({scrollTop:position},"fast")},addHeader:function($header){$(">.header",this.$root).after($header.addClass("marginal"));this.updateMarginalCount(+1)},addFooter:function($footer){this.$wrapper.after($footer.addClass("marginal"));this.updateMarginalCount(+1)},removeMarginal:function($marginal){$marginal.remove();this.updateMarginalCount(-1)},updateMarginalCount:function(sign){var marginalCount=this.$wrapper.data("marginals")+sign;var height=_native.height()-marginalCount*44;this.$wrapper.data("marginals",marginalCount).height(height)}})});define("view/extending-list",["ext/underscore","moment","view/page"],function(_,moment,PageView){var $=jQuery;return PageView.extend({tagName:"ul",className:"list-unstyled",initialize:function(options){PageView.prototype.initialize.apply(this,arguments);_(this.emptyMsgCode,"empty list message code required").assert();_(this.itemViewClass,"list item view class required").assert();_(this.handleEndOfList,"end of list handler required").assert();this.$loading=$("<li>").addClass("thin").html(this.message("m_page_loading"))},render:function(){PageView.prototype.render.apply(this,arguments);if(this.collection.length==0){$("<li>").addClass("thin").html(this.message(this.emptyMsgCode)).appendTo(this.$el)}else{this._renderPage(this.collection)}return this},refresh:function(){this.$el.empty();if(this.collection.length==0){$("<li>").addClass("thin").html(this.message(this.emptyMsgCode)).appendTo(this.$el)}else{this._renderPage(this.collection)}},renderPage:function(page){this.$loading.remove();this._renderPage(page)},_renderPage:function(page){page.each(function(model){var itemView=new this.itemViewClass({model:model});this.$el.append(itemView.render().el)},this);if(page.more){this.$loading.one("inview",this.handleEndOfList).appendTo(this.$el)}},extractDateLabel:function(date){var label;if(this.isToday(date)){label=this.message("m_today")}else if(this.isTomorrow(date)){label=this.message("m_tomorrow")}else{var format;if(this.isThisWeek(date)){format="dddd"}else if(this.isThisYear(date)){format="DD MMMM"}else{format="DD MMMM YYYY"}label=moment(date).format(format)}return label},isToday:function(date){var now=new Date;now.setHours(0,0,0,0);var date=new Date(date);date.setHours(0,0,0,0);return now.getTime()==date.getTime()},isTomorrow:function(date){var now=new Date;now.setHours(0,0,0,0);var date=new Date(date);date.setHours(0,0,0,0);return now.getTime()+864e5==date.getTime()},isThisWeek:function(date){var now=moment().format("YYYY ww");date=moment(date).format("YYYY ww");return now==date},isThisYear:function(date){return moment().format("YYYY")==moment(date).format("YYYY")}})});define("api/model/content",["api/model/base","api/model/group"],function(BaseModel,Group){return BaseModel.extend({url:function(){var id="";if(this.id){id="@"+this.id+"/"}else{var name=this.get("name");if(name){id=name+"/"}}return"/groups/@"+this.get("group").id+"/"+this.type+"s/"+id},getGroup:function(){return new Group(this.get("group"))}})});define("api/model/file",["api/model/content"],function(Content){return Content.extend({initialize:function(){this.type="file"},isFolder:function(){return this.get("contentType")=="@folder"},getExtension:function(){if(this.isFolder()){return"folder"}var filename=this.get("friendlyName");var extensionPos=filename.lastIndexOf(".");if(filename.lastIndexOf("/")>extensionPos){return""}return filename.substring(extensionPos+1).toLowerCase()}},{type:"file"})});define("api/model/note",["api/model/content"],function(Content){return Content.extend({initialize:function(){this.type="page"}},{type:"page"})});define("api/model/discussion",["ext/underscore","api/model/content"],function(_,Content){return Content.extend({initialize:function(){this.type="discussion"}},{type:"discussion"})});define("api/model/event",["moment","api/model/content"],function(moment,Content){return Content.extend({initialize:function(){this.type="event"
    9 },getStartDate:function(){var startDate=moment(this.get("startDate"));if(this.get("allDay")){startDate.startOf("day")}return startDate},getEndDate:function(){var endDate=moment(this.get("endDate"));if(this.get("allDay")){endDate.subtract(1,"days").startOf("day")}return endDate},isSameDay:function(){var start=new Date(this.get("startDate"));start.setHours(0,0,0,0);var end=this.getEndDate().toDate();end.setHours(0,0,0,0);return start.getTime()==end.getTime()}},{type:"event"})});define("api/model/task",["api/model/content"],function(Content){return Content.extend({initialize:function(){this.type="task"},isOverdue:function(){return this.get("overdue")&&!this.get("completed")}},{type:"task"})});define("api/factory",["api/model/file","api/model/note","api/model/discussion","api/model/event","api/model/task"],function(File,Note,Discussion,Event,Task){return{createEntity:function(attributes){if(attributes.type=="page"){return new Note(attributes)}else if(attributes.type=="file"){return new File(attributes)}else if(attributes.type=="discussion"){return new Discussion(attributes)}else if(attributes.type=="event"){return new Event(attributes)}else if(attributes.type=="task"){return new Task(attributes)}return null}}});define("text",["module"],function(module){var text,fs,progIds=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],xmlRegExp=/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,bodyRegExp=/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,hasLocation=typeof location!=="undefined"&&location.href,defaultProtocol=hasLocation&&location.protocol&&location.protocol.replace(/\:/,""),defaultHostName=hasLocation&&location.hostname,defaultPort=hasLocation&&(location.port||undefined),buildMap=[],masterConfig=module.config&&module.config()||{};text={version:"2.0.3",strip:function(content){if(content){content=content.replace(xmlRegExp,"");var matches=content.match(bodyRegExp);if(matches){content=matches[1]}}else{content=""}return content},jsEscape:function(content){return content.replace(/(['\\])/g,"\\$1").replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r").replace(/[\u2028]/g,"\\u2028").replace(/[\u2029]/g,"\\u2029")},createXhr:masterConfig.createXhr||function(){var xhr,i,progId;if(typeof XMLHttpRequest!=="undefined"){return new XMLHttpRequest}else if(typeof ActiveXObject!=="undefined"){for(i=0;i<3;i+=1){progId=progIds[i];try{xhr=new ActiveXObject(progId)}catch(e){}if(xhr){progIds=[progId];break}}}return xhr},parseName:function(name){var strip=false,index=name.indexOf("."),modName=name.substring(0,index),ext=name.substring(index+1,name.length);index=ext.indexOf("!");if(index!==-1){strip=ext.substring(index+1,ext.length);strip=strip==="strip";ext=ext.substring(0,index)}return{moduleName:modName,ext:ext,strip:strip}},xdRegExp:/^((\w+)\:)?\/\/([^\/\\]+)/,useXhr:function(url,protocol,hostname,port){var uProtocol,uHostName,uPort,match=text.xdRegExp.exec(url);if(!match){return true}uProtocol=match[2];uHostName=match[3];uHostName=uHostName.split(":");uPort=uHostName[1];uHostName=uHostName[0];return(!uProtocol||uProtocol===protocol)&&(!uHostName||uHostName.toLowerCase()===hostname.toLowerCase())&&(!uPort&&!uHostName||uPort===port)},finishLoad:function(name,strip,content,onLoad){content=strip?text.strip(content):content;if(masterConfig.isBuild){buildMap[name]=content}onLoad(content)},load:function(name,req,onLoad,config){if(config.isBuild&&!config.inlineText){onLoad();return}masterConfig.isBuild=config.isBuild;var parsed=text.parseName(name),nonStripName=parsed.moduleName+"."+parsed.ext,url=req.toUrl(nonStripName),useXhr=masterConfig.useXhr||text.useXhr;if(!hasLocation||useXhr(url,defaultProtocol,defaultHostName,defaultPort)){text.get(url,function(content){text.finishLoad(name,parsed.strip,content,onLoad)},function(err){if(onLoad.error){onLoad.error(err)}})}else{req([nonStripName],function(content){text.finishLoad(parsed.moduleName+"."+parsed.ext,parsed.strip,content,onLoad)})}},write:function(pluginName,moduleName,write,config){if(buildMap.hasOwnProperty(moduleName)){var content=text.jsEscape(buildMap[moduleName]);write.asModule(pluginName+"!"+moduleName,"define(function () { return '"+content+"';});\n")}},writeFile:function(pluginName,moduleName,req,write,config){var parsed=text.parseName(moduleName),nonStripName=parsed.moduleName+"."+parsed.ext,fileName=req.toUrl(parsed.moduleName+"."+parsed.ext)+".js";text.load(nonStripName,req,function(value){var textWrite=function(contents){return write(fileName,contents)};textWrite.asModule=function(moduleName,contents){return write.asModule(moduleName,fileName,contents)};text.write(pluginName,nonStripName,textWrite,config)},config)}};if(masterConfig.env==="node"||!masterConfig.env&&typeof process!=="undefined"&&process.versions&&!!process.versions.node){fs=require.nodeRequire("fs");text.get=function(url,callback){var file=fs.readFileSync(url,"utf8");if(file.indexOf("")===0){file=file.substring(1)}callback(file)}}else if(masterConfig.env==="xhr"||!masterConfig.env&&text.createXhr()){text.get=function(url,callback,errback){var xhr=text.createXhr();xhr.open("GET",url,true);if(masterConfig.onXhr){masterConfig.onXhr(xhr,url)}xhr.onreadystatechange=function(evt){var status,err;if(xhr.readyState===4){status=xhr.status;if(status>399&&status<600){err=new Error(url+" HTTP status: "+status);err.xhr=xhr;errback(err)}else{callback(xhr.responseText)}}};xhr.send(null)}}else if(masterConfig.env==="rhino"||!masterConfig.env&&typeof Packages!=="undefined"&&typeof java!=="undefined"){text.get=function(url,callback){var stringBuffer,line,encoding="utf-8",file=new java.io.File(url),lineSeparator=java.lang.System.getProperty("line.separator"),input=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file),encoding)),content="";try{stringBuffer=new java.lang.StringBuffer;line=input.readLine();if(line&&line.length()&&line.charAt(0)===65279){line=line.substring(1)}stringBuffer.append(line);while((line=input.readLine())!==null){stringBuffer.append(lineSeparator);stringBuffer.append(line)}content=String(stringBuffer.toString())}finally{input.close()}callback(content)}}return text});define("text!text/search/item.html",[],function(){return"<a href=\"<%= link %>\">\n    <img src=\"<%= appurl %>/svg/<%= extension %>.svg\" onerror='this.onerror = null; this.src=\"<%= appurl %>/svg/file.svg\"'>\n   <p><b><%= get('name') %></b></p>\n  <abbr><%= m_last_updated %>: <%= $.timeago(new Date(get('timestamp'))) %></abbr>\n</a>\n"});define("view/search/item",["ext/underscore","view/base","api/factory","text!text/search/item.html"],function(_,BaseView,factory,template){return BaseView.extend({tagName:"li",className:"fat",render:function(){var extension=this.model.get("type");if(extension=="file"){var parts=this.model.get("name").split(".");extension=parts[parts.length-1]}this.model.set("group",{id:this.model.get("space")});var entity=factory.createEntity(this.model.toJSON());var args=_.extend({link:"#"+this.model.get("type")+"/"+entity.getKey(),extension:extension},this.model);this.$el.html(this.template(template,args));return this}})});define("view/search/list",["api/service/general","view/extending-list","view/search/item"],function(service,ExtendingListView,SearchItemView){var view=ExtendingListView.extend({back:{code:"m_context_dashboard",link:"#updates/dashboard"},title:ExtendingListView.message("m_search"),emptyMsgCode:"m_search_nothing",itemViewClass:SearchItemView,handleEndOfList:function(){service.getNextSearchResults(this.collection,this.renderPage)}});return view});define("text!text/search/suggestions.html",[],function(){return'&nbsp;&nbsp;<%= m_search_suggestions %>\n<% _.each(suggestions, function(suggestion, index) { %><!--\n \n --><% if (index != 0) { %>,<% } %>\n   <a href="#search/<%= suggestion.suggestion %>"><%= suggestion.suggestion %></a><!-- \n  \n --><% }); %>?\n'});define("view/search/suggestions",["ext/underscore","view/page","text!text/search/suggestions.html"],function(_,PageView,template){return PageView.extend({tagName:"h4",back:{code:"m_context_dashboard",link:"#updates/dashboard"},title:PageView.message("m_search_nothing"),render:function(){PageView.prototype.render.apply(this,arguments);if(this.collection.length>0){var args={suggestions:this.collection.toJSON()};this.$el.html(this.template(template,args))}return this}})});define("view/public/branding",["app-context"],function(appContext){var $=jQuery;return{brand:function(){this.$view.addClass("wallpaper");var $logo=$("<div>").addClass("logo").prependTo(this.$el);if(appContext.startOptions.logo){$logo.css("background-image","url("+appContext.startOptions.logo+")");this.$view.css("background-image","none")}if(appContext.startOptions.wallpaper){this.$view.css("background-image","url("+appContext.startOptions.wallpaper+")")}}}});define("view/dialog",["ext/underscore","native","view/base"],function(_,_native,BaseView){var $=jQuery;return BaseView.extend({initialize:function(options){_.assert(options.callback,"callback required");_.assert(this.title,"title required");_.bindToMethods(this);this.options=options},render:function(){$(".modal-title").html(this.title);$(".modal-body").html(this.el);var $dialog=$(".modal-dialog").css({width:this.options.width?this.options.width:_native.width()-20+"px"});$(".modal").modal("show");$dialog.css("margin-left",function(){return($(window).width()-$(this).width())/2});return this},callback:function(){$(".modal").modal("hide");this.remove();this.options.callback.apply(this,arguments)}})});define("text!text/validated-input.html",[],function(){return'<input class="form-control" type="<%= type %>" name="<%= name %>" value="<%= value %>"   \n   <% if (maxlength) { print(\'maxlength=\' + maxlength) } %>\n    placeholder="<%= label ? messages[label] : \'\' %>"\n    autocorrect="<%= autocomplete ? \'on\' : \'off\' %>"\n    autocapitalize="<%= autocomplete ? \'on\' : \'off\' %>" >\n<p class="hidden invalid"></p>\n'});define("view/validated-input",["ext/underscore","view/base","text!text/validated-input.html"],function(_,BaseView,template){var $=jQuery;return BaseView.extend({events:{"keyup input":"keyup","blur input":"blur"},initialize:function(){BaseView.prototype.initialize.apply(this,arguments);_.assert(this.options.name,"name required");if(!this.options.validate){this.options.validate=function(text,handler){handler()}}},render:function(){var defs={type:"text",value:"",maxlength:null,autocomplete:true};this.$el.html(this.template(template,_.extend(defs,this.options)));return this},keyup:function(){if(this.options.keyup){this.options.keyup.call(this,$("input",this.$el).val())}},blur:function(){this.options.validate.call(this,$("input",this.$el).val(),this.displayValidation)},val:function(){return $("input",this.$el).val()},displayValidation:function(error){var $error=$("p",this.$el).html(this.message(error));if(error){$error.removeClass("hidden")}else{$error.addClass("hidden")}}})});define("view/validated-email",["ext/underscore","view/validated-input"],function(_,ValidatedInput){return ValidatedInput.extend({initialize:function(options){_.extend(options,{type:"text",name:"email",autocomplete:false,validate:function(text,handler){var re=/^([^\s\"\(\)\[\]\{\}])+@([\w-]+\.)+[A-Za-z]{2,4}$/;if(re.test(text)){handler()}else{handler("m_email_input_error")}}});ValidatedInput.prototype.initialize.apply(this,arguments)}})});define("text!text/public/forgotten.html",[],function(){return'<a href="javascript:void(0)" class="btn btn-primary">\n    <%= m_forgotten_request %>\n</a>\n'});define("view/public/forgotten",["view/dialog","view/validated-email","text!text/public/forgotten.html"],function(DialogView,ValidatedEmail,template){var $=jQuery;return DialogView.extend({tagName:"fieldset",title:DialogView.message("m_forgotten_title"),events:{"click a":"validate"},emailInput:new ValidatedEmail({label:"m_forgotten_email"}),render:function(){DialogView.prototype.render.apply(this,arguments);this.$el.html(this.template(template));$("a",this.$el).before(this.emailInput.render().el);return this},validate:function(){var self=this;this.emailInput.options.validate(this.emailInput.val(),function(error){self.emailInput.displayValidation(error);!error&&self.request()})},request:function(){var $email=$("input[name=email]",this.$el);this.callback($email.val())}})});define("text!text/public/signin.html",[],function(){return'<% if (error) { %>\n  <div class="alert alert-danger"><%= error %></div>\n<% } %>\n<input class="form-control" name="username" placeholder="<%= m_signin_username %>" type="text" autocorrect="off" autocapitalize="off">\n<input class="form-control" name="password" placeholder="<%= m_signin_password %>" type="password">\n<a href="javascript:void(0)" id="signin" class="btn btn-primary">\n   <%= m_signin_signin %>\n</a>\n<a href="javascript:void(0)" id="forgotten-link">\n   <%= m_signin_forgotten %>\n</a>\n<% if (thirdPartySignin) { %>\n    <a data-external class="btn btn-default linkedin" href="<%= appRoot %>/linkedin?referrer=mobile" >\n        <i class="fa fa-linkedin"></i>\n        <%= m_signin_linkedin %>\n  </a>\n  <a data-external class="btn btn-default google" href="<%= appRoot %>/google/oauth2?referrer=mobile" >\n     <i class="fa fa-google-plus"></i>\n     <%= m_signin_google %>\n    </a>\n<% } %>\n<% if (env != \'prod\') { %>\n   <div class="alert alert-success"><%= env %></div>\n<% } %>\n'});define("view/public/signin",["ext/underscore","view/page","native","app-context","api/service/general","view/public/branding","view/public/forgotten","text!text/public/signin.html"],function(_,PageView,native,appContext,service,branding,ForgottenView,template){return PageView.extend(_.extend(branding,{tagName:"fieldset",events:{"click #signin":"signin","click #forgotten-link":"openForgotten"},nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.title=PageView.message("m_signin_title")},render:function(){PageView.prototype.render.apply(this,arguments);var args={error:this.message(this.options.error),appRoot:appContext.resolveAppEndPoint(),env:appContext.getEnvironment(),thirdPartySignin:native.thirdPartySignin};this.$el.html(this.template(template,args));this.brand();return this},openForgotten:function(){var forgotten=new ForgottenView({callback:this.handleForgotten});forgotten.render()},handleForgotten:function(email){service.requestPasswordReset(email,function(success){success=success?"sent":"fail";appContext.navigate("#public/signin/m_forgotten_request_"+success,true)})},signin:function(){var $username=this.$el.find("input[name=username]");var $password=this.$el.find("input[name=password]");var credentials={username:$username.val(),password:$password.val()};if(credentials.username.indexOf("@")==0){appContext.removeDashboard();appContext.setEnvironment(credentials.username.substr(1));appContext.navigate("#public/signin",true)}else{this.options.authenticate(credentials)}}}))});define("text!text/public/signup.html",[],function(){return'<p><b>Your Email: <%= email %></b></p>\n<a href="javascript:void(0)" id="signup" class="btn btn-primary">\n <%= m_signup_signup %>\n</a>\n'});define("view/public/signup",["ext/underscore","view/page","app-context","api/service/general","view/public/branding","view/validated-input","text!text/public/signup.html"],function(_,PageView,appContext,service,branding,ValidatedInput,template){var $=jQuery;var _formatUsername=function(name){name=name.toLowerCase();var result=[];for(var i=0;i<name.length;i++){result.push(!name.charAt(i).match(/[a-z0-9_]/)?".":name.charAt(i))}return result.join("")};return PageView.extend(_.extend(branding,{tagName:"fieldset",events:{"click #signup":"validate"},nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.title=PageView.message("m_signup_header");var usernameView=new ValidatedInput({autocomplete:false,name:"user.username",label:"m_input_username",maxlength:32,validate:function(text,handler){if(!text){handler("m_input_error_username")}else if(text.length>2){service.isUsernameTaken(text,function(status){handler(status?"m_input_error_taken":null)})}else{handler()}},keyup:function(text){var name=$("input",nameView.$el).val();this.manual=_formatUsername(name)!=text}});var nameView=new ValidatedInput({name:"user.name",label:"m_input_name",maxlength:32,validate:function(text,handler){_.defer(usernameView.blur);handler(text?null:"m_input_error_name")},keyup:function(text){if(!usernameView.manual){var username=_formatUsername(text);$("input",usernameView.$el).val(username)}}});var passwordView=new ValidatedInput({type:"password",name:"user.password",label:"m_input_password",validate:function(text,handler){if(!text){handler("m_input_error_password")}else if(text.length<6){handler("m_input_error_minimum_6")}else{handler()}}});this.inputs=[nameView,usernameView,passwordView,new ValidatedInput({type:"password",name:"passwordConfirm",label:"m_input_confirm",validate:function(text,handler){if(!text){handler("m_input_error_confirm")}else{var password=$("input",passwordView.$el).val();handler(text==password?null:"m_input_error_mismatch")}}}),new ValidatedInput({name:"user.telephone",label:"m_input_telephone",maxlength:20}),new ValidatedInput({name:"user.organisation",label:"m_input_organisation",maxlength:100})]},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,this.options));this.brand();var $signup=$("#signup",this.$el);_.each(this.inputs,function(input){$signup.before(input.render().el)});return this},validate:function(){var allValid=true;var inputCount=this.inputs.length;var self=this;_.each(this.inputs,function(input){input.options.validate(input.val(),function(error){inputCount--;input.displayValidation(error);!error||(allValid=false);if(inputCount==0&&allValid){self.signup()}})})},signup:function(){var user=$("input",this.$el).serializeArray();user.push({name:"inviteKey",value:this.options.inviteKey});user.push({name:"user.email",value:this.options.email});var currentYear=(new Date).getFullYear();var rawOffset=Date.UTC(currentYear,0,1)-new Date(currentYear,0,1).getTime();user.push({name:"rawOffset",value:rawOffset});user.push({name:"dstSavings",value:Date.UTC(currentYear,6,1)-new Date(currentYear,6,1).getTime()-rawOffset});service.createUser(user,this.signupComplete)},signupComplete:function(success){if(success){var credentials={username:$("[name='user.username']",this.$el).val(),password:$("[name='user.password']",this.$el).val()};this.options.authenticate(credentials)}else{appContext.navigate("#public/signin/m_error_unexpected",true)}}}))});define("text!text/public/reset.html",[],function(){return'<a href="javascript:void(0)" id="reset" class="btn btn-primary">\n    <%= m_reset_reset %>\n</a>\n'});define("view/public/reset",["ext/underscore","view/page","app-context","api/service/general","view/public/branding","view/validated-input","text!text/public/reset.html"],function(_,PageView,appContext,service,branding,ValidatedInput,template){var $=jQuery;return PageView.extend(_.extend(branding,{tagName:"fieldset",events:{"click #reset":"validate"},title:PageView.message("m_reset_header"),nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var passwordView=this.passwordView=new ValidatedInput({type:"password",name:"password",label:"m_input_password",validate:function(text,handler){if(!text){handler("m_input_error_password")}else if(text.length<6){handler("m_input_error_minimum_6")}else{handler()}}});this.confirmView=new ValidatedInput({type:"password",name:"confirmedPassword",label:"m_input_confirm",validate:function(text,handler){if(!text){handler("m_input_error_confirm")}else{var password=$("input",passwordView.$el).val();handler(text==password?null:"m_input_error_mismatch")}}})},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,this.options));this.brand();var $reset=$("#reset",this.$el);$reset.before(this.passwordView.render().el);$reset.before(this.confirmView.render().el);return this},validate:function(){var self=this;var valid=0,count=0;var check=function(error){count++;if(!error){valid++}if(count==2&&valid==2){self.reset()}};this.passwordView.options.validate(this.passwordView.val(),function(error){self.passwordView.displayValidation(error);check(error)});this.confirmView.options.validate(this.confirmView.val(),function(error){self.confirmView.displayValidation(error);check(error)})},reset:function(){service.resetPassword(this.options.username,this.options.tokenKey,$("input",this.$el).serializeArray(),this.resetComplete)},resetComplete:function(success){if(success){var credentials={username:this.options.username,password:$("[name=password]",this.$el).val()};this.options.authenticate(credentials)}else{appContext.navigate("#public/signin/m_error_unexpected",true)}}}))});define("text!text/context-item.html",[],function(){return"<a href=\"#updates/<%= model.getKey() %>\">\n  <% if (model.type == 'group') { %>\n        <img src=\"<%= cdn %>/customise/<%= model.get('hash') %>/@logo?_=<%= model.get('lastModified') %>\">\n  <% } %>\n   <%= _.escape(model.get('friendlyName')) %>\n</a>\n"});define("view/context/item",["ext/underscore","app-context","text!text/context-item.html"],function(_,appContext,template){return Backbone.View.extend({tagName:"li",className:"context-item",render:function(){if(!this.model.id){this.$el.addClass("hidden")}else if(this.model.type=="account"){this.$el.addClass("list-header")}var args={cdn:appContext.cdn,model:this.model};this.$el.html(_.template(template,args));return this}})});define("view/context/select",["ext/underscore","view/page","view/context/item"],function(_,PageView,ContextItemView){return PageView.extend({title:PageView.message("m_context_select_header"),nosearch:true,action:{code:"m_context_signout",link:"#signout"},tagName:"ul",className:"list-unstyled",append:function(model){var view=new ContextItemView({model:model});this.$el.append(view.render().el)},render:function(){PageView.prototype.render.apply(this,arguments);this.collection.each(function(account){this.append(account);_.each(account.groups,function(group){this.append(group)},this)},this);return this}})});define("text!text/error.html",[],function(){return'<div class="alert alert-danger">\n   <%= online ? (!code ? m_error_unexpected : message) : m_error_network %>\n</div>\n<a href="#updates/dashboard" class="btn btn-primary">\n   <%= online ? m_error_dashboard : m_error_retry %>\n</a>\n'});define("view/error",["ext/underscore","view/page","text!text/error.html"],function(_,PageView,template){return PageView.extend({tagName:"fieldset",title:PageView.message("m_error_title"),nosearch:true,render:function(){PageView.prototype.render.apply(this,arguments);if(this.options.code){this.options.message=this.message(this.options.code)}this.$el.html(this.template(template,this.options));return this}})});define("router/default",["router/base","native","app-context","api/cache","api/service/general","api/model/account","api/model/group","api/model/request","view/search/list","view/search/suggestions","view/public/signin","view/public/signup","view/public/reset","view/context/select","view/error"],function(BaseRouter,_native,appContext,cache,service,Account,Group,Request,SearchListView,SearchSuggestionsView,SigninView,SignupView,ResetView,ContextSelectView,ErrorView){return BaseRouter.extend({routes:{"search/:query":"getSearch","defer/:organisation/requests/:id/:answer":"handleDeferredRequest","defer/:organisation/:group":"handleDeferredContent","defer/:organisation/:group/:type/:id":"handleDeferredContent","public/signup/:inviteKey":"showSignup","public/signin":"showSignin","public/signin/:error":"showSignin","public/reset/:username/:tokenKey":"showReset","public/auth/:session":"authenticateWithSession",signout:"actionSignout",context:"getAccounts",error:"showError","error/:code":"showError","*splat":"splat"},getSearch:function(query){var self=this;service.getContext(appContext.getDashboard(),function(context){var account=context.type=="group"?new Account(context.get("account")):context;service.getSearchResults(account,decodeURIComponent(query),self.showSearch)})},showSearch:function(results){if(results.suggestions){new SearchSuggestionsView({collection:results}).render()}else{new SearchListView({collection:results}).render()}},handleDeferredRequest:function(organisation,id,answer){var request=new Request({id:id});request.answer=answer;request.once("sync",this.answerRequest);request.fetch()},answerRequest:function(request){request.set("status",request.answer.toUpperCase());request.once("sync",function(){var key=request.get("contextKey");type=key.objectType.split(".")[4].toLowerCase();if(type=="space"){if(request.answer=="accept"){appContext.navigate("#updates/groups:@"+key.objectId,true)}else{appContext.navigate("#updates/dashboard",true)}}else{appContext.navigate("#"+type+"/"+type+":"+key.parent.objectId+":@"+key.objectId,true)}});request.save()},handleDeferredContent:function(organisation,group,type,id){group=new Group({name:organisation+":"+group});if(type){group.entity={type:type,id:id}}group.once("sync",this.redirectToGroupContent);group.fetch()},redirectToGroupContent:function(group){if(group.entity){var type=group.entity.type.substr(0,group.entity.type.length-1);appContext.navigate("#"+type+"/"+type+":"+group.id+":"+group.entity.id,true)}else{appContext.navigate("#updates/groups:@"+group.id,true)}},showSignin:function(error){var self=this;if(appContext.getCredentials()){appContext.navigate("#updates/dashboard",true)}else{new SigninView({authenticate:self.authenticate,error:error}).render()}},actionSignout:function(){appContext.removeAccessToken();appContext.removePrinciple();cache.clear();appContext.removeCredentials();appContext.navigate("#public/signin",true)},getAccounts:function(){service.getAccountsWithGroups(this.showContextSelect)},showContextSelect:function(accounts){new ContextSelectView({collection:accounts}).render()},showError:function(code){_native.online(function(online){new ErrorView({code:code,online:online}).render()})},splat:function(){this.showError("m_error_not_found")},showSignup:function(inviteKey){var self=this;service.getEmailFromInviteKey(inviteKey,function(email){if(email){appContext.removeAccessToken();appContext.removePrinciple();cache.clear();new SignupView({authenticate:self.authenticate,email:email,inviteKey:inviteKey}).render()}else{appContext.navigate("#error/m_error_invite",true)}})},showReset:function(username,tokenKey){appContext.removeAccessToken();appContext.removePrinciple();cache.clear();new ResetView({authenticate:this.authenticate,username:username,tokenKey:tokenKey}).render()},authenticateWithSession:function(session){this.authenticate({session:session})},authenticate:function(credentials){appContext.setCredentials(credentials);service.fetchPrinciple(function(principle){appContext.setPrinciple(principle.toJSON());appContext.navigate("#updates/dashboard",true)})}})});define("api/model/update",["ext/underscore","api/model/base","api/model/account","api/model/group","api/factory"],function(_,BaseModel,Account,Group,factory){return BaseModel.extend({initialize:function(attributes){if(attributes.component){this.component=factory.createEntity(attributes.component)}},urlRoot:"/updates",isMicroblog:function(){return this.get("messageCode").search(/\.private$/)!=-1},getComponent:function(){return this.component},getAccount:function(){if(!this.account){this.account=this.get("account");if(this.account){this.account=new Account(this.account)}}return this.account},getGroup:function(){if(!this.group){this.group=this.get("group");if(this.group){this.group=new Group(this.group)}}return this.group},getContext:function(){if(this.getGroup()){return this.getGroup()}else if(this.getAccount()){return this.getAccount()}},format:function(template){var user=this.get("user");var account=this.get("account");var group=this.get("group");var args=[user?user.name:this.get("userName"),account?account.friendlyName:this.get("accountName"),group?group.friendlyName:this.get("groupName"),_.escape(this.get("componentName")),null,this.get("reservedName")];var parts=template.split(/[\{\}]+/);for(var i=1;i<parts.length;i+=2){parts[i]=args[parseInt(parts[i])]}var control={max:80};var description="";for(var i=0;i<parts.length&&!control.truncate;i++){var part=this.truncate(control,parts[i]);description+=i%2?part.bold():part}return description},truncate:function(control,part){if(!part){part=""}if(!control.current){control.current=0}control.current+=part.length;if(control.current>control.max){control.truncate=true;return part.substr(0,control.current-control.max)+".."}return part}})});define("api/collection/updates",["api/collection/base","api/model/update"],function(BaseCollection,Update){return BaseCollection.extend({model:Update,url:"/updates",initialize:function(models,options){this.context=options.context;this.params={currentPage:1,pageSize:25};if(options.current){if(options.current.offset){this.params.offset=options.current.offset}else{this.params.currentPage+=options.current.params.currentPage}}this.params[this.context.type+"Id"]=this.context.id},parse:function(response){if(response.page){this.more=response.nextPage;return response.page}this.offset=response.offset;this.more=response.more;return response.items},addPage:function(page){this.add(page.models);if(page.offset){this.offset=page.offset}else{this.params.currentPage=page.params.currentPage}this.more=page.more},_getKey:function(key){return key+":"+this.context.getKey()}})});define("api/model/microblog-reply",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(){this.reply=true},getComment:function(){return this.get("comment")},getCommenter:function(){return this.get("commenter")},getDateCreated:function(){return new Date(this.get("dateCreated"))}})});define("api/collection/microblog-replies",["api/collection/base","api/model/microblog-reply"],function(BaseCollection,Reply){return BaseCollection.extend({model:Reply,initialize:function(models,options){this.parent=options.parent},url:function(){return this.parent.url()+"/comments"}})});define("api/model/microblog",["ext/underscore","api/collection/microblog-replies","api/model/update"],function(_,Replies,Update){return Update.extend({getComment:function(){return this.get("message")},getCommenter:function(){return this.get("user")},getDateCreated:function(){return new Date(this.get("lastModified"))},getReplies:function(){if(!this.replies){this.replies=new Replies(this.get("replies"),{parent:this})}return this.replies},_getKey:function(key){return key+":microblog"}})});define("api/model/base-comment",["api/model/base"],function(BaseModel){return BaseModel.extend({url:function(){var id=this.id?"/@"+this.id:"";return this.collection.url()+id},getComment:function(){return this.get("comment")},getCommenter:function(){var commenter=this.get("commenter");return commenter?commenter:{name:this.get("commenterName")}},getDateCreated:function(){return new Date(this.get("dateCreated"))}})});define("api/model/reply",["api/model/base-comment"],function(BaseComment){return BaseComment.extend({initialize:function(){this.reply=true}})});define("api/service/update",["ext/underscore","api/cache","api/service/general","api/collection/updates","api/model/microblog","api/model/reply"],function(_,cache,service,Updates,Microblog,Reply){var _getUpdatesPage=function(updates,handler){updates.once("sync",function(){updates.each(function(update){var component=update.getComponent();if(component){cache.putModel(component)}});handler(updates)});updates.fetch()};return{getUpdates:function(contextKey,handler,force){service.getContext(contextKey,function(context){var updates=new Updates([],{context:context});if(!force){updates=cache.getFrom(updates);if(updates._expiry){handler(updates);return}}_getUpdatesPage(updates,function(updates){cache.putModel(updates);handler(updates)})})},getCachedUpdates:function(contextKey,handler){service.getContext(contextKey,function(context){var updates=new Updates([],{context:context});
    10 handler(cache.getFrom(updates))})},getNextUpdates:function(updates,handler){_getUpdatesPage(new Updates([],{context:updates.context,current:updates}),function(next){updates.addPage(next);handler(next)})},getMicroblog:function(id,handler,force){var microblog=new Microblog({id:id});if(!force){microblog=cache.getFrom(microblog);if(microblog._expiry){handler(microblog);return}}microblog.once("change",function(){handler(microblog)});microblog.fetch()},createMicroblog:function(context,text,handler){var attributes={message:text};attributes[context.type]={id:context.id};var microblog=new Microblog(attributes);microblog.save();microblog.once("change",_.bind(handler,this,microblog))},createMicroblogReply:function(microblog,text,handler){var replies=microblog.getReplies();var reply=new Reply({comment:text});replies.once("change",_.bind(handler,this,reply));replies.add(reply);reply.save()}}});define("text!text/navbar.html",[],function(){return"<% _.each(btns, function(btn, i) { %>\n   <div class=\"btn-group <%= btn.name %>\">\n     <a href=\"<%= btn.link %>\" class=\"btn btn-default <%= btn.name == focus ? 'selected' : '' %>\">\n         <img src=\"<%= appurl %>/svg/components/<%= btn.name %><%= btn.name == focus ? '-white' : '' %>.svg\" />\n      </a>\n  </div>\n<% }); %>\n"});define("view/navbar",["ext/underscore","view/base","text!text/navbar.html"],function(_,BaseView,template){return BaseView.extend({className:"btn-group btn-group-justified",initialize:function(options){_.assert(options.btns,"btns required");_.assert(options.focus,"focus required");this.options=options},render:function(){this.$el.html(this.template(template,this.options));return this}})});define("view/navbar-factory",["ext/underscore","api/service/general","view/navbar"],function(_,service,NavBar){return{navbarCreate:function(focus,groupId,callback){service.getGroup(groupId,function(group){var choiceMap={pages:{name:"notes",link:"#notes/"+group.getKey()},files:{name:"files",link:"#files/"+group.getKey()},discussions:{name:"discussions",link:"#discussions/"+group.getKey()},events:{name:"events",link:"#events/"+group.getKey()},tasks:{name:"tasks",link:"#tasks/"+group.getKey()}};var btns=[{name:"overview",link:"#updates/"+group.getKey()}];_.each(group.get("components"),function(component){if(choiceMap[component]){btns.push(choiceMap[component])}});btns.push({name:"messages",link:"#messages/"+group.getKey()});callback(new NavBar({focus:focus,btns:btns}))})}}});define("text!text/update-item.html",[],function(){return"<img class=\"svg-1default <%= sprite %>\" src=\"<%= image %>\" \n  onerror='this.onerror = null; this.src=\"<%= appurl %>/styles/images/default_thumbnail.png\"'>\n<% var template = messages[model.get('messageCode')]; %>\n<p><%= template ? model.format(template) : m_update_unknown %></p>\n<abbr><%= $.timeago(new Date(model.get('lastModified'))) %></abbr>\n"});define("view/update/item",["ext/underscore","view/base","app-context","api/cache","text!text/update-item.html"],function(_,BaseView,appContext,cache,template){var $=jQuery;return BaseView.extend({tagName:"li",className:"fat update-item",render:function(){var args=this.addImageArgs({model:this.model});var parent=null;var link=this.createLink();if(link){parent=$("<a>").attr("href",link).appendTo(this.el)}else{parent=this.$el}parent.addClass("list-parent").append(this.template(template,args));return this},createLink:function(){if(this.model.isMicroblog()){cache.putModel(this.model);return"#microblog/"+this.model.getKey()}else if(this.model.get("component")){var component=this.model.getComponent();if(component){if(this.model.get("message")){var root="#comments/";if(this.model.get("messageCode")=="update.discussion.createreply"){root="#discussion/"}return root+component.getKey()+"/"+this.model.get("lastModified")}return"#"+component.type+"/"+component.getKey()}}else if(this.model.getContext()){var contextKey=this.model.getContext().getKey();if(contextKey!=this.model.collection.context.getKey()){return"#updates/"+contextKey}}return null},addImageArgs:function(args){if(this.model.isMicroblog()){args.sprite="";var blogger=this.model.get("user");if(blogger.logo){args.image=appContext.cdn+"/users/"+blogger.id+"/thumbnail"}else{args.image=appContext.defaultThumb}}else{args.sprite="svg-"+this.model.get("messageCode").replace(/\./g,"");var component=this.model.getComponent();if(component&&component.isFolder&&component.isFolder()){args.sprite+=" folder"}args.image=appContext.getAppUrl()+"/styles/images/transparent.gif"}return args}})});define("view/update/list",["ext/underscore","api/service/update","view/navbar-factory","view/extending-list","view/update/item"],function(_,service,navbarFactory,ExtendingListView,UpdateItemView){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);this.title=_.escape(this.options.context.get("friendlyName"));this.action={code:"m_comment",icon:"comment",link:"#updates/"+this.options.context.getKey()+"/create"};if(this.options.context.type=="group"){this.navbar=this._navbar}},emptyMsgCode:"m_updates_nothing",itemViewClass:UpdateItemView,handleEndOfList:function(){service.getNextUpdates(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getUpdates(this.collection.context.getKey(),function(updates){self.collection=updates;self.refresh()},true)},_navbar:function(callback){this.navbarCreate("overview",this.options.context.id,callback)}}).extend(navbarFactory)});define("text!text/people-item.html",[],function(){return'<a class="item-with-icon" href="javascript:void(0)">\n   <img src="<%= thumb %>">\n  <h4><%= name %></h4>\n</a>\n'});define("view/people/item",["ext/underscore","app-context","text!text/people-item.html"],function(_,appContext,template){return Backbone.View.extend({tagName:"li",className:"fat",events:{"click a":"select"},initialize:function(options){_.assert(options.callback,"callback required");this.options=options},render:function(){var thumb=appContext.getAppUrl()+"/styles/images/default_thumbnail.png";if(this.model.get("logo")){thumb=appContext.cdn+"/users/"+this.model.id+"/thumbnail"}var args={name:this.model.get("name"),thumb:thumb};this.$el.html(_.template(template,args));return this},select:function(){this.options.callback(this.model)}})});define("view/people/list",["ext/underscore","view/dialog","view/people/item"],function(_,DialogView,PeopleItemView){return DialogView.extend({tagName:"ul",className:"list-unstyled",title:DialogView.message("m_mention_title"),render:function(){DialogView.prototype.render.apply(this,arguments);var keys={};this.options.filter&&_.each(this.options.filter,function(id){keys[id]=true});this.collection.each(function(user){if(!keys[user.id]){var view=new PeopleItemView({model:user,callback:this.callback});this.$el.append(view.render().el)}},this);return this}})});define("view/editor",["ext/underscore","native","api/service/general","view/people/list"],function(_,native,generalService,PeopleListView){var $=jQuery;return Backbone.View.extend({tagName:"iframe",attributes:{scrolling:"no",frameBorder:"0"},initialize:function(options){_.bindToMethods(this);this.context=options.context;this.$page=options.$page;this.content=options.content},render:function(){var $target=$("textarea.editor",this.$page);this.placeholder='<span style="color:gray;">'+$target.attr("placeholder")+"</span>";$target.replaceWith(this.el);this.frameWin=this.el.contentWindow;this.frameDoc=this.frameWin.document;this.frameDoc.designMode="on";this.$frameBody=$(this.frameDoc.body);this.$frameBody.css("font-family","Helvetica,Arial,sans-serif");if(_.isBlank(this.content)){this.$frameBody.html(this.placeholder)}else{this.$frameBody.html(this.content)}$(this.frameDoc).keydown(this.onKeydown);var self=this;$(this.frameDoc).keyup(function(e){self.$el.trigger("_change")});$(this.frameWin).focus(this.onFocus).blur(this.onBlur);native.keyboardCancelRequired&&this.frameDoc.body.blur()},render_delayed:function(focus){_.delay(function(self){self.render();focus&&self.frameWin.focus()},100,this)},onFocus:function(){if(this.getText()==""){this.$frameBody.html("")}},onBlur:function(){if(_.isBlank(_.stripTags(this.getText()))){this.$frameBody.html(this.placeholder)}},onKeydown:function(e){if(e.keyCode==13){e.preventDefault();var br=$("<br>").addClass("new-line").appendTo(this.frameDoc.body);var space=$(document.createTextNode(String.fromCharCode(160))).insertAfter(br);var selection=this.frameWin.getSelection();var range=this.frameDoc.createRange();range.selectNode(selection.anchorNode);range.setStartBefore(space[0]);range.collapse(true);selection.removeAllRanges();selection.addRange(range)}},doAction:function(){var self=this;generalService.getUsers(this.context,function(users){self.users=users;var people=new PeopleListView({collection:users,callback:function(user){self.insertMention(user)}});people.render()})},insertMention:function(user){this.frameDoc.body.focus();var anchor=$("<a/>").css({"background-color":"grey"}).text("@"+user.get("username"));anchor.appendTo(this.frameDoc.body);var space=$(document.createTextNode(String.fromCharCode(160))).insertAfter(anchor);var selection=this.frameWin.getSelection();var range=this.frameDoc.createRange();range.selectNode(selection.anchorNode);range.setStartAfter(space[0]);range.collapse(true);selection.removeAllRanges();selection.addRange(range);native.keyboardCancelRequired&&this.frameDoc.body.blur()},getText:function(){var text=this.$frameBody.html();return text==this.placeholder?"":text}})});define("text!text/editor.html",[],function(){return'<textarea class="editor hidden" placeholder="<%= m_type_here %>"></textarea>\n<fieldset>\n  <a href="javascript:void(0)" id="post" class="btn btn-primary" disabled="disabled">\n       <%= m_post %>\n </a>\n</fieldset>\n'});define("view/editor-page",["ext/underscore","view/page","view/editor","text!text/editor.html"],function(_,PageView,EditorView,template){var $=jQuery;return PageView.extend({events:{"_change iframe":"onChange","click #post":"post"},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);_.assert(this.post,"title post");this.editor=new EditorView({context:this.options.context,$page:this.$el});this.action={code:"m_mention",view:this.editor}},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template));this.editor.render_delayed(true);return this},onChange:function(){$("#post",this.$el).attr("disabled",_.isBlank(this.editor.getText()))}})});define("view/update/create",["app-context","view/editor-page","api/service/update"],function(appContext,EditorPageView,service){return EditorPageView.extend({title:EditorPageView.message("m_make_comment"),nosearch:true,initialize:function(){EditorPageView.prototype.initialize.apply(this,arguments);this.back={code:"m_btn_updates",link:"#updates/"+this.options.context.getKey()}},post:function(){service.createMicroblog(this.options.context,this.editor.getText(),this.microblogCreated)},microblogCreated:function(microblog){appContext.navigate("#microblog/"+microblog.getKey());service.getUpdates(this.options.context.getKey(),function(updates){updates.unshift(microblog)})}})});define("view/update/reply",["app-context","view/editor-page","api/service/update"],function(appContext,EditorPageView,service){return EditorPageView.extend({title:EditorPageView.message("m_reply"),nosearch:true,initialize:function(){EditorPageView.prototype.initialize.apply(this,arguments);this.back={code:"m_comment",link:"#microblog/"+this.options.update.getKey()}},post:function(){var microblog=this.options.update;service.createMicroblogReply(microblog,this.editor.getText(),function(microblogReply){appContext.navigate("#microblog/"+microblog.getKey())})}})});define("text!text/comment-item.html",[],function(){return'<div>\n <img src="<%= cdn %>/users/<%= commenter.id %>/thumbnail" \n        onerror=\'this.onerror = null; this.src="<%= appurl %>/styles/images/default_thumbnail.png"\'>\n    <p><%= model.getComment() %></p>\n  <p class="who-when"><%= commenter.name %> (<%= $.timeago(model.getDateCreated()) %>)</p>\n  \n  <% if (!model.reply) { %>\n     <a href="javascript:void(0)" class="comment-reply">\n           <span class="glyphicon glyphicon-repeat"></span>\n      </a>\n  <% } %>\n   <% if (me.id == commenter.id) { %>\n        <a href="javascript:void(0)" class="comment-delete">\n          <span class="glyphicon glyphicon-trash"></span>\n       </a>\n  <% } %>\n</div>\n'});define("view/comment/item",["ext/underscore","view/base","app-context","text!text/comment-item.html"],function(_,BaseView,appContext,template){return BaseView.extend({className:"comment",events:{"click .comment-delete":"onDelete","click .comment-reply":"onReply"},initialize:function(options){BaseView.prototype.initialize.apply(this,arguments);this.replyViews=[]},render:function(){var args={model:this.model,commenter:this.model.getCommenter(),selected:this.options.selected,cdn:appContext.cdn,me:appContext.getPrinciple()};this.$el.html(this.template(template,args));if(this.options.selected){this.$el.addClass("selected")}if(this.model.reply){this.$el.addClass("reply")}return this},onReply:function(){this.options.onReply(this.model)},onDelete:function(){this.options.onDelete(this.model,this.onDeleted)},onDeleted:function(){this.$el.remove();_.each(this.replyViews,function(view){view.$el.remove()})}})});define("view/comment/list",["ext/underscore","view/page","view/comment/item"],function(_,PageView,CommentItemView){var $=jQuery;return PageView.extend({className:"comments",initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.collection.on("remove",this.onRemove);var context=this.collection.context;this.back={code:"m_"+context.type,link:"#"+context.type+"/"+context.getKey()};this.title=_.escape(context.get("friendlyName"));this.action={code:"m_new",link:"#comments/"+context.getKey()+"/create"}},render:function(){PageView.prototype.render.apply(this,arguments);var selectedId=this.getSelectedComment();this.collection.each(function(comment){var commentView=this.createAndRender(comment,selectedId==comment.id);comment.getReplies().each(function(reply){var replyView=this.createAndRender(reply,selectedId==reply.id);commentView.replyViews.push(replyView)},this)},this);this.onRemove();return this},createAndRender:function(comment,selected){var view=new CommentItemView({model:comment,selected:selected,onDelete:this.options.onDelete,onReply:this.options.onReply});this.$el.append(view.render().el);selected&&this.scroll(view.$el.offset().top-52);return view},getSelectedComment:function(){if(!this.options.dateOfSelection){return-1}var flattened=[];this.collection.each(function(comment){flattened.push(comment);comment.getReplies().each(function(reply){flattened.push(reply)})});flattened=_.sortBy(flattened,function(comment){return-comment.get("dateCreated")});var selected=_.find(flattened,function(comment){return comment.get("dateCreated")<=this.options.dateOfSelection},this);return selected?selected.id:-1},remove:function(){this.collection.off("remove",this.onRemove);this.$el.remove();return this},onRemove:function(){if(this.collection.length==0){$("<div>").addClass("ui-body-d ui-corner-all").html(this.message("m_comments_nothing")).appendTo(this.el)}}})});define("view/update/microblog",["view/page","view/comment/list","messages"],function(PageView,CommentListView,messages){return CommentListView.extend({initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var microblog=options.microblog;this.back={code:"m_btn_updates",link:"#updates/"+microblog.getContext().getKey()};this.title=microblog.format(messages.messages[microblog.get("messageCode")]);this.collection=new Backbone.Collection([microblog]);this.collection.on("remove",this.onRemove)}})});define("router/update",["app-context","router/base","api/service/general","api/service/update","view/update/list","view/update/create","view/update/reply","view/update/microblog"],function(appContext,BaseRouter,generalService,updateService,UpdateListView,UpdateCreateView,UpdateReplyView,UpdateMicroblogView){return BaseRouter.extend({routes:{"updates/:contextKey/create":"createMicroblog","updates/dashboard":"getDashboardUpdates","updates/:contextKey":"getUpdates","microblog/:microblogKey/create":"createMicroblogReply","microblog/:microblogKey":"getMicroblog"},getDashboardUpdates:function(){var contextKey=appContext.getDashboard();if(contextKey){this.getUpdates(contextKey)}else{appContext.navigate("#context",true)}},getUpdates:function(contextKey){appContext.setDashboard(contextKey);updateService.getCachedUpdates(contextKey,this.showUpdates)},showUpdates:function(updates){var view=new UpdateListView({context:updates.context,collection:updates});view.render();view.handleRefresh()},createMicroblog:function(contextKey){generalService.getContext(contextKey,this.showCreateMicroblog)},showCreateMicroblog:function(context){new UpdateCreateView({context:context}).render()},getMicroblog:function(microblogKey){var parts=microblogKey.split(":");updateService.getMicroblog(parts[1],this.showMicroblog,true)},showMicroblog:function(microblog){var view=new UpdateMicroblogView({microblog:microblog,onDelete:function(target,onDeleted){generalService.deleteModel(target,onDeleted);if(!target.reply){updateService.getUpdates(target.getContext().getKey(),function(updates){updates.remove(target,{silent:true})})}},onReply:function(microblog){appContext.navigate("#microblog/"+microblog.getKey()+"/create")}});view.render()},createMicroblogReply:function(microblogKey){var parts=microblogKey.split(":");updateService.getMicroblog(parts[1],this.showCreateMicroblogReply)},showCreateMicroblogReply:function(microblog){new UpdateReplyView({context:microblog.getContext(),update:microblog}).render()}})});define("api/model/permission",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(attributes,options){this.context=options.context},url:function(){return this.context.url()+"/permission"},canEdit:function(){return(18&this.get("mask"))>0},canCreate:function(){return(20&this.get("mask"))>0}})});define("api/service/base",["ext/underscore","api/model/permission"],function(_,Permission){return{getCollection:function(collection,handler){collection.once("sync",function(){handler(collection)});collection.fetch()},getPermission:function(model,handler){if(model.permission){handler(model)}else{var permission=new Permission({},{context:model});permission.once("sync",function(){model.permission=permission;handler(model)});permission.fetch()}}}});define("api/collection/more",["ext/underscore","api/collection/base"],function(_,BaseCollection){return BaseCollection.extend({initialize:function(models,options){if(options){this.params=options.params}this.params=this.params||{}},parse:function(response){this.more=response.nextPage;return response.page}})});define("api/collection/files",["api/collection/more","api/model/file"],function(MoreCollection,File){return MoreCollection.extend({model:File,initialize:function(models,options){MoreCollection.prototype.initialize.apply(this,arguments);if(options){this.context=options.context}},url:function(){var base="/groups/@"+this.getGroup().id+"/files";if(this.context.type=="group"){return base}var id=this.context.id?"@"+this.context.id:this.context.get("name");return base+"/"+id},_getKey:function(key){return key+":"+this.params.orderBy},parse:function(response){if(this.context.type=="file"){response=response.children}this.more=response.nextPage;return response.page},getGroup:function(){if(this.context.type=="group"){return this.context}return this.context.get("group")}})});define("api/service/file",["ext/underscore","app-context","api/cache","api/service/base","api/service/general","api/collection/files","api/model/file"],function(_,appContext,cache,base,service,Files,File){return _.extend({getFiles:function(contextKey,handler,force){var self=this;this.getContextWithPermission(contextKey,function(context){var files=new Files([],{context:context,params:self.createFileParams(1)});if(!force){files=cache.getFrom(files);if(files){handler(files);return}}self.getCollection(files,function(files){cache.putModel(files);files.each(function(file){cache.putModel(file)});handler(files)})})},getCachedFiles:function(contextKey,handler){var self=this;this.getContextWithPermission(contextKey,function(context){var files=new Files([],{context:context,params:self.createFileParams(1)});handler(cache.getFrom(files))})},getContextWithPermission:function(contextKey,handler){var self=this;this.getContext(contextKey,function(context){self.getPermission(context,handler)})},getContext:function(contextKey,handler){var parts=contextKey.split(":");if(parts.length==2){service.getGroup(parseInt(parts[1].substr(1)),handler)}else{this.getFile({id:parts[1].substr(1)},parts[3],handler)}},getNextFiles:function(files,handler){var next=new Files([],{context:files.context,params:this.createFileParams(files.params.currentPage+1)});this.getCollection(next,function(next){files.add(next.models);files.params.currentPage=next.params.currentPage;files.more=next.more;handler(next)})},getFile:function(group,id,handler){var self=this;this.getFileOnly(group,id,function(file){self.getPermission(file,handler)})},getFileOnly:function(group,id,handler){var file=new File({name:id});if(id.charAt(0)=="@"){file=new File({id:parseInt(id.slice(1))})}file.set("group",group);file.params=this.createFileParams(1);file=cache.getFrom(file);if(file._expiry){handler(file);return}cache.putModel(file);file.once("change",handler);file.fetch()},createFileParams:function(currentPage){var orderBy=appContext.getFileSort();return{currentPage:currentPage,pageSize:appContext.pageSize,orderBy:orderBy,ascending:orderBy=="name"}}},base)});define("text!text/file/item.html",[],function(){return"<a href=\"#file/<%= getKey() %>\">\n  <img src=\"<%= appurl %>/svg/<%= getExtension() %>.svg\" onerror='this.onerror = null; this.src=\"<%= appurl %>/svg/file.svg\"'>\n  <p><b><%= get('friendlyName') %></b></p>\n  <abbr><%= m_last_updated %>: <%= $.timeago(new Date(get('lastModified'))) %></abbr>\n</a>\n"});define("view/file/item",["view/base","text!text/file/item.html"],function(BaseView,template){return BaseView.extend({tagName:"li",className:"fat",render:function(){this.$el.html(this.template(template,this.model));return this}})});define("view/file/list",["ext/underscore","api/service/file","view/navbar-factory","view/extending-list","view/file/item"],function(_,service,navbarFactory,ExtendingListView,FileItemView){return ExtendingListView.extend({initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);this.title=_.escape(this.collection.context.get("friendlyName"));this.back=this.options.back;this.action=this.options.action},emptyMsgCode:"m_files_nothing",itemViewClass:FileItemView,handleEndOfList:function(){service.getNextFiles(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getFiles(this.collection.context.getKey(),function(files){self.collection=files;self.refresh()},true)},navbar:function(callback){this.navbarCreate("files",this.collection.getGroup().id,callback)}}).extend(navbarFactory)});define("text!text/sort-action.html",[],function(){return'<div>\n   <input type="radio" name="sort_by" id="lastModified" value="lastModified" \n        <% if (sort == \'lastModified\') { print(\'checked\') } %> >\n  <label for="lastModified"><%= m_actions_sort_latest %></label>\n</div>\n<div>\n <input type="radio" name="sort_by" id="name" value="name" \n        <% if (sort == \'name\') { print(\'checked\') } %> >\n  <label for="name"><%= m_actions_sort_name %></label>\n</div>\n'});define("view/sort-action",["view/dialog","text!text/sort-action.html"],function(DialogView,template){return DialogView.extend({className:"choice-list",title:DialogView.message("m_actions_sort_header"),events:{"change input[type=radio]":"select"},render:function(){DialogView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,this.options));return this},doAction:function(){this.render()},select:function(event){this.callback(this.options.context,event.target.value)}})});define("text!text/file/upload.html",[],function(){return'<ul>\n  <li>\n      <span class="btn btn-success add" id="complex-flash-wrapper">\n         <%= m_file_upload_add %>\n      </span>\n       <input type="file" name="file" multiple />\n    </li>\n <li><a href="javascript:void(0)" class="btn btn-primary upload-all"><%= m_file_upload_start %></a></li>\n   <li><a href="javascript:void(0)" class="btn btn-default cancel-all"><%= m_file_upload_cancel %></a></li>\n</ul>\n<table class="table">\n    <tbody>\n       <tr class="template">\n         <td class="name">&nbsp;</td>\n          <td class="size">&nbsp;</td>\n          <td class="progress-container">\n               <div class="progress progress-striped">\n                   <div class="progress-bar">&nbsp;</div>\n                </div>\n            </td>\n         <td class="buttons">\n              <a href="javascript:void(0)" class="btn btn-xs btn-primary submit"><%= m_file_upload_upload %></a>\n                <a href="javascript:void(0)" class="btn btn-xs btn-primary retry"><%= m_file_upload_retry %></a>\n              <a href="javascript:void(0)" class="btn btn-xs btn-danger cancel"><%= m_file_upload_stop %></a>\n               <a href="javascript:void(0)" class="btn btn-xs btn-default remove"><%= m_file_upload_remove %></a>\n            </td>\n     </tr>\n </tbody>\n</table>\n'});define("view/file/upload",["view/dialog","app-context","text!text/file/upload.html"],function(DialogView,appContext,template){var $=jQuery;return DialogView.extend({tagName:"form",className:"upload-container",title:DialogView.message("m_file_upload_header"),events:{"click a.cancel-all":"cancel"},initialize:function(options){DialogView.prototype.initialize.apply(this,arguments);this.options.width="600px"},doAction:function(){$(".modal").on("hidden.bs.modal",this.close);var endpoint=this.getEndpoint();if(this.options.context.type=="file"){endpoint+="/"+this.options.context.id}$.get(appContext.fullUrl(endpoint+"/index"),this.retrievePath)},retrievePath:function(index){this.index=JSON.parse($.base64.atob(index));if(this.options.context.type=="file"){if(this.index.fileSystem.length==0){var endpoint=this.options.context.url()+"path";$.get(appContext.fullUrl(endpoint),this.setPath)}else{var aFile=this.index.fileSystem[0];this.setPath(aFile.substring(1,aFile.lastIndexOf("/")))}}else{this.render()}},setPath:function(path){this.path=path;this.render()},render:function(){DialogView.prototype.render.apply(this,arguments);this.$el.html(this.template(template));var endpoint=appContext.resolveEndPoint()+this.getEndpoint();var path="";if(this.path){path="&path="+encodeURIComponent(this.path)}var token=appContext.getAccessToken().access_token;this.$el.fileupload({beforeFinalSend:this.beforeFinalSend,chunkEndpoint:endpoint+"/upload/data?access_token="+token,finalEndpoint:endpoint+"/upload/complete?success=True&access_token="+token+"&forwardContext="+encodeURIComponent(endpoint)+path,layout:"Complex",ajaxLoader:appContext.getAppUrl()+"/styles/images/ajax-loader.gif",defaultContentType:"application/json; charset=UTF-8",fileComplete:this.message("m_file_upload_success"),filefinish:this.filefinish});return this},beforeFinalSend:function(xhr,options){xhr.setRequestHeader("X-File-Id",options.file.fuid);xhr.setRequestHeader("X-File-Name",options.file.name);xhr.setRequestHeader("X-File-Size",options.file.size);xhr.setRequestHeader("X-File-Type",options.file.type);var data={sharing:"MEMBERS",memberPermission:8};var file=this.index.metadata["/"+(this.path?this.path+"/":"")+options.file.name];if(file){data.id=file.ID}options.data=JSON.stringify(data)},filefinish:function(file,success,isError){if(isError){var bar=$("tr#file_"+file.fuid+" .progress-bar",this.$el);bar.text(this.message("m_file_upload_failure"))}},getEndpoint:function(){var context=this.options.context;var group=context.toJSON();if(context.type=="file"){group=context.get("group")}var accountId=group.contextKey.parent.objectId;return"/v2/accounts/"+accountId+"/groups/"+group.id+"/files"},cancel:function(){$(".modal").modal("hide")},close:function(){$(".modal").off("hidden.bs.modal",this.close);this.options.callback(this.options.context)}})});define("text!text/file/native-item.html",[],function(){return"<a class='item' href=\"javascript:void(0)\">\n  <img src=\"<%= appurl %>/svg/<%= extension %>.svg\" onerror='this.onerror = null; this.src=\"<%= appurl %>/svg/file.svg\"'>\n   <%= _.escape(file.name) %>\n</a>\n<div class='item progress hidden'>\n  <div class='progress-bar progress-bar-striped progress-bar-info'></div>\n</div>\n<div class='item failure hidden'>\n    <div class='progress-bar progress-bar-striped progress-bar-danger'>\n       <span><%= m_file_native_failure %></span>\n </div>\n</div>\n<div class='item success hidden'>\n <div class='progress-bar progress-bar-striped progress-bar-success'>\n      <span><b><%= _.escape(file.name) %></b><%= m_file_native_success %></span>\n    </div>\n</div>\n"});define("view/file/native-item",["ext/underscore","view/base","native","app-context","api/service/file","text!text/file/native-item.html"],function(_,BaseView,native,appContext,service,template){return BaseView.extend({tagName:"li",className:"native-item",events:{"click .failure, a":"select","click .success":"dismiss"},initialize:function(options){_.bindToMethods(this);this.options=options},render:function(){var args=_.extend({extension:this.getExtension(this.options.file)},this.options);this.$el.html(this.template(template,args));return this},getExtension:function(file){if(file.folder){return"folder"}var extensionPos=file.name.lastIndexOf(".");if(file.name.lastIndexOf("/")>extensionPos){return""}return file.name.substring(extensionPos+1).toLowerCase()},dismiss:function(){$(".item",this.$el).addClass("hidden");$("a",this.$el).removeClass("hidden")},select:function(){if(this.options.list.uploading){return}if(this.options.file.folder){var path=(this.options.path?this.options.path+"/":"")+this.options.file.name;var link="#native/"+this.options.context.getKey()+"/"+encodeURIComponent(path);appContext.navigate(link,true)}else{var self=this;this.retrievePath(function(path){self.retrieveFileId(path,function(fileId){self.upload(path,fileId)})});$(".item",this.$el).addClass("hidden");$(".progress",this.$el).removeClass("hidden")}},retrievePath:function(handler){if(this.options.context.type=="file"){$.get(appContext.fullUrl(this.options.context.url()+"path"),handler)}else{handler(null)}},retrieveFileId:function(path,handler){var endpoint=this.getEndpoint();if(this.options.context.type=="file"){endpoint+="/"+this.options.context.id}var self=this;$.get(appContext.fullUrl(endpoint+"/index"),function(index){index=JSON.parse($.base64.atob(index));var existing=index.metadata["/"+(path?path+"/":"")+self.options.file.name];var fileId=null;if(existing){fileId=existing.ID}handler(fileId)})},upload:function(path,fileId){var file=(this.options.path?this.options.path+"/":"")+this.options.file.name;this.options.list.uploading=true;var token=appContext.getAccessToken().access_token;var endpoint=appContext.resolveEndPoint()+this.getEndpoint();native.upload(file,endpoint,token,path,fileId,this.progress)},getEndpoint:function(){var context=this.options.context;var group=context.toJSON();if(context.type=="file"){group=context.get("group")}var accountId=group.contextKey.parent.objectId;return"/v2/accounts/"+accountId+"/groups/"+group.id+"/files"},progress:function(percent){if(percent==-1){this.finish();$(".failure",this.$el).removeClass("hidden")}else if(percent==100){this.finish();$(".success",this.$el).removeClass("hidden")}else{$(".progress-bar-info",this.$el).css("width",percent+"%").html("<span>"+percent+"%</span>")}},finish:function(){this.options.list.uploading=false;$(".item",this.$el).addClass("hidden");$(".progress-bar-info",this.$el).css("width",0).html("")}})});define("view/file/native-list",["ext/underscore","view/page","view/file/native-item"],function(_,PageView,NativeItemView){return PageView.extend({tagName:"ul",className:"list-unstyled",title:PageView.message("m_file_native_header"),nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);
    11 this.action={code:"m_cancel",link:"#files/"+this.options.context.getKey()};if(this.options.path){this.title=this.options.path;var path="";var last=this.options.path.lastIndexOf("/");if(last!=-1){path=this.options.path.substr(0,last);path="/"+encodeURIComponent(path);this.title=this.options.path.substr(last+1)}this.back={code:"m_back",link:"#native/"+this.options.context.getKey()+path}}},render:function(){PageView.prototype.render.apply(this,arguments);_.each(this.options.files,function(file){var view=new NativeItemView({list:this,context:this.options.context,path:this.options.path,file:file});this.$el.append(view.render().el)},this);return this}})});define("text!text/file/view.html",[],function(){return"<% if (type == 'image') { %>\n <img class=\"sized\" src=\"<%= preview %>\">\n<% } %>\n<div class=\"entity-info\" >\n   <p><%= m_file_uploader %>: <%= model.get('uploaded').name %></p>\n  <p>\n       <img src=\"<%= cdn %>/users/<%= model.get('uploaded').id %>/thumbnail\" \n          onerror='this.onerror = null; this.src=\"<%= appurl %>/styles/images/default_thumbnail.png\"'>\n    </p>\n  <p><%= m_on %>: <%= lastModified.format('ddd, DD MMM YYYY, HH:mm') %></p>\n <p><%= m_version %>: <%= model.get('versions') %></p>\n <p><%= m_size %>: <%= size %></p>\n <p>\n       <img src=\"<%= appurl %>/svg/<%= model.getExtension() %>.svg\" \n           onerror='this.onerror = null; this.src=\"<%= appurl %>/svg/file.svg\"'>\n   </p>\n  <% if (type != 'document' && type != 'image') { %>\n        <p><%= m_file_preview_failed %></p>\n   <% } %>\n</div>\n<% if (type == 'document') { %>\n  <a href=\"javascript:void(0)\" class=\"btn btn-primary preview\">\n     <%= m_preview %>\n  </a>\n<% } %>\n"});define("view/file/view",["ext/underscore","native","view/page","moment","app-context","view/navbar-factory","text!text/file/view.html"],function(_,native,PageView,moment,appContext,navbarFactory,template){return PageView.extend({KB:1024,MB:1024*1024,GB:1024*1024*1024,tagName:"fieldset",events:{"click a.preview":"preview"},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.back=this.options.back;this.title=this.model.get("friendlyName");this.actions=[{code:"m_comments",icon:"comment",link:"#comments/"+this.model.getKey()}];if(this.model.permission.canEdit()){this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()})}if(native.list&&!native.upload){this.actions.unshift({code:"m_download",link:appContext.fullUrl(this.model.url()+"download")})}},render:function(){PageView.prototype.render.apply(this,arguments);var args={type:this.options.type,model:this.model,lastModified:moment(this.model.get("lastModified")),size:this.formatSize(),cdn:appContext.cdn,preview:appContext.fullUrl(this.model.url()+"preview")};this.$el.html(this.template(template,args));return this},formatSize:function(){var size=this.model.get("size");var unit="bytes";var divisor=1;if(size>this.GB){unit="GB";divisor=this.GB}else if(size>this.MB){unit="MB";divisor=this.MB}else if(size>this.KB){unit="KB";divisor=this.KB}return Math.round(size*10/divisor)/10+" "+unit},navbar:function(callback){this.navbarCreate("files",this.model.getGroup().id,callback)},preview:function(){appContext.preview(this.model,this.options.type=="document")}}).extend(navbarFactory)});define("router/file",["ext/underscore","app-context","api/cache","native","router/base","api/service/file","api/collection/files","view/file/list","view/sort-action","view/file/upload","view/file/native-list","view/file/view"],function(_,appContext,cache,native,BaseRouter,service,Files,FileListView,SortActionView,FileUploadView,NativeListView,FileViewView){return BaseRouter.extend({routes:{"files/:contextKey":"getFiles","file/:fileKey":"getFile","native/:contextKey/:path":"getNative","native/:contextKey":"getNative"},getFiles:function(contextKey){service.getCachedFiles(contextKey,this.showFiles)},showFiles:function(files){var view=this.createFileListView(files.context,files);view.render();view.handleRefresh()},getFile:function(fileKey){var parts=fileKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getFile(group,parts[3],this.handleFile)},handleFile:function(file){if(file.isFolder()){var children=file.get("children");if(children){var files=new Files(children.page,{context:file,params:service.createFileParams(1)});files.more=children.nextPage;cache.putModel(files);files.each(function(file){cache.putModel(file)});var view=this.createFileListView(file,files);view.render()}else{this.getFiles(file.getKey())}}else{this.showFile(file)}},showFile:function(file){var type=this.getFileType(file);var view=new FileViewView({back:this.createFileBack(file),model:file,type:type});if(type=="unknown"||type=="image"||native.popupPreview){view.render()}else{appContext.setHeader(view);_.defer(function(){appContext.preview(file,type=="document")})}},getFileType:function(file){var contentType=file.get("contentType");if(_.startsWith(contentType,"image/")){return"image"}if(_.startsWith(contentType,"video/")){return"video"}if(_.startsWith(contentType,"audio/")&&native.audioPreview){return"video"}if(_.find(appContext.mimetypes,function(mimetype){return this==mimetype},contentType)){return"document"}return"unknown"},createFileListView:function(context,collection){var canCreate=context.permission.canCreate();if(native.upload&&canCreate){var action={code:"m_actions_upload",link:"#native/"+context.getKey()}}else if(native.list&&canCreate){var action={code:"m_actions_upload",view:new FileUploadView({context:context,callback:this.refresh})}}else{var action={code:"m_actions_sort",view:new SortActionView({context:context,sort:appContext.getFileSort(),callback:this.sortFiles})}}return new FileListView({back:this.createFileBack(context),action:action,collection:collection})},sortFiles:function(context,field){appContext.setFileSort(field);this.refresh(context)},refresh:function(context){appContext.navigate("#files/"+context.getKey(),true)},createFileBack:function(context){if(context.type=="group"){return{code:"m_btn_context",link:"#context"}}var parent=context.get("parent");if(parent.type=="group"){return{code:"m_btn_files",link:"#files/groups:@"+parent.id}}return{code:"m_back",link:"#file/groups:@"+context.get("group").id+":files:@"+parent.id}},getNative:function(contextKey,path){service.getContext(contextKey,function(context){native.list(path,function(files){var view=new NativeListView({context:context,path:path,files:files});view.render()})})}})});define("router/group",["router/base","api/cache","api/model/group","api/model/permission"],function(BaseRouter,cache,Group,Permission){return BaseRouter.extend({execute:function(callback,args){var groupId=this.getGroupId(args);if(groupId){args.unshift(cache.getFrom(new Group({id:groupId})));this.retrieveGroupWithPermission(callback,args)}else{callback.apply(this,args)}},getGroupId:function(args){if(args.length>0){var key=args[0].split(":");if(key.length==2&&key[0]=="groups"){return key[1].substr(1)}}return null},retrieveGroupWithPermission:function(callback,args){var group=args[0];this.retrieveGroup(group,function(){if(group.permission){callback.apply(self,args)}else{var permission=new Permission({},{context:group});permission.once("sync",function(){group.permission=permission;callback.apply(self,args)});permission.fetch()}})},retrieveGroup:function(group,handler){if(group.get("components")){handler()}else{group.once("change",function(){cache.putModel(group);handler()});group.fetch()}}})});define("api/collection/content",["api/collection/more","api/model/file"],function(MoreCollection,File){return MoreCollection.extend({initialize:function(models,options){MoreCollection.prototype.initialize.apply(this,arguments);if(options){this.group=options.group}},url:function(){return"/groups/@"+this.group.id+"/"+this.model.type+"s"}})});define("api/collection/notes",["api/collection/content","api/model/note"],function(ContentCollection,Note){return ContentCollection.extend({model:Note,_getKey:function(key){return key+":"+this.params.orderBy}})});define("api/service/note",["ext/underscore","app-context","api/cache","api/service/base","api/collection/notes","api/model/note"],function(_,appContext,cache,base,Notes,Note){return _.extend({getNotes:function(group,handler){var notes=this.createNotes(group,1);cache.putModel(notes);this.getCollection(notes,handler)},getNextNotes:function(notes,handler){var next=this.createNotes(notes.group,notes.params.currentPage+1);this.getCollection(next,function(next){notes.add(next.models);notes.params.currentPage=next.params.currentPage;notes.more=next.more;handler(next)})},getNote:function(group,id,handler){var self=this;this.getNoteOnly(group,id,function(note){self.getPermission(note,handler)})},getNoteOnly:function(group,id,handler){var note=new Note({name:id});if(id.charAt(0)=="@"){note=new Note({id:parseInt(id.slice(1))})}note.set("group",group);note=cache.getFrom(note);if(note._expiry&&note.get("content")){handler(note);return}cache.putModel(note);note.once("change",handler);note.fetch()},createNotes:function(group,currentPage){var orderBy=appContext.getNoteSort();return new Notes([],{group:group,params:{type:"page",currentPage:currentPage,pageSize:appContext.pageSize,orderBy:orderBy,ascending:orderBy=="name"}})}},base)});define("text!text/note-item.html",[],function(){return"<a class=\"no-icon\" href=\"#note/<%= getKey() %>\">\n   <p><b><%= _.escape(get('friendlyName')) %></b></p>\n    <abbr><%= m_last_updated %>: <%= $.timeago(new Date(get('lastModified'))) %></abbr>\n</a>\n"});define("view/note/item",["view/base","text!text/note-item.html"],function(BaseView,template){return BaseView.extend({tagName:"li",className:"fat",render:function(){this.$el.html(this.template(template,this.model));return this}})});define("view/note/list",["ext/underscore","app-context","view/navbar-factory","view/extending-list","view/sort-action","view/note/item","api/service/note"],function(_,appContext,navbarFactory,ExtendingListView,SortActionView,NoteItemView,service){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);this.title=_.escape(this.collection.group.get("friendlyName"));this.action={code:"m_actions_sort",view:new SortActionView({context:this.collection.group,sort:appContext.getNoteSort(),callback:this.sortNotes})}},sortNotes:function(context,field){appContext.setNoteSort(field);appContext.navigate("#notes/"+context.getKey(),true)},emptyMsgCode:"m_notes_nothing",itemViewClass:NoteItemView,handleEndOfList:function(){service.getNextNotes(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getNotes(this.collection.group,function(pages){self.collection=pages;self.refresh()})},navbar:function(callback){this.navbarCreate("pages",this.collection.group.id,callback)}}).extend(navbarFactory)});define("api/model/attachment",["api/model/base"],function(BaseModel){return BaseModel.extend({url:function(){var container=this.get("parent");var id=this.id?"@"+this.id:this.get("name");return"/groups/@"+container.group.id+"/"+container.type+"s/@"+container.id+"/attachments/"+id+"/"}})});define("view/link-resolver",["ext/underscore","app-context","api/factory","api/model/attachment"],function(_,appContext,factory,Attachment){var $=jQuery;var linkResolver={handleImage:function(element,parts){element.src=appContext.fullUrl("/groups/@"+this.model.getGroup().id+"/pages/"+this.model.get("name")+"/attachments/"+parts[0]+"/preview")},handleDocument:function(element,parts){var link=$("<a>").attr("href","javascript:void(0)").html(parts[0]).click(_.bind(this.showAttachment,this,parts[0]));$(element).replaceWith(link)},showAttachment:function(fileName){var attachment=new Attachment({name:fileName,parent:this.model.toJSON()});attachment.on("change",function(){appContext.preview(this)});attachment.fetch()},handleVideo:function(element){element.src=appContext.getAppUrl()+"/styles/images/video_preview.png"},handleLinks:function(element,parts){if(parts[0]=="url"){$(element).attr("data-external",true);return}var entity=factory.createEntity({type:parts[0],group:this.model.getGroup().toJSON(),name:parts[1]});if(entity){element.href="#"+parts[0]+"/"+entity.getKey()}else{$(element).removeAttr("href")}},resolveLinks:function(){_.each($("[media_link]",this.$el),function(element){var parts=$(element).attr("media_link").split(":");var handler=this.handlers[parts[0]];handler&&handler.apply(this,[element,_.rest(parts)])},this)}};linkResolver.handlers={attachment:linkResolver.handleImage,attachment_document:linkResolver.handleDocument,video:linkResolver.handleVideo,attachment_video:linkResolver.handleVideo,link:linkResolver.handleLinks};return linkResolver});(function(window,doc){var m=Math,dummyStyle=doc.createElement("div").style,vendor=function(){var vendors="t,webkitT,MozT,msT,OT".split(","),t,i=0,l=vendors.length;for(;i<l;i++){t=vendors[i]+"ransform";if(t in dummyStyle){return vendors[i].substr(0,vendors[i].length-1)}}return false}(),cssVendor=vendor?"-"+vendor.toLowerCase()+"-":"",transform=prefixStyle("transform"),transitionProperty=prefixStyle("transitionProperty"),transitionDuration=prefixStyle("transitionDuration"),transformOrigin=prefixStyle("transformOrigin"),transitionTimingFunction=prefixStyle("transitionTimingFunction"),transitionDelay=prefixStyle("transitionDelay"),isAndroid=/android/gi.test(navigator.appVersion),isIDevice=/iphone|ipad/gi.test(navigator.appVersion),isTouchPad=/hp-tablet/gi.test(navigator.appVersion),has3d=prefixStyle("perspective")in dummyStyle,hasTouch="ontouchstart"in window&&!isTouchPad,hasTransform=vendor!==false,hasTransitionEnd=prefixStyle("transition")in dummyStyle,RESIZE_EV="onorientationchange"in window?"orientationchange":"resize",START_EV=hasTouch?"touchstart":"mousedown",MOVE_EV=hasTouch?"touchmove":"mousemove",END_EV=hasTouch?"touchend":"mouseup",CANCEL_EV=hasTouch?"touchcancel":"mouseup",WHEEL_EV=vendor=="Moz"?"DOMMouseScroll":"mousewheel",TRNEND_EV=function(){if(vendor===false)return false;var transitionEnd={"":"transitionend",webkit:"webkitTransitionEnd",Moz:"transitionend",O:"otransitionend",ms:"MSTransitionEnd"};return transitionEnd[vendor]}(),nextFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){return setTimeout(callback,1)}}(),cancelFrame=function(){return window.cancelRequestAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.mozCancelRequestAnimationFrame||window.oCancelRequestAnimationFrame||window.msCancelRequestAnimationFrame||clearTimeout}(),translateZ=has3d?" translateZ(0)":"",iScroll=function(el,options){var that=this,i;that.wrapper=typeof el=="object"?el:doc.getElementById(el);that.wrapper.style.overflow="hidden";that.scroller=that.wrapper.children[0];that.options={hScroll:true,vScroll:true,x:0,y:0,bounce:true,bounceLock:false,momentum:true,lockDirection:true,useTransform:true,useTransition:false,topOffset:0,checkDOMChanges:false,handleClick:true,hScrollbar:true,vScrollbar:true,fixedScrollbar:isAndroid,hideScrollbar:isIDevice,fadeScrollbar:isIDevice&&has3d,scrollbarClass:"",zoom:false,zoomMin:1,zoomMax:4,doubleTapZoom:2,wheelAction:"scroll",snap:false,snapThreshold:1,onRefresh:null,onBeforeScrollStart:function(e){e.preventDefault()},onScrollStart:null,onBeforeScrollMove:null,onScrollMove:null,onBeforeScrollEnd:null,onScrollEnd:null,onTouchEnd:null,onDestroy:null,onZoomStart:null,onZoom:null,onZoomEnd:null};for(i in options)that.options[i]=options[i];that.x=that.options.x;that.y=that.options.y;that.options.useTransform=hasTransform&&that.options.useTransform;that.options.hScrollbar=that.options.hScroll&&that.options.hScrollbar;that.options.vScrollbar=that.options.vScroll&&that.options.vScrollbar;that.options.zoom=that.options.useTransform&&that.options.zoom;that.options.useTransition=hasTransitionEnd&&that.options.useTransition;if(that.options.zoom&&isAndroid){translateZ=""}that.scroller.style[transitionProperty]=that.options.useTransform?cssVendor+"transform":"top left";that.scroller.style[transitionDuration]="0";that.scroller.style[transformOrigin]="0 0";if(that.options.useTransition)that.scroller.style[transitionTimingFunction]="cubic-bezier(0.33,0.66,0.66,1)";if(that.options.useTransform)that.scroller.style[transform]="translate("+that.x+"px,"+that.y+"px)"+translateZ;else that.scroller.style.cssText+=";position:absolute;top:"+that.y+"px;left:"+that.x+"px";if(that.options.useTransition)that.options.fixedScrollbar=true;that.refresh();that._bind(RESIZE_EV,window);that._bind(START_EV);if(!hasTouch){if(that.options.wheelAction!="none")that._bind(WHEEL_EV)}if(that.options.checkDOMChanges)that.checkDOMTime=setInterval(function(){that._checkDOMChanges()},500)};iScroll.prototype={enabled:true,x:0,y:0,steps:[],scale:1,currPageX:0,currPageY:0,pagesX:[],pagesY:[],aniTime:null,wheelZoomCount:0,handleEvent:function(e){var that=this;switch(e.type){case START_EV:if(!hasTouch&&e.button!==0)return;that._start(e);break;case MOVE_EV:that._move(e);break;case END_EV:case CANCEL_EV:that._end(e);break;case RESIZE_EV:that._resize();break;case WHEEL_EV:that._wheel(e);break;case TRNEND_EV:that._transitionEnd(e);break}},_checkDOMChanges:function(){if(this.moved||this.zoomed||this.animating||this.scrollerW==this.scroller.offsetWidth*this.scale&&this.scrollerH==this.scroller.offsetHeight*this.scale)return;this.refresh()},_scrollbar:function(dir){var that=this,bar;if(!that[dir+"Scrollbar"]){if(that[dir+"ScrollbarWrapper"]){if(hasTransform)that[dir+"ScrollbarIndicator"].style[transform]="";that[dir+"ScrollbarWrapper"].parentNode.removeChild(that[dir+"ScrollbarWrapper"]);that[dir+"ScrollbarWrapper"]=null;that[dir+"ScrollbarIndicator"]=null}return}if(!that[dir+"ScrollbarWrapper"]){bar=doc.createElement("div");if(that.options.scrollbarClass)bar.className=that.options.scrollbarClass+dir.toUpperCase();else bar.style.cssText="position:absolute;z-index:100;"+(dir=="h"?"height:7px;bottom:1px;left:2px;right:"+(that.vScrollbar?"7":"2")+"px":"width:7px;bottom:"+(that.hScrollbar?"7":"2")+"px;top:2px;right:1px");bar.style.cssText+=";pointer-events:none;"+cssVendor+"transition-property:opacity;"+cssVendor+"transition-duration:"+(that.options.fadeScrollbar?"350ms":"0")+";overflow:hidden;opacity:"+(that.options.hideScrollbar?"0":"1");that.wrapper.appendChild(bar);that[dir+"ScrollbarWrapper"]=bar;bar=doc.createElement("div");if(!that.options.scrollbarClass){bar.style.cssText="position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);"+cssVendor+"background-clip:padding-box;"+cssVendor+"box-sizing:border-box;"+(dir=="h"?"height:100%":"width:100%")+";"+cssVendor+"border-radius:3px;border-radius:3px"}bar.style.cssText+=";pointer-events:none;"+cssVendor+"transition-property:"+cssVendor+"transform;"+cssVendor+"transition-timing-function:cubic-bezier(0.33,0.66,0.66,1);"+cssVendor+"transition-duration:0;"+cssVendor+"transform: translate(0,0)"+translateZ;if(that.options.useTransition)bar.style.cssText+=";"+cssVendor+"transition-timing-function:cubic-bezier(0.33,0.66,0.66,1)";that[dir+"ScrollbarWrapper"].appendChild(bar);that[dir+"ScrollbarIndicator"]=bar}if(dir=="h"){that.hScrollbarSize=that.hScrollbarWrapper.clientWidth;that.hScrollbarIndicatorSize=m.max(m.round(that.hScrollbarSize*that.hScrollbarSize/that.scrollerW),8);that.hScrollbarIndicator.style.width=that.hScrollbarIndicatorSize+"px";that.hScrollbarMaxScroll=that.hScrollbarSize-that.hScrollbarIndicatorSize;that.hScrollbarProp=that.hScrollbarMaxScroll/that.maxScrollX}else{that.vScrollbarSize=that.vScrollbarWrapper.clientHeight;that.vScrollbarIndicatorSize=m.max(m.round(that.vScrollbarSize*that.vScrollbarSize/that.scrollerH),8);that.vScrollbarIndicator.style.height=that.vScrollbarIndicatorSize+"px";that.vScrollbarMaxScroll=that.vScrollbarSize-that.vScrollbarIndicatorSize;that.vScrollbarProp=that.vScrollbarMaxScroll/that.maxScrollY}that._scrollbarPos(dir,true)},_resize:function(){var that=this;setTimeout(function(){that.refresh()},isAndroid?200:0)},_pos:function(x,y){if(this.zoomed)return;x=this.hScroll?x:0;y=this.vScroll?y:0;if(this.options.useTransform){this.scroller.style[transform]="translate("+x+"px,"+y+"px) scale("+this.scale+")"+translateZ}else{x=m.round(x);y=m.round(y);this.scroller.style.left=x+"px";this.scroller.style.top=y+"px"}this.x=x;this.y=y;this._scrollbarPos("h");this._scrollbarPos("v")},_scrollbarPos:function(dir,hidden){var that=this,pos=dir=="h"?that.x:that.y,size;if(!that[dir+"Scrollbar"])return;pos=that[dir+"ScrollbarProp"]*pos;if(pos<0){if(!that.options.fixedScrollbar){size=that[dir+"ScrollbarIndicatorSize"]+m.round(pos*3);if(size<8)size=8;that[dir+"ScrollbarIndicator"].style[dir=="h"?"width":"height"]=size+"px"}pos=0}else if(pos>that[dir+"ScrollbarMaxScroll"]){if(!that.options.fixedScrollbar){size=that[dir+"ScrollbarIndicatorSize"]-m.round((pos-that[dir+"ScrollbarMaxScroll"])*3);if(size<8)size=8;that[dir+"ScrollbarIndicator"].style[dir=="h"?"width":"height"]=size+"px";pos=that[dir+"ScrollbarMaxScroll"]+(that[dir+"ScrollbarIndicatorSize"]-size)}else{pos=that[dir+"ScrollbarMaxScroll"]}}that[dir+"ScrollbarWrapper"].style[transitionDelay]="0";that[dir+"ScrollbarWrapper"].style.opacity=hidden&&that.options.hideScrollbar?"0":"1";that[dir+"ScrollbarIndicator"].style[transform]="translate("+(dir=="h"?pos+"px,0)":"0,"+pos+"px)")+translateZ},_start:function(e){var that=this,point=hasTouch?e.touches[0]:e,matrix,x,y,c1,c2;if(!that.enabled)return;if(that.options.onBeforeScrollStart)that.options.onBeforeScrollStart.call(that,e);if(that.options.useTransition||that.options.zoom)that._transitionTime(0);that.moved=false;that.animating=false;that.zoomed=false;that.distX=0;that.distY=0;that.absDistX=0;that.absDistY=0;that.dirX=0;that.dirY=0;if(that.options.zoom&&hasTouch&&e.touches.length>1){c1=m.abs(e.touches[0].pageX-e.touches[1].pageX);c2=m.abs(e.touches[0].pageY-e.touches[1].pageY);that.touchesDistStart=m.sqrt(c1*c1+c2*c2);that.originX=m.abs(e.touches[0].pageX+e.touches[1].pageX-that.wrapperOffsetLeft*2)/2-that.x;that.originY=m.abs(e.touches[0].pageY+e.touches[1].pageY-that.wrapperOffsetTop*2)/2-that.y;if(that.options.onZoomStart)that.options.onZoomStart.call(that,e)}if(that.options.momentum){if(that.options.useTransform){matrix=getComputedStyle(that.scroller,null)[transform].replace(/[^0-9\-.,]/g,"").split(",");x=+matrix[4];y=+matrix[5]}else{x=+getComputedStyle(that.scroller,null).left.replace(/[^0-9-]/g,"");y=+getComputedStyle(that.scroller,null).top.replace(/[^0-9-]/g,"")}if(x!=that.x||y!=that.y){if(that.options.useTransition)that._unbind(TRNEND_EV);else cancelFrame(that.aniTime);that.steps=[];that._pos(x,y);if(that.options.onScrollEnd)that.options.onScrollEnd.call(that)}}that.absStartX=that.x;that.absStartY=that.y;that.startX=that.x;that.startY=that.y;that.pointX=point.pageX;that.pointY=point.pageY;that.startTime=e.timeStamp||Date.now();if(that.options.onScrollStart)that.options.onScrollStart.call(that,e);that._bind(MOVE_EV,window);that._bind(END_EV,window);that._bind(CANCEL_EV,window)},_move:function(e){var that=this,point=hasTouch?e.touches[0]:e,deltaX=point.pageX-that.pointX,deltaY=point.pageY-that.pointY,newX=that.x+deltaX,newY=that.y+deltaY,c1,c2,scale,timestamp=e.timeStamp||Date.now();if(that.options.onBeforeScrollMove)that.options.onBeforeScrollMove.call(that,e);if(that.options.zoom&&hasTouch&&e.touches.length>1){c1=m.abs(e.touches[0].pageX-e.touches[1].pageX);c2=m.abs(e.touches[0].pageY-e.touches[1].pageY);that.touchesDist=m.sqrt(c1*c1+c2*c2);that.zoomed=true;scale=1/that.touchesDistStart*that.touchesDist*this.scale;if(scale<that.options.zoomMin)scale=.5*that.options.zoomMin*Math.pow(2,scale/that.options.zoomMin);else if(scale>that.options.zoomMax)scale=2*that.options.zoomMax*Math.pow(.5,that.options.zoomMax/scale);that.lastScale=scale/this.scale;newX=this.originX-this.originX*that.lastScale+this.x,newY=this.originY-this.originY*that.lastScale+this.y;this.scroller.style[transform]="translate("+newX+"px,"+newY+"px) scale("+scale+")"+translateZ;if(that.options.onZoom)that.options.onZoom.call(that,e);return}that.pointX=point.pageX;that.pointY=point.pageY;if(newX>0||newX<that.maxScrollX){newX=that.options.bounce?that.x+deltaX/2:newX>=0||that.maxScrollX>=0?0:that.maxScrollX}if(newY>that.minScrollY||newY<that.maxScrollY){newY=that.options.bounce?that.y+deltaY/2:newY>=that.minScrollY||that.maxScrollY>=0?that.minScrollY:that.maxScrollY}that.distX+=deltaX;that.distY+=deltaY;that.absDistX=m.abs(that.distX);that.absDistY=m.abs(that.distY);if(that.absDistX<6&&that.absDistY<6){return}if(that.options.lockDirection){if(that.absDistX>that.absDistY+5){newY=that.y;deltaY=0}else if(that.absDistY>that.absDistX+5){newX=that.x;deltaX=0}}that.moved=true;that._pos(newX,newY);that.dirX=deltaX>0?-1:deltaX<0?1:0;that.dirY=deltaY>0?-1:deltaY<0?1:0;if(timestamp-that.startTime>300){that.startTime=timestamp;that.startX=that.x;that.startY=that.y}if(that.options.onScrollMove)that.options.onScrollMove.call(that,e)},_end:function(e){if(hasTouch&&e.touches.length!==0)return;var that=this,point=hasTouch?e.changedTouches[0]:e,target,ev,momentumX={dist:0,time:0},momentumY={dist:0,time:0},duration=(e.timeStamp||Date.now())-that.startTime,newPosX=that.x,newPosY=that.y,distX,distY,newDuration,snap,scale;that._unbind(MOVE_EV,window);that._unbind(END_EV,window);that._unbind(CANCEL_EV,window);if(that.options.onBeforeScrollEnd)that.options.onBeforeScrollEnd.call(that,e);if(that.zoomed){scale=that.scale*that.lastScale;scale=Math.max(that.options.zoomMin,scale);scale=Math.min(that.options.zoomMax,scale);that.lastScale=scale/that.scale;that.scale=scale;that.x=that.originX-that.originX*that.lastScale+that.x;that.y=that.originY-that.originY*that.lastScale+that.y;that.scroller.style[transitionDuration]="200ms";that.scroller.style[transform]="translate("+that.x+"px,"+that.y+"px) scale("+that.scale+")"+translateZ;that.zoomed=false;that.refresh();if(that.options.onZoomEnd)that.options.onZoomEnd.call(that,e);return}if(!that.moved){if(hasTouch){if(that.doubleTapTimer&&that.options.zoom){clearTimeout(that.doubleTapTimer);that.doubleTapTimer=null;if(that.options.onZoomStart)that.options.onZoomStart.call(that,e);that.zoom(that.pointX,that.pointY,that.scale==1?that.options.doubleTapZoom:1);if(that.options.onZoomEnd){setTimeout(function(){that.options.onZoomEnd.call(that,e)},200)}}else if(this.options.handleClick){that.doubleTapTimer=setTimeout(function(){that.doubleTapTimer=null;target=point.target;while(target.nodeType!=1)target=target.parentNode;if(target.tagName!="SELECT"&&target.tagName!="INPUT"&&target.tagName!="TEXTAREA"){ev=doc.createEvent("MouseEvents");ev.initMouseEvent("click",true,true,e.view,1,point.screenX,point.screenY,point.clientX,point.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,0,null);ev._fake=true;target.dispatchEvent(ev)}},that.options.zoom?250:0)}}that._resetPos(400);if(that.options.onTouchEnd)that.options.onTouchEnd.call(that,e);return}if(duration<300&&that.options.momentum){momentumX=newPosX?that._momentum(newPosX-that.startX,duration,-that.x,that.scrollerW-that.wrapperW+that.x,that.options.bounce?that.wrapperW:0):momentumX;momentumY=newPosY?that._momentum(newPosY-that.startY,duration,-that.y,that.maxScrollY<0?that.scrollerH-that.wrapperH+that.y-that.minScrollY:0,that.options.bounce?that.wrapperH:0):momentumY;newPosX=that.x+momentumX.dist;newPosY=that.y+momentumY.dist;if(that.x>0&&newPosX>0||that.x<that.maxScrollX&&newPosX<that.maxScrollX)momentumX={dist:0,time:0};if(that.y>that.minScrollY&&newPosY>that.minScrollY||that.y<that.maxScrollY&&newPosY<that.maxScrollY)momentumY={dist:0,time:0}}if(momentumX.dist||momentumY.dist){newDuration=m.max(m.max(momentumX.time,momentumY.time),10);if(that.options.snap){distX=newPosX-that.absStartX;distY=newPosY-that.absStartY;if(m.abs(distX)<that.options.snapThreshold&&m.abs(distY)<that.options.snapThreshold){that.scrollTo(that.absStartX,that.absStartY,200)}else{snap=that._snap(newPosX,newPosY);newPosX=snap.x;newPosY=snap.y;newDuration=m.max(snap.time,newDuration)}}that.scrollTo(m.round(newPosX),m.round(newPosY),newDuration);if(that.options.onTouchEnd)that.options.onTouchEnd.call(that,e);return}if(that.options.snap){distX=newPosX-that.absStartX;distY=newPosY-that.absStartY;if(m.abs(distX)<that.options.snapThreshold&&m.abs(distY)<that.options.snapThreshold)that.scrollTo(that.absStartX,that.absStartY,200);else{snap=that._snap(that.x,that.y);if(snap.x!=that.x||snap.y!=that.y)that.scrollTo(snap.x,snap.y,snap.time)}if(that.options.onTouchEnd)that.options.onTouchEnd.call(that,e);return}that._resetPos(200);if(that.options.onTouchEnd)that.options.onTouchEnd.call(that,e)},_resetPos:function(time){var that=this,resetX=that.x>=0?0:that.x<that.maxScrollX?that.maxScrollX:that.x,resetY=that.y>=that.minScrollY||that.maxScrollY>0?that.minScrollY:that.y<that.maxScrollY?that.maxScrollY:that.y;if(resetX==that.x&&resetY==that.y){if(that.moved){that.moved=false;if(that.options.onScrollEnd)that.options.onScrollEnd.call(that)}if(that.hScrollbar&&that.options.hideScrollbar){if(vendor=="webkit")that.hScrollbarWrapper.style[transitionDelay]="300ms";that.hScrollbarWrapper.style.opacity="0"}if(that.vScrollbar&&that.options.hideScrollbar){if(vendor=="webkit")that.vScrollbarWrapper.style[transitionDelay]="300ms";that.vScrollbarWrapper.style.opacity="0"}return}that.scrollTo(resetX,resetY,time||0)},_wheel:function(e){var that=this,wheelDeltaX,wheelDeltaY,deltaX,deltaY,deltaScale;if("wheelDeltaX"in e){wheelDeltaX=e.wheelDeltaX/12;wheelDeltaY=e.wheelDeltaY/12}else if("wheelDelta"in e){wheelDeltaX=wheelDeltaY=e.wheelDelta/12}else if("detail"in e){wheelDeltaX=wheelDeltaY=-e.detail*3}else{return}if(that.options.wheelAction=="zoom"){deltaScale=that.scale*Math.pow(2,1/3*(wheelDeltaY?wheelDeltaY/Math.abs(wheelDeltaY):0));if(deltaScale<that.options.zoomMin)deltaScale=that.options.zoomMin;if(deltaScale>that.options.zoomMax)deltaScale=that.options.zoomMax;if(deltaScale!=that.scale){if(!that.wheelZoomCount&&that.options.onZoomStart)that.options.onZoomStart.call(that,e);that.wheelZoomCount++;that.zoom(e.pageX,e.pageY,deltaScale,400);setTimeout(function(){that.wheelZoomCount--;if(!that.wheelZoomCount&&that.options.onZoomEnd)that.options.onZoomEnd.call(that,e)},400)}return}deltaX=that.x+wheelDeltaX;deltaY=that.y+wheelDeltaY;if(deltaX>0)deltaX=0;else if(deltaX<that.maxScrollX)deltaX=that.maxScrollX;if(deltaY>that.minScrollY)deltaY=that.minScrollY;else if(deltaY<that.maxScrollY)deltaY=that.maxScrollY;if(that.maxScrollY<0){that.scrollTo(deltaX,deltaY,0)}},_transitionEnd:function(e){var that=this;if(e.target!=that.scroller)return;that._unbind(TRNEND_EV);that._startAni()},_startAni:function(){var that=this,startX=that.x,startY=that.y,startTime=Date.now(),step,easeOut,animate;if(that.animating)return;if(!that.steps.length){that._resetPos(400);return}step=that.steps.shift();if(step.x==startX&&step.y==startY)step.time=0;that.animating=true;that.moved=true;if(that.options.useTransition){that._transitionTime(step.time);that._pos(step.x,step.y);that.animating=false;if(step.time)that._bind(TRNEND_EV);else that._resetPos(0);return}animate=function(){var now=Date.now(),newX,newY;if(now>=startTime+step.time){that._pos(step.x,step.y);that.animating=false;if(that.options.onAnimationEnd)that.options.onAnimationEnd.call(that);that._startAni();return}now=(now-startTime)/step.time-1;easeOut=m.sqrt(1-now*now);newX=(step.x-startX)*easeOut+startX;newY=(step.y-startY)*easeOut+startY;that._pos(newX,newY);if(that.animating)that.aniTime=nextFrame(animate)};animate()},_transitionTime:function(time){time+="ms";this.scroller.style[transitionDuration]=time;if(this.hScrollbar)this.hScrollbarIndicator.style[transitionDuration]=time;if(this.vScrollbar)this.vScrollbarIndicator.style[transitionDuration]=time},_momentum:function(dist,time,maxDistUpper,maxDistLower,size){var deceleration=6e-4,speed=m.abs(dist)/time,newDist=speed*speed/(2*deceleration),newTime=0,outsideDist=0;
    12 if(dist>0&&newDist>maxDistUpper){outsideDist=size/(6/(newDist/speed*deceleration));maxDistUpper=maxDistUpper+outsideDist;speed=speed*maxDistUpper/newDist;newDist=maxDistUpper}else if(dist<0&&newDist>maxDistLower){outsideDist=size/(6/(newDist/speed*deceleration));maxDistLower=maxDistLower+outsideDist;speed=speed*maxDistLower/newDist;newDist=maxDistLower}newDist=newDist*(dist<0?-1:1);newTime=speed/deceleration;return{dist:newDist,time:m.round(newTime)}},_offset:function(el){var left=-el.offsetLeft,top=-el.offsetTop;while(el=el.offsetParent){left-=el.offsetLeft;top-=el.offsetTop}if(el!=this.wrapper){left*=this.scale;top*=this.scale}return{left:left,top:top}},_snap:function(x,y){var that=this,i,l,page,time,sizeX,sizeY;page=that.pagesX.length-1;for(i=0,l=that.pagesX.length;i<l;i++){if(x>=that.pagesX[i]){page=i;break}}if(page==that.currPageX&&page>0&&that.dirX<0)page--;x=that.pagesX[page];sizeX=m.abs(x-that.pagesX[that.currPageX]);sizeX=sizeX?m.abs(that.x-x)/sizeX*500:0;that.currPageX=page;page=that.pagesY.length-1;for(i=0;i<page;i++){if(y>=that.pagesY[i]){page=i;break}}if(page==that.currPageY&&page>0&&that.dirY<0)page--;y=that.pagesY[page];sizeY=m.abs(y-that.pagesY[that.currPageY]);sizeY=sizeY?m.abs(that.y-y)/sizeY*500:0;that.currPageY=page;time=m.round(m.max(sizeX,sizeY))||200;return{x:x,y:y,time:time}},_bind:function(type,el,bubble){(el||this.scroller).addEventListener(type,this,!!bubble)},_unbind:function(type,el,bubble){(el||this.scroller).removeEventListener(type,this,!!bubble)},destroy:function(){var that=this;that.scroller.style[transform]="";that.hScrollbar=false;that.vScrollbar=false;that._scrollbar("h");that._scrollbar("v");that._unbind(RESIZE_EV,window);that._unbind(START_EV);that._unbind(MOVE_EV,window);that._unbind(END_EV,window);that._unbind(CANCEL_EV,window);if(!that.options.hasTouch){that._unbind(WHEEL_EV)}if(that.options.useTransition)that._unbind(TRNEND_EV);if(that.options.checkDOMChanges)clearInterval(that.checkDOMTime);if(that.options.onDestroy)that.options.onDestroy.call(that)},refresh:function(){var that=this,offset,i,l,els,pos=0,page=0;if(that.scale<that.options.zoomMin)that.scale=that.options.zoomMin;that.wrapperW=that.wrapper.clientWidth||1;that.wrapperH=that.wrapper.clientHeight||1;that.minScrollY=-that.options.topOffset||0;that.scrollerW=m.round(that.scroller.offsetWidth*that.scale);that.scrollerH=m.round((that.scroller.offsetHeight+that.minScrollY)*that.scale);that.maxScrollX=that.wrapperW-that.scrollerW;that.maxScrollY=that.wrapperH-that.scrollerH+that.minScrollY;that.dirX=0;that.dirY=0;if(that.options.onRefresh)that.options.onRefresh.call(that);that.hScroll=that.options.hScroll&&that.maxScrollX<0;that.vScroll=that.options.vScroll&&(!that.options.bounceLock&&!that.hScroll||that.scrollerH>that.wrapperH);that.hScrollbar=that.hScroll&&that.options.hScrollbar;that.vScrollbar=that.vScroll&&that.options.vScrollbar&&that.scrollerH>that.wrapperH;offset=that._offset(that.wrapper);that.wrapperOffsetLeft=-offset.left;that.wrapperOffsetTop=-offset.top;if(typeof that.options.snap=="string"){that.pagesX=[];that.pagesY=[];els=that.scroller.querySelectorAll(that.options.snap);for(i=0,l=els.length;i<l;i++){pos=that._offset(els[i]);pos.left+=that.wrapperOffsetLeft;pos.top+=that.wrapperOffsetTop;that.pagesX[i]=pos.left<that.maxScrollX?that.maxScrollX:pos.left*that.scale;that.pagesY[i]=pos.top<that.maxScrollY?that.maxScrollY:pos.top*that.scale}}else if(that.options.snap){that.pagesX=[];while(pos>=that.maxScrollX){that.pagesX[page]=pos;pos=pos-that.wrapperW;page++}if(that.maxScrollX%that.wrapperW)that.pagesX[that.pagesX.length]=that.maxScrollX-that.pagesX[that.pagesX.length-1]+that.pagesX[that.pagesX.length-1];pos=0;page=0;that.pagesY=[];while(pos>=that.maxScrollY){that.pagesY[page]=pos;pos=pos-that.wrapperH;page++}if(that.maxScrollY%that.wrapperH)that.pagesY[that.pagesY.length]=that.maxScrollY-that.pagesY[that.pagesY.length-1]+that.pagesY[that.pagesY.length-1]}that._scrollbar("h");that._scrollbar("v");if(!that.zoomed){that.scroller.style[transitionDuration]="0";that._resetPos(400)}},scrollTo:function(x,y,time,relative){var that=this,step=x,i,l;that.stop();if(!step.length)step=[{x:x,y:y,time:time,relative:relative}];for(i=0,l=step.length;i<l;i++){if(step[i].relative){step[i].x=that.x-step[i].x;step[i].y=that.y-step[i].y}that.steps.push({x:step[i].x,y:step[i].y,time:step[i].time||0})}that._startAni()},scrollToElement:function(el,time){var that=this,pos;el=el.nodeType?el:that.scroller.querySelector(el);if(!el)return;pos=that._offset(el);pos.left+=that.wrapperOffsetLeft;pos.top+=that.wrapperOffsetTop;pos.left=pos.left>0?0:pos.left<that.maxScrollX?that.maxScrollX:pos.left;pos.top=pos.top>that.minScrollY?that.minScrollY:pos.top<that.maxScrollY?that.maxScrollY:pos.top;time=time===undefined?m.max(m.abs(pos.left)*2,m.abs(pos.top)*2):time;that.scrollTo(pos.left,pos.top,time)},scrollToPage:function(pageX,pageY,time){var that=this,x,y;time=time===undefined?400:time;if(that.options.onScrollStart)that.options.onScrollStart.call(that);if(that.options.snap){pageX=pageX=="next"?that.currPageX+1:pageX=="prev"?that.currPageX-1:pageX;pageY=pageY=="next"?that.currPageY+1:pageY=="prev"?that.currPageY-1:pageY;pageX=pageX<0?0:pageX>that.pagesX.length-1?that.pagesX.length-1:pageX;pageY=pageY<0?0:pageY>that.pagesY.length-1?that.pagesY.length-1:pageY;that.currPageX=pageX;that.currPageY=pageY;x=that.pagesX[pageX];y=that.pagesY[pageY]}else{x=-that.wrapperW*pageX;y=-that.wrapperH*pageY;if(x<that.maxScrollX)x=that.maxScrollX;if(y<that.maxScrollY)y=that.maxScrollY}that.scrollTo(x,y,time)},disable:function(){this.stop();this._resetPos(0);this.enabled=false;this._unbind(MOVE_EV,window);this._unbind(END_EV,window);this._unbind(CANCEL_EV,window)},enable:function(){this.enabled=true},stop:function(){if(this.options.useTransition)this._unbind(TRNEND_EV);else cancelFrame(this.aniTime);this.steps=[];this.moved=false;this.animating=false},zoom:function(x,y,scale,time){var that=this,relScale=scale/that.scale;if(!that.options.useTransform)return;that.zoomed=true;time=time===undefined?200:time;x=x-that.wrapperOffsetLeft-that.x;y=y-that.wrapperOffsetTop-that.y;that.x=x-x*relScale+that.x;that.y=y-y*relScale+that.y;that.scale=scale;that.refresh();that.x=that.x>0?0:that.x<that.maxScrollX?that.maxScrollX:that.x;that.y=that.y>that.minScrollY?that.minScrollY:that.y<that.maxScrollY?that.maxScrollY:that.y;that.scroller.style[transitionDuration]=time+"ms";that.scroller.style[transform]="translate("+that.x+"px,"+that.y+"px) scale("+scale+")"+translateZ;that.zoomed=false},isReady:function(){return!this.moved&&!this.zoomed&&!this.animating}};function prefixStyle(style){if(vendor==="")return style;style=style.charAt(0).toUpperCase()+style.substr(1);return vendor+style}dummyStyle=null;if(typeof exports!=="undefined")exports.iScroll=iScroll;else window.iScroll=iScroll})(window,document);define("lib/iscroll",function(global){return function(){var ret,fn;return ret||global.iScroll}}(this));define("view/note/view",["ext/underscore","view/page","view/link-resolver","lib/iscroll","view/navbar-factory"],function(_,PageView,linkResolver,iScroll,navbarFactory){var $=jQuery;return PageView.extend({attributes:{id:"scroll-wrapper"},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.group=this.model.getGroup();this.back={code:"m_btn_notes",link:"#notes/"+this.group.getKey()};this.title=_.escape(this.model.get("friendlyName")),this.actions=[{code:"m_comments",icon:"comment",link:"#comments/"+this.model.getKey()}];if(this.model.permission.canEdit()){this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()})}},render:function(){PageView.prototype.render.apply(this,arguments);$("<div>").addClass("html-content").html(this.model.get("content")).appendTo(this.$el);this.resolveLinks();var fudge=30;var zoomMin=this.$root.width()/($("div.html-content",this.$el).width()+fudge);var iscroll=new iScroll(this.el,{zoom:true,zoomMin:zoomMin});iscroll.zoom(0,0,zoomMin,0);iscroll.refresh();return this},navbar:function(callback){this.navbarCreate("pages",this.group.id,callback)}}).extend(navbarFactory).extend(linkResolver)});define("router/note",["router/group","api/cache","api/service/note","view/note/list","view/note/view"],function(GroupRouter,cache,service,NoteListView,NoteViewView){return GroupRouter.extend({routes:{"notes/:groupKey":"showNotes","note/:noteKey":"getNote","page/:noteKey":"getNote"},showNotes:function(group){var notes=cache.getFrom(service.createNotes(group,1));var view=new NoteListView({collection:notes});view.render();view.handleRefresh()},getNote:function(noteKey){var parts=noteKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getNote(group,parts[3],this.showNote)},showNote:function(note){new NoteViewView({model:note}).render()}})});define("api/collection/discussions",["api/collection/content","api/model/discussion"],function(ContentCollection,Discussion){return ContentCollection.extend({model:Discussion})});define("api/model/discussion-reply",["api/model/base"],function(BaseModel){return BaseModel.extend({url:function(){var id=this.id?"/@"+this.id:"";return this.collection.url()+id}})});define("api/collection/discussion-replies",["api/collection/base","api/model/discussion-reply"],function(BaseCollection,DiscussionReply){return BaseCollection.extend({model:DiscussionReply,initialize:function(models,options){this.discussion=options.discussion},url:function(){return this.discussion.url()+"/replies"}})});define("api/service/discussion",["ext/underscore","app-context","api/cache","api/service/base","api/collection/discussions","api/collection/discussion-replies","api/model/discussion-reply","api/model/discussion"],function(_,appContext,cache,base,Discussions,DiscussionReplies,DiscussionReply,Discussion){return _.extend({getDiscussions:function(group,handler){var discussions=this.createDiscussions(group,1);cache.putModel(discussions);this.getCollection(discussions,handler)},getNextDiscussions:function(discussions,handler){var next=this.createDiscussions(group,discussions.params.currentPage+1);this.getCollection(next,function(next){discussions.add(next.models);discussions.params.currentPage=next.params.currentPage;discussions.more=next.more;handler(next)})},getDiscussion:function(group,id,handler){var self=this;this.getDiscussionOnly(group,id,function(discussion){self.getPermission(discussion,handler)})},getDiscussionOnly:function(group,id,handler){var discussion=new Discussion({name:id});if(id.charAt(0)=="@"){discussion=new Discussion({id:parseInt(id.slice(1))})}discussion.set("group",group);discussion=cache.getFrom(discussion);if(discussion._expiry){if(discussion.replies){handler(discussion)}else{this._getReplies(discussion,handler)}return}cache.putModel(discussion);var _handler=_.after(2,handler);discussion.once("change",_handler);discussion.fetch();this._getReplies(discussion,_handler)},_getReplies:function(discussion,handler){discussion.replies=new DiscussionReplies([],{discussion:discussion});discussion.replies.once("sync",function(){handler(discussion)});discussion.replies.fetch()},createDiscussion:function(discussions,discussion,handler){discussion["group"]={id:discussions.group.id};var model=new Discussion(discussion);discussions.add(model);model.save();model.once("change",_.bind(handler,this,model))},createReply:function(replies,text,handler){var reply=new DiscussionReply({reply:text});replies.add(reply);reply.save();reply.once("change",_.bind(handler,this,reply))},createDiscussions:function(group,currentPage){return new Discussions([],{group:group,params:{currentPage:currentPage,pageSize:appContext.pageSize}})}},base)});define("text!text/discussion/item.html",[],function(){return"<a class=\"no-icon\" href=\"#discussion/<%= getKey() %>\">\n   <p><b><%= _.escape(get('friendlyName')) %></b></p>\n    <abbr><%= m_last_updated %>: <%= $.timeago(new Date(get('lastModified'))) %></abbr>\n   <span class=\"badge\"><%= get('replies') %></span>\n</a>\n"});define("view/discussion/item",["view/base","text!text/discussion/item.html"],function(BaseView,template){return BaseView.extend({tagName:"li",className:"fat",render:function(){this.$el.html(this.template(template,this.model));return this}})});define("view/discussion/list",["ext/underscore","view/navbar-factory","view/extending-list","view/discussion/item","api/service/discussion"],function(_,navbarFactory,ExtendingListView,DiscussionItemView,service){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);var group=this.collection.group;this.title=_.escape(group.get("friendlyName"));if(group.permission.canCreate()){this.action={code:"m_new",link:"#discussions/"+group.getKey()+"/create"}}},emptyMsgCode:"m_discussions_nothing",itemViewClass:DiscussionItemView,handleEndOfList:function(){service.getNextDiscussions(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getDiscussions(this.collection.group,function(discussions){self.collection=discussions;self.refresh()})},navbar:function(callback){this.navbarCreate("discussions",this.collection.group.id,callback)}}).extend(navbarFactory)});define("text!text/discussion/create.html",[],function(){return'<input class="form-control" name="topic" placeholder="<%= m_discussion_topic %>" type="text" maxlength="128">\n<textarea class="editor hidden" placeholder="<%= m_discussion_first %>"></textarea>\n<a href="javascript:void(0)" id="post" class="btn btn-primary" disabled="disabled">\n  <%= m_post %>\n</a>\n'});define("view/discussion/create",["ext/underscore","app-context","view/page","view/editor","api/service/discussion","text!text/discussion/create.html"],function(_,appContext,PageView,EditorView,service,template){var $=jQuery;return PageView.extend({tagName:"fieldset",events:{"keyup [name=topic]":"onKeyup","click #post":"post"},title:PageView.message("m_create_discussion"),nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.editor=new EditorView({context:this.options.discussions.group,$page:this.$el});this.action={code:"m_mention",view:this.editor};this.back={code:"m_btn_discussions",link:"#discussions/"+this.options.discussions.group.getKey()}},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template));this.editor.render_delayed();return this},onKeyup:function(){$("#post",this.$el).attr("disabled",_.isBlank($("[name=topic]",this.el).val()))},post:function(){service.createDiscussion(this.options.discussions,{friendlyName:$("[name=topic]",this.el).val(),description:this.editor.getText()},function(discussion){appContext.navigate("#discussion/"+discussion.getKey())})}})});define("text!text/discussion/reply.html",[],function(){return"<div>\n    <img src=\"<%= cdn %>/users/<%= model.get('author').id %>/thumbnail\"\n     onerror='this.onerror = null; this.src=\"<%= appurl %>/styles/images/default_thumbnail.png\"'>\n    <p><%= _.isBlank(model.get('reply')) ? '&nbsp;' : model.get('reply') %></p>\n   <p class=\"who-when\"><%= model.get('author').name %> (<%= $.timeago(new Date(model.get('dateCreated'))) %>)</p>\n  <% if ((me.id == model.get('author').id) && !readonly) { %>\n       <a href=\"javascript:void(0)\" class=\"comment-delete\">\n          <span class=\"glyphicon glyphicon-trash\"></span>\n     </a>\n  <% } %>\n</div>\n"});define("view/discussion/reply",["ext/underscore","view/base","app-context","api/service/general","text!text/discussion/reply.html"],function(_,BaseView,appContext,service,template){return BaseView.extend({attributes:{"class":"comment"},events:{"click .comment-delete":"onDelete"},initialize:function(options){_.bindToMethods(this);this.replyViews=[];this.options=options},render:function(){var args={readonly:this.options.readonly,model:this.model,cdn:appContext.cdn,me:appContext.getPrinciple()};this.$el.html(this.template(template,args));return this},onDelete:function(){service.deleteModel(this.model,this.onDeleted)},onDeleted:function(){this.$el.remove()}})});define("view/discussion/view",["ext/underscore","view/page","api/model/discussion-reply","view/navbar-factory","view/discussion/reply"],function(_,PageView,DiscussionReply,navbarFactory,DiscussionReplyView){return PageView.extend({className:"comments",initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.group=this.model.getGroup();this.back={code:"m_btn_discussions",link:"#discussions/"+this.group.getKey()};this.title=_.escape(this.model.get("friendlyName"));this.actions=[{code:"m_reply",link:"#discussion/"+this.model.getKey()+"/create"}];if(this.model.permission.canEdit()){this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()})}},render:function(){PageView.prototype.render.apply(this,arguments);var view=new DiscussionReplyView({model:new DiscussionReply({author:this.model.get("author"),reply:this.model.get("description"),dateCreated:this.model.get("dateCreated")}),readonly:true});this.$el.append(view.render().el);var selectedId=this.getSelectedReply();this.model.replies.each(function(reply){var view=new DiscussionReplyView({model:reply});var $item=view.render().$el;this.$el.append($item);if(selectedId==reply.id){$item.addClass("selected");this.scroll($item.offset().top-52)}},this);return this},getSelectedReply:function(){var reversed=_.sortBy(this.model.replies.toJSON(),function(reply){return-reply.dateCreated});var selected=_.find(reversed,function(reply){return reply.dateCreated<=this.options.dateOfSelection},this);return selected?selected.id:-1},navbar:function(callback){this.navbarCreate("discussions",this.group.id,callback)}}).extend(navbarFactory)});define("view/discussion/create-reply",["app-context","view/editor-page","api/service/discussion"],function(appContext,EditorPageView,service){return EditorPageView.extend({title:EditorPageView.message("m_create_reply"),nosearch:true,initialize:function(){EditorPageView.prototype.initialize.apply(this,arguments);this.back={code:"m_discussion",link:"#discussion/"+this.options.replies.discussion.getKey()}},post:function(){var backLink=this.back.link;service.createReply(this.options.replies,this.editor.getText(),function(reply){appContext.navigate(backLink+"/"+reply.get("dateCreated"))})}})});define("router/discussion",["router/group","api/cache","api/service/discussion","view/discussion/list","view/discussion/create","view/discussion/view","view/discussion/create-reply"],function(GroupRouter,cache,service,DiscussionListView,DiscussionCreateView,DiscussionViewView,ReplyCreateView){return GroupRouter.extend({routes:{"discussions/:groupKey/create":"createDiscussion","discussions/:groupKey":"showDiscussions","discussion/:discussionKey/create":"createReply","discussion/:discussionKey/:dateOfSelection":"getDiscussion","discussion/:discussionKey":"getDiscussion"},showDiscussions:function(group){var discussions=cache.getFrom(service.createDiscussions(group,1));var view=new DiscussionListView({collection:discussions});view.render();view.handleRefresh()},createDiscussion:function(group){var discussions=cache.getFrom(service.createDiscussions(group,1));new DiscussionCreateView({discussions:discussions}).render()},getDiscussion:function(discussionKey,dateOfSelection){var parts=discussionKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getDiscussion(group,parts[3],function(discussion){var options={model:discussion};if(dateOfSelection){options["dateOfSelection"]=parseInt(dateOfSelection)}new DiscussionViewView(options).render()})},createReply:function(discussionKey){var self=this;var parts=discussionKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getDiscussion(group,parts[3],function(discussion){self.showReplyCreate(discussion.replies)})},showReplyCreate:function(replies){new ReplyCreateView({context:replies.discussion.getGroup(),replies:replies}).render()}})});define("api/collection/requests",["api/collection/base","api/model/request"],function(BaseCollection,Request){return BaseCollection.extend({model:Request,initialize:function(models,options){if(options&&options.context){this.context=options.context}},url:function(){return this.context.url()+"/requests"}})});define("api/service/request",["ext/underscore","app-context","api/service/base","api/collection/requests","api/model/request"],function(_,appContext,base,Requests,Request){return _.extend({getRequests:function(model,handler){model.requests=new Requests([],{context:model});model.requests.once("sync",function(){handler(model)});model.requests.fetch()},saveRequests:function(model,requests,handler){requests["context"]=model;var requestMap={};requests.each(function(request){requestMap[request.get("target").id]=request});model.requests&&model.requests.each(function(request){if(requestMap[request.get("target").id]){delete requestMap[request.get("target").id]}else{request.destroy()}});var newRequests=_.values(requestMap);if(newRequests.length==0){handler()}else{var _handler=_.after(newRequests.length,handler);var me=appContext.getPrinciple();_.each(newRequests,function(request){model.requests&&model.requests.add(request);request.set("source",{id:me.id});request.once("sync",_handler);request.save()})}},createRequests:function(existingRequests){var requests=new Requests;if(existingRequests){existingRequests.each(function(request){requests.add(new Request(request.toJSON()))})}else{requests.add(this.createRequest(appContext.getPrinciple()))}return requests},createRequest:function(user){return new Request({target:user.toJSON?user.toJSON():user,status:appContext.getPrinciple().id==user.id?"ACCEPT":"NONE"})}},base)});define("api/collection/events",["api/collection/content","api/model/event"],function(ContentCollection,Event){return ContentCollection.extend({model:Event})});define("api/service/event",["ext/underscore","app-context","api/cache","api/service/base","api/service/request","api/collection/events","api/model/event"],function(_,appContext,cache,base,requestService,Events,Event){return _.extend({getEvents:function(group,handler){var events=this.createEvents(group,1);cache.putModel(events);this.getCollection(events,handler)},getNextEvents:function(events,handler){var next=this.createEvents(events.group,events.params.currentPage+1);this.getCollection(next,function(next){events.add(next.models);events.params.currentPage=next.params.currentPage;events.more=next.more;handler(next)})},getEvent:function(group,id,handler){var self=this;this.getEventOnly(group,id,function(event){self.getPermission(event,handler)})},getEventOnly:function(group,id,handler){var event=new Event({name:id});if(id.charAt(0)=="@"){event=new Event({id:parseInt(id.slice(1))})}event.set("group",group);event=cache.getFrom(event);if(event._expiry){if(event.requests){handler(event)}else{requestService.getRequests(event,handler)}return}cache.putModel(event);var _handler=_.after(2,handler);event.once("change",_handler);event.fetch();requestService.getRequests(event,_handler)},saveEvent:function(context,attributes,requests,handler){var event;if(context.type){event=context;event.set(attributes)}else{attributes["group"]=context.group;event=new Event(attributes);context.add(event)}var self=this;event.once("sync",function(){requestService.saveRequests(event,requests,_.bind(handler,self,event))});event.save()},createEvents:function(group,currentPage){return new Events([],{group:group,params:{currentPage:currentPage,pageSize:appContext.pageSize}})}},base)});define("text!text/event/item.html",[],function(){return"<a class=\"no-icon\" href=\"#event/<%= getKey() %>\">\n   <p><b><%= _.escape(get('friendlyName')) %></b></p>\n    <abbr><%= when %>, <%= m_by %> <%= get('author').name %></abbr>\n   <span class=\"badge\"><%= get('attendees') %></span>\n</a>\n"});define("view/event/item",["ext/underscore","moment","view/base","text!text/event/item.html"],function(_,moment,BaseView,template){return BaseView.extend({tagName:"li",render:function(){var dateLabel=this.model.get("dateLabel");if(dateLabel){this.$el.addClass("list-divider").html(dateLabel)}else{this.$el.addClass("fat");var args=_.extend({when:this.getTime()},this.model);this.$el.html(this.template(template,args))}return this},getTime:function(){if(this.model.get("allDay")){if(this.model.isSameDay()){return this.message("m_all_day")}else{return this.message("m_all_day")+" "+this.message("m_to")+this.model.getEndDate().format(" DD/MM/YY")}}else{var startDate=moment(this.model.get("startDate")).format("HH:mm ");var endDate=moment(this.model.get("endDate"));if(this.model.isSameDay()){return startDate+this.message("m_to")+endDate.format(" HH:mm")}else{return startDate+this.message("m_to")+endDate.format(" DD/MM/YY, HH:mm")}}}})});define("view/event/list",["ext/underscore","api/service/event","api/collection/events","api/model/event","view/navbar-factory","view/extending-list","view/event/item"],function(_,service,Events,Event,navbarFactory,ExtendingListView,EventItemView){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);var group=this.collection.group;this.title=_.escape(group.get("friendlyName"));if(group.permission.canCreate()){this.action={code:"m_new",link:"#events/"+group.getKey()+"/create"}}this.groupEvents()},groupEvents:function(){var eventMap=_.groupBy(this.collection.models,function(event){return this.extractDateLabel(event.get("startDate"))},this);this.collection=new Events([],{group:this.collection.group});_.each(_.keys(eventMap),function(dateLabel){this.collection.add(new Event({dateLabel:dateLabel}));this.collection.add(eventMap[dateLabel])},this)},emptyMsgCode:"m_events_nothing",itemViewClass:EventItemView,handleEndOfList:function(){service.getNextEvents(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getEvents(this.collection.group,function(events){self.collection=events;self.groupEvents();self.refresh()})},navbar:function(callback){this.navbarCreate("events",this.collection.group.id,callback)}}).extend(navbarFactory)});define("text!text/request/item.html",[],function(){return'<% if (request.get(\'target\').logo) { %>\n  <img src="<%= appContext.cdn %>/users/<%= request.get(\'target\').id %>/thumbnail">\n<% } else { %>\n   <img src="<%= appContext.defaultThumb %>">\n<% } %>\n<span><%= request.get(\'target\').name %></span>\n<% if (deletable) { %>\n <a href="javascript:void(0)" class="comment-delete">\n      <span class="glyphicon glyphicon-trash"></span>\n   </a>\n<% } %>\n'});define("view/request/item",["ext/underscore","app-context","text!text/request/item.html"],function(_,appContext,template){return Backbone.View.extend({tagName:"li",events:{"click .comment-delete":"onDelete"},initialize:function(options){this.options=options},render:function(){var args=_.extend({appContext:appContext,deletable:false},this.options);this.$el.html(_.template(template,args));return this},onDelete:function(){this.options.collection.remove(this.options.request)}})});define("text!text/request/group.html",[],function(){return"<h5 class=\"request-<%= status %>\">\n   <%= messages['m_request_' + type + '_' + status] %>\n</h5>\n<ul class=\"list-unstyled\"></ul>\n"});define("view/request/group",["ext/underscore","view/base","view/request/item","text!text/request/group.html"],function(_,BaseView,RequestItemView,template){var $=jQuery;return BaseView.extend({initialize:function(options){this.options=options},render:function(){this.$el.html(this.template(template,this.options));var $list=$("ul",this.$el);_.each(this.options.requestGroup,function(request){var options=_.extend({request:request},this.options);var view=new RequestItemView(options);$list.append(view.render().el)},this);return this}})});define("view/request/list",["ext/underscore","view/request/group"],function(_,RequestGroupView){return Backbone.View.extend({className:"requests",initialize:function(options){this.options=options},render:function(){var requestMap=_.groupBy(this.collection.models,function(request){return request.get("status")});this.$el.empty();_.each(["ACCEPT","REJECT","DECLINE","MAYBE","NONE"],function(status){if(!requestMap[status]){return}var options=_.extend({status:status,requestGroup:requestMap[status]},this.options);var view=new RequestGroupView(options);this.$el.append(view.render().el)},this);return this}})});define("text!text/date-time.html",[],function(){return"<input name=\"date\" class=\"form-control date\" type=\"text\"\n   placeholder=\"<%= messages[placeholder] %>\" \n value=\"<%= date ? date.format('DD MMM, YYYY') : '' %>\" >\n\n<% var time = date ? date.format('HH:mm') : ''; %>\n\n<input name=\"time\" class=\"form-control time\" type=\"text\" \n   placeholder=\"<%= time == '00:00' || time == '' ? 'hh:mm' : '' %>\" \n  value=\"<%= time == '00:00' ? '' : time %>\" <%= date ? '' : 'disabled=\"disabled\"' %> >\n\n<p class=\"invalid hidden\"></p>\n"});define("view/date-time",["ext/underscore","native","view/base","moment","text!text/date-time.html"],function(_,_native,BaseView,moment,template){var $=jQuery;return BaseView.extend({className:"date-time",render:function(){BaseView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,this.options));_native.datepicker(this.$el);return this},isTimeSet:function(){var dueTime=$("[name=time]",this.$el).val();return!_.isBlank(dueTime)},val:function(previousDate){this.error();var date=$("[name=date]",this.$el).val();if(_.isBlank(date)){if(this.options.required){this.error(this.message(this.options.required));throw"invalid"}}else{var time=$("[name=time]",this.$el).val();if(!_.isBlank(time)&&time.search(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/)==-1){this.error(this.message("m_error_time"));throw"invalid"}var format="DD MMM, YYYY HH:mm Z";var datetime=moment(date+" "+time+" +0000",format).valueOf();if(previousDate&&previousDate>datetime){this.error(this.message("m_error_date_range",moment(previousDate).format(format)));throw"invalid"}return datetime}return null},error:function(message){var $error=$("p.invalid",this.$el);if(message){$error.html(message).removeClass("hidden")}else{$error.addClass("hidden")}}})});define("text!text/event/save.html",[],function(){return'<input class="form-control" name="friendlyName" placeholder="<%= m_event_title %>" \n   type="text" maxlength="108" value="<%= event ? event.get(\'friendlyName\') : \'\' %>">\n<div id="startDate"></div>\n<div id="endDate"></div>\n<input class="form-control" name="location" placeholder="<%= m_event_location %>" \n  type="text" maxlength="128" value="<%= event ? event.get(\'location\') : \'\' %>">\n<textarea class="editor hidden" placeholder="<%= m_event_description %>"></textarea>\n<div id="requests"></div>\n<a href="javascript:void(0)" id="save" class="btn btn-primary" <%= event ? \'\' : \'disabled="disabled"\' %>>\n    <%= m_save %>\n</a>\n'});define("view/event/save",["ext/underscore","view/page","view/editor","app-context","moment","api/service/general","api/service/request","api/service/event","view/people/list","view/request/list","view/date-time","text!text/event/save.html"],function(_,PageView,EditorView,appContext,moment,generalService,requestService,eventService,PeopleListView,RequestListView,DateTimeView,template){var $=jQuery;return PageView.extend({tagName:"fieldset",events:{"keyup [name=friendlyName]":"onKeyup","click #save":"save"},nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var group=this.resolveGroup();this.editor=new EditorView({context:group,$page:this.$el,content:options.model?options.model.get("description"):null});this.back={code:options.model?"m_event":"m_btn_events",link:options.model?"#event/"+options.model.getKey():"#events/"+group.getKey()};this.action={code:"m_assign",view:this};this.title=this.message(options.model?"m_update_event":"m_create_event");this.requestList=new RequestListView({collection:requestService.createRequests(options.model?options.model.requests:null),type:"event",deletable:true});
    13 this.requestList.collection.on("remove",this.renderRequests);this.startDate=new DateTimeView({date:options.model?options.model.getStartDate():null,placeholder:"m_event_startdate",required:"m_error_startdate"});this.endDate=new DateTimeView({date:options.model?options.model.getEndDate():null,placeholder:"m_event_enddate",required:"m_error_enddate"})},resolveGroup:function(){if(this.options.model){return this.options.model.getGroup()}return this.options.collection.group},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,{statuses:["NOT_STARTED","IN_PROGRESS","DEFERRED","WAITING","COMPLETED"],event:this.options.model}));$("#startDate",this.$el).replaceWith(this.startDate.render().$el);$("#endDate",this.$el).replaceWith(this.endDate.render().$el);this.renderRequests();this.editor.render_delayed();return this},renderRequests:function(){var $requests=$("#requests",this.$el).empty();if(this.requestList.collection.length>0){$requests.append(this.requestList.render().el)}},onKeyup:function(){$("#save",this.$el).attr("disabled",_.isBlank($("[name=friendlyName]",this.el).val()))},doAction:function(container){var filter=this.requestList.collection.map(function(request){return request.get("target").id});var self=this;generalService.getUsers(this.resolveGroup(),function(users){var people=new PeopleListView({collection:users,callback:self.addRequest,filter:filter});people.render()},true)},addRequest:function(user){this.requestList.collection.add(requestService.createRequest(user));this.renderRequests()},save:function(){this.requestList.collection.off("remove",this.renderRequests);var attributes={friendlyName:$("[name=friendlyName]",this.el).val(),location:$("[name=location]",this.el).val(),description:this.editor.getText(),allDay:!(this.startDate.isTimeSet()||this.endDate.isTimeSet())};var valid=true;try{attributes.startDate=this.startDate.val()}catch(e){valid=false}try{attributes.endDate=this.endDate.val(attributes.startDate)}catch(e){valid=false}if(attributes.allDay){attributes.startDate+=432e5;attributes.endDate+=432e5;if(this.startDate!=this.endDate){attributes.endDate+=864e5}}valid&&eventService.saveEvent(this.options.model?this.options.model:this.options.collection,attributes,this.requestList.collection,function(event){appContext.navigate("#event/"+event.getKey())})}})});define("text!text/event/view.html",[],function(){return"<div class=\"entity-info\" >\n  <% if (!_.isBlank(get('description'))) { %>\n       <div class=\"description\">\n           <%= get('description') %>\n     </div>\n    <% } %>\n   <% if (get('location')) { %>\n      <p>\n           <%= m_event_location %>: <%= _.escape(get('location')) %>\n     </p>\n  <% } %>\n   <%= when %>\n   <% if (get('attendeeLimit')) { %>\n     <p>\n           <%= m_event_places %>: <%= get('attendees') %> <%= m_event_of %> <%= get('attendeeLimit') %>\n      </p>\n  <% } %>\n</div>\n<% if (answer) { %>\n  <a href='javascript:void(0)' class='btn btn-success'>\n     <%= m_event_ACCEPT %>\n </a>\n  <a href='javascript:void(0)' class='btn btn-danger'>\n      <%= m_event_DECLINE %>\n    </a>\n  <a href='javascript:void(0)' class='btn btn-warning'>\n     <%= m_event_MAYBE %>\n  </a>\n<% } %>\n<div id=\"requests\"></div>\n"});define("view/event/view",["ext/underscore","view/page","view/link-resolver","app-context","moment","view/navbar-factory","view/request/list","text!text/event/view.html"],function(_,PageView,linkResolver,appContext,moment,navbarFactory,RequestListView,template){var DATEF="dddd, DD MMMM YYYY";var TIMEF="HH:mm";var FULLF=DATEF+", "+TIMEF;return PageView.extend({tagName:"fieldset",events:{"click a.btn-success":function(){this.update("ACCEPT")},"click a.btn-danger":function(){this.update("DECLINE")},"click a.btn-warning":function(){this.update("MAYBE")}},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.group=this.model.getGroup();this.back={code:"m_btn_events",link:"#events/"+this.group.getKey()};this.title=_.escape(this.model.get("friendlyName"));this.actions=[{code:"m_comments",icon:"comment",link:"#comments/"+this.model.getKey()}];if(this.model.permission.canEdit()){this.actions.unshift({code:"m_edit",link:"#event/"+this.model.getKey()+"/edit"});this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()})}},update:function(status){this.answer.set("status",status);this.answer.once("sync",this.success);this.answer.save()},success:function(){appContext.navigate("#event/"+this.model.getKey(),true)},render:function(){PageView.prototype.render.apply(this,arguments);this.answer=this.model.requests.find(function(request){return request.get("target").id==appContext.getPrinciple().id&&request.get("status")=="NONE"});var args=_.extend({answer:this.answer,when:this.getTime()},this.model);this.$el.html(this.template(template,args));this.resolveLinks();if(this.model.requests.size()>0){var view=new RequestListView({collection:this.model.requests,type:"event"});view.render().$el.appendTo($("#requests",this.$el))}return this},getTime:function(){var startDate=moment(this.model.get("startDate"));if(this.model.get("allDay")){if(this.model.isSameDay()){return this.p(startDate.format(DATEF))}else{return this.p(startDate.format(DATEF))+this.p(this.message("m_to"))+this.p(this.model.getEndDate().format(DATEF))}}else{var endDate=moment(this.model.get("endDate"));if(this.model.isSameDay()){return this.p(startDate.format(DATEF))+this.p(startDate.format(TIMEF)+" "+this.message("m_to")+" "+endDate.format(TIMEF))}else{return this.p(startDate.format(FULLF))+this.p(this.message("m_to"))+this.p(endDate.format(FULLF))}}},p:function(text){return"<p>"+text+"</p>"},navbar:function(callback){this.navbarCreate("events",this.group.id,callback)}}).extend(navbarFactory).extend(linkResolver)});define("router/event",["ext/underscore","router/group","api/cache","api/service/event","view/event/list","view/event/save","view/event/view"],function(_,GroupRouter,cache,service,EventListView,EventSaveView,EventViewView){return GroupRouter.extend({routes:{"events/:groupKey/create":"createEvent","events/:groupKey":"showEvents","event/:eventKey/edit":"editEvent","event/:eventKey":"getEvent"},createEvent:function(group){var events=cache.getFrom(service.createEvents(group,1));new EventSaveView({collection:events}).render()},showEvents:function(group){var events=cache.getFrom(service.createEvents(group,1));var view=new EventListView({collection:events});view.render();view.handleRefresh()},getEvent:function(eventKey){var parts=eventKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getEvent(group,parts[3],function(event){new EventViewView({model:event}).render()})},editEvent:function(eventKey){var parts=eventKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getEvent(group,parts[3],function(event){new EventSaveView({model:event}).render()})}})});define("api/collection/tasks",["api/collection/content","api/model/task"],function(ContentCollection,Task){return ContentCollection.extend({model:Task,_getKey:function(key){return key+":"+this.params.completed}})});define("api/service/task",["ext/underscore","app-context","api/cache","api/service/base","api/service/request","api/collection/tasks","api/model/task"],function(_,appContext,cache,base,requestService,Tasks,Task){return _.extend({getTasks:function(group,handler){var tasks=this.createTasks(group,1);cache.putModel(tasks);this.getCollection(tasks,handler)},getNextTasks:function(tasks,handler){var next=this.createTasks(tasks.group,tasks.params.currentPage+1);this.getCollection(next,function(next){tasks.add(next.models);tasks.params.currentPage=next.params.currentPage;tasks.more=next.more;handler(next)})},getTask:function(group,id,handler){var self=this;this.getTaskOnly(group,id,function(task){self.getPermission(task,handler)})},getTaskOnly:function(group,id,handler){var task=new Task({name:id});if(id.charAt(0)=="@"){task=new Task({id:parseInt(id.slice(1))})}task.set("group",group);task=cache.getFrom(task);if(task._expiry){if(task.requests){handler(task)}else{requestService.getRequests(task,handler)}return}cache.putModel(task);var _handler=_.after(2,handler);task.once("change",_handler);task.fetch();requestService.getRequests(task,_handler)},saveTask:function(context,attributes,requests,handler){var task;if(context.type){task=context;task.set(attributes)}else{attributes["group"]=context.group;task=new Task(attributes);context.add(task)}var self=this;task.once("sync",function(){requestService.saveRequests(task,requests,_.bind(handler,self,task))});task.save()},createTasks:function(group,currentPage){return new Tasks([],{group:group,params:{currentPage:currentPage,pageSize:appContext.pageSize,completed:false}})}},base)});define("text!text/task/item.html",[],function(){return"<div class=\"task-status <%= model.isOverdue() ? 'OVERDUE' : model.get('status') %>\">\n    <span><%= messages['m_task_status_' + model.get('status')] %></span>\n</div>\n<a href=\"#task/<%= getKey() %>\" class=\"task-item\">\n  <p><b><%= _.escape(get('friendlyName')) %></b></p>\n    <abbr>\n        <%= m_tasks_requested_by %>\n       <%= get('author').name %><%= when %>\n  </abbr>\n</a>\n"});define("view/task/item",["ext/underscore","moment","view/base","text!text/task/item.html"],function(_,moment,BaseView,template){return BaseView.extend({tagName:"li",render:function(){var dateLabel=this.model.get("dateLabel");if(dateLabel){this.$el.addClass("list-divider").html(dateLabel)}else{this.$el.addClass("fat");var args=_.extend({model:this.model,when:this.getTime()},this.model);this.$el.html(this.template(template,args))}return this},getTime:function(){var dueDate=this.model.get("dueDate");if(!dueDate){return""}var dueDate=moment(dueDate);var dateString=dueDate.format(", DD/MM/YY");if(this.model.get("timeSet")){dateString+=" "+this.message("m_at")+" "+dueDate.format("HH:mm")}return dateString}})});define("view/task/list",["ext/underscore","api/service/task","api/collection/tasks","api/model/task","view/navbar-factory","view/extending-list","view/task/item"],function(_,service,Tasks,Task,navbarFactory,ExtendingListView,TaskItemView){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);var group=this.collection.group;this.title=_.escape(group.get("friendlyName"));if(group.permission.canCreate()){this.action={code:"m_new",link:"#tasks/"+group.getKey()+"/create"}}this.groupTasks()},groupTasks:function(){var taskMap=_.groupBy(this.collection.models,this.extractDueDateLabel);this.collection=new Tasks([],{group:this.collection.group});_.each(_.keys(taskMap),function(dateLabel){this.collection.add(new Task({dateLabel:dateLabel}));this.collection.add(taskMap[dateLabel])},this)},extractDueDateLabel:function(task){if(task.isOverdue()){return this.message("m_tasks_overdue")}var dueDate=task.get("dueDate");if(!dueDate){return this.message("m_tasks_no_due_date")}return this.extractDateLabel(dueDate)},emptyMsgCode:"m_tasks_nothing",itemViewClass:TaskItemView,handleEndOfList:function(){service.getNextTasks(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getTasks(this.collection.group,function(tasks){self.collection=tasks;self.groupTasks();self.refresh()})},navbar:function(callback){this.navbarCreate("tasks",this.collection.group.id,callback)}}).extend(navbarFactory)});define("text!text/task/save.html",[],function(){return'<input class="form-control" name="friendlyName" placeholder="<%= m_task_title %>" \n  type="text" maxlength="108" value="<%= task ? task.get(\'friendlyName\') : \'\' %>">\n<textarea class="editor hidden" placeholder="<%= m_task_description %>"></textarea>\n<div class="select">\n   <select name="status">\n        <% var status = task ? task.get(\'status\') : "NOT_STARTED"; %>\n       <% for (i = 0; i < statuses.length; i++) { %>\n         <option value="<%= statuses[i] %>" <%= statuses[i] == status ? \'selected="selected"\' : \'\' %> >\n                <%= messages[\'m_task_status_\' + statuses[i]] %>\n         </option>\n     <% } %>\n   </select>\n</div>\n<div id="dueDate"></div>\n<div id="requests"></div>\n<a href="javascript:void(0)" id="save" class="btn btn-primary" <%= task ? \'\' : \'disabled="disabled"\' %>>\n  <%= m_save %>\n</a>\n'});define("view/task/save",["ext/underscore","moment","view/page","view/editor","app-context","api/service/general","api/service/request","api/service/task","view/people/list","view/request/list","view/date-time","text!text/task/save.html"],function(_,moment,PageView,EditorView,appContext,generalService,requestService,taskService,PeopleListView,RequestListView,DateTimeView,template){var $=jQuery;return PageView.extend({tagName:"fieldset",events:{"keyup [name=friendlyName]":"onKeyup","click #save":"save"},nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var group=this.resolveGroup();this.editor=new EditorView({context:group,$page:this.$el,content:options.model?options.model.get("description"):null});this.back={code:options.model?"m_task":"m_btn_tasks",link:options.model?"#task/"+options.model.getKey():"#tasks/"+group.getKey()};this.action={code:"m_assign",view:this};this.title=this.message(options.model?"m_update_task":"m_create_task");this.requestList=new RequestListView({collection:requestService.createRequests(options.model?options.model.requests:null),type:"task",deletable:true});this.requestList.collection.on("remove",this.renderRequests);var dueDate=null;if(options.model){dueDate=options.model.get("dueDate")}this.dueDate=new DateTimeView({date:dueDate?moment(dueDate):null,placeholder:"m_task_duedate"})},resolveGroup:function(){if(this.options.model){return this.options.model.getGroup()}return this.options.collection.group},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,{statuses:["NOT_STARTED","IN_PROGRESS","DEFERRED","WAITING","COMPLETED"],task:this.options.model}));$("#dueDate",this.$el).replaceWith(this.dueDate.render().$el);this.renderRequests();this.editor.render_delayed();return this},renderRequests:function(){var $requests=$("#requests",this.$el).empty();if(this.requestList.collection.length>0){$requests.append(this.requestList.render().el)}},onKeyup:function(){$("#save",this.$el).attr("disabled",_.isBlank($("[name=friendlyName]",this.el).val()))},doAction:function(container){var filter=this.requestList.collection.map(function(request){return request.get("target").id});var self=this;generalService.getUsers(this.resolveGroup(),function(users){var people=new PeopleListView({collection:users,callback:self.addRequest,filter:filter});people.render()},true)},addRequest:function(user){this.requestList.collection.add(requestService.createRequest(user));this.renderRequests()},save:function(){this.requestList.collection.off("remove",this.renderRequests);try{var attributes={friendlyName:$("[name=friendlyName]",this.el).val(),description:this.editor.getText(),status:$("[name=status]",this.el).val(),dueDate:this.dueDate.val()};taskService.saveTask(this.options.model?this.options.model:this.options.collection,attributes,this.requestList.collection,function(task){appContext.navigate("#task/"+task.getKey())})}catch(e){}}})});define("text!text/task/view.html",[],function(){return"<div></div>\n<div class=\"task-status <%= isOverdue() ? 'OVERDUE' : get('status') %>\">\n   <span><%= messages['m_task_status_' + get('status')] %></span>\n</div>\n<div class=\"entity-info\" >\n  <% if (!_.isBlank(get('description'))) { %>\n       <div class=\"description\">\n           <%= get('description') %>\n     </div>\n    <% } %>\n   <p><%= when %></p>\n    <% if (get('status') == 'IN_PROGRESS') { %>\n       <p><%= m_task_progress %>: <%= get('progress') %>%</p>\n    <% } %>\n</div>\n<% if (answer) { %>\n  <a href='javascript:void(0)' class='btn btn-success'>\n     <%= m_task_ACCEPT %>\n  </a>\n  <a href='javascript:void(0)' class='btn btn-danger'>\n      <%= m_task_REJECT %>\n  </a>\n<% } %>\n<div id=\"requests\"></div>\n"});define("view/task/view",["ext/underscore","view/page","view/link-resolver","app-context","moment","view/navbar-factory","view/request/list","text!text/task/view.html"],function(_,PageView,linkResolver,appContext,moment,navbarFactory,RequestListView,template){return PageView.extend({tagName:"fieldset",events:{"click a.btn-success":function(){this.update("ACCEPT")},"click a.btn-danger":function(){this.update("REJECT")}},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.group=this.model.getGroup();this.back={code:"m_btn_tasks",link:"#tasks/"+this.group.getKey()};this.title=_.escape(this.model.get("friendlyName"));this.actions=[{code:"m_comments",icon:"comment",link:"#comments/"+this.model.getKey()}];if(this.model.permission.canEdit()){this.actions.unshift({code:"m_edit",link:"#task/"+this.model.getKey()+"/edit"});this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()})}},update:function(status){this.answer.set("status",status);this.answer.once("sync",this.success);this.answer.save()},success:function(){appContext.navigate("#task/"+this.model.getKey(),true)},render:function(){PageView.prototype.render.apply(this,arguments);this.answer=this.model.requests.find(function(request){return request.get("target").id==appContext.getPrinciple().id&&request.get("status")=="NONE"});var args=_.extend({answer:this.answer,when:this.getTime()},this.model);this.$el.html(this.template(template,args));this.resolveLinks();if(this.model.requests.size()>0){var view=new RequestListView({collection:this.model.requests,type:"task"});view.render().$el.appendTo($("#requests",this.$el))}return this},getTime:function(){var dueDate=this.model.get("dueDate");if(!dueDate){return this.message("m_task_no_due")}dueDate=moment(dueDate);var dateString=dueDate.format("DD/MM/YY");if(this.model.get("timeSet")){dateString+=" "+this.message("m_at")+" "+dueDate.format("HH:mm")}return this.message("m_task_due")+": "+dateString},navbar:function(callback){this.navbarCreate("tasks",this.group.id,callback)}}).extend(navbarFactory).extend(linkResolver)});define("router/task",["ext/underscore","router/group","app-context","api/cache","api/service/task","view/task/list","view/task/save","view/task/view"],function(_,GroupRouter,appContext,cache,service,TaskListView,TaskSaveView,TaskViewView){return GroupRouter.extend({routes:{"tasks/:groupKey/create":"createTask","tasks/:groupKey":"showTasks","task/:taskKey/edit":"editTask","task/:taskKey":"getTask"},createTask:function(group){var tasks=cache.getFrom(service.createTasks(group,1));new TaskSaveView({collection:tasks}).render()},showTasks:function(group){var tasks=cache.getFrom(service.createTasks(group,1));var view=new TaskListView({collection:tasks});view.render();view.handleRefresh()},getTask:function(taskKey){var parts=taskKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getTask(group,parts[3],function(task){new TaskViewView({model:task}).render()})},editTask:function(taskKey){var parts=taskKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getTask(group,parts[3],function(task){new TaskSaveView({model:task}).render()})}})});define("router/entity",["router/base","api/cache","api/service/file","api/service/note","api/service/discussion","api/service/event","api/service/task"],function(BaseRouter,cache,fileService,noteService,discussionService,eventService,taskService){return BaseRouter.extend({execute:function(callback,args){var keyParts=null;if(args.length>0){keyParts=args[0].split(":");if(keyParts.length!=5){keyParts=null}}var self=this;var handler=function(entity){args.unshift(entity);callback.apply(self,args)};if(keyParts){args.shift();var group={id:parseInt(keyParts[1].substr(1))};if(keyParts[2]=="files"){fileService.getFile(group,keyParts[3],handler)}else if(keyParts[2]=="pages"){noteService.getNote(group,keyParts[3],handler)}else if(keyParts[2]=="discussions"){discussionService.getDiscussion(group,keyParts[3],handler)}else if(keyParts[2]=="events"){eventService.getEvent(group,keyParts[3],handler)}else if(keyParts[2]=="tasks"){taskService.getTask(group,keyParts[3],handler)}}else{callback.apply(this,args)}}})});define("api/collection/replies",["api/collection/base","api/model/reply"],function(BaseCollection,Reply){return BaseCollection.extend({model:Reply,initialize:function(models,options){this.parent=options.parent},url:function(){return this.parent.url()}})});define("api/model/comment",["api/model/base-comment","api/collection/replies"],function(BaseComment,Replies){return BaseComment.extend({initialize:function(attributes){this.replies=new Replies(attributes.replies,{parent:this})},getReplies:function(){return this.replies}})});define("api/collection/comments",["api/collection/base","api/model/comment"],function(BaseCollection,Comment){return BaseCollection.extend({model:Comment,initialize:function(models,options){this.context=options.context},url:function(){return this.context.url()+"/comments"}})});define("api/service/comment",["ext/underscore","api/cache","api/collection/comments"],function(_,cache,Comments){return{getComments:function(context,handler){var comments=cache.getFrom(new Comments([],{context:context}));if(comments._expiry){handler(comments)}else{comments.fetch();comments.once("sync",function(){cache.putModel(comments);handler(comments)})}},createComment:function(comments,text,handler){var comment=new comments.model({comment:text});comments.add(comment);comment.save();comment.once("change",handler)}}});define("view/comment/create",["app-context","view/editor-page","api/service/comment"],function(appContext,EditorPageView,service){return EditorPageView.extend({title:EditorPageView.message("m_make_comment"),nosearch:true,initialize:function(){EditorPageView.prototype.initialize.apply(this,arguments);this.back={code:"m_comments",link:"#comments/"+this.options.entity.getKey()}},post:function(){var backLink=this.back.link;service.createComment(this.options.comments,this.editor.getText(),function(comment){appContext.navigate(backLink+"/"+comment.get("dateCreated"))})}})});define("router/comment",["ext/underscore","app-context","router/entity","api/cache","api/service/general","api/service/comment","view/comment/list","view/comment/create"],function(_,appContext,EntityRouter,cache,generalService,commentService,CommentListView,CommentCreateView){return EntityRouter.extend({routes:{"comments/:contextKey/create":"createComment","comments/:contextKey/:dateOfSelection":"getComments","comments/:contextKey":"getComments","replies/:commentKey/create":"createReply"},getComments:function(context,dateOfSelection){commentService.getComments(context,function(comments){comments.each(function(comment){cache.putModel(comment)});var options={collection:comments,onDelete:function(comment,onDeleted){generalService.deleteModel(comment,onDeleted)},onReply:function(comment){appContext.navigate("#replies/"+comment.getKey()+"/create")}};if(dateOfSelection){options["dateOfSelection"]=parseInt(dateOfSelection)}var view=new CommentListView(options);view.render()})},createComment:function(context){commentService.getComments(context,this.showCommentCreate)},createReply:function(commentKey){var comment=cache.get(commentKey);this.showCommentCreate(comment.getReplies(),comment.collection)},showCommentCreate:function(comments,parent){if(!parent){parent=comments}new CommentCreateView({context:parent.context.getGroup(),comments:comments,entity:parent.context}).render()}})});define("api/collection/base2",["ext/underscore","api/sync","api/cache"],function(_,sync,cache){var BaseCollection=_.extend({initialize:function(){this.on("remove",function(){cache.put2(this.getKey(),this.toJSON())},this)},add:function(model){var models=_.isArray(model)?model:[model];_.each(models,function(model){model.once("change",function(){cache.put2(this.getKey(),this.toJSON())},this)},this);Backbone.Collection.prototype.add.apply(this,arguments)},fetch:function(){var cached=cache.get2(this.getKey());if(cached){_.each(cached,function(attributes){this.add(new this.model(attributes))},this);this.trigger("sync",this)}else{Backbone.Collection.prototype.fetch.apply(this,arguments);this.once("sync",function(){cache.put2(this.getKey(),this.toJSON())},this)}}},sync);return Backbone.Collection.extend(BaseCollection)});define("api/model/share-token",["api/model/base"],function(BaseModel){return BaseModel.extend({idAttribute:"tokenKey"})});define("api/collection/share-tokens",["api/collection/base2","api/model/share-token"],function(BaseCollection,ShareToken){return BaseCollection.extend({model:ShareToken,initialize:function(models,options){BaseCollection.prototype.initialize.apply(this,arguments);this.context=options.context},url:function(){return this.context.url()+"/shares"}})});define("text!text/share-token/item.html",[],function(){return"<p>\n    <%= get('email') %>\n   <% if (get('name') && get('name') != get('email') ) { %>\n      (<%= get('name') %>)\n  <% } %>\n</p>\n\n<a href=\"javascript:void(0)\">\n  <span class=\"glyphicon glyphicon-trash\"></span>\n</a>\n"});define("view/share-token/item",["ext/underscore","view/base","text!text/share-token/item.html"],function(_,BaseView,template){return BaseView.extend({className:"share-token",events:{"click a":"onDelete"},render:function(){this.$el.html(this.template(template,this.model));return this},onDelete:function(){this.model.destroy({wait:true});this.model.once("destroy",this.onDeleted)},onDeleted:function(){this.$el.remove()}})});define("view/share-token/list",["ext/underscore","view/page","view/share-token/item"],function(_,PageView,ShareTokenItemView){var $=jQuery;return PageView.extend({className:"share-tokens",initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.collection.on("remove",this.onRemove);var context=this.collection.context;this.back={code:"m_"+context.type,link:"#"+context.type+"/"+context.getKey()};this.title=_.escape(context.get("friendlyName"));this.action={code:"m_new",link:"#shares/"+context.getKey()+"/create"}},render:function(){PageView.prototype.render.apply(this,arguments);this.collection.once("sync",this.renderList);this.collection.fetch();return this},renderList:function(){var contactMap={};_.each(this.options.contacts,function(contact){contactMap[contact.email.toLowerCase()]=contact});this.collection.each(function(shareToken){var contact=contactMap[shareToken.get("email").toLowerCase()];if(contact){shareToken.set("name",contact.name)}var itemView=new ShareTokenItemView({model:shareToken,collection:this.collection});this.$el.append(itemView.render().el)},this);this.onRemove()},remove:function(){this.collection.off("remove",this.onRemove);this.$el.remove();return this},onRemove:function(){if(this.collection.length==0){$("<div>").addClass("ui-body-d ui-corner-all").html(this.message("m_share_tokens_nothing")).appendTo(this.el)}}})});define("text!text/share-token/create.html",[],function(){return'<a href="javascript:void(0)" id="share" class="btn btn-primary">\n  <%= m_share %>\n</a>\n'});define("view/share-token/create",["ext/underscore","app-context","view/page","view/validated-email","text!text/share-token/create.html"],function(_,appContext,PageView,ValidatedEmail,template){var $=jQuery;return PageView.extend({tagName:"fieldset",events:{"click #share":"validate"},title:PageView.message("m_share_contact"),nosearch:true,emailInput:new ValidatedEmail({label:"m_share_input"}),initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var context=this.collection.context;this.back={code:"m_back",link:"#shares/"+this.collection.context.getKey()}},render:function(){PageView.prototype.render.apply(this,arguments);this.collection.fetch();this.$el.html(this.template(template,{}));$("#share",this.$el).before(this.emailInput.render().el);var self=this;var $input=this.$el.find("input");$input.autocomplete({appendTo:"#clinked-portal",source:function(request,response){var contacts=_.filter(self.options.contacts,function(contact){var term=request.term.toLowerCase();return contact.name.toLowerCase().indexOf(term)!=-1||contact.email.toLowerCase().indexOf(term)!=-1});response(contacts.slice(0,4))},select:function(event,ui){event.preventDefault()},focus:function(event,ui){$input.val(ui.item.email);event.preventDefault()}}).data("ui-autocomplete")._renderItem=function(ul,contact){var text=contact.email;if(contact.email!=contact.name){text+=" ("+contact.name+")"}return $("<li>").data("contact",contact).outerWidth($input.outerWidth()-3).append(text).appendTo(ul)};return this},validate:function(){var self=this;this.emailInput.options.validate(this.emailInput.val(),function(error){self.emailInput.displayValidation(error);!error&&self.share()})},share:function(){var shareToken=new this.collection.model({email:this.emailInput.val()});this.collection.add(shareToken);shareToken.save();var backLink=this.back.link;shareToken.once("change",function(){appContext.navigate(backLink)})}})});define("router/share-token",["ext/underscore","router/entity","native","api/cache","api/collection/share-tokens","view/share-token/list","view/share-token/create"],function(_,EntityRouter,native,cache,ShareTokens,ShareTokenListView,ShareTokenCreateView){return EntityRouter.extend({routes:{"shares/:contextKey/create":"createShareToken","shares/:contextKey":"getShareTokens"},getShareTokens:function(context){this.getContacts(function(contacts){var shareTokens=new ShareTokens([],{context:context});new ShareTokenListView({collection:shareTokens,contacts:contacts}).render()})},createShareToken:function(context){this.getContacts(function(contacts){var shareTokens=new ShareTokens([],{context:context});new ShareTokenCreateView({collection:shareTokens,contacts:contacts}).render()})},getContacts:function(handler){if(!native.contacts){handler([]);return}var contacts=cache.get2("contacts");if(contacts){handler(contacts)}else{native.contacts(function(contacts){cache.put2("contacts",contacts);handler(contacts)})}}})});var io="undefined"===typeof module?{}:module.exports;(function(){(function(exports,global){var io=exports;io.version="0.9.16";io.protocol=1;io.transports=[];io.j=[];io.sockets={};io.connect=function(host,details){var uri=io.util.parseUri(host),uuri,socket;if(global&&global.location){uri.protocol=uri.protocol||global.location.protocol.slice(0,-1);uri.host=uri.host||(global.document?global.document.domain:global.location.hostname);uri.port=uri.port||global.location.port}uuri=io.util.uniqueUri(uri);var options={host:uri.host,secure:"https"==uri.protocol,port:uri.port||("https"==uri.protocol?443:80),query:uri.query||""};io.util.merge(options,details);if(options["force new connection"]||!io.sockets[uuri]){socket=new io.Socket(options)}if(!options["force new connection"]&&socket){io.sockets[uuri]=socket}socket=socket||io.sockets[uuri];return socket.of(uri.path.length>1?uri.path:"")}})("object"===typeof module?module.exports:this.io={},this);(function(exports,global){var util=exports.util={};var re=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;var parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];util.parseUri=function(str){var m=re.exec(str||""),uri={},i=14;while(i--){uri[parts[i]]=m[i]||""}return uri};util.uniqueUri=function(uri){var protocol=uri.protocol,host=uri.host,port=uri.port;if("document"in global){host=host||document.domain;port=port||(protocol=="https"&&document.location.protocol!=="https:"?443:document.location.port)}else{host=host||"localhost";if(!port&&protocol=="https"){port=443}}return(protocol||"http")+"://"+host+":"+(port||80)};util.query=function(base,addition){var query=util.chunkQuery(base||""),components=[];util.merge(query,util.chunkQuery(addition||""));for(var part in query){if(query.hasOwnProperty(part)){components.push(part+"="+query[part])}}return components.length?"?"+components.join("&"):""
    14 };util.chunkQuery=function(qs){var query={},params=qs.split("&"),i=0,l=params.length,kv;for(;i<l;++i){kv=params[i].split("=");if(kv[0]){query[kv[0]]=kv[1]}}return query};var pageLoaded=false;util.load=function(fn){if("document"in global&&document.readyState==="complete"||pageLoaded){return fn()}util.on(global,"load",fn,false)};util.on=function(element,event,fn,capture){if(element.attachEvent){element.attachEvent("on"+event,fn)}else if(element.addEventListener){element.addEventListener(event,fn,capture)}};util.request=function(xdomain){if(xdomain&&"undefined"!=typeof XDomainRequest&&!util.ua.hasCORS){return new XDomainRequest}if("undefined"!=typeof XMLHttpRequest&&(!xdomain||util.ua.hasCORS)){return new XMLHttpRequest}if(!xdomain){try{return new(window[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}return null};if("undefined"!=typeof window){util.load(function(){pageLoaded=true})}util.defer=function(fn){if(!util.ua.webkit||"undefined"!=typeof importScripts){return fn()}util.load(function(){setTimeout(fn,100)})};util.merge=function merge(target,additional,deep,lastseen){var seen=lastseen||[],depth=typeof deep=="undefined"?2:deep,prop;for(prop in additional){if(additional.hasOwnProperty(prop)&&util.indexOf(seen,prop)<0){if(typeof target[prop]!=="object"||!depth){target[prop]=additional[prop];seen.push(additional[prop])}else{util.merge(target[prop],additional[prop],depth-1,seen)}}}return target};util.mixin=function(ctor,ctor2){util.merge(ctor.prototype,ctor2.prototype)};util.inherit=function(ctor,ctor2){function f(){}f.prototype=ctor2.prototype;ctor.prototype=new f};util.isArray=Array.isArray||function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};util.intersect=function(arr,arr2){var ret=[],longest=arr.length>arr2.length?arr:arr2,shortest=arr.length>arr2.length?arr2:arr;for(var i=0,l=shortest.length;i<l;i++){if(~util.indexOf(longest,shortest[i]))ret.push(shortest[i])}return ret};util.indexOf=function(arr,o,i){for(var j=arr.length,i=i<0?i+j<0?0:i+j:i||0;i<j&&arr[i]!==o;i++){}return j<=i?-1:i};util.toArray=function(enu){var arr=[];for(var i=0,l=enu.length;i<l;i++)arr.push(enu[i]);return arr};util.ua={};util.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var a=new XMLHttpRequest}catch(e){return false}return a.withCredentials!=undefined}();util.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent);util.ua.iDevice="undefined"!=typeof navigator&&/iPad|iPhone|iPod/i.test(navigator.userAgent)})("undefined"!=typeof io?io:module.exports,this);(function(exports,io){exports.EventEmitter=EventEmitter;function EventEmitter(){}EventEmitter.prototype.on=function(name,fn){if(!this.$events){this.$events={}}if(!this.$events[name]){this.$events[name]=fn}else if(io.util.isArray(this.$events[name])){this.$events[name].push(fn)}else{this.$events[name]=[this.$events[name],fn]}return this};EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prototype.once=function(name,fn){var self=this;function on(){self.removeListener(name,on);fn.apply(this,arguments)}on.listener=fn;this.on(name,on);return this};EventEmitter.prototype.removeListener=function(name,fn){if(this.$events&&this.$events[name]){var list=this.$events[name];if(io.util.isArray(list)){var pos=-1;for(var i=0,l=list.length;i<l;i++){if(list[i]===fn||list[i].listener&&list[i].listener===fn){pos=i;break}}if(pos<0){return this}list.splice(pos,1);if(!list.length){delete this.$events[name]}}else if(list===fn||list.listener&&list.listener===fn){delete this.$events[name]}}return this};EventEmitter.prototype.removeAllListeners=function(name){if(name===undefined){this.$events={};return this}if(this.$events&&this.$events[name]){this.$events[name]=null}return this};EventEmitter.prototype.listeners=function(name){if(!this.$events){this.$events={}}if(!this.$events[name]){this.$events[name]=[]}if(!io.util.isArray(this.$events[name])){this.$events[name]=[this.$events[name]]}return this.$events[name]};EventEmitter.prototype.emit=function(name){if(!this.$events){return false}var handler=this.$events[name];if(!handler){return false}var args=Array.prototype.slice.call(arguments,1);if("function"==typeof handler){handler.apply(this,args)}else if(io.util.isArray(handler)){var listeners=handler.slice();for(var i=0,l=listeners.length;i<l;i++){listeners[i].apply(this,args)}}else{return false}return true}})("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports);(function(exports,nativeJSON){if(nativeJSON&&nativeJSON.parse){return exports.JSON={parse:nativeJSON.parse,stringify:nativeJSON.stringify}}var JSON=exports.JSON={};function f(n){return n<10?"0"+n:n}function date(d,key){return isFinite(d.valueOf())?d.getUTCFullYear()+"-"+f(d.getUTCMonth()+1)+"-"+f(d.getUTCDate())+"T"+f(d.getUTCHours())+":"+f(d.getUTCMinutes())+":"+f(d.getUTCSeconds())+"Z":null}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","   ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value instanceof Date){value=date(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})};JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}})("undefined"!=typeof io?io:module.exports,typeof JSON!=="undefined"?JSON:undefined);(function(exports,io){var parser=exports.parser={};var packets=parser.packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"];var reasons=parser.reasons=["transport not supported","client not handshaken","unauthorized"];var advice=parser.advice=["reconnect"];var JSON=io.JSON,indexOf=io.util.indexOf;parser.encodePacket=function(packet){var type=indexOf(packets,packet.type),id=packet.id||"",endpoint=packet.endpoint||"",ack=packet.ack,data=null;switch(packet.type){case"error":var reason=packet.reason?indexOf(reasons,packet.reason):"",adv=packet.advice?indexOf(advice,packet.advice):"";if(reason!==""||adv!=="")data=reason+(adv!==""?"+"+adv:"");break;case"message":if(packet.data!=="")data=packet.data;break;case"event":var ev={name:packet.name};if(packet.args&&packet.args.length){ev.args=packet.args}data=JSON.stringify(ev);break;case"json":data=JSON.stringify(packet.data);break;case"connect":if(packet.qs)data=packet.qs;break;case"ack":data=packet.ackId+(packet.args&&packet.args.length?"+"+JSON.stringify(packet.args):"");break}var encoded=[type,id+(ack=="data"?"+":""),endpoint];if(data!==null&&data!==undefined)encoded.push(data);return encoded.join(":")};parser.encodePayload=function(packets){var decoded="";if(packets.length==1)return packets[0];for(var i=0,l=packets.length;i<l;i++){var packet=packets[i];decoded+="�"+packet.length+"�"+packets[i]}return decoded};var regexp=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;parser.decodePacket=function(data){var pieces=data.match(regexp);if(!pieces)return{};var id=pieces[2]||"",data=pieces[5]||"",packet={type:packets[pieces[1]],endpoint:pieces[4]||""};if(id){packet.id=id;if(pieces[3])packet.ack="data";else packet.ack=true}switch(packet.type){case"error":var pieces=data.split("+");packet.reason=reasons[pieces[0]]||"";packet.advice=advice[pieces[1]]||"";break;case"message":packet.data=data||"";break;case"event":try{var opts=JSON.parse(data);packet.name=opts.name;packet.args=opts.args}catch(e){}packet.args=packet.args||[];break;case"json":try{packet.data=JSON.parse(data)}catch(e){}break;case"connect":packet.qs=data||"";break;case"ack":var pieces=data.match(/^([0-9]+)(\+)?(.*)/);if(pieces){packet.ackId=pieces[1];packet.args=[];if(pieces[3]){try{packet.args=pieces[3]?JSON.parse(pieces[3]):[]}catch(e){}}}break;case"disconnect":case"heartbeat":break}return packet};parser.decodePayload=function(data){if(data.charAt(0)=="�"){var ret=[];for(var i=1,length="";i<data.length;i++){if(data.charAt(i)=="�"){ret.push(parser.decodePacket(data.substr(i+1).substr(0,length)));i+=Number(length)+1;length=""}else{length+=data.charAt(i)}}return ret}else{return[parser.decodePacket(data)]}}})("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports);(function(exports,io){exports.Transport=Transport;function Transport(socket,sessid){this.socket=socket;this.sessid=sessid}io.util.mixin(Transport,io.EventEmitter);Transport.prototype.heartbeats=function(){return true};Transport.prototype.onData=function(data){this.clearCloseTimeout();if(this.socket.connected||this.socket.connecting||this.socket.reconnecting){this.setCloseTimeout()}if(data!==""){var msgs=io.parser.decodePayload(data);if(msgs&&msgs.length){for(var i=0,l=msgs.length;i<l;i++){this.onPacket(msgs[i])}}}return this};Transport.prototype.onPacket=function(packet){this.socket.setHeartbeatTimeout();if(packet.type=="heartbeat"){return this.onHeartbeat()}if(packet.type=="connect"&&packet.endpoint==""){this.onConnect()}if(packet.type=="error"&&packet.advice=="reconnect"){this.isOpen=false}this.socket.onPacket(packet);return this};Transport.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var self=this;this.closeTimeout=setTimeout(function(){self.onDisconnect()},this.socket.closeTimeout)}};Transport.prototype.onDisconnect=function(){if(this.isOpen)this.close();this.clearTimeouts();this.socket.onDisconnect();return this};Transport.prototype.onConnect=function(){this.socket.onConnect();return this};Transport.prototype.clearCloseTimeout=function(){if(this.closeTimeout){clearTimeout(this.closeTimeout);this.closeTimeout=null}};Transport.prototype.clearTimeouts=function(){this.clearCloseTimeout();if(this.reopenTimeout){clearTimeout(this.reopenTimeout)}};Transport.prototype.packet=function(packet){this.send(io.parser.encodePacket(packet))};Transport.prototype.onHeartbeat=function(heartbeat){this.packet({type:"heartbeat"})};Transport.prototype.onOpen=function(){this.isOpen=true;this.clearCloseTimeout();this.socket.onOpen()};Transport.prototype.onClose=function(){var self=this;this.isOpen=false;this.socket.onClose();this.onDisconnect()};Transport.prototype.prepareUrl=function(){var options=this.socket.options;return this.scheme()+"://"+options.host+":"+options.port+"/"+options.resource+"/"+io.protocol+"/"+this.name+"/"+this.sessid};Transport.prototype.ready=function(socket,fn){fn.call(this)}})("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports);(function(exports,io,global){exports.Socket=Socket;function Socket(options){this.options={port:80,secure:false,document:"document"in global?document:false,resource:"socket.io",transports:io.transports,"connect timeout":1e4,"try multiple transports":true,reconnect:true,"reconnection delay":500,"reconnection limit":Infinity,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":false,"auto connect":true,"flash policy port":10843,manualFlush:false};io.util.merge(this.options,options);this.connected=false;this.open=false;this.connecting=false;this.reconnecting=false;this.namespaces={};this.buffer=[];this.doBuffer=false;if(this.options["sync disconnect on unload"]&&(!this.isXDomain()||io.util.ua.hasCORS)){var self=this;io.util.on(global,"beforeunload",function(){self.disconnectSync()},false)}if(this.options["auto connect"]){this.connect()}}io.util.mixin(Socket,io.EventEmitter);Socket.prototype.of=function(name){if(!this.namespaces[name]){this.namespaces[name]=new io.SocketNamespace(this,name);if(name!==""){this.namespaces[name].packet({type:"connect"})}}return this.namespaces[name]};Socket.prototype.publish=function(){this.emit.apply(this,arguments);var nsp;for(var i in this.namespaces){if(this.namespaces.hasOwnProperty(i)){nsp=this.of(i);nsp.$emit.apply(nsp,arguments)}}};function empty(){}Socket.prototype.handshake=function(fn){var self=this,options=this.options;function complete(data){if(data instanceof Error){self.connecting=false;self.onError(data.message)}else{fn.apply(null,data.split(":"))}}var url=["http"+(options.secure?"s":"")+":/",options.host+":"+options.port,options.resource,io.protocol,io.util.query(this.options.query,"t="+ +new Date)].join("/");if(this.isXDomain()&&!io.util.ua.hasCORS){var insertAt=document.getElementsByTagName("script")[0],script=document.createElement("script");script.src=url+"&jsonp="+io.j.length;insertAt.parentNode.insertBefore(script,insertAt);io.j.push(function(data){complete(data);script.parentNode.removeChild(script)})}else{var xhr=io.util.request();xhr.open("GET",url,true);if(this.isXDomain()){xhr.withCredentials=true}xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty;if(xhr.status==200){complete(xhr.responseText)}else if(xhr.status==403){self.onError(xhr.responseText)}else{self.connecting=false;!self.reconnecting&&self.onError(xhr.responseText)}}};xhr.send(null)}};Socket.prototype.getTransport=function(override){var transports=override||this.transports,match;for(var i=0,transport;transport=transports[i];i++){if(io.Transport[transport]&&io.Transport[transport].check(this)&&(!this.isXDomain()||io.Transport[transport].xdomainCheck(this))){return new io.Transport[transport](this,this.sessionid)}}return null};Socket.prototype.connect=function(fn){if(this.connecting){return this}var self=this;self.connecting=true;this.handshake(function(sid,heartbeat,close,transports){self.sessionid=sid;self.closeTimeout=close*1e3;self.heartbeatTimeout=heartbeat*1e3;if(!self.transports)self.transports=self.origTransports=transports?io.util.intersect(transports.split(","),self.options.transports):self.options.transports;self.setHeartbeatTimeout();function connect(transports){if(self.transport)self.transport.clearTimeouts();self.transport=self.getTransport(transports);if(!self.transport)return self.publish("connect_failed");self.transport.ready(self,function(){self.connecting=true;self.publish("connecting",self.transport.name);self.transport.open();if(self.options["connect timeout"]){self.connectTimeoutTimer=setTimeout(function(){if(!self.connected){self.connecting=false;if(self.options["try multiple transports"]){var remaining=self.transports;while(remaining.length>0&&remaining.splice(0,1)[0]!=self.transport.name){}if(remaining.length){connect(remaining)}else{self.publish("connect_failed")}}}},self.options["connect timeout"])}})}connect(self.transports);self.once("connect",function(){clearTimeout(self.connectTimeoutTimer);fn&&typeof fn=="function"&&fn()})});return this};Socket.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);if(this.transport&&!this.transport.heartbeats())return;var self=this;this.heartbeatTimeoutTimer=setTimeout(function(){self.transport.onClose()},this.heartbeatTimeout)};Socket.prototype.packet=function(data){if(this.connected&&!this.doBuffer){this.transport.packet(data)}else{this.buffer.push(data)}return this};Socket.prototype.setBuffer=function(v){this.doBuffer=v;if(!v&&this.connected&&this.buffer.length){if(!this.options["manualFlush"]){this.flushBuffer()}}};Socket.prototype.flushBuffer=function(){this.transport.payload(this.buffer);this.buffer=[]};Socket.prototype.disconnect=function(){if(this.connected||this.connecting){if(this.open){this.of("").packet({type:"disconnect"})}this.onDisconnect("booted")}return this};Socket.prototype.disconnectSync=function(){var xhr=io.util.request();var uri=["http"+(this.options.secure?"s":"")+":/",this.options.host+":"+this.options.port,this.options.resource,io.protocol,"",this.sessionid].join("/")+"/?disconnect=1";xhr.open("GET",uri,false);xhr.send(null);this.onDisconnect("booted")};Socket.prototype.isXDomain=function(){var port=global.location.port||("https:"==global.location.protocol?443:80);return this.options.host!==global.location.hostname||this.options.port!=port};Socket.prototype.onConnect=function(){if(!this.connected){this.connected=true;this.connecting=false;if(!this.doBuffer){this.setBuffer(false)}this.emit("connect")}};Socket.prototype.onOpen=function(){this.open=true};Socket.prototype.onClose=function(){this.open=false;clearTimeout(this.heartbeatTimeoutTimer)};Socket.prototype.onPacket=function(packet){this.of(packet.endpoint).onPacket(packet)};Socket.prototype.onError=function(err){if(err&&err.advice){if(err.advice==="reconnect"&&(this.connected||this.connecting)){this.disconnect();if(this.options.reconnect){this.reconnect()}}}this.publish("error",err&&err.reason?err.reason:err)};Socket.prototype.onDisconnect=function(reason){var wasConnected=this.connected,wasConnecting=this.connecting;this.connected=false;this.connecting=false;this.open=false;if(wasConnected||wasConnecting){this.transport.close();this.transport.clearTimeouts();if(wasConnected){this.publish("disconnect",reason);if("booted"!=reason&&this.options.reconnect&&!this.reconnecting){this.reconnect()}}}};Socket.prototype.reconnect=function(){this.reconnecting=true;this.reconnectionAttempts=0;this.reconnectionDelay=this.options["reconnection delay"];var self=this,maxAttempts=this.options["max reconnection attempts"],tryMultiple=this.options["try multiple transports"],limit=this.options["reconnection limit"];function reset(){if(self.connected){for(var i in self.namespaces){if(self.namespaces.hasOwnProperty(i)&&""!==i){self.namespaces[i].packet({type:"connect"})}}self.publish("reconnect",self.transport.name,self.reconnectionAttempts)}clearTimeout(self.reconnectionTimer);self.removeListener("connect_failed",maybeReconnect);self.removeListener("connect",maybeReconnect);self.reconnecting=false;delete self.reconnectionAttempts;delete self.reconnectionDelay;delete self.reconnectionTimer;delete self.redoTransports;self.options["try multiple transports"]=tryMultiple}function maybeReconnect(){if(!self.reconnecting){return}if(self.connected){return reset()}if(self.connecting&&self.reconnecting){return self.reconnectionTimer=setTimeout(maybeReconnect,1e3)}if(self.reconnectionAttempts++>=maxAttempts){if(!self.redoTransports){self.on("connect_failed",maybeReconnect);self.options["try multiple transports"]=true;self.transports=self.origTransports;self.transport=self.getTransport();self.redoTransports=true;self.connect()}else{self.publish("reconnect_failed");reset()}}else{if(self.reconnectionDelay<limit){self.reconnectionDelay*=2}self.connect();self.publish("reconnecting",self.reconnectionDelay,self.reconnectionAttempts);self.reconnectionTimer=setTimeout(maybeReconnect,self.reconnectionDelay)}}this.options["try multiple transports"]=false;this.reconnectionTimer=setTimeout(maybeReconnect,this.reconnectionDelay);this.on("connect",maybeReconnect)}})("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports,this);(function(exports,io){exports.SocketNamespace=SocketNamespace;function SocketNamespace(socket,name){this.socket=socket;this.name=name||"";this.flags={};this.json=new Flag(this,"json");this.ackPackets=0;this.acks={}}io.util.mixin(SocketNamespace,io.EventEmitter);SocketNamespace.prototype.$emit=io.EventEmitter.prototype.emit;SocketNamespace.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)};SocketNamespace.prototype.packet=function(packet){packet.endpoint=this.name;this.socket.packet(packet);this.flags={};return this};SocketNamespace.prototype.send=function(data,fn){var packet={type:this.flags.json?"json":"message",data:data};if("function"==typeof fn){packet.id=++this.ackPackets;packet.ack=true;this.acks[packet.id]=fn}return this.packet(packet)};SocketNamespace.prototype.emit=function(name){var args=Array.prototype.slice.call(arguments,1),lastArg=args[args.length-1],packet={type:"event",name:name};if("function"==typeof lastArg){packet.id=++this.ackPackets;packet.ack="data";this.acks[packet.id]=lastArg;args=args.slice(0,args.length-1)}packet.args=args;return this.packet(packet)};SocketNamespace.prototype.disconnect=function(){if(this.name===""){this.socket.disconnect()}else{this.packet({type:"disconnect"});this.$emit("disconnect")}return this};SocketNamespace.prototype.onPacket=function(packet){var self=this;function ack(){self.packet({type:"ack",args:io.util.toArray(arguments),ackId:packet.id})}switch(packet.type){case"connect":this.$emit("connect");break;case"disconnect":if(this.name===""){this.socket.onDisconnect(packet.reason||"booted")}else{this.$emit("disconnect",packet.reason)}break;case"message":case"json":var params=["message",packet.data];if(packet.ack=="data"){params.push(ack)}else if(packet.ack){this.packet({type:"ack",ackId:packet.id})}this.$emit.apply(this,params);break;case"event":var params=[packet.name].concat(packet.args);if(packet.ack=="data")params.push(ack);this.$emit.apply(this,params);break;case"ack":if(this.acks[packet.ackId]){this.acks[packet.ackId].apply(this,packet.args);delete this.acks[packet.ackId]}break;case"error":if(packet.advice){this.socket.onError(packet)}else{if(packet.reason=="unauthorized"){this.$emit("connect_failed",packet.reason)}else{this.$emit("error",packet.reason)}}break}};function Flag(nsp,name){this.namespace=nsp;this.name=name}Flag.prototype.send=function(){this.namespace.flags[this.name]=true;this.namespace.send.apply(this.namespace,arguments)};Flag.prototype.emit=function(){this.namespace.flags[this.name]=true;this.namespace.emit.apply(this.namespace,arguments)}})("undefined"!=typeof io?io:module.exports,"undefined"!=typeof io?io:module.parent.exports);(function(exports,io,global){exports.websocket=WS;function WS(socket){io.Transport.apply(this,arguments)}io.util.inherit(WS,io.Transport);WS.prototype.name="websocket";WS.prototype.open=function(){var query=io.util.query(this.socket.options.query),self=this,Socket;if(!Socket){Socket=global.MozWebSocket||global.WebSocket}this.websocket=new Socket(this.prepareUrl()+query);this.websocket.onopen=function(){self.onOpen();self.socket.setBuffer(false)};this.websocket.onmessage=function(ev){self.onData(ev.data)};this.websocket.onclose=function(){self.onClose();self.socket.setBuffer(true)};this.websocket.onerror=function(e){self.onError(e)};return this};if(io.util.ua.iDevice){WS.prototype.send=function(data){var self=this;setTimeout(function(){self.websocket.send(data)},0);return this}}else{WS.prototype.send=function(data){this.websocket.send(data);return this}}WS.prototype.payload=function(arr){for(var i=0,l=arr.length;i<l;i++){this.packet(arr[i])}return this};WS.prototype.close=function(){this.websocket.close();return this};WS.prototype.onError=function(e){this.socket.onError(e)};WS.prototype.scheme=function(){return this.socket.options.secure?"wss":"ws"};WS.check=function(){return"WebSocket"in global&&!("__addTask"in WebSocket)||"MozWebSocket"in global};WS.xdomainCheck=function(){return true};io.transports.push("websocket")})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this);(function(exports,io){exports.flashsocket=Flashsocket;function Flashsocket(){io.Transport.websocket.apply(this,arguments)}io.util.inherit(Flashsocket,io.Transport.websocket);Flashsocket.prototype.name="flashsocket";Flashsocket.prototype.open=function(){var self=this,args=arguments;WebSocket.__addTask(function(){io.Transport.websocket.prototype.open.apply(self,args)});return this};Flashsocket.prototype.send=function(){var self=this,args=arguments;WebSocket.__addTask(function(){io.Transport.websocket.prototype.send.apply(self,args)});return this};Flashsocket.prototype.close=function(){WebSocket.__tasks.length=0;io.Transport.websocket.prototype.close.call(this);return this};Flashsocket.prototype.ready=function(socket,fn){function init(){var options=socket.options,port=options["flash policy port"],path=["http"+(options.secure?"s":"")+":/",options.host+":"+options.port,options.resource,"static/flashsocket","WebSocketMain"+(socket.isXDomain()?"Insecure":"")+".swf"];if(!Flashsocket.loaded){if(typeof WEB_SOCKET_SWF_LOCATION==="undefined"){WEB_SOCKET_SWF_LOCATION=path.join("/")}if(port!==843){WebSocket.loadFlashPolicyFile("xmlsocket://"+options.host+":"+port)}WebSocket.__initialize();Flashsocket.loaded=true}fn.call(self)}var self=this;if(document.body)return init();io.util.load(init)};Flashsocket.check=function(){if(typeof WebSocket=="undefined"||!("__initialize"in WebSocket)||!swfobject)return false;return swfobject.getFlashPlayerVersion().major>=10};Flashsocket.xdomainCheck=function(){return true};if(typeof window!="undefined"){WEB_SOCKET_DISABLE_AUTO_INITIALIZATION=true}io.transports.push("flashsocket")})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports);if("undefined"!=typeof window){var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"
    15 1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O[["Active"].concat("Object").join("X")]!=D){try{var ad=new(window[["Active"].concat("Object").join("X")])(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if(typeof j.readyState!=D&&j.readyState=="complete"||typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body)){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return!a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||!/%$/.test(aa.width)&&parseInt(aa.width,10)<310){aa.width="310"}if(typeof aa.height==D||!/%$/.test(aa.height)&&parseInt(aa.height,10)<137){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?["Active"].concat("").join("X"):"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)
    16 }})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return Y[0]>X[0]||Y[0]==X[0]&&Y[1]>X[1]||Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=ad&&typeof ad=="string"?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring(Y[X].indexOf("=")+1))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}()}(function(){if("undefined"==typeof window||window.WebSocket)return;var console=window.console;if(!console||!console.log||!console.error){console={log:function(){},error:function(){}}}if(!swfobject.hasFlashPlayerVersion("10.0.0")){console.error("Flash Player >= 10.0.0 is required.");return}if(location.protocol=="file:"){console.error("WARNING: web-socket-js doesn't work in file:///... URL "+"unless you set Flash Security Settings properly. "+"Open the page via Web server i.e. http://...")}WebSocket=function(url,protocols,proxyHost,proxyPort,headers){var self=this;self.__id=WebSocket.__nextId++;WebSocket.__instances[self.__id]=self;self.readyState=WebSocket.CONNECTING;self.bufferedAmount=0;self.__events={};if(!protocols){protocols=[]}else if(typeof protocols=="string"){protocols=[protocols]}setTimeout(function(){WebSocket.__addTask(function(){WebSocket.__flash.create(self.__id,url,protocols,proxyHost||null,proxyPort||0,headers||null)})},0)};WebSocket.prototype.send=function(data){if(this.readyState==WebSocket.CONNECTING){throw"INVALID_STATE_ERR: Web Socket connection has not been established"}var result=WebSocket.__flash.send(this.__id,encodeURIComponent(data));if(result<0){return true}else{this.bufferedAmount+=result;return false}};WebSocket.prototype.close=function(){if(this.readyState==WebSocket.CLOSED||this.readyState==WebSocket.CLOSING){return}this.readyState=WebSocket.CLOSING;WebSocket.__flash.close(this.__id)};WebSocket.prototype.addEventListener=function(type,listener,useCapture){if(!(type in this.__events)){this.__events[type]=[]}this.__events[type].push(listener)};WebSocket.prototype.removeEventListener=function(type,listener,useCapture){if(!(type in this.__events))return;var events=this.__events[type];for(var i=events.length-1;i>=0;--i){if(events[i]===listener){events.splice(i,1);break}}};WebSocket.prototype.dispatchEvent=function(event){var events=this.__events[event.type]||[];for(var i=0;i<events.length;++i){events[i](event)}var handler=this["on"+event.type];if(handler)handler(event)};WebSocket.prototype.__handleEvent=function(flashEvent){if("readyState"in flashEvent){this.readyState=flashEvent.readyState}if("protocol"in flashEvent){this.protocol=flashEvent.protocol}var jsEvent;if(flashEvent.type=="open"||flashEvent.type=="error"){jsEvent=this.__createSimpleEvent(flashEvent.type)}else if(flashEvent.type=="close"){jsEvent=this.__createSimpleEvent("close")}else if(flashEvent.type=="message"){var data=decodeURIComponent(flashEvent.message);jsEvent=this.__createMessageEvent("message",data)}else{throw"unknown event type: "+flashEvent.type}this.dispatchEvent(jsEvent)};WebSocket.prototype.__createSimpleEvent=function(type){if(document.createEvent&&window.Event){var event=document.createEvent("Event");event.initEvent(type,false,false);return event}else{return{type:type,bubbles:false,cancelable:false}}};WebSocket.prototype.__createMessageEvent=function(type,data){if(document.createEvent&&window.MessageEvent&&!window.opera){var event=document.createEvent("MessageEvent");event.initMessageEvent("message",false,false,data,null,null,window,null);return event}else{return{type:type,data:data,bubbles:false,cancelable:false}}};WebSocket.CONNECTING=0;WebSocket.OPEN=1;WebSocket.CLOSING=2;WebSocket.CLOSED=3;WebSocket.__flash=null;WebSocket.__instances={};WebSocket.__tasks=[];WebSocket.__nextId=0;WebSocket.loadFlashPolicyFile=function(url){WebSocket.__addTask(function(){WebSocket.__flash.loadManualPolicyFile(url)})};WebSocket.__initialize=function(){if(WebSocket.__flash)return;if(WebSocket.__swfLocation){window.WEB_SOCKET_SWF_LOCATION=WebSocket.__swfLocation}if(!window.WEB_SOCKET_SWF_LOCATION){console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");return}var container=document.createElement("div");container.id="webSocketContainer";container.style.position="absolute";if(WebSocket.__isFlashLite()){container.style.left="0px";container.style.top="0px"}else{container.style.left="-100px";container.style.top="-100px"}var holder=document.createElement("div");holder.id="webSocketFlash";container.appendChild(holder);document.body.appendChild(container);swfobject.embedSWF(WEB_SOCKET_SWF_LOCATION,"webSocketFlash","1","1","10.0.0",null,null,{hasPriority:true,swliveconnect:true,allowScriptAccess:"always"},null,function(e){if(!e.success){console.error("[WebSocket] swfobject.embedSWF failed")}})};WebSocket.__onFlashInitialized=function(){setTimeout(function(){WebSocket.__flash=document.getElementById("webSocketFlash");WebSocket.__flash.setCallerUrl(location.href);WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);for(var i=0;i<WebSocket.__tasks.length;++i){WebSocket.__tasks[i]()}WebSocket.__tasks=[]},0)};WebSocket.__onFlashEvent=function(){setTimeout(function(){try{var events=WebSocket.__flash.receiveEvents();for(var i=0;i<events.length;++i){WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i])}}catch(e){console.error(e)}},0);return true};WebSocket.__log=function(message){console.log(decodeURIComponent(message))};WebSocket.__error=function(message){console.error(decodeURIComponent(message))};WebSocket.__addTask=function(task){if(WebSocket.__flash){task()}else{WebSocket.__tasks.push(task)}};WebSocket.__isFlashLite=function(){if(!window.navigator||!window.navigator.mimeTypes){return false}var mimeType=window.navigator.mimeTypes["application/x-shockwave-flash"];if(!mimeType||!mimeType.enabledPlugin||!mimeType.enabledPlugin.filename){return false}return mimeType.enabledPlugin.filename.match(/flashlite/i)?true:false};if(!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION){if(window.addEventListener){window.addEventListener("load",function(){WebSocket.__initialize()},false)}else{window.attachEvent("onload",function(){WebSocket.__initialize()})}}})();(function(exports,io,global){exports.XHR=XHR;function XHR(socket){if(!socket)return;io.Transport.apply(this,arguments);this.sendBuffer=[]}io.util.inherit(XHR,io.Transport);XHR.prototype.open=function(){this.socket.setBuffer(false);this.onOpen();this.get();this.setCloseTimeout();return this};XHR.prototype.payload=function(payload){var msgs=[];for(var i=0,l=payload.length;i<l;i++){msgs.push(io.parser.encodePacket(payload[i]))}this.send(io.parser.encodePayload(msgs))};XHR.prototype.send=function(data){this.post(data);return this};function empty(){}XHR.prototype.post=function(data){var self=this;this.socket.setBuffer(true);function stateChange(){if(this.readyState==4){this.onreadystatechange=empty;self.posting=false;if(this.status==200){self.socket.setBuffer(false)}else{self.onClose()}}}function onload(){this.onload=empty;self.socket.setBuffer(false)}this.sendXHR=this.request("POST");if(global.XDomainRequest&&this.sendXHR instanceof XDomainRequest){this.sendXHR.onload=this.sendXHR.onerror=onload}else{this.sendXHR.onreadystatechange=stateChange}this.sendXHR.send(data)};XHR.prototype.close=function(){this.onClose();return this};XHR.prototype.request=function(method){var req=io.util.request(this.socket.isXDomain()),query=io.util.query(this.socket.options.query,"t="+ +new Date);req.open(method||"GET",this.prepareUrl()+query,true);if(method=="POST"){try{if(req.setRequestHeader){req.setRequestHeader("Content-type","text/plain;charset=UTF-8")}else{req.contentType="text/plain"}}catch(e){}}return req};XHR.prototype.scheme=function(){return this.socket.options.secure?"https":"http"};XHR.check=function(socket,xdomain){try{var request=io.util.request(xdomain),usesXDomReq=global.XDomainRequest&&request instanceof XDomainRequest,socketProtocol=socket&&socket.options&&socket.options.secure?"https:":"http:",isXProtocol=global.location&&socketProtocol!=global.location.protocol;if(request&&!(usesXDomReq&&isXProtocol)){return true}}catch(e){}return false};XHR.xdomainCheck=function(socket){return XHR.check(socket,true)}})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this);(function(exports,io){exports.htmlfile=HTMLFile;function HTMLFile(socket){io.Transport.XHR.apply(this,arguments)}io.util.inherit(HTMLFile,io.Transport.XHR);HTMLFile.prototype.name="htmlfile";HTMLFile.prototype.get=function(){this.doc=new(window[["Active"].concat("Object").join("X")])("htmlfile");this.doc.open();this.doc.write("<html></html>");this.doc.close();this.doc.parentWindow.s=this;var iframeC=this.doc.createElement("div");iframeC.className="socketio";this.doc.body.appendChild(iframeC);this.iframe=this.doc.createElement("iframe");iframeC.appendChild(this.iframe);var self=this,query=io.util.query(this.socket.options.query,"t="+ +new Date);this.iframe.src=this.prepareUrl()+query;io.util.on(window,"unload",function(){self.destroy()})};HTMLFile.prototype._=function(data,doc){data=data.replace(/\\\//g,"/");this.onData(data);try{var script=doc.getElementsByTagName("script")[0];script.parentNode.removeChild(script)}catch(e){}};HTMLFile.prototype.destroy=function(){if(this.iframe){try{this.iframe.src="about:blank"}catch(e){}this.doc=null;this.iframe.parentNode.removeChild(this.iframe);this.iframe=null;CollectGarbage()}};HTMLFile.prototype.close=function(){this.destroy();return io.Transport.XHR.prototype.close.call(this)};HTMLFile.check=function(socket){if(typeof window!="undefined"&&["Active"].concat("Object").join("X")in window){try{var a=new(window[["Active"].concat("Object").join("X")])("htmlfile");return a&&io.Transport.XHR.check(socket)}catch(e){}}return false};HTMLFile.xdomainCheck=function(){return false};io.transports.push("htmlfile")})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports);(function(exports,io,global){exports["xhr-polling"]=XHRPolling;function XHRPolling(){io.Transport.XHR.apply(this,arguments)}io.util.inherit(XHRPolling,io.Transport.XHR);io.util.merge(XHRPolling,io.Transport.XHR);XHRPolling.prototype.name="xhr-polling";XHRPolling.prototype.heartbeats=function(){return false};XHRPolling.prototype.open=function(){var self=this;io.Transport.XHR.prototype.open.call(self);return false};function empty(){}XHRPolling.prototype.get=function(){if(!this.isOpen)return;var self=this;function stateChange(){if(this.readyState==4){this.onreadystatechange=empty;if(this.status==200){self.onData(this.responseText);self.get()}else{self.onClose()}}}function onload(){this.onload=empty;this.onerror=empty;self.retryCounter=1;self.onData(this.responseText);self.get()}function onerror(){self.retryCounter++;if(!self.retryCounter||self.retryCounter>3){self.onClose()}else{self.get()}}this.xhr=this.request();if(global.XDomainRequest&&this.xhr instanceof XDomainRequest){this.xhr.onload=onload;this.xhr.onerror=onerror}else{this.xhr.onreadystatechange=stateChange}this.xhr.send(null)};XHRPolling.prototype.onClose=function(){io.Transport.XHR.prototype.onClose.call(this);if(this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=empty;try{this.xhr.abort()}catch(e){}this.xhr=null}};XHRPolling.prototype.ready=function(socket,fn){var self=this;io.util.defer(function(){fn.call(self)})};io.transports.push("xhr-polling")})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this);(function(exports,io,global){var indicator=global.document&&"MozAppearance"in global.document.documentElement.style;exports["jsonp-polling"]=JSONPPolling;function JSONPPolling(socket){io.Transport["xhr-polling"].apply(this,arguments);this.index=io.j.length;var self=this;io.j.push(function(msg){self._(msg)})}io.util.inherit(JSONPPolling,io.Transport["xhr-polling"]);JSONPPolling.prototype.name="jsonp-polling";JSONPPolling.prototype.post=function(data){var self=this,query=io.util.query(this.socket.options.query,"t="+ +new Date+"&i="+this.index);if(!this.form){var form=document.createElement("form"),area=document.createElement("textarea"),id=this.iframeId="socketio_iframe_"+this.index,iframe;form.className="socketio";form.style.position="absolute";form.style.top="0px";form.style.left="0px";form.style.display="none";form.target=id;form.method="POST";form.setAttribute("accept-charset","utf-8");area.name="d";form.appendChild(area);document.body.appendChild(form);this.form=form;this.area=area}this.form.action=this.prepareUrl()+query;function complete(){initIframe();self.socket.setBuffer(false)}function initIframe(){if(self.iframe){self.form.removeChild(self.iframe)}try{iframe=document.createElement('<iframe name="'+self.iframeId+'">')}catch(e){iframe=document.createElement("iframe");iframe.name=self.iframeId}iframe.id=self.iframeId;self.form.appendChild(iframe);self.iframe=iframe}initIframe();this.area.value=io.JSON.stringify(data);try{this.form.submit()}catch(e){}if(this.iframe.attachEvent){iframe.onreadystatechange=function(){if(self.iframe.readyState=="complete"){complete()}}}else{this.iframe.onload=complete}this.socket.setBuffer(true)};JSONPPolling.prototype.get=function(){var self=this,script=document.createElement("script"),query=io.util.query(this.socket.options.query,"t="+ +new Date+"&i="+this.index);if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}script.async=true;script.src=this.prepareUrl()+query;script.onerror=function(){self.onClose()};var insertAt=document.getElementsByTagName("script")[0];insertAt.parentNode.insertBefore(script,insertAt);this.script=script;if(indicator){setTimeout(function(){var iframe=document.createElement("iframe");document.body.appendChild(iframe);document.body.removeChild(iframe)},100)}};JSONPPolling.prototype._=function(msg){this.onData(msg);if(this.isOpen){this.get()}return this};JSONPPolling.prototype.ready=function(socket,fn){var self=this;if(!indicator)return fn.call(this);io.util.load(function(){fn.call(self)})};JSONPPolling.check=function(){return"document"in global};JSONPPolling.xdomainCheck=function(){return true};io.transports.push("jsonp-polling")})("undefined"!=typeof io?io.Transport:module.exports,"undefined"!=typeof io?io:module.parent.exports,this);if(typeof define==="function"&&define.amd){define("io",[],function(){return io})}})();define("pubsub",["ext/underscore","app-context","io"],function(_,appContext,io){var $=jQuery;var groupIdMap={};var getGroupId=function(conversationId,callback){if(groupIdMap[conversationId]){callback(groupIdMap[conversationId])}else{$.ajax({url:appContext.fullUrl("/v2/messages/"+conversationId+"/participants"),success:function(participants){_.assert(participants.length==1,"only 1 participant expected");var idParts=participants[0].id.split(":");_.assert(idParts[1]=="group","not a group participant: "+idParts[1]);groupIdMap[conversationId]=idParts[3];callback(groupIdMap[conversationId])},error:function(jqXHR,textStatus,errorThrown){console.log(JSON.stringify(jqXHR));console.log(JSON.stringify(textStatus));console.log(JSON.stringify(errorThrown));appContext.navigate("#error",true)}})}};var createSocket=function(accessToken){console.log("creating socket ..");var socket=io.connect(appContext.resolvePubsubEndPoint()+"?auth_type=token&token="+accessToken.access_token+"&subscribe=chat");socket.on("connect",function(){setInterval(function(){socket.emit("ping")},3e4)});socket.on("buddies",function(conversation,buddies){var receiver=$(".receiver-"+conversation);_.each(buddies,function(buddy){receiver.trigger("buddy",buddy)})});socket.on("chat-message",function(message){var receiver=$(".receiver-"+message.conversation);if(receiver.length==1){receiver.trigger("chatmsg",message)}else{if(message.type=="text"){getGroupId(message.conversation,function(groupId){appContext.addNotification("#messages/groups:@"+groupId)})}}});socket.on("unread",function(conversations){_.each(conversations,function(conversation){getGroupId(conversation.id,function(groupId){appContext.addNotification("#messages/groups:@"+groupId)})})});return socket};var socket=null;var accessToken=appContext.getAccessToken();if(accessToken){socket=createSocket(accessToken)}appContext.on("accessToken",function(){if(socket){socket.removeAllListeners("unread");socket.removeAllListeners("chat-message");socket.removeAllListeners("buddies");socket.removeAllListeners("connect")}socket=createSocket(appContext.getAccessToken())});return{emit:function(event,data){if(!socket){throw"no socket available"}socket.emit(event,data)}}});define("api/model/message",["ext/underscore","moment","api/model/base"],function(_,moment,BaseModel){return BaseModel.extend({initialize:function(attributes,options){this.principle=options.principle;this.created=new Date},getSourceId:function(){var source=this.get("source");return source?source.id.split(":")[3]:this.principle.id},getSourceName:function(){var source=this.get("source");return source?source.name:this.principle.name},getDateReceived:function(){var date=moment(this.get("dateReceived"));return date?new Date(moment(date,"YYYY-MM-DDTHH:mm:ss.SSSZ").valueOf()):this.created},isType:function(){return this.get("type")=="type"},isTyping:function(){_.assert(this.isType(),"not a type message");return this.get("body")=="yes"},noThumb:function(){var noThumb=_.find(this.get("properties"),function(property){return property=="nothumb"});return!!noThumb}})});define("api/collection/messages",["api/collection/base","api/model/message"],function(BaseCollection,Message){return BaseCollection.extend({model:Message,initialize:function(models,options){if(options.current){this.conversation=options.current.conversation;if(options.current.offset){this.params={offset:options.current.offset}}else if(options.current.length>0){this.params={"condition.offset":options.current.length}}}else{this.conversation=options.conversation}},url:function(){return"/v2/messages/"+this.conversation.id+"/history"},parse:function(response){if(response instanceof Array){this.more=response.length>0;return response}this.offset=response.offset;this.more=response.more;return response.items},addPage:function(page){this.add(page.models);this.offset=page.offset;this.more=page.more},comparator:function(model){return-model.getDateReceived().getTime()}})});define("text!text/message/item.html",[],function(){return'\n<% if (noThumb()) { %>\n   <img src="<%= appurl %>/styles/images/default_thumbnail.png">\n<% } else { %>\n <img src="<%= cdn %>/users/<%= getSourceId() %>/thumbnail">\n<% } %>\n<div class="info <% if (getSourceId() == me.id) { print(\'self\') } %>">\n    <p>\n       <strong class="name"><%= getSourceName() %></strong>\n      <abbr data-time="<%= getDateReceived().getTime() %>" class="timeago">\n         <%= $.timeago(getDateReceived()) %>\n       </abbr>\n   </p>\n  <p class="body"><%= get(\'body\') %></p>\n</div>    \n'});define("view/message/item",["ext/underscore","app-context","view/base","text!text/message/item.html"],function(_,appContext,BaseView,template){var $=jQuery;return BaseView.extend({tagName:"li",events:{"click div.self":"update"},initialize:function(options){_.bindToMethods(this);this.options=options;this.model.on("change",this.change)},render:function(){var args=_.extend({cdn:appContext.cdn,me:appContext.getPrinciple()},this.model);this.$el.html(this.template(template,args));return this},change:function(){$(".body",this.$el).html(this.model.get("body"))},update:function(){this.options.inputView.update(this.model)}})});define("text!text/message/input.html",[],function(){return'<textarea placeholder="<%= m_message_placeholder %>"></textarea>\n<a href="javascript:void(0)" class="send hidden">\n <span class="glyphicon glyphicon-send"></span>\n</a>\n<div class="update-btns hidden">\n    <a href="javascript:void(0)" class="update">\n      <span class="glyphicon glyphicon-ok"></span>\n  </a>\n  <a href="javascript:void(0)" class="cancel">\n      <span class="glyphicon glyphicon-remove"></span>\n  </a>\n</div>\n'});define("view/message/input",["ext/underscore","view/base","app-context","pubsub","text!text/message/input.html"],function(_,BaseView,appContext,pubsub,template){var $=jQuery;return BaseView.extend({back:{code:"m_btn_context",link:"#context"},className:"messages-input",events:{"keyup textarea":"keyup","click .send,.update":"send","click .cancel":"cancel"},initialize:function(options){_.bindToMethods(this);this.options=options},render:function(){this.$el.html(this.template(template));this.$input=$("textarea",this.$el);this.$send=$(".send",this.$el);return this},keyup:function(){if(_.trim(this.$input.val()).length==0){if(this.target){this.cancel()}else{this.stopTyping;this.sendBtn(false)}}else{if(!this.typing){this.emitMessage("type","yes")}this.typing=true;this.stopTyping_debounced();if(!this.target){this.sendBtn(true)}}},send:function(){var body=_.trim(this.$input.val()).replace(/\n/gm,"<br/>");if(this.target){this.emitMessage("update",body,this.target);this.cancel()}else{this.emitMessage("text",body);this.$input.val("");this.stopTyping();this.sendBtn(false)}},cancel:function(){this.target=null;this.$input.val("");this.updateBtns(false);this.stopTyping()},emitMessage:function(type,body,target){var conversationId=this.options.conversation.id;var message={conversation:conversationId,deliveryId:conversationId+Math.random().toString(36).substr(2),body:body,type:type,properties:[]};if(typeof target!="undefined"){message.id=target.id;message.deliveryId=target.get("deliveryId")}if(!appContext.getPrinciple().logo){message.properties.push("nothumb")}pubsub.emit("chat-message",message);$(".receiver-"+conversationId).trigger("chatmsg",message)},stopTyping:function(){this.emitMessage("type","no");this.typing=false},stopTyping_debounced:_.debounce(function(){this.stopTyping()},5e3),update:function(message){this.target=message;this.$input.val(message.get("body").replace(/<br ?\/>/g,"\n")).focus();this.sendBtn(false);this.updateBtns(true)},updateBtns:function(show){var $btns=$(".update-btns",this.$el);if(show){$btns.removeClass("hidden");this.$input.width(this.$el.width()-65)}else{$btns.addClass("hidden");this.$input.css("width","100%")}},sendBtn:function(show){if(show){this.$send.removeClass("hidden");this.$input.width(this.$el.width()-40)}else{this.$send.addClass("hidden");this.$input.css("width","100%")}}})});define("view/message/list",["ext/underscore","app-context","view/page","api/collection/messages","api/model/message","view/navbar-factory","view/message/item","view/message/input"],function(_,appContext,PageView,Messages,Message,navbarFactory,MessageItemView,MessageInputView){var $=jQuery;return PageView.extend({back:{code:"m_btn_context",link:"#context"},tagName:"ul",className:"messages list-unstyled",events:{buddy:"receiveBuddy",chatmsg:"receiveMessage"},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.title=_.escape(this.collection.conversation.group.get("friendlyName"));this.timer=setInterval(this.updateTime,6e4)},render:function(){PageView.prototype.render.apply(this,arguments);this.inputView=new MessageInputView({conversation:this.collection.conversation});this.addFooter(this.inputView.render().$el);this.$el.addClass("receiver-"+this.collection.conversation.id);this.$header=$("<div>").addClass("messages-header");this.addHeader(this.$header);this.retrievePage();return this},receiveBuddy:function(e,buddy){var $image=$(".user-"+buddy.user.id,this.$header);if(buddy.online&&$image.length==0){var src=appContext.defaultThumb;if(buddy.user.logo){src=appContext.cdn+"/users/"+buddy.user.id+"/thumbnail"}$("<img>").addClass("user-"+buddy.user.id).attr("src",src).appendTo(this.$header)}else if(!buddy.online&&$image.length>0){$image.remove()}},receiveMessage:function(e,message){message=new Message(message,{principle:appContext.getPrinciple()});if(message.isType()){if(message.isTyping()){if(message.get("source")){var html=message.get("source").name+" typing..";$("<li>").addClass("typing").html(html).appendTo(this.$el)}}else{$("li.typing",this.$el).remove()}}else{var target=this.collection.findWhere({deliveryId:message.get("deliveryId")});if(target){target.set("body",message.get("body"))}else{var itemView=new MessageItemView({model:message,inputView:this.inputView});this.$el.append(itemView.render().el);this.collection.add(message)}}this.scrollToEnd()},retrievePage:function(){var messages=new Messages([],{current:this.collection});messages.once("sync",this.renderPage);messages.fetch()},renderPage:function(messages){var $first=$("li",this.$el).first();messages.each(function(message){var itemView=new MessageItemView({model:message,inputView:this.inputView});this.$el.prepend(itemView.render().el)},this);if(this.collection.length==0){this.scrollToEnd()}else{this.scroll($first.position().top-1)}messages.more&&_.defer(_.bind(function(){$("li",this.$el).first().one("inview",this.retrievePage)},this));this.collection.addPage(messages)},scrollToEnd:function(){var last=$("li",this.$el).last();if(last.length>0){this.scroll(last.position().top+last.height())}},updateTime:function(){$("abbr.timeago",this.$el).each(function(){var $abbr=$(this);$abbr.html($.timeago(new Date($abbr.data("time"))))})},remove:function(){PageView.prototype.remove.apply(this,arguments);clearInterval(this.timer);this.removeMarginal(this.$header);this.removeMarginal(this.inputView.$el)},navbar:function(callback){this.navbarCreate("messages",this.collection.conversation.group.id,callback)}}).extend(navbarFactory)});define("api/model/conversation",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(attributes,options){this.group=options.group},url:function(){return this.group.url()+"/conversation"}})});define("router/message",["ext/underscore","router/group","app-context","pubsub","view/message/list","api/model/conversation","api/collection/messages"],function(_,GroupRouter,appContext,pubsub,MessageListView,Conversation,Messages){var $=jQuery;var showMessages=function(conversation){var view=new MessageListView({collection:new Messages([],{conversation:conversation})});view.render();pubsub.emit("buddies-notify",conversation.id);$.ajax({type:"POST",url:appContext.fullUrl("/v2/messages"),data:JSON.stringify({conversations:[conversation.id]}),error:function(){appContext.navigate("#error",true)},contentType:"application/json"})};return GroupRouter.extend({routes:{"messages/:groupKey":"getConversation"},getConversation:function(group){var conversation=new Conversation({},{group:group});conversation.once("sync",showMessages);conversation.fetch()}})});requirejs.config({baseUrl:"app",paths:{io:"lib/socket.io","native":"../native","underscore.string":"lib/underscore.string",moment:"lib/moment.min"},shim:{"lib/iscroll":{exports:"iScroll"}}});require(["app-context","native","router/default","router/update","router/file","router/note","router/discussion","router/event","router/task","router/comment","router/share-token","router/message"],function(appContext,_native,DefaultRouter,UpdateRouter,FileRouter,NoteRouter,DiscussionRouter,EventRouter,TaskRouter,CommentRouter,ShareTokenRouter,MessageRouter){new DefaultRouter;new UpdateRouter;new FileRouter;new NoteRouter;new DiscussionRouter;new EventRouter;new TaskRouter;new CommentRouter;new ShareTokenRouter;new MessageRouter;Backbone.history.start({silent:true});_native.start(function(options){console.log("initialising: "+JSON.stringify(options));appContext.setStartOptions(options);
    17 appContext.navigate(options.location?options.location:"#updates/dashboard",true)})});define("main",function(){});
     1(function($,undef){"use strict";var debug=false;window.FileUpload_Debug=function(){if(debug&&console.log)if($.browser.msie){var output="Log: ";$.each(arguments,function(){output+=this});console.log(output)}else console.log.apply(console,arguments)};window.FileUpload_ToJSONIfPossible=function(responseText){if(responseText)try{return $.parseJSON(responseText)}catch(e){window.FileUpload_Debug(e)}return responseText}})(jQuery,"undefined");(function($,undef,debug){"use strict";var default_options={chunkEndpoint:"",finalEndpoint:"",beforeFinalSend:function(){},multipartEndpoint:"",completeRetries:300,defaultDataType:"json",defaultContentType:"application/x-www-form-urlencoded; charset=UTF-8",numberOfSimultaneousFileUploads:2,serializeFormData:true,chunkSize:5242880,maxFileSize:4294967296,runtimes:["HTMLRuntime","FlashRuntime","FrameRuntime"],autoUpload:false,deleteOnFailure:false,flashPath:"../swf/",ajaxLoader:"../img/ajax-loader.gif",fileLoading:"Loading file",fileComplete:"Complete",fileSize:"File too large"};function assert(expr,exception){if(expr)throw exception}function FileUpload(element,options){assert(element.nodeName.toLowerCase()!=="form","Invalid element, expected form nodeName");this.options=$.extend({},default_options,options||{});this.element=$(element);this.runtime=this.createRuntime();assert(!this.runtime,"No runtime supported");if(this.options.layout){this.element.addClass("layout-"+this.options.layout.toLowerCase());this.layout=new FileUpload.Layout[this.options.layout](this);this.layout.create()}this.runtime.create(this)}FileUpload.defaultOptions=default_options;FileUpload.hasSupport=function(runtimes){try{return new FileUpload(document.createElement("form"),{runtimes:runtimes||["HTMLRuntime","FlashRuntime"]})!==null}catch(e){return false}};FileUpload.formatBytes=function(bytes){var output=bytes/1024;if(output<1024)return output.toFixed(2)+"KB";output=output/1024;if(output<1024)return output.toFixed(2)+"MB";return(output/1024).toFixed(2)+"GB"};FileUpload.prototype.createRuntime=function(){var runtimeIndex,runtimes=this.options.runtimes;for(runtimeIndex=0;runtimeIndex<runtimes.length;runtimeIndex++){var runtimeName=runtimes[runtimeIndex];var Runtime=FileUpload.Runtime[runtimeName];if(Runtime.supports()){this.runtimeName=runtimeName;return new Runtime(this)}}return null};FileUpload.prototype.triggerEvent=function(eventName){if($.isFunction(this.options[eventName]))this.options[eventName].apply(this,$.makeArray(arguments).slice(1));this.element.trigger("FileUpload_"+eventName,$.makeArray(arguments).slice(1))};FileUpload.prototype.on=function(eventName,handler){var eventNames=$.map(eventName.split(" "),function(value){return"FileUpload_"+value+".FileUpload"}).join(" ");this.element.on(eventNames,handler)};$.each(["send","abort","remove"],function(){var functionName=this;FileUpload.prototype[functionName]=function(){this.runtime[functionName].apply(this.runtime,arguments)}});FileUpload.prototype.finalizeSend=function(file,success,responseHandler){responseHandler=responseHandler||$.noop;var submitData=$.extend({},{FileUploadId:file.fuid,FileUploadName:encodeURIComponent(file.name),FileUploadType:file.type,FileUploadSuccess:success,FileUploadSize:file.size},this.options.data||{});if(this.options.serializeFormData)$.each(this.element.serializeArray(),function(i,item){submitData[item.name]=item.value});var self=this;$.ajax(this.options.finalEndpoint,{beforeSend:this.options.beforeFinalSend,type:"post",dataType:this.options.defaultDataType,data:submitData,contentType:this.options.defaultContentType,success:function(response){responseHandler(false,response);self.triggerEvent("filefinish",file,success,false,response)},error:function(xhr){var text=window.FileUpload_ToJSONIfPossible(xhr.responseText);responseHandler(true,text);self.triggerEvent("filefinish",file,success,true,text)},file:file})};FileUpload.prototype.destroy=function(){if(this.layout){this.element.removeClass("layout-"+this.options.layout.toLowerCase());this.layout.destroy(this);delete this.layout}this.runtime.destroy(this);delete this.runtime;this.element.unbind(".FileUpload")};window.FileUpload=FileUpload})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.File=function(fuid,name,size,type){this.fuid=fuid||0;this.name=name||"unknown";this.size=size||0;this.type=type||"application/octet-stream"}})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";function Runtime(){}Runtime.create=function(name,runtimeCode){var runtime=function(fileUpload){this.fileUpload=fileUpload};$.extend(runtime.prototype,Runtime.prototype,runtimeCode);FileUpload.Runtime[name]=runtime;FileUpload.Runtime[name].supports=runtimeCode.supports};$.each(["create","destroy","send","abort","supports","remove","uploading"],function(){Runtime.prototype[this]=$.noop});Runtime.prototype.abort=function(fileId){if(fileId&&this.files[fileId]){debug("Aborting file id:",fileId);this.files[fileId].abort()}else if(!fileId){this.fileUpload.triggerEvent("abort");debug("Aborting all file uploads");this.fileStack=[];$.each(this.files,function(){this.abort()})}};Runtime.prototype.remove=function(fileId){if(fileId&&this.files[fileId]){var file=this.files[fileId];if(file.isUploading())throw"Abort or complete in order to remove";file.destroy();delete this.files[fileId]}else if(!fileId){if(this.uploading())throw"Abort or complete in order to remove";$.each(this.files,function(){this.destroy()});this.files={}}};FileUpload.Runtime=Runtime})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";function Layout(){}Layout.create=function(name,layoutCode){var layout=function(fileUpload){this.fileUpload=fileUpload};$.extend(layout.prototype,Layout.prototype,layoutCode);window.FileUpload.Layout[name]=layout};Layout.prototype.create=Layout.prototype.destroy=$.noop;FileUpload.Layout=Layout})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.Runtime.create("HTMLRuntime",{create:function(){this.filesUploading=0;this.files={};this.counter=0;var self=this,HTMLFile=FileUpload.Runtime.HTMLRuntime.File;this.fileUpload.element.on("change.FileUpload",":file",function(e){var target=e.target,newFiles=[];$.each(target.files,function(){var htmlFile=new HTMLFile(this,self.createFileOptions(self.counter));if(this.size>self.fileUpload.options.maxFileSize)self.fileUpload.triggerEvent("filesizeerror",htmlFile.info);else{self.files[self.counter]=new HTMLFile(this,self.createFileOptions(self.counter));newFiles.push(self.files[self.counter].info);self.counter++}});self.fileUpload.triggerEvent("select",newFiles);if(self.fileUpload.options.autoUpload)self.fileUpload.send();if(self.fileUpload.options.clearInputOnChange)target.value=""})},destroy:function(){if(this.timer)clearTimeout(this.timer);$.each(this.files,function(){this.destroy()});this.files=this.fileStack=null},createFileOptions:function(counter){var self=this,options=$.extend({},this.fileUpload.options,{finalize:function(success){var innerSelf=this;self.fileUpload.finalizeSend(this.info,success,function(isError,response,onComplete){if(!isError&&success){if(!innerSelf.aborted){debug("Deleting file with counter",innerSelf.options.counter);delete self.files[innerSelf.options.counter]}}else if(self.fileUpload.options.deleteOnFailure)delete self.files[innerSelf.options.counter]});self.filesUploading--},progress:function(percentage,bytesLoaded,progressEvent,xhrOptions){self.percentLoaded[this.info.fuid]=percentage;var percentTotal=0;$.each(self.percentLoaded,function(){percentTotal+=this});self.fileUpload.triggerEvent("totalprogress",Math.min(100,Math.ceil(percentTotal/self.stackCount)));self.fileUpload.triggerEvent("fileprogress",this.info,percentage)},counter:counter});var defaultEventHandler=function(eventName){return function(chunk){self.fileUpload.triggerEvent(eventName,this.info,chunk)}};$.each(["beforeStart","beforeSend","success","error"],function(){options[this]=defaultEventHandler("file"+this.toLowerCase())});return options},uploading:function(){return!!this.timeout},send:function(fileId){if(!this.uploading()){this.stackLoaded=0;this.percentLoaded={};this.stackSize=0;this.stackCount=0;this.fileStack=[]}var self=this;if(!fileId){$.each(this.files,function(counter){if($.inArray(counter,self.fileStack)===-1&&!self.files[counter].isUploading()){self.fileStack.push(counter);self.stackSize+=this.file.size;self.stackCount++}})}else if(this.files[fileId]&&!this.files[fileId].isUploading()){this.fileStack.push(fileId);this.stackSize+=this.files[fileId].file.size;this.stackCount++}debug("Total stack size: ",this.stackSize);this.fileUpload.triggerEvent("beforestart",{fileStack:this.fileStack,stackSize:this.stackSize,fileId:fileId,running:this.uploading()});this.fileStack=this.fileStack.reverse();if(!this.uploading())this.timeout=setInterval(function(){if(self.fileStack.length===0){clearInterval(self.timeout);self.timeout=null}else if(self.filesUploading<self.fileUpload.options.numberOfSimultaneousFileUploads){var counter=self.fileStack.pop();if(self.files[counter]){debug("Uploading file: ",counter,self.fileStack,self.files);self.files[counter].upload();self.filesUploading++}}},500)},supports:function(){if(typeof File===undef||typeof Blob===undef)return false;var isFn=$.isFunction;return isFn(Blob.prototype.webkitSlice)||isFn(Blob.prototype.mozSlice)||isFn(Blob.prototype.slice)}});$.ajaxPrefilter(function(options){options.xhr=function createStandardXhrWithUpload(){var xhr=$.ajaxSettings.xhr();if(xhr.upload)$.each(options.upload||{},function(event,listener){var optionsWrapper=function(e){return listener.call(this,e,options)};xhr.upload.addEventListener(event,optionsWrapper,false)});return xhr}})})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";var default_options={method:"post",chunkEndpoint:"",dataType:"html",numberOfSimultaneousChunkUploads:1,numberOfRetriesBeforeFailure:1e3,chunkSize:5242880,beforeStart:$.noop,beforeSend:$.noop,success:$.noop,error:$.noop,finalize:$.noop,progress:$.noop};function File(file,options){this.options=$.extend({},default_options,options||{});this.file=file;this.info=new FileUpload.File(this.options.counter,file.name,file.size,file.type);this.totalChunks=Math.ceil(file.size/this.options.chunkSize);this.chunksUploading=0;this.chunksUploaded=0}File.prototype.destroy=function(){if(this.timer)clearTimeout(this.timer);this.chunks=this.xhr=null};File.prototype.slice=function(start,end){if(this.file.slice)return this.file.slice(start,end);if(this.file.mozSlice)return this.file.mozSlice(start,end);return this.file.webkitSlice(start,end)};File.prototype.isUploading=function(){return!!this.timeout};File.prototype.upload=function(){debug("Starting upload process for file");if(this.isUploading()){debug("File is in uploading state, exit");return false}this.chunks=[];this.chunksLoaded=[];this.xhr={};this.uploaded=0;var startPosition=0,endPosition=this.options.chunkSize,index=0;while(startPosition<this.file.size){if(endPosition>this.file.size)endPosition=this.file.size;this.chunks.push({id:index,start:startPosition,end:endPosition,failures:0});index++;startPosition=endPosition;endPosition+=this.options.chunkSize}this.chunks=this.chunks.reverse();this.options.beforeStart.call(this);var self=this;this.percentage=0;this.aborted=false;this.timeout=setInterval(function(){if(self.chunks.length===0&&self.chunksUploading===0){clearInterval(self.timeout);self.timeout=null;self.finalize(self.chunksUploaded===self.totalChunks)}else if(!self.aborted)if(self.chunksUploading<self.options.numberOfSimultaneousChunkUploads&&self.chunks.length!==0)self.send()},500);return true};File.prototype.progressHandler=function(e,options){var self=this;setTimeout(function(){var bytesLoaded=0;$.each(self.chunksLoaded,function(){bytesLoaded+=this.end-this.start});bytesLoaded+=e.loaded;self.percentage=Math.max(self.percentage,Math.min(100,Math.ceil(bytesLoaded/self.file.size*100)));self.options.progress.call(self,self.percentage,bytesLoaded,e,options);debug("File progress: ",self.file.name," = ",self.percentage,"% (chunk:",options.chunk.id,")")},0)};File.prototype.send=function(){var chunk=this.chunks.pop(),blob=this.slice(chunk.start,chunk.end);debug("Sending a new file chunk",chunk);var options=this.options,self=this;var ajaxOptions={dataType:options.dataType,type:options.method,data:blob,timeout:3e4*(chunk.failures+1),contentType:"application/octet-stream",processData:false,chunk:chunk,upload:{progress:$.proxy(this.progressHandler,this),load:$.proxy(this.progressHandler,this)},beforeSend:function(xhr,settings){xhr.setRequestHeader("X-File-Chunk",settings.chunk.id);xhr.setRequestHeader("X-File-Start",settings.chunk.start);xhr.setRequestHeader("X-File-End",settings.chunk.end);xhr.setRequestHeader("X-File-Id",self.info.fuid);xhr.setRequestHeader("X-File-Name",encodeURIComponent(self.info.name));xhr.setRequestHeader("X-File-Size",self.info.size);xhr.setRequestHeader("X-File-Type",self.info.type);self.xhr[settings.chunk.id]=xhr;self.options.beforeSend.apply(self,$.merge([this.chunk],arguments))},success:function(){self.chunksUploaded++;self.chunksUploading--;self.chunksLoaded.push(this.chunk);delete self.xhr[this.chunk.id];self.options.success.apply(self,$.merge([this.chunk],arguments))},error:function(e,statusText){var errorChunk=this.chunk;debug("Failed to upload chunk",errorChunk,statusText);if(statusText!=="abort"&&errorChunk.failures<options.numberOfRetriesBeforeFailure){errorChunk.failures++;self.chunks.push(errorChunk);debug("Retrying to upload chunk",errorChunk)}self.chunksUploading--;delete self.xhr[errorChunk.id];self.options.error.apply(self,$.merge([this.chunk],arguments))}};$.ajax(options.chunkEndpoint,ajaxOptions);this.chunksUploading++};File.prototype.abort=function(){debug("Aborting file upload");this.aborted=true;this.chunks=[];this.chunksUploaded=0;$.each(this.xhr||[],function(){this.abort()})};File.prototype.finalize=function(success){debug("Finalizing file upload, success state: ",success);this.chunksUploading=0;this.options.finalize.apply(this,arguments)};window.FileUpload.Runtime.HTMLRuntime.File=File})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";var instanceCounter=0;var instances={};FileUpload.Runtime.create("FlashRuntime",{create:function(){var instanceId=this.instanceId=++instanceCounter;var options=this.fileUpload.options;this.fileUpload.options.numberOfRetriesBeforeFailure=1e3;var wrapElement=this.wrapElement=this.fileUpload.element.find(options.flashWrapper||":file");$("<div />").attr("id","runtime_"+this.instanceId).insertAfter(wrapElement);$(window).on("resize.FileUpload scroll.FileUpload DOMNodeInserted.FileUpload",$.proxy(this.positionAndResize,this));instances[instanceId]=this;this.embedSWF()},destroy:function(){this.getMovieObject().remove();$(window).unbind(".FileUpload")},init:function(){this.getMovie().setOptions(this.fileUpload.options);this.positionAndResize()},send:function(fileId){this.getMovie().upload(fileId||-1)},abort:function(fileId){this.getMovie().abort(fileId||-1)},remove:function(fileId){this.getMovie().remove(fileId||-1)},uploading:function(){return this.getMovie().uploading()},embedSWF:function(){var flashPath=this.fileUpload.options.flashPath;var flashvars={id:this.instanceId};var params={menu:"false",scale:"noScale",allowFullscreen:"true",allowNetworking:"all",allowScriptAccess:"always",bgcolor:"",wmode:"transparent"};var attributes={id:"flash_runtime_"+this.instanceId};swfobject.embedSWF(flashPath+"fileupload.swf","runtime_"+this.instanceId,"100%","100%","11.1.0",flashPath+"expressInstall.swf",flashvars,params,attributes)},handleFlashEvent:function(eventName,eventArgs){if(eventName==="filefinish"){var self=this;this.fileUpload.finalizeSend.call(this.fileUpload,eventArgs[0],eventArgs[1],function(isError,response,onComplete){if(eventArgs[1]&&!isError||self.fileUpload.options.deleteOnFailure)self.getMovie().deleteFile(eventArgs[0].fuid)})}else this.fileUpload.triggerEvent.apply(this.fileUpload,$.merge([eventName],eventArgs))},positionAndResize:function(){this.getMovieObject().css($.extend(this.wrapElement.position(),{position:"absolute",outline:0})).width(this.wrapElement.outerWidth()).height(this.wrapElement.outerHeight())},getMovieObject:function(){return $("#flash_runtime_"+this.instanceId)},getMovie:function(){var name="flash_runtime_"+this.instanceId;return document[name]||window[name]},supports:function(){return swfobject.hasFlashPlayerVersion("10")}});FileUpload.Runtime.FlashRuntime.EventHandler=function(instanceId,args){var instance=instances[instanceId],safeCall="handleFlashEvent";var eventName=args[0],eventArgs=[];if(args.length>1)eventArgs=args.slice(1);debug("Flash event:",eventName,eventArgs);if(eventName!=="abort")if($.isFunction(instance[eventName]))instance[eventName].apply(instance,eventArgs);else if($.isFunction(instance[safeCall]))instance[safeCall].call(instance,eventName,eventArgs)}})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.Runtime.create("FrameRuntime",{create:function(){if(!this.fileUpload.options.multipartEndpoint)throw"Unable to use FrameRuntime, define multipartEndpoint in options";this.filesUploading=0;this.counter=0;this.files={};this.percentLoaded={};var self=this,FrameFile=FileUpload.Runtime.FrameRuntime.File;this.fileUpload.element.on("change.FileUpload",":file",function(e){var target=$(e.target);target.clone(true).insertBefore(target).val("");var file=new FrameFile(target,self.createFileOptions(self.counter));self.files[self.counter]=file;self.counter++;self.fileUpload.triggerEvent("select",[file.info]);if(self.fileUpload.options.autoUpload)self.fileUpload.send()})},destroy:function(){if(this.timer)clearTimeout(this.timer);$.each(this.files,function(){this.destroy()});this.files=null},send:function(fileId){if(!this.uploading()){this.fileStack=[];this.stackComplete=0;this.stackCount=0;this.percentLoaded={}}var self=this;if(!fileId){$.each(this.files,function(counter){if($.inArray(counter,self.fileStack)===-1&&!self.files[counter].isUploading()){self.fileStack.push(counter);self.stackCount++}})}else if(this.files[fileId]){this.fileStack.push(fileId);this.stackCount++}debug("Total stack count: ",this.stackCount);this.fileUpload.triggerEvent("beforestart",{fileStack:this.fileStack,stackSize:0,fileId:fileId,running:this.uploading()});this.fileStack=this.fileStack.reverse();if(!this.uploading())this.timeout=setInterval(function(){if(self.fileStack.length===0){clearInterval(self.timeout);self.timeout=null}else if(self.filesUploading<self.fileUpload.options.numberOfSimultaneousFileUploads){var counter=self.fileStack.pop();debug("Uploading file: ",counter,self.fileStack,self.files);self.files[counter].upload();self.filesUploading++}},500)},uploading:function(){return!!this.timeout},createFileOptions:function(counter){var self=this;function handleSuccessOrError(success){return function(){var innerSelf=this;self.fileUpload.finalizeSend(this.info,success,function(isError,response,onComplete){if(!isError&&success){var c=innerSelf.options.counter;debug("Deleting file with counter",c);self.files[c].destroy();delete self.files[c]}});self.filesUploading--;self.stackComplete++}}return $.extend({},this.fileUpload.options,{counter:counter,beforeStart:function(){self.fileUpload.triggerEvent("filebeforestart",this.info)},progress:function(percentage){self.percentLoaded[this.info.fuid]=percentage;var percentTotal=0;$.each(self.percentLoaded,function(){percentTotal+=this});self.fileUpload.triggerEvent("totalprogress",Math.min(100,Math.ceil(percentTotal/self.stackCount)));self.fileUpload.triggerEvent("fileprogress",this.info,percentage)},success:handleSuccessOrError(true),error:handleSuccessOrError(false)})},supports:function(){return true}})})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";var default_options={beforeStart:$.noop,success:$.noop,progress:$.noop};function File(fileElement,options){this.options=$.extend({},default_options,options);var path=fileElement.val(),tokens=path.split(/\\|\//),name=tokens[tokens.length-1];this.info=new FileUpload.File(this.options.counter,name);this.createFormWrapper(fileElement);this.uploading=false}File.prototype.upload=function(){if(this.isUploading()){debug("File already in upload state");return false}this.options.beforeStart.call(this);this.uploading=true;this.frameElement.removeClass("abort");this.formElement.submit();return true};File.prototype.isUploading=function(){return false};File.prototype.abort=function(){this.frameElement.attr("src","about:blank").addClass("abort")};File.prototype.destroy=function(){this.frameElement.add(this.formElement).remove()};File.prototype.handleFrameComplete=function(){try{var response=this.frameElement[0].contentWindow.document.body.innerHTML,type="success";debug("Frame Loaded");debug(response);try{response=$.parseJSON($("<span />").append(response).text())||{}}catch(e){debug("Failed to parse JSON response",e.message);type="error";response={}}if(response.error||response.exception||this.frameElement.hasClass("abort"))type="error";if(response.request){this.info.size=response.request.fileSize;this.info.type=response.request.fileType}this.options.progress.call(this,100);this.options[type].call(this,response)}catch(ad){debug("Failed to get frame contents (Access Denied?): ",ad)}this.uploading=false};File.prototype.createFormWrapper=function(domElement){var hash="Form_"+Math.round(Math.random()*1e5);var endpoint=this.options.multipartEndpoint;var form=this.formElement=$("<form />").append(domElement).attr({action:endpoint,enctype:"multipart/form-data",method:"post",id:hash,target:hash}).addClass("fileupload-frame");form.insertBefore("body").hide();form.append($('<input type="text" name="X-File-Id" />').val(this.info.fuid));form.append($('<input type="text" name="X-File-Name" />').val(this.info.name));form.append($('<input type="text" name="X-File-Type" />').val(this.info.type));form.append($('<input type="text" name="X-File-Size" />').val(this.info.size));var frame=this.frameElement=$('<iframe src="javascript:;" name="'+hash+'" />').on("load",$.proxy(this.handleFrameComplete,this)).attr({id:"IFrame_"+hash}).hide().insertBefore(form)};window.FileUpload.Runtime.FrameRuntime.File=File})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.Layout.create("Simple",{create:function(){this.progressBar=$("<div />").insertAfter(this.fileUpload.element.find(":file")).addClass("progress").append($("<div/>").addClass("progress-bar progress-bar-striped"));if(this.fileUpload.runtimeName==="FlashRuntime"){this.flashContainer=this.fileUpload.element.find("#simple-flash-wrapper");if(this.flashContainer.size()!==0){this.fileUpload.options.flashWrapper="#simple-flash-wrapper :button";this.fileUpload.element.find(":file").hide();this.flashContainer.show()}}var self=this;this.fileUpload.element.on("submit.FileUpload",function(e){e.preventDefault();self.progressBar.find(".progress-bar").text("");self.fileUpload.send()});this.fileUpload.on("select",function(e,files){if(self.flashContainer){var fileArray=[];$.each(files,function(){fileArray.push(this.name)});self.flashContainer.find(".selection").text(fileArray.join(", "))}});this.fileUpload.on("filebebeforeloading",function(){self.appendLoadingIfNotPresent()});this.fileUpload.on("fileloading",function(e,file,percentage){var bar=self.progressBar.find(".progress-bar").text(self.fileUpload.options.fileLoading+" ("+percentage+"%)");if(bar.width()<120)bar.width(120)});this.fileUpload.on("filesizeerror",function(e,file){self.progressBar.find(".progress-bar").addClass("progress-bar-danger").removeClass("active").width("100%").text(self.fileUpload.options.fileSize)});this.fileUpload.on("beforestart totalprogress",function(e,ui){var isStart=e.type==="FileUpload_beforestart";if(isStart){self.stackFileFailures=0;self.stackFileCount=0;self.stackSizeCount=ui.fileStack.length;if(self.stackSizeCount>0){self.appendLoadingIfNotPresent();self.fileUpload.element.find(":submit").addClass("disabled")}}self.handleProgress(isStart?0:ui)});this.fileUpload.on("filefinish",$.proxy(this.handleFileFinalize,this));this.fileUpload.on("abort",$.proxy(this.handleAbort,this));this.fileUpload.element.find("button.abort, input.abort").on("click.FileUpload",function(){self.fileUpload.element.find(":submit").removeClass("disabled");self.fileUpload.abort()})},destroy:function(){this.progressBar.remove();if(this.flashContainer&&this.flashContainer.size()!==0){this.flashContainer.hide();this.fileUpload.element.find(":file").show()}this.fileUpload.element.find("button.abort, input.abort").unbind(".FileUpload")},handleProgress:function(width){this.width=Math.max(this.width||0,width);var bar=this.progressBar.find(".progress-bar").width(width+"%");if(width===0)bar.addClass("active").removeClass("progress-bar-danger progress-bar-warning progress-bar-success");else bar.text(width+"%")},handleAbort:function(){this.progressBar.find(".progress-bar").addClass("progress-bar-danger").removeClass("active")},handleFileFinalize:function(e,file,success,isError,response){this.progressBar.removeClass("active");if(!success)this.stackFileFailures++;this.stackFileCount++;if(this.stackFileCount===this.stackSizeCount){this.fileUpload.element.find(".ajax-loading").remove();this.fileUpload.element.find(":submit").removeClass("disabled");var className="progress-bar-success";if(isError||this.stackFileFailures===this.stackSizeCount)className="progress-bar-danger";else if(this.stackFileFailures>0)className="progress-bar-warning";this.progressBar.find(".progress-bar").text(this.fileUpload.options.fileComplete).addClass(className).removeClass("active")}},appendLoadingIfNotPresent:function(){var loader=$("<img />").addClass("ajax-loading").attr("src",this.fileUpload.options.ajaxLoader);if(this.flashContainer&&this.flashContainer.size()!==0&&this.flashContainer.find(".ajax-loading").size()===0)loader.appendTo(this.flashContainer);else if(this.fileUpload.element.find(".ajax-loading").size()===0)loader.insertAfter(this.fileUpload.element.find(":file"))}})})(jQuery,"undefined",FileUpload_Debug);(function($,undef,debug){"use strict";FileUpload.Layout.create("Complex",{create:function(){if(this.fileUpload.runtimeName==="FlashRuntime"){this.fileUpload.options.flashWrapper="#complex-flash-wrapper";this.fileUpload.element.find(":file").hide()}this.table=this.fileUpload.element.find("table");this.tbody=this.table.find("tbody");this.fileUpload.on("select",$.proxy(this.handleFileSelect,this));this.fileUpload.on("filebebeforeloading",$.proxy(this.handleFileStart,this));this.fileUpload.on("filebeforestart",$.proxy(this.handleFileStart,this));this.fileUpload.on("filefinish",$.proxy(this.handleFileComplete,this));this.fileUpload.on("fileprogress",$.proxy(this.handleFileProgress,this));this.fileUpload.on("fileloading",$.proxy(this.handleFileLoading,this));this.fileUpload.on("filesizeerror",$.proxy(this.handleFileSizeError,this));var self=this;this.table.on("click.FileUpload",".btn",function(e){var target=$(e.target),row=target.parents("tr:first"),id=row.attr("id").substring(5);if(target.hasClass("submit")||target.hasClass("retry")){debug("Uploading new file: ",id);self.fileUpload.send(id)}if(target.hasClass("cancel"))self.fileUpload.abort(id);if(target.hasClass("remove")){self.fileUpload.remove(id);row.fadeOut("fast",function(){row.remove()})}});this.fileUpload.element.find(".upload-all").on("click.FileUpload",function(){self.fileUpload.send()});this.fileUpload.element.find(".cancel-all").on("click.FileUpload",function(){self.fileUpload.abort()})},destroy:function(){this.fileUpload.element.find(".upload-all, .cancel-all").unbind(".FileUpload");this.table.unbind(".FileUpload");this.table.find("tr").not(".template").remove();if(this.fileUpload.runtimeName==="FlashRuntime")this.fileUpload.element.find(":file").show()},getFileRow:function(file,selector){var row=this.tbody.find("#file_"+file.fuid);if(selector)return row.find(selector);return row},handleFileSelect:function(e,files){var template=this.fileUpload.element.find(".template"),i;for(i=0;i<files.length;i++){var file=files[i],newTemplate=template.clone();newTemplate.removeClass("template").attr("id","file_"+file.fuid);newTemplate.find(".name").html(file.name);newTemplate.find(".size").html(FileUpload.formatBytes(file.size));newTemplate.appendTo(this.tbody);newTemplate.find(".submit, .remove").show()}},handleFileProgress:function(e,file,progress){this.getFileRow(file,".progress .progress-bar").data("progress",progress).width(progress+"%").text(progress+"%")},handleFileBeforeLoad:function(e,file){this.appendLoadingIfNotPresent(file)},handleFileLoading:function(e,file,percentage){var tableRow=this.getFileRow(file);var msg=this.fileUpload.options.fileLoading+" ("+percentage+"%)";var bar=this.getFileRow(file,".progress .progress-bar").text(msg);if(bar.width()<120)bar.width(120)},handleFileStart:function(e,file){var tableRow=this.getFileRow(file);var selector=".submit, .retry";if(e.type!=="FileUpload_filebeforestart")selector+=", .cancel";else tableRow.find(".cancel").removeClass("disabled");var buttons=tableRow.find(selector);setTimeout(function(){buttons.addClass("disabled")},0);tableRow.find(".remove").hide();tableRow.find(".cancel").show();this.appendLoadingIfNotPresent(file);tableRow.find(".progress-bar").removeClass("progress-bar-success progress-bar-danger").addClass("active");tableRow.addClass("is-loading")},handleFileComplete:function(e,file,success,isError){var tableRow=this.getFileRow(file);var failure=isError||!success,bar=tableRow.find(".progress .progress-bar");if(failure){tableRow.find(".retry").button("reset").removeClass("disabled").show();tableRow.find(".submit").button("reset").hide()}else bar.text(this.fileUpload.options.fileComplete);tableRow.find(".cancel").hide();tableRow.find(".remove").show();tableRow.find(".progress-bar").addClass(!failure?"progress-bar-success":"progress-bar-danger").removeClass("active");tableRow.find(".ajax-loading").remove();tableRow.removeClass("is-loading error").addClass("complete")},handleFileSizeError:function(e,info){$("<div />").addClass("alert alert-error").text(info.name+" "+this.fileUpload.options.fileSize).prepend($('<button type="button" class="close" data-dismiss="alert">×</button>')).prependTo(this.fileUpload.element)},appendLoadingIfNotPresent:function(file){var tableRow=this.getFileRow(file);var loader=$("<img />").addClass("ajax-loading").attr("src",this.fileUpload.options.ajaxLoader);if(tableRow.find(".ajax-loading").size()===0)tableRow.find("td:last").append(loader)}})})(jQuery,"undefined",FileUpload_Debug);(function($,undef){"use strict";var default_options={layout:"Simple"};$.fn.extend({fileupload:function(options){var args=Array.prototype.slice.call(arguments);return $.each(this,function(){var element=$(this),instance=element.data("fileupload");if(instance){if(typeof options==="string"&&$.isFunction(instance[options])){instance[options].apply(instance,args.slice(1));if(options==="destroy")element.removeData("fileupload")}}else element.data("fileupload",new FileUpload(this,$.extend({},default_options,options||{})))})}})})(jQuery,"undefined");(function($){$.timeago=function(timestamp){if(timestamp instanceof Date)return inWords(timestamp);else if(typeof timestamp=="string")return inWords($.timeago.parse(timestamp));else return inWords($.timeago.datetime(timestamp))};var $t=$.timeago;$.extend($.timeago,{settings:{refreshMillis:6e4,allowFuture:false,strings:{prefixAgo:null,prefixFromNow:null,suffixAgo:"ago",suffixFromNow:"from now",seconds:"less than a minute",minute:"about a minute",minutes:"%d minutes",hour:"about an hour",hours:"about %d hours",day:"a day",days:"%d days",month:"about a month",months:"%d months",year:"about a year",years:"%d years",numbers:[]}},inWords:function(distanceMillis){var $l=this.settings.strings;var prefix=$l.prefixAgo;var suffix=$l.suffixAgo;if(this.settings.allowFuture){if(distanceMillis<0){
     2prefix=$l.prefixFromNow;suffix=$l.suffixFromNow}distanceMillis=Math.abs(distanceMillis)}var seconds=distanceMillis/1e3;var minutes=seconds/60;var hours=minutes/60;var days=hours/24;var years=days/365;function substitute(stringOrFunction,number){var string=$.isFunction(stringOrFunction)?stringOrFunction(number,distanceMillis):stringOrFunction;var value=$l.numbers&&$l.numbers[number]||number;return string.replace(/%d/i,value)}var words=seconds<45&&substitute($l.seconds,Math.round(seconds))||seconds<90&&substitute($l.minute,1)||minutes<45&&substitute($l.minutes,Math.round(minutes))||minutes<90&&substitute($l.hour,1)||hours<24&&substitute($l.hours,Math.round(hours))||hours<48&&substitute($l.day,1)||days<30&&substitute($l.days,Math.floor(days))||days<60&&substitute($l.month,1)||days<365&&substitute($l.months,Math.floor(days/30))||years<2&&substitute($l.year,1)||substitute($l.years,Math.floor(years));return $.trim([prefix,words,suffix].join(" "))},parse:function(iso8601){var s=$.trim(iso8601);s=s.replace(/\.\d\d\d+/,"");s=s.replace(/-/,"/").replace(/-/,"/");s=s.replace(/T/," ").replace(/Z/," UTC");s=s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2");return new Date(s)},datetime:function(elem){var isTime=$(elem).get(0).tagName.toLowerCase()=="time";var iso8601=isTime?$(elem).attr("datetime"):$(elem).attr("title");return $t.parse(iso8601)}});$.fn.timeago=function(){var self=this;self.each(refresh);var $s=$t.settings;if($s.refreshMillis>0){setInterval(function(){self.each(refresh)},$s.refreshMillis)}return self};function refresh(){var data=prepareData(this);if(!isNaN(data.datetime)){$(this).text(inWords(data.datetime))}return this}function prepareData(element){element=$(element);if(!element.data("timeago")){element.data("timeago",{datetime:$t.datetime(element)});var text=$.trim(element.text());if(text.length>0)element.attr("title",text)}return element.data("timeago")}function inWords(date){return $t.inWords(distance(date))}function distance(date){return(new Date).getTime()-date.getTime()}document.createElement("abbr");document.createElement("time")})(jQuery);(function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,s){var n,a,o,r=t.nodeName.toLowerCase();return"area"===r?(n=t.parentNode,a=n.name,t.href&&a&&"map"===n.nodeName.toLowerCase()?(o=e("img[usemap='#"+a+"']")[0],!!o&&i(o)):!1):(/^(input|select|textarea|button|object)$/.test(r)?!t.disabled:"a"===r?t.href||s:s)&&i(t)}function i(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(t){var i=this.css("position"),s="absolute"===i,n=t?/(auto|scroll|hidden)/:/(auto|scroll)/,a=this.parents().filter(function(){var t=e(this);return s&&"static"===t.css("position")?!1:n.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==i&&a.length?a:e(this[0].ownerDocument||document)},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(i){return t(i,!isNaN(e.attr(i,"tabindex")))},tabbable:function(i){var s=e.attr(i,"tabindex"),n=isNaN(s);return(n||s>=0)&&t(i,!n)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,i){function s(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],a=i.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+i]=function(t){return void 0===t?o["inner"+i].call(this):this.each(function(){e(this).css(a,s(this,t)+"px")})},e.fn["outer"+i]=function(t,n){return"number"!=typeof t?o["outer"+i].call(this,t):this.each(function(){e(this).css(a,s(this,t,!0,n)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(void 0!==t)return this.css("zIndex",t);if(this.length)for(var i,s,n=e(this[0]);n.length&&n[0]!==document;){if(i=n.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(n.css("zIndex"),10),!isNaN(s)&&0!==s))return s;n=n.parent()}return 0}}),e.ui.plugin={add:function(t,i,s){var n,a=e.ui[t].prototype;for(n in s)a.plugins[n]=a.plugins[n]||[],a.plugins[n].push([i,s[n]])},call:function(e,t,i,s){var n,a=e.plugins[t];if(a&&(s||e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType))for(n=0;a.length>n;n++)e.options[a[n][0]]&&a[n][1].apply(e.element,i)}};var s=0,n=Array.prototype.slice;e.cleanData=function(t){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=e._data(n,"events"),s&&s.remove&&e(n).triggerHandler("remove")}catch(o){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var n,a,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],n=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[l]=e[l]||{},a=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,a,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},n=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,a=this._superApply;return this._super=e,this._superApply=n,t=s.apply(this,arguments),this._super=i,this._superApply=a,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:a?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:n}),a?(e.each(a._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete a._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var i,s,a=n.call(arguments,1),o=0,r=a.length;r>o;o++)for(i in a[o])s=a[o][i],a[o].hasOwnProperty(i)&&void 0!==s&&(t[i]=e.isPlainObject(s)?e.isPlainObject(t[i])?e.widget.extend({},t[i],s):e.widget.extend({},s):s);return t},e.widget.bridge=function(t,i){var s=i.prototype.widgetFullName||t;e.fn[t]=function(a){var o="string"==typeof a,r=n.call(arguments,1),h=this;return o?this.each(function(){var i,n=e.data(this,s);return"instance"===a?(h=n,!1):n?e.isFunction(n[a])&&"_"!==a.charAt(0)?(i=n[a].apply(n,r),i!==n&&void 0!==i?(h=i&&i.jquery?h.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+a+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+a+"'")}):(r.length&&(a=e.widget.extend.apply(null,[a].concat(r))),this.each(function(){var t=e.data(this,s);t?(t.option(a||{}),t._init&&t._init()):e.data(this,s,new i(a,this))})),h}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,i){i=e(i||this.defaultElement||this)[0],this.element=e(i),this.uuid=s++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),i!==this&&(e.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===i&&this.destroy()}}),this.document=e(i.style?i.ownerDocument:i.document||i),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(t,i){var s,n,a,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(n=o[t]=e.widget.extend({},this.options[t]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(t=s.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var n,a=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=n=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),e.each(s,function(s,o){function r(){return t||a.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.delegate(u,l,r):i.bind(l,r)})},_off:function(t,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(i).undelegate(i),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var o,r=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),o=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&e.effects&&e.effects.effect[r]?s[t](n):r!==t&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}}),e.widget,function(){function t(e,t,i){return[parseFloat(e[0])*(p.test(e[0])?t/100:1),parseFloat(e[1])*(p.test(e[1])?i/100:1)]}function i(t,i){return parseInt(e.css(t,i),10)||0}function s(t){var i=t[0];return 9===i.nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(i)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var n,a,o=Math.max,r=Math.abs,h=Math.round,l=/left|center|right/,u=/top|center|bottom/,d=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,p=/%$/,f=e.fn.position;e.position={scrollbarWidth:function(){if(void 0!==n)return n;var t,i,s=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),a=s.children()[0];return e("body").append(s),t=a.offsetWidth,s.css("overflow","scroll"),i=a.offsetWidth,t===i&&(i=s[0].clientWidth),s.remove(),n=t-i},getScrollInfo:function(t){var i=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),s=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),n="scroll"===i||"auto"===i&&t.width<t.element[0].scrollWidth,a="scroll"===s||"auto"===s&&t.height<t.element[0].scrollHeight;return{width:a?e.position.scrollbarWidth():0,height:n?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var i=e(t||window),s=e.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s||n?i.width():i.outerWidth(),height:s||n?i.height():i.outerHeight()}}},e.fn.position=function(n){if(!n||!n.of)return f.apply(this,arguments);n=e.extend({},n);var p,m,g,v,y,b,_=e(n.of),x=e.position.getWithinInfo(n.within),w=e.position.getScrollInfo(x),k=(n.collision||"flip").split(" "),T={};return b=s(_),_[0].preventDefault&&(n.at="left top"),m=b.width,g=b.height,v=b.offset,y=e.extend({},v),e.each(["my","at"],function(){var e,t,i=(n[this]||"").split(" ");1===i.length&&(i=l.test(i[0])?i.concat(["center"]):u.test(i[0])?["center"].concat(i):["center","center"]),i[0]=l.test(i[0])?i[0]:"center",i[1]=u.test(i[1])?i[1]:"center",e=d.exec(i[0]),t=d.exec(i[1]),T[this]=[e?e[0]:0,t?t[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===k.length&&(k[1]=k[0]),"right"===n.at[0]?y.left+=m:"center"===n.at[0]&&(y.left+=m/2),"bottom"===n.at[1]?y.top+=g:"center"===n.at[1]&&(y.top+=g/2),p=t(T.at,m,g),y.left+=p[0],y.top+=p[1],this.each(function(){var s,l,u=e(this),d=u.outerWidth(),c=u.outerHeight(),f=i(this,"marginLeft"),b=i(this,"marginTop"),D=d+f+i(this,"marginRight")+w.width,S=c+b+i(this,"marginBottom")+w.height,N=e.extend({},y),M=t(T.my,u.outerWidth(),u.outerHeight());"right"===n.my[0]?N.left-=d:"center"===n.my[0]&&(N.left-=d/2),"bottom"===n.my[1]?N.top-=c:"center"===n.my[1]&&(N.top-=c/2),N.left+=M[0],N.top+=M[1],a||(N.left=h(N.left),N.top=h(N.top)),s={marginLeft:f,marginTop:b},e.each(["left","top"],function(t,i){e.ui.position[k[t]]&&e.ui.position[k[t]][i](N,{targetWidth:m,targetHeight:g,elemWidth:d,elemHeight:c,collisionPosition:s,collisionWidth:D,collisionHeight:S,offset:[p[0]+M[0],p[1]+M[1]],my:n.my,at:n.at,within:x,elem:u})}),n.using&&(l=function(e){var t=v.left-N.left,i=t+m-d,s=v.top-N.top,a=s+g-c,h={target:{element:_,left:v.left,top:v.top,width:m,height:g},element:{element:u,left:N.left,top:N.top,width:d,height:c},horizontal:0>i?"left":t>0?"right":"center",vertical:0>a?"top":s>0?"bottom":"middle"};d>m&&m>r(t+i)&&(h.horizontal="center"),c>g&&g>r(s+a)&&(h.vertical="middle"),h.important=o(r(t),r(i))>o(r(s),r(a))?"horizontal":"vertical",n.using.call(this,e,h)}),u.offset(e.extend(N,{using:l}))})},e.ui.position={fit:{left:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=e.left-t.collisionPosition.marginLeft,h=n-r,l=r+t.collisionWidth-a-n;t.collisionWidth>a?h>0&&0>=l?(i=e.left+h+t.collisionWidth-a-n,e.left+=h-i):e.left=l>0&&0>=h?n:h>l?n+a-t.collisionWidth:n:h>0?e.left+=h:l>0?e.left-=l:e.left=o(e.left-r,e.left)},top:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollTop:s.offset.top,a=t.within.height,r=e.top-t.collisionPosition.marginTop,h=n-r,l=r+t.collisionHeight-a-n;t.collisionHeight>a?h>0&&0>=l?(i=e.top+h+t.collisionHeight-a-n,e.top+=h-i):e.top=l>0&&0>=h?n:h>l?n+a-t.collisionHeight:n:h>0?e.top+=h:l>0?e.top-=l:e.top=o(e.top-r,e.top)}},flip:{left:function(e,t){var i,s,n=t.within,a=n.offset.left+n.scrollLeft,o=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=e.left-t.collisionPosition.marginLeft,u=l-h,d=l+t.collisionWidth-o-h,c="left"===t.my[0]?-t.elemWidth:"right"===t.my[0]?t.elemWidth:0,p="left"===t.at[0]?t.targetWidth:"right"===t.at[0]?-t.targetWidth:0,f=-2*t.offset[0];0>u?(i=e.left+c+p+f+t.collisionWidth-o-a,(0>i||r(u)>i)&&(e.left+=c+p+f)):d>0&&(s=e.left-t.collisionPosition.marginLeft+c+p+f-h,(s>0||d>r(s))&&(e.left+=c+p+f))},top:function(e,t){var i,s,n=t.within,a=n.offset.top+n.scrollTop,o=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=e.top-t.collisionPosition.marginTop,u=l-h,d=l+t.collisionHeight-o-h,c="top"===t.my[1],p=c?-t.elemHeight:"bottom"===t.my[1]?t.elemHeight:0,f="top"===t.at[1]?t.targetHeight:"bottom"===t.at[1]?-t.targetHeight:0,m=-2*t.offset[1];0>u?(s=e.top+p+f+m+t.collisionHeight-o-a,(0>s||r(u)>s)&&(e.top+=p+f+m)):d>0&&(i=e.top-t.collisionPosition.marginTop+p+f+m-h,(i>0||d>r(i))&&(e.top+=p+f+m))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,i,s,n,o,r=document.getElementsByTagName("body")[0],h=document.createElement("div");t=document.createElement(r?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},r&&e.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in s)t.style[o]=s[o];t.appendChild(h),i=r||document.documentElement,i.insertBefore(t,i.firstChild),h.style.cssText="position: absolute; left: 10.7432222px;",n=e(h).offset().left,a=n>10&&11>n,t.innerHTML="",i.removeChild(t)}()}(),e.ui.position,e.widget("ui.menu",{version:"1.11.4",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},items:"> *",menus:"ul",position:{my:"left-1 top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item":function(e){e.preventDefault()},"click .ui-menu-item":function(t){var i=e(t.target);!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&e(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){if(!this.previousFilter){var i=e(t.currentTarget);i.siblings(".ui-state-active").removeClass("ui-state-active"),this.focus(t,i)}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var i=this.active||this.element.find(this.options.items).eq(0);t||this.focus(e,i)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){this._closeOnDocumentClick(e)&&this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-menu-icons ui-front").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").removeUniqueId().removeClass("ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){var i,s,n,a,o=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:o=!1,s=this.previousFilter||"",n=String.fromCharCode(t.keyCode),a=!1,clearTimeout(this.filterTimer),n===s?a=!0:n=s+n,i=this._filterMenuItems(n),i=a&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(t.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(t,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}o&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.is("[aria-haspopup='true']")?this.expand(e):this.select(e))},refresh:function(){var t,i,s=this,n=this.options.icons.submenu,a=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),a.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-front").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=e(this),i=t.parent(),s=e("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);i.attr("aria-haspopup","true").prepend(s),t.attr("aria-labelledby",i.attr("id"))}),t=a.add(this.element),i=t.find(this.options.items),i.not(".ui-menu-item").each(function(){var t=e(this);s._isDivider(t)&&t.addClass("ui-widget-content ui-menu-divider")}),i.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(e,t){"icons"===e&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu),"disabled"===e&&this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this._super(e,t)},focus:function(e,t){var i,s;this.blur(e,e&&"focus"===e.type),this._scrollIntoView(t),this.active=t.first(),s=this.active.addClass("ui-state-focus").removeClass("ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"),e&&"keydown"===e.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=t.children(".ui-menu"),i.length&&e&&/^mouse/.test(e.type)&&this._startOpening(i),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,n=t.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=t.outerHeight(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(e,t){t||clearTimeout(this.timer),this.active&&(this.active.removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active}))},_startOpening:function(e){clearTimeout(this.timer),"true"===e.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(e)},this.delay))},_open:function(t){var i=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(t,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(t),this.activeMenu=s},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find(".ui-state-active").not(".ui-state-focus").removeClass("ui-state-active")},_closeOnDocumentClick:function(t){return!e(t.target).closest(".ui-menu").length},_isDivider:function(e){return!/[^\-\u2014\u2013\s]/.test(e.text())},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,i){var s;this.active&&(s="first"===e||"last"===e?this.active["first"===e?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[e+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[t]()),this.focus(i,s)},nextPage:function(t){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=e(this),0>i.offset().top-s-n}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(t),void 0)},previousPage:function(t){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=e(this),i.offset().top-s+n>0}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items).first())),void 0):(this.next(t),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,i)},_filterMenuItems:function(t){var i=t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(e.trim(e(this).text()))})}}),e.widget("ui.autocomplete",{version:"1.11.4",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var t,i,s,n=this.element[0].nodeName.toLowerCase(),a="textarea"===n,o="input"===n;this.isMultiLine=a?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[a||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return t=!0,s=!0,i=!0,void 0;t=!1,s=!1,i=!1;var a=e.ui.keyCode;switch(n.keyCode){case a.PAGE_UP:t=!0,this._move("previousPage",n);break;case a.PAGE_DOWN:t=!0,this._move("nextPage",n);break;case a.UP:t=!0,this._keyEvent("previous",n);break;case a.DOWN:t=!0,this._keyEvent("next",n);break;case a.ENTER:this.menu.active&&(t=!0,n.preventDefault(),this.menu.select(n));break;case a.TAB:this.menu.active&&this.menu.select(n);break;case a.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(t)return t=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=e.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(e){return s?(s=!1,e.preventDefault(),void 0):(this._searchTimeout(e),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(e),this._change(e),void 0)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(s){s.target===t.element[0]||s.target===i||e.contains(i,s.target)||t.close()})})},menufocus:function(t,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",t,{item:n})&&t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&e.trim(s).length&&(this.liveRegion.children().hide(),e("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,t){var i=t.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",e,{item:i})&&this._value(i.value),this.term=this._value(),this.close(e),this.selectedItem=i}}),this.liveRegion=e("<span>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),"source"===e&&this._initSource(),"appendTo"===e&&this.menu.element.appendTo(this._appendTo()),"disabled"===e&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t&&t[0]||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),
     3t},_initSource:function(){var t,i,s=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(i,s){s(e.ui.autocomplete.filter(t,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(t,n){s.xhr&&s.xhr.abort(),s.xhr=e.ajax({url:i,data:t,dataType:"json",success:function(e){n(e)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){var t=this.term===this._value(),i=this.menu.element.is(":visible"),s=e.altKey||e.ctrlKey||e.metaKey||e.shiftKey;(!t||t&&!i&&!s)&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){return e=null!=e?e:this._value(),this.term=this._value(),e.length<this.options.minLength?this.close(t):this._trigger("search",t)!==!1?this._search(e):void 0},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var t=++this.requestIndex;return e.proxy(function(e){t===this.requestIndex&&this.__response(e),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return"string"==typeof t?{label:t,value:t}:e.extend({},t,{label:t.label||t.value,value:t.value||t.label})})},_suggest:function(t){var i=this.menu.element.empty();this._renderMenu(i,t),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,i){var s=this;e.each(i,function(e,i){s._renderItemData(t,i)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,i){return e("<li>").text(i.label).appendTo(t)},_move:function(e,t){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[e](t),void 0):(this.search(null,t),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(e,t),t.preventDefault())}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,i){var s=RegExp(e.ui.autocomplete.escapeRegex(i),"i");return e.grep(t,function(e){return s.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(t){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=t&&t.length?this.options.messages.results(t.length):this.options.messages.noResults,this.liveRegion.children().hide(),e("<div>").text(i).appendTo(this.liveRegion))}}),e.ui.autocomplete});(function($){$.timeago.regional={};$.timeago.regional["es"]={prefixAgo:"hace",prefixFromNow:"dentro de",suffixAgo:"",suffixFromNow:"",seconds:"menos de un minuto",minute:"un minuto",minutes:"unos %d minutos",hour:"una hora",hours:"%d horas",day:"un día",days:"%d días",month:"un mes",months:"%d meses",year:"un año",years:"%d años"};$.timeago.regional["fr"]={prefixAgo:"il y a",prefixFromNow:"d'ici",seconds:"moins d'une minute",minute:"environ une minute",minutes:"environ %d minutes",hour:"environ une heure",hours:"environ %d heures",day:"environ un jour",days:"environ %d jours",month:"environ un mois",months:"environ %d mois",year:"un an",years:"%d ans"};$.timeago.regional["pt"]={suffixAgo:"atrás",suffixFromNow:"a partir de agora",seconds:"menos de um minuto",minute:"cerca de um minuto",minutes:"%d minutos",hour:"cerca de uma hora",hours:"cerca de %d horas",day:"um dia",days:"%d dias",month:"cerca de um mês",months:"%d meses",year:"cerca de um ano",years:"%d anos"};$.timeago.regional["sv"]={prefixAgo:"för",prefixFromNow:"om",suffixAgo:"sedan",suffixFromNow:"",seconds:"mindre än en minut",minute:"ungefär en minut",minutes:"%d minuter",hour:"ungefär en timme",hours:"ungefär %d timmar",day:"en dag",days:"%d dagar",month:"ungefär en månad",months:"%d månader",year:"ungefär ett år",years:"%d år"};$.timeago.regional["zh"]={prefixAgo:null,prefixFromNow:"从现在开始",suffixAgo:"之前",suffixFromNow:null,seconds:"不到 1 分钟",minute:"大约 1 分钟",minutes:"%d 分钟",hour:"大约 1 小时",hours:"大约 %d 小时",day:"1 天",days:"%d 天",month:"大约 1 个月",months:"%d 月",year:"大约 1 年",years:"%d 年",numbers:[]};$.timeago.regional["ja"]={prefixAgo:"",prefixFromNow:"今から",suffixAgo:"前",suffixFromNow:"後",seconds:"ほんの数秒",minute:"約一分",minutes:"%d 分",hour:"大体一時間",hours:"大体 %d 時間位",day:"一日",days:"%d 日ほど",month:"大体一ヶ月",months:"%d ヶ月ほど",year:"丁度一年(虎舞流w)",years:"%d 年"};function numpf(n,f,s,t){var n10=n%10;if(n10==1&&(n==1||n>20)){return f}else if(n10>1&&n10<5&&(n>20||n<10)){return s}else{return t}}$.timeago.regional["ru"]={prefixAgo:null,prefixFromNow:"через",suffixAgo:"назад",suffixFromNow:null,seconds:"меньше минуты",minute:"минуту",minutes:function(value){return numpf(value,"%d минута","%d минуты","%d минут")},hour:"час",hours:function(value){return numpf(value,"%d час","%d часа","%d часов")},day:"день",days:function(value){return numpf(value,"%d день","%d дня","%d дней")},month:"месяц",months:function(value){return numpf(value,"%d месяц","%d месяца","%d месяцев")},year:"год",years:function(value){return numpf(value,"%d год","%d года","%d лет")}};$.timeago.regional["tr"]={suffixAgo:"önce",suffixFromNow:null,seconds:"1 dakikadan",minute:"1 dakika",minutes:"%d dakika",hour:"1 saat",hours:"%d saat",day:"1 gün",days:"%d gün",month:"1 ay",months:"%d ay",year:"1 yıl",years:"%d yıl"};$.timeago.regional["ca"]={prefixAgo:"fa",prefixFromNow:"d'aqui a",suffixAgo:null,suffixFromNow:null,seconds:"menys d'un minut",minute:"un minut",minutes:"uns %d minuts",hour:"una hora",hours:"unes %d hores",day:"1 dia",days:"%d dies",month:"aproximadament un mes",months:"%d mesos",year:"aproximadament un any",years:"%d anys"};$.timeago.regional["de"]={prefixAgo:"vor",prefixFromNow:"in",suffixAgo:"",suffixFromNow:"",seconds:"wenigen Sekunden",minute:"etwa einer Minute",minutes:"%d Minuten",hour:"etwa einer Stunde",hours:"%d Stunden",day:"etwa einem Tag",days:"%d Tagen",month:"etwa einem Monat",months:"%d Monaten",year:"etwa einem Jahr",years:"%d Jahren"}})(jQuery);(function(c){function p(){var d,a={height:h.innerHeight,width:h.innerWidth};if(!a.height&&((d=i.compatMode)||!c.support.boxModel))d=d==="CSS1Compat"?k:i.body,a={height:d.clientHeight,width:d.clientWidth};return a}var m={},e,a,i=document,h=window,k=i.documentElement,j=c.expando;c.event.special.inview={add:function(a){m[a.guid+"-"+this[j]]={data:a,$element:c(this)}},remove:function(a){try{delete m[a.guid+"-"+this[j]]}catch(c){}}};c(h).bind("scroll resize",function(){e=a=null});setInterval(function(){var d=c(),j,l=0;c.each(m,function(a,b){var c=b.data.selector,e=b.$element;d=d.add(c?e.find(c):e)});if(j=d.length){e=e||p();for(a=a||{top:h.pageYOffset||k.scrollTop||i.body.scrollTop,left:h.pageXOffset||k.scrollLeft||i.body.scrollLeft};l<j;l++)if(c.contains(k,d[l])){var g=c(d[l]),f={height:g.height(),width:g.width()},b=g.offset(),n=g.data("inview"),o;if(!a||!e)break;b.top+f.height>a.top&&b.top<a.top+e.height&&b.left+f.width>a.left&&b.left<a.left+e.width?(o=a.left>b.left?"right":a.left+e.width<b.left+f.width?"left":"both",f=a.top>b.top?"bottom":a.top+e.height<b.top+f.height?"top":"both",b=o+"-"+f,(!n||n!==b)&&g.data("inview",b).trigger("inview",[!0,o,f])):n&&g.data("inview",!1).trigger("inview",[!1])}}},250)})(jQuery);(function($){var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a256="",r64=[256],r256=[256],i=0;var UTF8={encode:function(strUni){var strUtf=strUni.replace(/[\u0080-\u07ff]/g,function(c){var cc=c.charCodeAt(0);return String.fromCharCode(192|cc>>6,128|cc&63)}).replace(/[\u0800-\uffff]/g,function(c){var cc=c.charCodeAt(0);return String.fromCharCode(224|cc>>12,128|cc>>6&63,128|cc&63)});return strUtf},decode:function(strUtf){var strUni=strUtf.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g,function(c){var cc=(c.charCodeAt(0)&15)<<12|(c.charCodeAt(1)&63)<<6|c.charCodeAt(2)&63;return String.fromCharCode(cc)}).replace(/[\u00c0-\u00df][\u0080-\u00bf]/g,function(c){var cc=(c.charCodeAt(0)&31)<<6|c.charCodeAt(1)&63;return String.fromCharCode(cc)});return strUni}};while(i<256){var c=String.fromCharCode(i);a256+=c;r256[i]=i;r64[i]=b64.indexOf(c);++i}function code(s,discard,alpha,beta,w1,w2){s=String(s);var buffer=0,i=0,length=s.length,result="",bitsInBuffer=0;while(i<length){var c=s.charCodeAt(i);c=c<256?alpha[c]:-1;buffer=(buffer<<w1)+c;bitsInBuffer+=w1;while(bitsInBuffer>=w2){bitsInBuffer-=w2;var tmp=buffer>>bitsInBuffer;result+=beta.charAt(tmp);buffer^=tmp<<bitsInBuffer}++i}if(!discard&&bitsInBuffer>0)result+=beta.charAt(buffer<<w2-bitsInBuffer);return result}var Plugin=$.base64=function(dir,input,encode){return input?Plugin[dir](input,encode):dir?null:this};Plugin.btoa=Plugin.encode=function(plain,utf8encode){plain=Plugin.raw===false||Plugin.utf8encode||utf8encode?UTF8.encode(plain):plain;plain=code(plain,false,r256,b64,8,6);return plain+"====".slice(plain.length%4||4)};Plugin.atob=Plugin.decode=function(coded,utf8decode){coded=String(coded).split("=");var i=coded.length;do{--i;coded[i]=code(coded[i],true,r64,a256,6,8)}while(i>0);coded=coded.join("");return Plugin.raw===false||Plugin.utf8decode||utf8decode?UTF8.decode(coded):coded}})(jQuery);+function($){"use strict";var Modal=function(element,options){this.options=options;this.$body=$(document.body);this.$element=$(element);this.$backdrop=this.isShown=null;this.scrollbarWidth=0;if(this.options.remote){this.$element.find("#clinked-portal .modal-content").load(this.options.remote,$.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))}};Modal.VERSION="3.3.2";Modal.TRANSITION_DURATION=300;Modal.BACKDROP_TRANSITION_DURATION=150;Modal.DEFAULTS={backdrop:true,keyboard:true,show:true};Modal.prototype.toggle=function(_relatedTarget){return this.isShown?this.hide():this.show(_relatedTarget)};Modal.prototype.show=function(_relatedTarget){var that=this;var e=$.Event("show.bs.modal",{relatedTarget:_relatedTarget});this.$element.trigger(e);if(this.isShown||e.isDefaultPrevented())return;this.isShown=true;this.checkScrollbar();this.setScrollbar();this.$body.addClass("modal-open");this.escape();this.resize();this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',$.proxy(this.hide,this));this.backdrop(function(){var transition=$.support.transition&&that.$element.hasClass("fade");if(!that.$element.parent().length){that.$element.appendTo(that.$body)}that.$element.show().scrollTop(0);if(that.options.backdrop)that.adjustBackdrop();that.adjustDialog();if(transition){that.$element[0].offsetWidth}that.$element.addClass("in").attr("aria-hidden",false);that.enforceFocus();var e=$.Event("shown.bs.modal",{relatedTarget:_relatedTarget});transition?that.$element.find("#clinked-portal .modal-dialog").one("bsTransitionEnd",function(){that.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(Modal.TRANSITION_DURATION):that.$element.trigger("focus").trigger(e)})};Modal.prototype.hide=function(e){if(e)e.preventDefault();e=$.Event("hide.bs.modal");this.$element.trigger(e);if(!this.isShown||e.isDefaultPrevented())return;this.isShown=false;this.escape();this.resize();$(document).off("focusin.bs.modal");this.$element.removeClass("in").attr("aria-hidden",true).off("click.dismiss.bs.modal");$.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",$.proxy(this.hideModal,this)).emulateTransitionEnd(Modal.TRANSITION_DURATION):this.hideModal()};Modal.prototype.enforceFocus=function(){$(document).off("focusin.bs.modal").on("focusin.bs.modal",$.proxy(function(e){if(this.$element[0]!==e.target&&!this.$element.has(e.target).length){this.$element.trigger("focus")}},this))};Modal.prototype.escape=function(){if(this.isShown&&this.options.keyboard){this.$element.on("keydown.dismiss.bs.modal",$.proxy(function(e){e.which==27&&this.hide()},this))}else if(!this.isShown){this.$element.off("keydown.dismiss.bs.modal")}};Modal.prototype.resize=function(){if(this.isShown){$(window).on("resize.bs.modal",$.proxy(this.handleUpdate,this))}else{$(window).off("resize.bs.modal")}};Modal.prototype.hideModal=function(){var that=this;this.$element.hide();this.backdrop(function(){that.$body.removeClass("modal-open");that.resetAdjustments();that.resetScrollbar();that.$element.trigger("hidden.bs.modal")})};Modal.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove();this.$backdrop=null};Modal.prototype.backdrop=function(callback){var that=this;var animate=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var doAnimate=$.support.transition&&animate;this.$backdrop=$('<div class="modal-backdrop '+animate+'" />').prependTo(this.$element).on("click.dismiss.bs.modal",$.proxy(function(e){if(e.target!==e.currentTarget)return;this.options.backdrop=="static"?this.$element[0].focus.call(this.$element[0]):this.hide.call(this)},this));if(doAnimate)this.$backdrop[0].offsetWidth;this.$backdrop.addClass("in");if(!callback)return;doAnimate?this.$backdrop.one("bsTransitionEnd",callback).emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION):callback()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var callbackRemove=function(){that.removeBackdrop();callback&&callback()};$.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",callbackRemove).emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION):callbackRemove()}else if(callback){callback()}};Modal.prototype.handleUpdate=function(){if(this.options.backdrop)this.adjustBackdrop();this.adjustDialog()};Modal.prototype.adjustBackdrop=function(){this.$backdrop.css("height",0).css("height",this.$element[0].scrollHeight)};Modal.prototype.adjustDialog=function(){var modalIsOverflowing=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&modalIsOverflowing?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!modalIsOverflowing?this.scrollbarWidth:""})};Modal.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})};Modal.prototype.checkScrollbar=function(){this.bodyIsOverflowing=document.body.scrollHeight>document.documentElement.clientHeight;this.scrollbarWidth=this.measureScrollbar()};Modal.prototype.setScrollbar=function(){var bodyPad=parseInt(this.$body.css("padding-right")||0,10);if(this.bodyIsOverflowing)this.$body.css("padding-right",bodyPad+this.scrollbarWidth)};Modal.prototype.resetScrollbar=function(){this.$body.css("padding-right","")};Modal.prototype.measureScrollbar=function(){var scrollDiv=document.createElement("div");scrollDiv.className="modal-scrollbar-measure";this.$body.append(scrollDiv);var scrollbarWidth=scrollDiv.offsetWidth-scrollDiv.clientWidth;this.$body[0].removeChild(scrollDiv);return scrollbarWidth};function Plugin(option,_relatedTarget){return this.each(function(){var $this=$(this);var data=$this.data("bs.modal");var options=$.extend({},Modal.DEFAULTS,$this.data(),typeof option=="object"&&option);if(!data)$this.data("bs.modal",data=new Modal(this,options));if(typeof option=="string")data[option](_relatedTarget);else if(options.show)data.show(_relatedTarget)})}var old=$.fn.modal;$.fn.modal=Plugin;$.fn.modal.Constructor=Modal;$.fn.modal.noConflict=function(){$.fn.modal=old;return this};$(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(e){var $this=$(this);var href=$this.attr("href");var $target=$($this.attr("data-target")||href&&href.replace(/.*(?=#[^\s]+$)/,""));var option=$target.data("bs.modal")?"toggle":$.extend({remote:!/#/.test(href)&&href},$target.data(),$this.data());if($this.is("a"))e.preventDefault();$target.one("show.bs.modal",function(showEvent){if(showEvent.isDefaultPrevented())return;$target.one("hidden.bs.modal",function(){$this.is(":visible")&&$this.trigger("focus")})});Plugin.call($target,option,this)})}(jQuery);(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,w=Object.keys,_=i.bind,j=function(n){return n instanceof j?n:this instanceof j?void(this._wrapped=n):new j(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=j),exports._=j):n._=j,j.VERSION="1.6.0";var A=j.each=j.forEach=function(n,t,e){if(null==n)return n;if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a=j.keys(n),u=0,i=a.length;i>u;u++)if(t.call(e,n[a[u]],a[u],n)===r)return;return n};j.map=j.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e.push(t.call(r,n,u,i))}),e)};var O="Reduce of empty array with no initial value";j.reduce=j.foldl=j.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=j.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},j.reduceRight=j.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=j.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=j.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},j.find=j.detect=function(n,t,r){var e;return k(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},j.filter=j.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&e.push(n)}),e)},j.reject=function(n,t,r){return j.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},j.every=j.all=function(n,t,e){t||(t=j.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var k=j.some=j.any=function(n,t,e){t||(t=j.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};j.contains=j.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:k(n,function(n){return n===t})},j.invoke=function(n,t){var r=o.call(arguments,2),e=j.isFunction(t);return j.map(n,function(n){return(e?t:n[t]).apply(n,r)})},j.pluck=function(n,t){return j.map(n,j.property(t))},j.where=function(n,t){return j.filter(n,j.matches(t))},j.findWhere=function(n,t){return j.find(n,j.matches(t))},j.max=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.max.apply(Math,n);var e=-1/0,u=-1/0;return A(n,function(n,i,a){var o=t?t.call(r,n,i,a):n;o>u&&(e=n,u=o)}),e},j.min=function(n,t,r){if(!t&&j.isArray(n)&&n[0]===+n[0]&&n.length<65535)return Math.min.apply(Math,n);var e=1/0,u=1/0;return A(n,function(n,i,a){var o=t?t.call(r,n,i,a):n;u>o&&(e=n,u=o)}),e},j.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=j.random(r++),e[r-1]=e[t],e[t]=n}),e},j.sample=function(n,t,r){return null==t||r?(n.length!==+n.length&&(n=j.values(n)),n[j.random(n.length-1)]):j.shuffle(n).slice(0,Math.max(0,t))};var E=function(n){return null==n?j.identity:j.isFunction(n)?n:j.property(n)};j.sortBy=function(n,t,r){return t=E(t),j.pluck(j.map(n,function(n,e,u){return{value:n,index:e,criteria:t.call(r,n,e,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=E(r),A(t,function(i,a){var o=r.call(e,i,a,t);n(u,o,i)}),u}};j.groupBy=F(function(n,t,r){j.has(n,t)?n[t].push(r):n[t]=[r]}),j.indexBy=F(function(n,t,r){n[t]=r}),j.countBy=F(function(n,t){j.has(n,t)?n[t]++:n[t]=1}),j.sortedIndex=function(n,t,r,e){r=E(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;r.call(e,n[o])<u?i=o+1:a=o}return i},j.toArray=function(n){return n?j.isArray(n)?o.call(n):n.length===+n.length?j.map(n,j.identity):j.values(n):[]},j.size=function(n){return null==n?0:n.length===+n.length?n.length:j.keys(n).length},j.first=j.head=j.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:0>t?[]:o.call(n,0,t)},j.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},j.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},j.rest=j.tail=j.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},j.compact=function(n){return j.filter(n,j.identity)};var M=function(n,t,r){return t&&j.every(n,j.isArray)?c.apply(r,n):(A(n,function(n){j.isArray(n)||j.isArguments(n)?t?a.apply(r,n):M(n,t,r):r.push(n)}),r)};j.flatten=function(n,t){return M(n,t,[])},j.without=function(n){return j.difference(n,o.call(arguments,1))},j.partition=function(n,t){var r=[],e=[];return A(n,function(n){(t(n)?r:e).push(n)}),[r,e]},j.uniq=j.unique=function(n,t,r,e){j.isFunction(t)&&(e=r,r=t,t=!1);var u=r?j.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:j.contains(a,r))||(a.push(r),i.push(n[e]))}),i},j.union=function(){return j.uniq(j.flatten(arguments,!0))},j.intersection=function(n){var t=o.call(arguments,1);return j.filter(j.uniq(n),function(n){return j.every(t,function(t){return j.contains(t,n)})})},j.difference=function(n){var t=c.apply(e,o.call(arguments,1));return j.filter(n,function(n){return!j.contains(t,n)})},j.zip=function(){for(var n=j.max(j.pluck(arguments,"length").concat(0)),t=new Array(n),r=0;n>r;r++)t[r]=j.pluck(arguments,""+r);return t},j.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},j.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=j.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},j.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},j.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=new Array(e);e>u;)i[u++]=n,n+=r;return i};var R=function(){};j.bind=function(n,t){var r,e;if(_&&n.bind===_)return _.apply(n,o.call(arguments,1));if(!j.isFunction(n))throw new TypeError;return r=o.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(o.call(arguments)));R.prototype=n.prototype;var u=new R;R.prototype=null;var i=n.apply(u,r.concat(o.call(arguments)));return Object(i)===i?i:u}},j.partial=function(n){var t=o.call(arguments,1);return function(){for(var r=0,e=t.slice(),u=0,i=e.length;i>u;u++)e[u]===j&&(e[u]=arguments[r++]);for(;r<arguments.length;)e.push(arguments[r++]);return n.apply(this,e)}},j.bindAll=function(n){var t=o.call(arguments,1);if(0===t.length)throw new Error("bindAll must be passed function names");return A(t,function(t){n[t]=j.bind(n[t],n)}),n},j.memoize=function(n,t){var r={};return t||(t=j.identity),function(){var e=t.apply(this,arguments);return j.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},j.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},j.defer=function(n){return j.delay.apply(j,[n,1].concat(o.call(arguments,1)))},j.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var c=function(){o=r.leading===!1?0:j.now(),a=null,i=n.apply(e,u),e=u=null};return function(){var l=j.now();o||r.leading!==!1||(o=l);var f=t-(l-o);return e=this,u=arguments,0>=f?(clearTimeout(a),a=null,o=l,i=n.apply(e,u),e=u=null):a||r.trailing===!1||(a=setTimeout(c,f)),i}},j.debounce=function(n,t,r){var e,u,i,a,o,c=function(){var l=j.now()-a;t>l?e=setTimeout(c,t-l):(e=null,r||(o=n.apply(i,u),i=u=null))};return function(){i=this,u=arguments,a=j.now();var l=r&&!e;return e||(e=setTimeout(c,t)),l&&(o=n.apply(i,u),i=u=null),o}},j.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},j.wrap=function(n,t){return j.partial(t,n)},j.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},j.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},j.keys=function(n){if(!j.isObject(n))return[];if(w)return w(n);var t=[];for(var r in n)j.has(n,r)&&t.push(r);return t},j.values=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},j.pairs=function(n){for(var t=j.keys(n),r=t.length,e=new Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},j.invert=function(n){for(var t={},r=j.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},j.functions=j.methods=function(n){var t=[];for(var r in n)j.isFunction(n[r])&&t.push(r);return t.sort()},j.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},j.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},j.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)j.contains(r,u)||(t[u]=n[u]);return t},j.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]===void 0&&(n[r]=t[r])}),n},j.clone=function(n){return j.isObject(n)?j.isArray(n)?n.slice():j.extend({},n):n},j.tap=function(n,t){return t(n),n};var S=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof j&&(n=n._wrapped),t instanceof j&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==String(t);case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;var a=n.constructor,o=t.constructor;if(a!==o&&!(j.isFunction(a)&&a instanceof a&&j.isFunction(o)&&o instanceof o)&&"constructor"in n&&"constructor"in t)return!1;r.push(n),e.push(t);var c=0,f=!0;if("[object Array]"==u){if(c=n.length,f=c==t.length)for(;c--&&(f=S(n[c],t[c],r,e)););}else{for(var s in n)if(j.has(n,s)&&(c++,!(f=j.has(t,s)&&S(n[s],t[s],r,e))))break;if(f){for(s in t)if(j.has(t,s)&&!c--)break;f=!c}}return r.pop(),e.pop(),f};j.isEqual=function(n,t){return S(n,t,[],[])},j.isEmpty=function(n){if(null==n)return!0;if(j.isArray(n)||j.isString(n))return 0===n.length;for(var t in n)if(j.has(n,t))return!1;return!0},j.isElement=function(n){return!(!n||1!==n.nodeType)},j.isArray=x||function(n){return"[object Array]"==l.call(n)},j.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){j["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),j.isArguments(arguments)||(j.isArguments=function(n){return!(!n||!j.has(n,"callee"))}),"function"!=typeof/./&&(j.isFunction=function(n){return"function"==typeof n}),j.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},j.isNaN=function(n){return j.isNumber(n)&&n!=+n},j.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},j.isNull=function(n){return null===n},j.isUndefined=function(n){return n===void 0},j.has=function(n,t){return f.call(n,t)},j.noConflict=function(){return n._=t,this},j.identity=function(n){return n},j.constant=function(n){return function(){return n}},j.property=function(n){return function(t){return t[n]}},j.matches=function(n){return function(t){if(t===n)return!0;for(var r in n)if(n[r]!==t[r])return!1;return!0}},j.times=function(n,t,r){for(var e=Array(Math.max(0,n)),u=0;n>u;u++)e[u]=t.call(r,u);return e},j.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},j.now=Date.now||function(){return(new Date).getTime()};var T={escape:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"}};T.unescape=j.invert(T.escape);var I={escape:new RegExp("["+j.keys(T.escape).join("")+"]","g"),unescape:new RegExp("("+j.keys(T.unescape).join("|")+")","g")};j.each(["escape","unescape"],function(n){j[n]=function(t){return null==t?"":(""+t).replace(I[n],function(t){return T[n][t]})}}),j.result=function(n,t){if(null==n)return void 0;var r=n[t];return j.isFunction(r)?r.call(n):r},j.mixin=function(n){A(j.functions(n),function(t){var r=j[t]=n[t];j.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),z.call(this,r.apply(j,n))}})};var N=0;j.uniqueId=function(n){var t=++N+"";return n?n+t:t},j.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var q=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n","    ":"t","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\t|\u2028|\u2029/g;j.template=function(n,t,r){var e;r=j.defaults({},r,j.templateSettings);var u=new RegExp([(r.escape||q).source,(r.interpolate||q).source,(r.evaluate||q).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(D,function(n){return"\\"+B[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=new Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,j);var c=function(n){return e.call(this,n,j)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},j.chain=function(n){return j(n).chain()};var z=function(n){return this._chain?j(n).chain():n};j.mixin(j),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];j.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],z.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];j.prototype[n]=function(){return z.call(this,t.apply(this._wrapped,arguments))}}),j.extend(j.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}}),"function"==typeof define&&define.amd&&define("underscore",[],function(){return j})}).call(this);(function(root,factory){if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(_,$,exports){root.Backbone=factory(root,exports,_,$)})}else if(typeof exports!=="undefined"){var _=require("underscore");factory(root,exports,_)}else{root.Backbone=factory(root,{},root._,root.jQuery||root.Zepto||root.ender||root.$)}})(this,function(root,Backbone,_,$){var previousBackbone=root.Backbone;var array=[];var push=array.push;var slice=array.slice;var splice=array.splice;Backbone.VERSION="1.1.2";Backbone.$=$;Backbone.noConflict=function(){root.Backbone=previousBackbone;
     4
     5return this};Backbone.emulateHTTP=false;Backbone.emulateJSON=false;var Events=Backbone.Events={on:function(name,callback,context){if(!eventsApi(this,"on",name,[callback,context])||!callback)return this;this._events||(this._events={});var events=this._events[name]||(this._events[name]=[]);events.push({callback:callback,context:context,ctx:context||this});return this},once:function(name,callback,context){if(!eventsApi(this,"once",name,[callback,context])||!callback)return this;var self=this;var once=_.once(function(){self.off(name,once);callback.apply(this,arguments)});once._callback=callback;return this.on(name,once,context)},off:function(name,callback,context){var retain,ev,events,names,i,l,j,k;if(!this._events||!eventsApi(this,"off",name,[callback,context]))return this;if(!name&&!callback&&!context){this._events=void 0;return this}names=name?[name]:_.keys(this._events);for(i=0,l=names.length;i<l;i++){name=names[i];if(events=this._events[name]){this._events[name]=retain=[];if(callback||context){for(j=0,k=events.length;j<k;j++){ev=events[j];if(callback&&callback!==ev.callback&&callback!==ev.callback._callback||context&&context!==ev.context){retain.push(ev)}}}if(!retain.length)delete this._events[name]}}return this},trigger:function(name){if(!this._events)return this;var args=slice.call(arguments,1);if(!eventsApi(this,"trigger",name,args))return this;var events=this._events[name];var allEvents=this._events.all;if(events)triggerEvents(events,args);if(allEvents)triggerEvents(allEvents,arguments);return this},stopListening:function(obj,name,callback){var listeningTo=this._listeningTo;if(!listeningTo)return this;var remove=!name&&!callback;if(!callback&&typeof name==="object")callback=this;if(obj)(listeningTo={})[obj._listenId]=obj;for(var id in listeningTo){obj=listeningTo[id];obj.off(name,callback,this);if(remove||_.isEmpty(obj._events))delete this._listeningTo[id]}return this}};var eventSplitter=/\s+/;var eventsApi=function(obj,action,name,rest){if(!name)return true;if(typeof name==="object"){for(var key in name){obj[action].apply(obj,[key,name[key]].concat(rest))}return false}if(eventSplitter.test(name)){var names=name.split(eventSplitter);for(var i=0,l=names.length;i<l;i++){obj[action].apply(obj,[names[i]].concat(rest))}return false}return true};var triggerEvents=function(events,args){var ev,i=-1,l=events.length,a1=args[0],a2=args[1],a3=args[2];switch(args.length){case 0:while(++i<l)(ev=events[i]).callback.call(ev.ctx);return;case 1:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1);return;case 2:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2);return;case 3:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2,a3);return;default:while(++i<l)(ev=events[i]).callback.apply(ev.ctx,args);return}};var listenMethods={listenTo:"on",listenToOnce:"once"};_.each(listenMethods,function(implementation,method){Events[method]=function(obj,name,callback){var listeningTo=this._listeningTo||(this._listeningTo={});var id=obj._listenId||(obj._listenId=_.uniqueId("l"));listeningTo[id]=obj;if(!callback&&typeof name==="object")callback=this;obj[implementation](name,callback,this);return this}});Events.bind=Events.on;Events.unbind=Events.off;_.extend(Backbone,Events);var Model=Backbone.Model=function(attributes,options){var attrs=attributes||{};options||(options={});this.cid=_.uniqueId("c");this.attributes={};if(options.collection)this.collection=options.collection;if(options.parse)attrs=this.parse(attrs,options)||{};attrs=_.defaults({},attrs,_.result(this,"defaults"));this.set(attrs,options);this.changed={};this.initialize.apply(this,arguments)};_.extend(Model.prototype,Events,{changed:null,validationError:null,idAttribute:"id",initialize:function(){},toJSON:function(options){return _.clone(this.attributes)},sync:function(){return Backbone.sync.apply(this,arguments)},get:function(attr){return this.attributes[attr]},escape:function(attr){return _.escape(this.get(attr))},has:function(attr){return this.get(attr)!=null},set:function(key,val,options){var attr,attrs,unset,changes,silent,changing,prev,current;if(key==null)return this;if(typeof key==="object"){attrs=key;options=val}else{(attrs={})[key]=val}options||(options={});if(!this._validate(attrs,options))return false;unset=options.unset;silent=options.silent;changes=[];changing=this._changing;this._changing=true;if(!changing){this._previousAttributes=_.clone(this.attributes);this.changed={}}current=this.attributes,prev=this._previousAttributes;if(this.idAttribute in attrs)this.id=attrs[this.idAttribute];for(attr in attrs){val=attrs[attr];if(!_.isEqual(current[attr],val))changes.push(attr);if(!_.isEqual(prev[attr],val)){this.changed[attr]=val}else{delete this.changed[attr]}unset?delete current[attr]:current[attr]=val}if(!silent){if(changes.length)this._pending=options;for(var i=0,l=changes.length;i<l;i++){this.trigger("change:"+changes[i],this,current[changes[i]],options)}}if(changing)return this;if(!silent){while(this._pending){options=this._pending;this._pending=false;this.trigger("change",this,options)}}this._pending=false;this._changing=false;return this},unset:function(attr,options){return this.set(attr,void 0,_.extend({},options,{unset:true}))},clear:function(options){var attrs={};for(var key in this.attributes)attrs[key]=void 0;return this.set(attrs,_.extend({},options,{unset:true}))},hasChanged:function(attr){if(attr==null)return!_.isEmpty(this.changed);return _.has(this.changed,attr)},changedAttributes:function(diff){if(!diff)return this.hasChanged()?_.clone(this.changed):false;var val,changed=false;var old=this._changing?this._previousAttributes:this.attributes;for(var attr in diff){if(_.isEqual(old[attr],val=diff[attr]))continue;(changed||(changed={}))[attr]=val}return changed},previous:function(attr){if(attr==null||!this._previousAttributes)return null;return this._previousAttributes[attr]},previousAttributes:function(){return _.clone(this._previousAttributes)},fetch:function(options){options=options?_.clone(options):{};if(options.parse===void 0)options.parse=true;var model=this;var success=options.success;options.success=function(resp){if(!model.set(model.parse(resp,options),options))return false;if(success)success(model,resp,options);model.trigger("sync",model,resp,options)};wrapError(this,options);return this.sync("read",this,options)},save:function(key,val,options){var attrs,method,xhr,attributes=this.attributes;if(key==null||typeof key==="object"){attrs=key;options=val}else{(attrs={})[key]=val}options=_.extend({validate:true},options);if(attrs&&!options.wait){if(!this.set(attrs,options))return false}else{if(!this._validate(attrs,options))return false}if(attrs&&options.wait){this.attributes=_.extend({},attributes,attrs)}if(options.parse===void 0)options.parse=true;var model=this;var success=options.success;options.success=function(resp){model.attributes=attributes;var serverAttrs=model.parse(resp,options);if(options.wait)serverAttrs=_.extend(attrs||{},serverAttrs);if(_.isObject(serverAttrs)&&!model.set(serverAttrs,options)){return false}if(success)success(model,resp,options);model.trigger("sync",model,resp,options)};wrapError(this,options);method=this.isNew()?"create":options.patch?"patch":"update";if(method==="patch")options.attrs=attrs;xhr=this.sync(method,this,options);if(attrs&&options.wait)this.attributes=attributes;return xhr},destroy:function(options){options=options?_.clone(options):{};var model=this;var success=options.success;var destroy=function(){model.trigger("destroy",model,model.collection,options)};options.success=function(resp){if(options.wait||model.isNew())destroy();if(success)success(model,resp,options);if(!model.isNew())model.trigger("sync",model,resp,options)};if(this.isNew()){options.success();return false}wrapError(this,options);var xhr=this.sync("delete",this,options);if(!options.wait)destroy();return xhr},url:function(){var base=_.result(this,"urlRoot")||_.result(this.collection,"url")||urlError();if(this.isNew())return base;return base.replace(/([^\/])$/,"$1/")+encodeURIComponent(this.id)},parse:function(resp,options){return resp},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.has(this.idAttribute)},isValid:function(options){return this._validate({},_.extend(options||{},{validate:true}))},_validate:function(attrs,options){if(!options.validate||!this.validate)return true;attrs=_.extend({},this.attributes,attrs);var error=this.validationError=this.validate(attrs,options)||null;if(!error)return true;this.trigger("invalid",this,error,_.extend(options,{validationError:error}));return false}});var modelMethods=["keys","values","pairs","invert","pick","omit"];_.each(modelMethods,function(method){Model.prototype[method]=function(){var args=slice.call(arguments);args.unshift(this.attributes);return _[method].apply(_,args)}});var Collection=Backbone.Collection=function(models,options){options||(options={});if(options.model)this.model=options.model;if(options.comparator!==void 0)this.comparator=options.comparator;this._reset();this.initialize.apply(this,arguments);if(models)this.reset(models,_.extend({silent:true},options))};var setOptions={add:true,remove:true,merge:true};var addOptions={add:true,remove:false};_.extend(Collection.prototype,Events,{model:Model,initialize:function(){},toJSON:function(options){return this.map(function(model){return model.toJSON(options)})},sync:function(){return Backbone.sync.apply(this,arguments)},add:function(models,options){return this.set(models,_.extend({merge:false},options,addOptions))},remove:function(models,options){var singular=!_.isArray(models);models=singular?[models]:_.clone(models);options||(options={});var i,l,index,model;for(i=0,l=models.length;i<l;i++){model=models[i]=this.get(models[i]);if(!model)continue;delete this._byId[model.id];delete this._byId[model.cid];index=this.indexOf(model);this.models.splice(index,1);this.length--;if(!options.silent){options.index=index;model.trigger("remove",model,this,options)}this._removeReference(model,options)}return singular?models[0]:models},set:function(models,options){options=_.defaults({},options,setOptions);if(options.parse)models=this.parse(models,options);var singular=!_.isArray(models);models=singular?models?[models]:[]:_.clone(models);var i,l,id,model,attrs,existing,sort;var at=options.at;var targetModel=this.model;var sortable=this.comparator&&at==null&&options.sort!==false;var sortAttr=_.isString(this.comparator)?this.comparator:null;var toAdd=[],toRemove=[],modelMap={};var add=options.add,merge=options.merge,remove=options.remove;var order=!sortable&&add&&remove?[]:false;for(i=0,l=models.length;i<l;i++){attrs=models[i]||{};if(attrs instanceof Model){id=model=attrs}else{id=attrs[targetModel.prototype.idAttribute||"id"]}if(existing=this.get(id)){if(remove)modelMap[existing.cid]=true;if(merge){attrs=attrs===model?model.attributes:attrs;if(options.parse)attrs=existing.parse(attrs,options);existing.set(attrs,options);if(sortable&&!sort&&existing.hasChanged(sortAttr))sort=true}models[i]=existing}else if(add){model=models[i]=this._prepareModel(attrs,options);if(!model)continue;toAdd.push(model);this._addReference(model,options)}model=existing||model;if(order&&(model.isNew()||!modelMap[model.id]))order.push(model);modelMap[model.id]=true}if(remove){for(i=0,l=this.length;i<l;++i){if(!modelMap[(model=this.models[i]).cid])toRemove.push(model)}if(toRemove.length)this.remove(toRemove,options)}if(toAdd.length||order&&order.length){if(sortable)sort=true;this.length+=toAdd.length;if(at!=null){for(i=0,l=toAdd.length;i<l;i++){this.models.splice(at+i,0,toAdd[i])}}else{if(order)this.models.length=0;var orderedModels=order||toAdd;for(i=0,l=orderedModels.length;i<l;i++){this.models.push(orderedModels[i])}}}if(sort)this.sort({silent:true});if(!options.silent){for(i=0,l=toAdd.length;i<l;i++){(model=toAdd[i]).trigger("add",model,this,options)}if(sort||order&&order.length)this.trigger("sort",this,options)}return singular?models[0]:models},reset:function(models,options){options||(options={});for(var i=0,l=this.models.length;i<l;i++){this._removeReference(this.models[i],options)}options.previousModels=this.models;this._reset();models=this.add(models,_.extend({silent:true},options));if(!options.silent)this.trigger("reset",this,options);return models},push:function(model,options){return this.add(model,_.extend({at:this.length},options))},pop:function(options){var model=this.at(this.length-1);this.remove(model,options);return model},unshift:function(model,options){return this.add(model,_.extend({at:0},options))},shift:function(options){var model=this.at(0);this.remove(model,options);return model},slice:function(){return slice.apply(this.models,arguments)},get:function(obj){if(obj==null)return void 0;return this._byId[obj]||this._byId[obj.id]||this._byId[obj.cid]},at:function(index){return this.models[index]},where:function(attrs,first){if(_.isEmpty(attrs))return first?void 0:[];return this[first?"find":"filter"](function(model){for(var key in attrs){if(attrs[key]!==model.get(key))return false}return true})},findWhere:function(attrs){return this.where(attrs,true)},sort:function(options){if(!this.comparator)throw new Error("Cannot sort a set without a comparator");options||(options={});if(_.isString(this.comparator)||this.comparator.length===1){this.models=this.sortBy(this.comparator,this)}else{this.models.sort(_.bind(this.comparator,this))}if(!options.silent)this.trigger("sort",this,options);return this},pluck:function(attr){return _.invoke(this.models,"get",attr)},fetch:function(options){options=options?_.clone(options):{};if(options.parse===void 0)options.parse=true;var success=options.success;var collection=this;options.success=function(resp){var method=options.reset?"reset":"set";collection[method](resp,options);if(success)success(collection,resp,options);collection.trigger("sync",collection,resp,options)};wrapError(this,options);return this.sync("read",this,options)},create:function(model,options){options=options?_.clone(options):{};if(!(model=this._prepareModel(model,options)))return false;if(!options.wait)this.add(model,options);var collection=this;var success=options.success;options.success=function(model,resp){if(options.wait)collection.add(model,options);if(success)success(model,resp,options)};model.save(null,options);return model},parse:function(resp,options){return resp},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(attrs,options){if(attrs instanceof Model)return attrs;options=options?_.clone(options):{};options.collection=this;var model=new this.model(attrs,options);if(!model.validationError)return model;this.trigger("invalid",this,model.validationError,options);return false},_addReference:function(model,options){this._byId[model.cid]=model;if(model.id!=null)this._byId[model.id]=model;if(!model.collection)model.collection=this;model.on("all",this._onModelEvent,this)},_removeReference:function(model,options){if(this===model.collection)delete model.collection;model.off("all",this._onModelEvent,this)},_onModelEvent:function(event,model,collection,options){if((event==="add"||event==="remove")&&collection!==this)return;if(event==="destroy")this.remove(model,options);if(model&&event==="change:"+model.idAttribute){delete this._byId[model.previous(model.idAttribute)];if(model.id!=null)this._byId[model.id]=model}this.trigger.apply(this,arguments)}});var methods=["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","difference","indexOf","shuffle","lastIndexOf","isEmpty","chain","sample"];_.each(methods,function(method){Collection.prototype[method]=function(){var args=slice.call(arguments);args.unshift(this.models);return _[method].apply(_,args)}});var attributeMethods=["groupBy","countBy","sortBy","indexBy"];_.each(attributeMethods,function(method){Collection.prototype[method]=function(value,context){var iterator=_.isFunction(value)?value:function(model){return model.get(value)};return _[method](this.models,iterator,context)}});var View=Backbone.View=function(options){this.cid=_.uniqueId("view");options||(options={});_.extend(this,_.pick(options,viewOptions));this._ensureElement();this.initialize.apply(this,arguments);this.delegateEvents()};var delegateEventSplitter=/^(\S+)\s*(.*)$/;var viewOptions=["model","collection","el","id","attributes","className","tagName","events"];_.extend(View.prototype,Events,{tagName:"div",$:function(selector){return this.$el.find(selector)},initialize:function(){},render:function(){return this},remove:function(){this.$el.remove();this.stopListening();return this},setElement:function(element,delegate){if(this.$el)this.undelegateEvents();this.$el=element instanceof Backbone.$?element:Backbone.$(element);this.el=this.$el[0];if(delegate!==false)this.delegateEvents();return this},delegateEvents:function(events){if(!(events||(events=_.result(this,"events"))))return this;this.undelegateEvents();for(var key in events){var method=events[key];if(!_.isFunction(method))method=this[events[key]];if(!method)continue;var match=key.match(delegateEventSplitter);var eventName=match[1],selector=match[2];method=_.bind(method,this);eventName+=".delegateEvents"+this.cid;if(selector===""){this.$el.on(eventName,method)}else{this.$el.on(eventName,selector,method)}}return this},undelegateEvents:function(){this.$el.off(".delegateEvents"+this.cid);return this},_ensureElement:function(){if(!this.el){var attrs=_.extend({},_.result(this,"attributes"));if(this.id)attrs.id=_.result(this,"id");if(this.className)attrs["class"]=_.result(this,"className");var $el=Backbone.$("<"+_.result(this,"tagName")+">").attr(attrs);this.setElement($el,false)}else{this.setElement(_.result(this,"el"),false)}}});Backbone.sync=function(method,model,options){var type=methodMap[method];_.defaults(options||(options={}),{emulateHTTP:Backbone.emulateHTTP,emulateJSON:Backbone.emulateJSON});var params={type:type,dataType:"json"};if(!options.url){params.url=_.result(model,"url")||urlError()}if(options.data==null&&model&&(method==="create"||method==="update"||method==="patch")){params.contentType="application/json";params.data=JSON.stringify(options.attrs||model.toJSON(options))}if(options.emulateJSON){params.contentType="application/x-www-form-urlencoded";params.data=params.data?{model:params.data}:{}}if(options.emulateHTTP&&(type==="PUT"||type==="DELETE"||type==="PATCH")){params.type="POST";if(options.emulateJSON)params.data._method=type;var beforeSend=options.beforeSend;options.beforeSend=function(xhr){xhr.setRequestHeader("X-HTTP-Method-Override",type);if(beforeSend)return beforeSend.apply(this,arguments)}}if(params.type!=="GET"&&!options.emulateJSON){params.processData=false}if(params.type==="PATCH"&&noXhrPatch){params.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}var xhr=options.xhr=Backbone.ajax(_.extend(params,options));model.trigger("request",model,xhr,options);return xhr};var noXhrPatch=typeof window!=="undefined"&&!!window.ActiveXObject&&!(window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent);var methodMap={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};Backbone.ajax=function(){return Backbone.$.ajax.apply(Backbone.$,arguments)};var Router=Backbone.Router=function(options){options||(options={});if(options.routes)this.routes=options.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var optionalParam=/\((.*?)\)/g;var namedParam=/(\(\?)?:\w+/g;var splatParam=/\*\w+/g;var escapeRegExp=/[\-{}\[\]+?.,\\\^$|#\s]/g;_.extend(Router.prototype,Events,{initialize:function(){},route:function(route,name,callback){if(!_.isRegExp(route))route=this._routeToRegExp(route);if(_.isFunction(name)){callback=name;name=""}if(!callback)callback=this[name];var router=this;Backbone.history.route(route,function(fragment){var args=router._extractParameters(route,fragment);router.execute(callback,args);router.trigger.apply(router,["route:"+name].concat(args));router.trigger("route",name,args);Backbone.history.trigger("route",router,name,args)});return this},execute:function(callback,args){if(callback)callback.apply(this,args)},navigate:function(fragment,options){Backbone.history.navigate(fragment,options);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=_.result(this,"routes");var route,routes=_.keys(this.routes);while((route=routes.pop())!=null){this.route(route,this.routes[route])}},_routeToRegExp:function(route){route=route.replace(escapeRegExp,"\\$&").replace(optionalParam,"(?:$1)?").replace(namedParam,function(match,optional){return optional?match:"([^/?]+)"}).replace(splatParam,"([^?]*?)");return new RegExp("^"+route+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(route,fragment){var params=route.exec(fragment).slice(1);return _.map(params,function(param,i){if(i===params.length-1)return param||null;return param?decodeURIComponent(param):null})}});var History=Backbone.History=function(){this.handlers=[];_.bindAll(this,"checkUrl");if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var routeStripper=/^[#\/]|\s+$/g;var rootStripper=/^\/+|\/+$/g;var isExplorer=/msie [\w.]+/;var trailingSlash=/\/$/;var pathStripper=/#.*$/;History.started=false;_.extend(History.prototype,Events,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root},getHash:function(window){var match=(window||this).location.href.match(/#(.*)$/);return match?match[1]:""},getFragment:function(fragment,forcePushState){if(fragment==null){if(this._hasPushState||!this._wantsHashChange||forcePushState){fragment=decodeURI(this.location.pathname+this.location.search);var root=this.root.replace(trailingSlash,"");if(!fragment.indexOf(root))fragment=fragment.slice(root.length)}else{fragment=this.getHash()}}return fragment.replace(routeStripper,"")},start:function(options){if(History.started)throw new Error("Backbone.history has already been started");History.started=true;this.options=_.extend({root:"/"},this.options,options);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var fragment=this.getFragment();var docMode=document.documentMode;var oldIE=isExplorer.exec(navigator.userAgent.toLowerCase())&&(!docMode||docMode<=7);this.root=("/"+this.root+"/").replace(rootStripper,"/");if(oldIE&&this._wantsHashChange){var frame=Backbone.$('<iframe src="javascript:0" tabindex="-1">');this.iframe=frame.hide().appendTo("body")[0].contentWindow;this.navigate(fragment)}if(this._hasPushState){Backbone.$(window).on("popstate",this.checkUrl)}else if(this._wantsHashChange&&"onhashchange"in window&&!oldIE){Backbone.$(window).on("hashchange",this.checkUrl)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}this.fragment=fragment;var loc=this.location;if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){this.fragment=this.getFragment(null,true);this.location.replace(this.root+"#"+this.fragment);return true}else if(this._hasPushState&&this.atRoot()&&loc.hash){this.fragment=this.getHash().replace(routeStripper,"");this.history.replaceState({},document.title,this.root+this.fragment)}}if(!this.options.silent)return this.loadUrl()},stop:function(){Backbone.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl);if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);History.started=false},route:function(route,callback){this.handlers.unshift({route:route,callback:callback})},checkUrl:function(e){var current=this.getFragment();if(current===this.fragment&&this.iframe){current=this.getFragment(this.getHash(this.iframe))}if(current===this.fragment)return false;if(this.iframe)this.navigate(current);this.loadUrl()},loadUrl:function(fragment){fragment=this.fragment=this.getFragment(fragment);return _.any(this.handlers,function(handler){if(handler.route.test(fragment)){handler.callback(fragment);return true}})},navigate:function(fragment,options){if(!History.started)return false;if(!options||options===true)options={trigger:!!options};var url=this.root+(fragment=this.getFragment(fragment||""));fragment=fragment.replace(pathStripper,"");if(this.fragment===fragment)return;this.fragment=fragment;if(fragment===""&&url!=="/")url=url.slice(0,-1);if(this._hasPushState){this.history[options.replace?"replaceState":"pushState"]({},document.title,url)}else if(this._wantsHashChange){this._updateHash(this.location,fragment,options.replace);if(this.iframe&&fragment!==this.getFragment(this.getHash(this.iframe))){if(!options.replace)this.iframe.document.open().close();this._updateHash(this.iframe.location,fragment,options.replace)}}else{return this.location.assign(url)}if(options.trigger)return this.loadUrl(fragment)},_updateHash:function(location,fragment,replace){if(replace){var href=location.href.replace(/(javascript:|#).*$/,"");location.replace(href+"#"+fragment)}else{location.hash="#"+fragment}}});Backbone.history=new History;var extend=function(protoProps,staticProps){var parent=this;var child;if(protoProps&&_.has(protoProps,"constructor")){child=protoProps.constructor}else{child=function(){return parent.apply(this,arguments)}}_.extend(child,parent,staticProps);var Surrogate=function(){this.constructor=child};Surrogate.prototype=parent.prototype;child.prototype=new Surrogate;if(protoProps)_.extend(child.prototype,protoProps);child.__super__=parent.prototype;return child};Model.extend=Collection.extend=Router.extend=View.extend=History.extend=extend;var urlError=function(){throw new Error('A "url" property or function must be specified')};var wrapError=function(model,options){var error=options.error;options.error=function(resp){if(error)error(model,resp,options);model.trigger("error",model,resp,options)}};return Backbone});var requirejs,require,define;(function(ba){function G(b){return"[object Function]"===K.call(b)}function H(b){return"[object Array]"===K.call(b)}function v(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function T(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));d-=1);}}function t(b,c){return fa.call(b,c)}function m(b,c){return t(b,c)&&b[c]}function B(b,c){for(var d in b)if(t(b,d)&&c(b[d],d))break}function U(b,c,d,e){c&&B(c,function(c,g){if(d||!t(b,g))e&&"object"===typeof c&&c&&!H(c)&&!G(c)&&!(c instanceof RegExp)?(b[g]||(b[g]={}),U(b[g],c,d,e)):b[g]=c});return b}function u(b,c){return function(){return c.apply(b,arguments)}}function ca(b){throw b}function da(b){if(!b)return b;var c=ba;v(b.split("."),function(b){c=c[b]});return c}function C(b,c,d,e){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=e;d&&(c.originalError=d);return c}function ga(b){function c(a,k,b){var f,l,c,d,e,g,i,p,k=k&&k.split("/"),h=j.map,n=h&&h["*"];if(a){a=a.split("/");l=a.length-1;j.nodeIdCompat&&Q.test(a[l])&&(a[l]=a[l].replace(Q,""));"."===a[0].charAt(0)&&k&&(l=k.slice(0,k.length-1),a=l.concat(a));l=a;for(c=0;c<l.length;c++)if(d=l[c],"."===d)l.splice(c,1),c-=1;else if(".."===d&&!(0===c||1==c&&".."===l[2]||".."===l[c-1])&&0<c)l.splice(c-1,2),c-=2;a=a.join("/")}if(b&&h&&(k||n)){l=a.split("/");c=l.length;a:for(;0<c;c-=1){e=l.slice(0,c).join("/");if(k)for(d=k.length;0<d;d-=1)if(b=m(h,k.slice(0,d).join("/")))if(b=m(b,e)){f=b;g=c;break a}!i&&(n&&m(n,e))&&(i=m(n,e),p=c)}!f&&i&&(f=i,g=p);f&&(l.splice(0,g,f),a=l.join("/"))}return(f=m(j.pkgs,a))?f:a}function d(a){z&&v(document.getElementsByTagName("script"),function(k){if(k.getAttribute("data-requiremodule")===a&&k.getAttribute("data-requirecontext")===i.contextName)return k.parentNode.removeChild(k),!0})}function e(a){var k=m(j.paths,a);if(k&&H(k)&&1<k.length)return k.shift(),i.require.undef(a),i.makeRequire(null,{skipMap:!0})([a]),!0}function n(a){var k,c=a?a.indexOf("!"):-1;-1<c&&(k=a.substring(0,c),a=a.substring(c+1,a.length));return[k,a]}function p(a,k,b,f){var l,d,e=null,g=k?k.name:null,j=a,p=!0,h="";a||(p=!1,a="_@r"+(K+=1));a=n(a);e=a[0];a=a[1];e&&(e=c(e,g,f),d=m(r,e));a&&(e?h=d&&d.normalize?d.normalize(a,function(a){return c(a,g,f)}):-1===a.indexOf("!")?c(a,g,f):a:(h=c(a,g,f),a=n(h),e=a[0],h=a[1],b=!0,l=i.nameToUrl(h)));b=e&&!d&&!b?"_unnormalized"+(O+=1):"";return{prefix:e,name:h,parentMap:k,unnormalized:!!b,url:l,originalName:j,isDefine:p,id:(e?e+"!"+h:h)+b}}function s(a){var k=a.id,b=m(h,k);b||(b=h[k]=new i.Module(a));return b}function q(a,k,b){var f=a.id,c=m(h,f);if(t(r,f)&&(!c||c.defineEmitComplete))"defined"===k&&b(r[f]);else if(c=s(a),c.error&&"error"===k)b(c.error);else c.on(k,b)}function w(a,b){var c=a.requireModules,f=!1;if(b)b(a);else if(v(c,function(b){if(b=m(h,b))b.error=a,b.events.error&&(f=!0,b.emit("error",a))}),!f)g.onError(a)}function x(){R.length&&(ha.apply(A,[A.length,0].concat(R)),R=[])}function y(a){delete h[a];delete V[a]}function F(a,b,c){var f=a.map.id;a.error?a.emit("error",a.error):(b[f]=!0,v(a.depMaps,function(f,d){var e=f.id,g=m(h,e);g&&(!a.depMatched[d]&&!c[e])&&(m(b,e)?(a.defineDep(d,r[e]),a.check()):F(g,b,c))}),c[f]=!0)}function D(){var a,b,c=(a=1e3*j.waitSeconds)&&i.startTime+a<(new Date).getTime(),f=[],l=[],g=!1,h=!0;if(!W){W=!0;B(V,function(a){var i=a.map,j=i.id;if(a.enabled&&(i.isDefine||l.push(a),!a.error))if(!a.inited&&c)e(j)?g=b=!0:(f.push(j),d(j));else if(!a.inited&&(a.fetched&&i.isDefine)&&(g=!0,!i.prefix))return h=!1});if(c&&f.length)return a=C("timeout","Load timeout for modules: "+f,null,f),a.contextName=i.contextName,w(a);h&&v(l,function(a){F(a,{},{})});if((!c||b)&&g)if((z||ea)&&!X)X=setTimeout(function(){X=0;D()},50);W=!1}}function E(a){t(r,a[0])||s(p(a[0],null,!0)).init(a[1],a[2])}function I(a){var a=a.currentTarget||a.srcElement,b=i.onScriptLoad;a.detachEvent&&!Y?a.detachEvent("onreadystatechange",b):a.removeEventListener("load",b,!1);b=i.onScriptError;(!a.detachEvent||Y)&&a.removeEventListener("error",b,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function J(){var a;for(x();A.length;){a=A.shift();if(null===a[0])return w(C("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));E(a)}}var W,Z,i,L,X,j={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},h={},V={},$={},A=[],r={},S={},aa={},K=1,O=1;L={require:function(a){return a.require?a.require:a.require=i.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports?r[a.map.id]=a.exports:a.exports=r[a.map.id]={}},module:function(a){return a.module?a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){return m(j.config,a.map.id)||{}},exports:a.exports||(a.exports={})}}};Z=function(a){this.events=m($,a.id)||{};this.map=a;this.shim=m(j.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};Z.prototype={init:function(a,b,c,f){f=f||{};if(!this.inited){this.factory=b;if(c)this.on("error",c);else this.events.error&&(c=u(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=c;this.inited=!0;this.ignore=f.ignore;f.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,b){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=b)},fetch:function(){if(!this.fetched){this.fetched=!0;i.startTime=(new Date).getTime();var a=this.map;if(this.shim)i.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],u(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=this.map.url;S[a]||(S[a]=!0,i.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,b,c=this.map.id;b=this.depExports;var f=this.exports,l=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){
     6this.defining=!0;if(1>this.depCount&&!this.defined){if(G(l)){if(this.events.error&&this.map.isDefine||g.onError!==ca)try{f=i.execCb(c,l,b,f)}catch(d){a=d}else f=i.execCb(c,l,b,f);this.map.isDefine&&void 0===f&&((b=this.module)?f=b.exports:this.usingExports&&(f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=l;this.exports=f;if(this.map.isDefine&&!this.ignore&&(r[c]=f,g.onResourceLoad))g.onResourceLoad(i,this.map,this.depMaps);y(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a=this.map,b=a.id,d=p(a.prefix);this.depMaps.push(d);q(d,"defined",u(this,function(f){var l,d;d=m(aa,this.map.id);var e=this.map.name,P=this.map.parentMap?this.map.parentMap.name:null,n=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(e=f.normalize(e,function(a){return c(a,P,!0)})||""),f=p(a.prefix+"!"+e,this.map.parentMap),q(f,"defined",u(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),d=m(h,f.id)){this.depMaps.push(f);if(this.events.error)d.on("error",u(this,function(a){this.emit("error",a)}));d.enable()}}else d?(this.map.url=i.nameToUrl(d),this.load()):(l=u(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),l.error=u(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(h,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),l.fromText=u(this,function(f,c){var d=a.name,e=p(d),P=M;c&&(f=c);P&&(M=!1);s(e);t(j.config,b)&&(j.config[d]=j.config[b]);try{g.exec(f)}catch(h){return w(C("fromtexteval","fromText eval for "+b+" failed: "+h,h,[b]))}P&&(M=!0);this.depMaps.push(e);i.completeLoad(d);n([d],l)}),f.load(a.name,n,l,j))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){V[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,u(this,function(a,b){var c,f;if("string"===typeof a){a=p(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=m(L,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;q(a,"defined",u(this,function(a){this.defineDep(b,a);this.check()}));this.errback&&q(a,"error",u(this,this.errback))}c=a.id;f=h[c];!t(L,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,u(this,function(a){var b=m(h,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:j,contextName:b,registry:h,defined:r,urlFetched:S,defQueue:A,Module:Z,makeModuleMap:p,nextTick:g.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=j.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(j[b]||(j[b]={}),U(j[b],a,!0,!0)):j[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(aa[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);b[c]=a}),j.shim=b);a.packages&&v(a.packages,function(a){var b,a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(j.paths[b]=a.location);j.pkgs[b]=a.name+"/"+(a.main||"main").replace(ia,"").replace(Q,"")});B(h,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=p(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ba,arguments));return b||a.exports&&da(a.exports)}},makeRequire:function(a,e){function j(c,d,m){var n,q;e.enableBuildCallback&&(d&&G(d))&&(d.__requireJsBuild=!0);if("string"===typeof c){if(G(d))return w(C("requireargs","Invalid require call"),m);if(a&&t(L,c))return L[c](h[a.id]);if(g.get)return g.get(i,c,a,j);n=p(c,a,!1,!0);n=n.id;return!t(r,n)?w(C("notloaded",'Module name "'+n+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):r[n]}J();i.nextTick(function(){J();q=s(p(null,a));q.skipMap=e.skipMap;q.init(c,d,m,{enabled:!0});D()});return j}e=e||{};U(j,{isBrowser:z,toUrl:function(b){var d,e=b.lastIndexOf("."),k=b.split("/")[0];if(-1!==e&&(!("."===k||".."===k)||1<e))d=b.substring(e,b.length),b=b.substring(0,e);return i.nameToUrl(c(b,a&&a.id,!0),d,!0)},defined:function(b){return t(r,p(b,a,!1,!0).id)},specified:function(b){b=p(b,a,!1,!0).id;return t(r,b)||t(h,b)}});a||(j.undef=function(b){x();var c=p(b,a,!0),e=m(h,b);d(b);delete r[b];delete S[c.url];delete $[b];T(A,function(a,c){a[0]===b&&A.splice(c,1)});e&&(e.events.defined&&($[b]=e.events),y(b))});return j},enable:function(a){m(h,a.id)&&s(a).enable()},completeLoad:function(a){var b,c,d=m(j.shim,a)||{},g=d.exports;for(x();A.length;){c=A.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);E(c)}c=m(h,a);if(!b&&!t(r,a)&&c&&!c.inited){if(j.enforceDefine&&(!g||!da(g)))return e(a)?void 0:w(C("nodefine","No define call for "+a,null,[a]));E([a,d.deps||[],d.exportsFn])}D()},nameToUrl:function(a,b,c){var d,e,h;(d=m(j.pkgs,a))&&(a=d);if(d=m(aa,a))return i.nameToUrl(d,b,c);if(g.jsExtRegExp.test(a))d=a+(b||"");else{d=j.paths;a=a.split("/");for(e=a.length;0<e;e-=1)if(h=a.slice(0,e).join("/"),h=m(d,h)){H(h)&&(h=h[0]);a.splice(0,e,h);break}d=a.join("/");d+=b||(/^data\:|\?/.test(d)||c?"":".js");d=("/"===d.charAt(0)||d.match(/^[\w\+\.\-]+:/)?"":j.baseUrl)+d}return j.urlArgs?d+((-1===d.indexOf("?")?"?":"&")+j.urlArgs):d},load:function(a,b){g.load(i,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if("load"===a.type||ja.test((a.currentTarget||a.srcElement).readyState))N=null,a=I(a),i.completeLoad(a.id)},onScriptError:function(a){var b=I(a);if(!e(b.id))return w(C("scripterror","Script error for: "+b.id,a,[b.id]))}};i.require=i.makeRequire();return i}var g,x,y,D,I,E,N,J,s,O,ka=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm,la=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,Q=/\.js$/,ia=/^\.\//;x=Object.prototype;var K=x.toString,fa=x.hasOwnProperty,ha=Array.prototype.splice,z=!!("undefined"!==typeof window&&"undefined"!==typeof navigator&&window.document),ea=!z&&"undefined"!==typeof importScripts,ja=z&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,Y="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),F={},q={},R=[],M=!1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(G(requirejs))return;q=requirejs;requirejs=void 0}"undefined"!==typeof require&&!G(require)&&(q=require,require=void 0);g=requirejs=function(b,c,d,e){var n,p="_";!H(b)&&"string"!==typeof b&&(n=b,H(c)?(b=c,c=d,d=e):b=[]);n&&n.context&&(p=n.context);(e=m(F,p))||(e=F[p]=g.s.newContext(p));n&&e.configure(n);return e.require(b,c,d)};g.config=function(b){return g(b)};g.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b,4)}:function(b){b()};require||(require=g);g.version="2.1.15";g.jsExtRegExp=/^\/|:|\?|\.js$/;g.isBrowser=z;x=g.s={contexts:F,newContext:ga};g({});v(["toUrl","undef","defined","specified"],function(b){g[b]=function(){var c=F._;return c.require[b].apply(c,arguments)}});if(z&&(y=x.head=document.getElementsByTagName("head")[0],D=document.getElementsByTagName("base")[0]))y=x.head=D.parentNode;g.onError=ca;g.createNode=function(b){var c=b.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");c.type=b.scriptType||"text/javascript";c.charset="utf-8";c.async=!0;return c};g.load=function(b,c,d){var e=b&&b.config||{};if(z)return e=g.createNode(e,c,d),e.setAttribute("data-requirecontext",b.contextName),e.setAttribute("data-requiremodule",c),e.attachEvent&&!(e.attachEvent.toString&&0>e.attachEvent.toString().indexOf("[native code"))&&!Y?(M=!0,e.attachEvent("onreadystatechange",b.onScriptLoad)):(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)),e.src=d,J=e,D?y.insertBefore(e,D):y.appendChild(e),J=null,e;if(ea)try{importScripts(d),b.completeLoad(c)}catch(m){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,m,[c]))}};z&&!q.skipDataMain&&T(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(I=b.getAttribute("data-main"))return s=I,q.baseUrl||(E=s.split("/"),s=E.pop(),O=E.length?E.join("/")+"/":"./",q.baseUrl=O),s=s.replace(Q,""),g.jsExtRegExp.test(s)&&(s=I),q.deps=q.deps?q.deps.concat(s):[s],!0});define=function(b,c,d){var e,g;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(ka,"").replace(la,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(M){if(!(e=J))N&&"interactive"===N.readyState||T(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return N=b}),e=N;e&&(b||(b=e.getAttribute("data-requiremodule")),g=F[e.getAttribute("data-requirecontext")])}(g?g.defQueue:R).push([b,c,d])};define.amd={jQuery:!0};g.exec=function(b){return eval(b)};g(q)}})(this);!function(root,String){"use strict";var nativeTrim=String.prototype.trim;var nativeTrimRight=String.prototype.trimRight;var nativeTrimLeft=String.prototype.trimLeft;var parseNumber=function(source){return source*1||0};var strRepeat=function(str,qty){if(qty<1)return"";var result="";while(qty>0){if(qty&1)result+=str;qty>>=1,str+=str}return result};var slice=[].slice;var defaultToWhiteSpace=function(characters){if(characters==null)return"\\s";else if(characters.source)return characters.source;else return"["+_s.escapeRegExp(characters)+"]"};var escapeChars={lt:"<",gt:">",quot:'"',amp:"&",apos:"'"};var reversedEscapeChars={};for(var key in escapeChars)reversedEscapeChars[escapeChars[key]]=key;reversedEscapeChars["'"]="#39";var sprintf=function(){function get_type(variable){return Object.prototype.toString.call(variable).slice(8,-1).toLowerCase()}var str_repeat=strRepeat;var str_format=function(){if(!str_format.cache.hasOwnProperty(arguments[0])){str_format.cache[arguments[0]]=str_format.parse(arguments[0])}return str_format.format.call(null,str_format.cache[arguments[0]],arguments)};str_format.format=function(parse_tree,argv){var cursor=1,tree_length=parse_tree.length,node_type="",arg,output=[],i,k,match,pad,pad_character,pad_length;for(i=0;i<tree_length;i++){node_type=get_type(parse_tree[i]);if(node_type==="string"){output.push(parse_tree[i])}else if(node_type==="array"){match=parse_tree[i];if(match[2]){arg=argv[cursor];for(k=0;k<match[2].length;k++){if(!arg.hasOwnProperty(match[2][k])){throw new Error(sprintf('[_.sprintf] property "%s" does not exist',match[2][k]))}arg=arg[match[2][k]]}}else if(match[1]){arg=argv[match[1]]}else{arg=argv[cursor++]}if(/[^s]/.test(match[8])&&get_type(arg)!="number"){throw new Error(sprintf("[_.sprintf] expecting number but found %s",get_type(arg)))}switch(match[8]){case"b":arg=arg.toString(2);break;case"c":arg=String.fromCharCode(arg);break;case"d":arg=parseInt(arg,10);break;case"e":arg=match[7]?arg.toExponential(match[7]):arg.toExponential();break;case"f":arg=match[7]?parseFloat(arg).toFixed(match[7]):parseFloat(arg);break;case"o":arg=arg.toString(8);break;case"s":arg=(arg=String(arg))&&match[7]?arg.substring(0,match[7]):arg;break;case"u":arg=Math.abs(arg);break;case"x":arg=arg.toString(16);break;case"X":arg=arg.toString(16).toUpperCase();break}arg=/[def]/.test(match[8])&&match[3]&&arg>=0?"+"+arg:arg;pad_character=match[4]?match[4]=="0"?"0":match[4].charAt(1):" ";pad_length=match[6]-String(arg).length;pad=match[6]?str_repeat(pad_character,pad_length):"";output.push(match[5]?arg+pad:pad+arg)}}return output.join("")};str_format.cache={};str_format.parse=function(fmt){var _fmt=fmt,match=[],parse_tree=[],arg_names=0;while(_fmt){if((match=/^[^\x25]+/.exec(_fmt))!==null){parse_tree.push(match[0])}else if((match=/^\x25{2}/.exec(_fmt))!==null){parse_tree.push("%")}else if((match=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt))!==null){if(match[2]){arg_names|=1;var field_list=[],replacement_field=match[2],field_match=[];if((field_match=/^([a-z_][a-z_\d]*)/i.exec(replacement_field))!==null){field_list.push(field_match[1]);while((replacement_field=replacement_field.substring(field_match[0].length))!==""){if((field_match=/^\.([a-z_][a-z_\d]*)/i.exec(replacement_field))!==null){field_list.push(field_match[1])}else if((field_match=/^\[(\d+)\]/.exec(replacement_field))!==null){field_list.push(field_match[1])}else{throw new Error("[_.sprintf] huh?")}}}else{throw new Error("[_.sprintf] huh?")}match[2]=field_list}else{arg_names|=2}if(arg_names===3){throw new Error("[_.sprintf] mixing positional and named placeholders is not (yet) supported")}parse_tree.push(match)}else{throw new Error("[_.sprintf] huh?")}_fmt=_fmt.substring(match[0].length)}return parse_tree};return str_format}();var _s={VERSION:"2.3.0",isBlank:function(str){if(str==null)str="";return/^\s*$/.test(str)},stripTags:function(str){if(str==null)return"";return String(str).replace(/<\/?[^>]+>/g,"")},capitalize:function(str){str=str==null?"":String(str);return str.charAt(0).toUpperCase()+str.slice(1)},chop:function(str,step){if(str==null)return[];str=String(str);step=~~step;return step>0?str.match(new RegExp(".{1,"+step+"}","g")):[str]},clean:function(str){return _s.strip(str).replace(/\s+/g," ")},count:function(str,substr){if(str==null||substr==null)return 0;str=String(str);substr=String(substr);var count=0,pos=0,length=substr.length;while(true){pos=str.indexOf(substr,pos);if(pos===-1)break;count++;pos+=length}return count},chars:function(str){if(str==null)return[];return String(str).split("")},swapCase:function(str){if(str==null)return"";return String(str).replace(/\S/g,function(c){return c===c.toUpperCase()?c.toLowerCase():c.toUpperCase()})},escapeHTML:function(str){if(str==null)return"";return String(str).replace(/[&<>"']/g,function(m){return"&"+reversedEscapeChars[m]+";"})},unescapeHTML:function(str){if(str==null)return"";return String(str).replace(/\&([^;]+);/g,function(entity,entityCode){var match;if(entityCode in escapeChars){return escapeChars[entityCode]}else if(match=entityCode.match(/^#x([\da-fA-F]+)$/)){return String.fromCharCode(parseInt(match[1],16))}else if(match=entityCode.match(/^#(\d+)$/)){return String.fromCharCode(~~match[1])}else{return entity}})},escapeRegExp:function(str){if(str==null)return"";return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")},splice:function(str,i,howmany,substr){var arr=_s.chars(str);arr.splice(~~i,~~howmany,substr);return arr.join("")},insert:function(str,i,substr){return _s.splice(str,i,0,substr)},include:function(str,needle){if(needle==="")return true;if(str==null)return false;return String(str).indexOf(needle)!==-1},join:function(){var args=slice.call(arguments),separator=args.shift();if(separator==null)separator="";return args.join(separator)},lines:function(str){if(str==null)return[];return String(str).split("\n")},reverse:function(str){return _s.chars(str).reverse().join("")},startsWith:function(str,starts){if(starts==="")return true;if(str==null||starts==null)return false;str=String(str);starts=String(starts);return str.length>=starts.length&&str.slice(0,starts.length)===starts},endsWith:function(str,ends){if(ends==="")return true;if(str==null||ends==null)return false;str=String(str);ends=String(ends);return str.length>=ends.length&&str.slice(str.length-ends.length)===ends},succ:function(str){if(str==null)return"";str=String(str);return str.slice(0,-1)+String.fromCharCode(str.charCodeAt(str.length-1)+1)},titleize:function(str){if(str==null)return"";return String(str).replace(/(?:^|\s)\S/g,function(c){return c.toUpperCase()})},camelize:function(str){return _s.trim(str).replace(/[-_\s]+(.)?/g,function(match,c){return c.toUpperCase()})},underscored:function(str){return _s.trim(str).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},dasherize:function(str){return _s.trim(str).replace(/([A-Z])/g,"-$1").replace(/[-_\s]+/g,"-").toLowerCase()},classify:function(str){return _s.titleize(String(str).replace(/_/g," ")).replace(/\s/g,"")},humanize:function(str){return _s.capitalize(_s.underscored(str).replace(/_id$/,"").replace(/_/g," "))},trim:function(str,characters){if(str==null)return"";if(!characters&&nativeTrim)return nativeTrim.call(str);characters=defaultToWhiteSpace(characters);return String(str).replace(new RegExp("^"+characters+"+|"+characters+"+$","g"),"")},ltrim:function(str,characters){if(str==null)return"";if(!characters&&nativeTrimLeft)return nativeTrimLeft.call(str);characters=defaultToWhiteSpace(characters);return String(str).replace(new RegExp("^"+characters+"+"),"")},rtrim:function(str,characters){if(str==null)return"";if(!characters&&nativeTrimRight)return nativeTrimRight.call(str);characters=defaultToWhiteSpace(characters);return String(str).replace(new RegExp(characters+"+$"),"")},truncate:function(str,length,truncateStr){if(str==null)return"";str=String(str);truncateStr=truncateStr||"...";length=~~length;return str.length>length?str.slice(0,length)+truncateStr:str},prune:function(str,length,pruneStr){if(str==null)return"";str=String(str);length=~~length;pruneStr=pruneStr!=null?String(pruneStr):"...";if(str.length<=length)return str;var tmpl=function(c){return c.toUpperCase()!==c.toLowerCase()?"A":" "},template=str.slice(0,length+1).replace(/.(?=\W*\w*$)/g,tmpl);if(template.slice(template.length-2).match(/\w\w/))template=template.replace(/\s*\S+$/,"");else template=_s.rtrim(template.slice(0,template.length-1));return(template+pruneStr).length>str.length?str:str.slice(0,template.length)+pruneStr},words:function(str,delimiter){if(_s.isBlank(str))return[];return _s.trim(str,delimiter).split(delimiter||/\s+/)},pad:function(str,length,padStr,type){str=str==null?"":String(str);length=~~length;var padlen=0;if(!padStr)padStr=" ";else if(padStr.length>1)padStr=padStr.charAt(0);switch(type){case"right":padlen=length-str.length;return str+strRepeat(padStr,padlen);case"both":padlen=length-str.length;return strRepeat(padStr,Math.ceil(padlen/2))+str+strRepeat(padStr,Math.floor(padlen/2));default:padlen=length-str.length;return strRepeat(padStr,padlen)+str}},lpad:function(str,length,padStr){return _s.pad(str,length,padStr)},rpad:function(str,length,padStr){return _s.pad(str,length,padStr,"right")},lrpad:function(str,length,padStr){return _s.pad(str,length,padStr,"both")},sprintf:sprintf,vsprintf:function(fmt,argv){argv.unshift(fmt);return sprintf.apply(null,argv)},toNumber:function(str,decimals){if(!str)return 0;str=_s.trim(str);if(!str.match(/^-?\d+(?:\.\d+)?$/))return NaN;return parseNumber(parseNumber(str).toFixed(~~decimals))},numberFormat:function(number,dec,dsep,tsep){if(isNaN(number)||number==null)return"";number=number.toFixed(~~dec);tsep=typeof tsep=="string"?tsep:",";var parts=number.split("."),fnums=parts[0],decimals=parts[1]?(dsep||".")+parts[1]:"";return fnums.replace(/(\d)(?=(?:\d{3})+$)/g,"$1"+tsep)+decimals},strRight:function(str,sep){if(str==null)return"";str=String(str);sep=sep!=null?String(sep):sep;var pos=!sep?-1:str.indexOf(sep);return~pos?str.slice(pos+sep.length,str.length):str},strRightBack:function(str,sep){if(str==null)return"";str=String(str);sep=sep!=null?String(sep):sep;var pos=!sep?-1:str.lastIndexOf(sep);return~pos?str.slice(pos+sep.length,str.length):str},strLeft:function(str,sep){if(str==null)return"";str=String(str);sep=sep!=null?String(sep):sep;var pos=!sep?-1:str.indexOf(sep);return~pos?str.slice(0,pos):str},strLeftBack:function(str,sep){if(str==null)return"";str+="";sep=sep!=null?""+sep:sep;var pos=str.lastIndexOf(sep);return~pos?str.slice(0,pos):str},toSentence:function(array,separator,lastSeparator,serial){separator=separator||", ";lastSeparator=lastSeparator||" and ";var a=array.slice(),lastMember=a.pop();if(array.length>2&&serial)lastSeparator=_s.rtrim(separator)+lastSeparator;return a.length?a.join(separator)+lastSeparator+lastMember:lastMember},toSentenceSerial:function(){var args=slice.call(arguments);args[3]=true;return _s.toSentence.apply(_s,args)},slugify:function(str){if(str==null)return"";var from="ąàáäâãåæćęèéëêìíïîłńòóöôõøùúüûñçżź",to="aaaaaaaaceeeeeiiiilnoooooouuuunczz",regex=new RegExp(defaultToWhiteSpace(from),"g");str=String(str).toLowerCase().replace(regex,function(c){var index=from.indexOf(c);return to.charAt(index)||"-"});return _s.dasherize(str.replace(/[^\w\s-]/g,""))},surround:function(str,wrapper){return[wrapper,str,wrapper].join("")},quote:function(str){return _s.surround(str,'"')},exports:function(){var result={};for(var prop in this){if(!this.hasOwnProperty(prop)||prop.match(/^(?:include|contains|reverse)$/))continue;result[prop]=this[prop]}return result},repeat:function(str,qty,separator){if(str==null)return"";qty=~~qty;if(separator==null)return strRepeat(String(str),qty);for(var repeat=[];qty>0;repeat[--qty]=str){}return repeat.join(separator)},levenshtein:function(str1,str2){if(str1==null&&str2==null)return 0;if(str1==null)return String(str2).length;if(str2==null)return String(str1).length;str1=String(str1);str2=String(str2);var current=[],prev,value;for(var i=0;i<=str2.length;i++)for(var j=0;j<=str1.length;j++){if(i&&j)if(str1.charAt(j-1)===str2.charAt(i-1))value=prev;else value=Math.min(current[j],current[j-1],prev)+1;else value=i+j;prev=current[j];current[j]=value}return current.pop()}};_s.strip=_s.trim;_s.lstrip=_s.ltrim;_s.rstrip=_s.rtrim;_s.center=_s.lrpad;_s.rjust=_s.lpad;_s.ljust=_s.rpad;_s.contains=_s.include;_s.q=_s.quote;if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)module.exports=_s;exports._s=_s}if(typeof define==="function"&&define.amd)define("underscore.string",[],function(){return _s});root._=root._||{};root._.string=root._.str=_s}(this,String);define("ext/underscore",["underscore.string"],function(_s){var self=_;_.mixin(_s.exports());_.mixin({assert:function(outcome,description){if(!outcome){throw description||"assertion failed"}},getProperty:function(object,property){if(object&&object[property]){if(self.isFunction(object[property])){return object[property].apply(object)}return object[property]}return null},bindToMethods:function(obj){var funcs=self.functions(obj);self.each(funcs,function(f){obj[f]=self.bind(obj[f],obj)});return obj}});return _.noConflict()});define("jquery",[],function(){return jQuery});!function(a){"function"==typeof define&&define.amd?define("picker",["jquery"],a):"object"==typeof exports?module.exports=a(require("jquery")):this.Picker=a(jQuery)}(function(a){function b(f,g,i,m){function n(){return b._.node("div",b._.node("div",b._.node("div",b._.node("div",B.component.nodes(w.open),y.box),y.wrap),y.frame),y.holder,'tabindex="-1"')}function o(){z.data(g,B).addClass(y.input).val(z.data("value")?B.get("select",x.format):f.value),x.editable||z.on("focus."+w.id+" click."+w.id,function(a){a.preventDefault(),B.open()}).on("keydown."+w.id,u),e(f,{haspopup:!0,expanded:!1,readonly:!1,owns:f.id+"_root"})}function p(){e(B.$root[0],"hidden",!0)}function q(){B.$holder.on({keydown:u,"focus.toOpen":t,blur:function(){z.removeClass(y.target)},focusin:function(a){B.$root.removeClass(y.focused),a.stopPropagation()},"mousedown click":function(b){var c=b.target;c!=B.$holder[0]&&(b.stopPropagation(),"mousedown"!=b.type||a(c).is("input, select, textarea, button, option")||(b.preventDefault(),B.$holder[0].focus()))}}).on("click","[data-pick], [data-nav], [data-clear], [data-close]",function(){var b=a(this),c=b.data(),d=b.hasClass(y.navDisabled)||b.hasClass(y.disabled),e=h();e=e&&(e.type||e.href),(d||e&&!a.contains(B.$root[0],e))&&B.$holder[0].focus(),!d&&c.nav?B.set("highlight",B.component.item.highlight,{nav:c.nav}):!d&&"pick"in c?(B.set("select",c.pick),x.closeOnSelect&&B.close(!0)):c.clear?(B.clear(),x.closeOnClear&&B.close(!0)):c.close&&B.close(!0)})}function r(){var b;x.hiddenName===!0?(b=f.name,f.name=""):(b=["string"==typeof x.hiddenPrefix?x.hiddenPrefix:"","string"==typeof x.hiddenSuffix?x.hiddenSuffix:"_submit"],b=b[0]+f.name+b[1]),B._hidden=a('<input type=hidden name="'+b+'"'+(z.data("value")||f.value?' value="'+B.get("select",x.formatSubmit)+'"':"")+">")[0],z.on("change."+w.id,function(){B._hidden.value=f.value?B.get("select",x.formatSubmit):""})}function s(){v&&l?B.$holder.find("."+y.frame).one("transitionend",function(){B.$holder[0].focus()}):B.$holder[0].focus()}function t(a){a.stopPropagation(),z.addClass(y.target),B.$root.addClass(y.focused),B.open()}function u(a){var b=a.keyCode,c=/^(8|46)$/.test(b);return 27==b?(B.close(!0),!1):void((32==b||c||!w.open&&B.component.key[b])&&(a.preventDefault(),a.stopPropagation(),c?B.clear().close():B.open()))}if(!f)return b;var v=!1,w={id:f.id||"P"+Math.abs(~~(Math.random()*new Date))},x=i?a.extend(!0,{},i.defaults,m):m||{},y=a.extend({},b.klasses(),x.klass),z=a(f),A=function(){return this.start()},B=A.prototype={constructor:A,$node:z,start:function(){return w&&w.start?B:(w.methods={},w.start=!0,w.open=!1,w.type=f.type,f.autofocus=f==h(),f.readOnly=!x.editable,f.id=f.id||w.id,"text"!=f.type&&(f.type="text"),B.component=new i(B,x),B.$root=a('<div class="'+y.picker+'" id="'+f.id+'_root" />'),p(),B.$holder=a(n()).appendTo(B.$root),q(),x.formatSubmit&&r(),o(),x.containerHidden?a(x.containerHidden).append(B._hidden):z.after(B._hidden),x.container?a(x.container).append(B.$root):z.after(B.$root),B.on({start:B.component.onStart,render:B.component.onRender,stop:B.component.onStop,open:B.component.onOpen,close:B.component.onClose,set:B.component.onSet}).on({start:x.onStart,render:x.onRender,stop:x.onStop,open:x.onOpen,close:x.onClose,set:x.onSet}),v=c(B.$holder[0]),f.autofocus&&B.open(),B.trigger("start").trigger("render"))},render:function(a){return a?(B.$holder=n(),B.$root.html(B.$holder)):B.$root.find("."+y.box).html(B.component.nodes(w.open)),B.trigger("render")},stop:function(){return w.start?(B.close(),B._hidden&&B._hidden.parentNode.removeChild(B._hidden),B.$root.remove(),z.removeClass(y.input).removeData(g),setTimeout(function(){z.off("."+w.id)},0),f.type=w.type,f.readOnly=!1,B.trigger("stop"),w.methods={},w.start=!1,B):B},open:function(c){return w.open?B:(z.addClass(y.active),e(f,"expanded",!0),setTimeout(function(){B.$root.addClass(y.opened),e(B.$root[0],"hidden",!1)},0),c!==!1&&(w.open=!0,v&&k.css("overflow","hidden").css("padding-right","+="+d()),s(),j.on("click."+w.id+" focusin."+w.id,function(a){var b=a.target;b!=f&&b!=document&&3!=a.which&&B.close(b===B.$holder[0])}).on("keydown."+w.id,function(c){var d=c.keyCode,e=B.component.key[d],f=c.target;27==d?B.close(!0):f!=B.$holder[0]||!e&&13!=d?a.contains(B.$root[0],f)&&13==d&&(c.preventDefault(),f.click()):(c.preventDefault(),e?b._.trigger(B.component.key.go,B,[b._.trigger(e)]):B.$root.find("."+y.highlighted).hasClass(y.disabled)||(B.set("select",B.component.item.highlight),x.closeOnSelect&&B.close(!0)))})),B.trigger("open"))},close:function(a){return a&&(x.editable?f.focus():(B.$holder.off("focus.toOpen").focus(),setTimeout(function(){B.$holder.on("focus.toOpen",t)},0))),z.removeClass(y.active),e(f,"expanded",!1),setTimeout(function(){B.$root.removeClass(y.opened+" "+y.focused),e(B.$root[0],"hidden",!0)},0),w.open?(w.open=!1,v&&k.css("overflow","").css("padding-right","-="+d()),j.off("."+w.id),B.trigger("close")):B},clear:function(a){return B.set("clear",null,a)},set:function(b,c,d){var e,f,g=a.isPlainObject(b),h=g?b:{};if(d=g&&a.isPlainObject(c)?c:d||{},b){g||(h[b]=c);for(e in h)f=h[e],e in B.component.item&&(void 0===f&&(f=null),B.component.set(e,f,d)),("select"==e||"clear"==e)&&z.val("clear"==e?"":B.get(e,x.format)).trigger("change");B.render()}return d.muted?B:B.trigger("set",h)},get:function(a,c){if(a=a||"value",null!=w[a])return w[a];if("valueSubmit"==a){if(B._hidden)return B._hidden.value;a="value"}if("value"==a)return f.value;if(a in B.component.item){if("string"==typeof c){var d=B.component.get(a);return d?b._.trigger(B.component.formats.toString,B.component,[c,d]):""}return B.component.get(a)}},on:function(b,c,d){var e,f,g=a.isPlainObject(b),h=g?b:{};if(b){g||(h[b]=c);for(e in h)f=h[e],d&&(e="_"+e),w.methods[e]=w.methods[e]||[],w.methods[e].push(f)}return B},off:function(){var a,b,c=arguments;for(a=0,namesCount=c.length;a<namesCount;a+=1)b=c[a],b in w.methods&&delete w.methods[b];return B},trigger:function(a,c){var d=function(a){var d=w.methods[a];d&&d.map(function(a){b._.trigger(a,B,[c])})};return d("_"+a),d(a),B}};return new A}function c(a){var b,c="position";return a.currentStyle?b=a.currentStyle[c]:window.getComputedStyle&&(b=getComputedStyle(a)[c]),"fixed"==b}function d(){if(k.height()<=i.height())return 0;var b=a('<div style="visibility:hidden;width:100px" />').appendTo("body"),c=b[0].offsetWidth;b.css("overflow","scroll");var d=a('<div style="width:100%" />').appendTo(b),e=d[0].offsetWidth;return b.remove(),c-e}function e(b,c,d){if(a.isPlainObject(c))for(var e in c)f(b,e,c[e]);else f(b,c,d)}function f(a,b,c){a.setAttribute(("role"==b?"":"aria-")+b,c)}function g(b,c){a.isPlainObject(b)||(b={attribute:c}),c="";for(var d in b){var e=("role"==d?"":"aria-")+d,f=b[d];c+=null==f?"":e+'="'+b[d]+'"'}return c}function h(){try{return document.activeElement}catch(a){}}var i=a(window),j=a(document),k=a(document.documentElement),l=null!=document.body.style.transition;return b.klasses=function(a){return a=a||"picker",{picker:a,opened:a+"--opened",focused:a+"--focused",input:a+"__input",active:a+"__input--active",target:a+"__input--target",holder:a+"__holder",frame:a+"__frame",wrap:a+"__wrap",box:a+"__box"}},b._={group:function(a){for(var c,d="",e=b._.trigger(a.min,a);e<=b._.trigger(a.max,a,[e]);e+=a.i)c=b._.trigger(a.item,a,[e]),d+=b._.node(a.node,c[0],c[1],c[2]);return d},node:function(b,c,d,e){return c?(c=a.isArray(c)?c.join(""):c,d=d?' class="'+d+'"':"",e=e?" "+e:"","<"+b+d+e+">"+c+"</"+b+">"):""},lead:function(a){return(10>a?"0":"")+a},trigger:function(a,b,c){return"function"==typeof a?a.apply(b,c||[]):a},digits:function(a){return/\d/.test(a[1])?2:1},isDate:function(a){return{}.toString.call(a).indexOf("Date")>-1&&this.isInteger(a.getDate())},isInteger:function(a){return{}.toString.call(a).indexOf("Number")>-1&&a%1===0},ariaAttr:g},b.extend=function(c,d){a.fn[c]=function(e,f){var g=this.data(c);return"picker"==e?g:g&&"string"==typeof e?b._.trigger(g[e],g,[f]):this.each(function(){var f=a(this);f.data(c)||new b(this,c,d,e)})},a.fn[c].defaults=d.defaults},b});!function(a){"function"==typeof define&&define.amd?define("lib/pickadate.min",["picker","jquery"],a):"object"==typeof exports?module.exports=a(require("./picker.js"),require("jquery")):a(Picker,jQuery)}(function(a,b){function c(a,b){var c=this,d=a.$node[0],e=d.value,f=a.$node.data("value"),g=f||e,h=f?b.formatSubmit:b.format,i=function(){return d.currentStyle?"rtl"==d.currentStyle.direction:"rtl"==getComputedStyle(a.$root[0]).direction};c.settings=b,c.$node=a.$node,c.queue={min:"measure create",max:"measure create",now:"now create",select:"parse create validate",highlight:"parse navigate create validate",view:"parse create validate viewset",disable:"deactivate",enable:"activate"},c.item={},c.item.clear=null,c.item.disable=(b.disable||[]).slice(0),c.item.enable=-function(a){return a[0]===!0?a.shift():-1}(c.item.disable),c.set("min",b.min).set("max",b.max).set("now"),g?c.set("select",g,{format:h,defaultValue:!0}):c.set("select",null).set("highlight",c.item.now),c.key={40:7,38:-7,39:function(){return i()?-1:1},37:function(){return i()?1:-1},go:function(a){var b=c.item.highlight,d=new Date(b.year,b.month,b.date+a);c.set("highlight",d,{interval:a}),this.render()}},a.on("render",function(){a.$root.find("."+b.klass.selectMonth).on("change",function(){var c=this.value;c&&(a.set("highlight",[a.get("view").year,c,a.get("highlight").date]),a.$root.find("."+b.klass.selectMonth).trigger("focus"))}),a.$root.find("."+b.klass.selectYear).on("change",function(){var c=this.value;c&&(a.set("highlight",[c,a.get("view").month,a.get("highlight").date]),a.$root.find("."+b.klass.selectYear).trigger("focus"));
     7
     8})},1).on("open",function(){var d="";c.disabled(c.get("now"))&&(d=":not(."+b.klass.buttonToday+")"),a.$root.find("button"+d+", select").attr("disabled",!1)},1).on("close",function(){a.$root.find("button, select").attr("disabled",!0)},1)}var d=7,e=6,f=a._;c.prototype.set=function(a,b,c){var d=this,e=d.item;return null===b?("clear"==a&&(a="select"),e[a]=b,d):(e["enable"==a?"disable":"flip"==a?"enable":a]=d.queue[a].split(" ").map(function(e){return b=d[e](a,b,c)}).pop(),"select"==a?d.set("highlight",e.select,c):"highlight"==a?d.set("view",e.highlight,c):a.match(/^(flip|min|max|disable|enable)$/)&&(e.select&&d.disabled(e.select)&&d.set("select",e.select,c),e.highlight&&d.disabled(e.highlight)&&d.set("highlight",e.highlight,c)),d)},c.prototype.get=function(a){return this.item[a]},c.prototype.create=function(a,c,d){var e,g=this;return c=void 0===c?a:c,c==-1/0||1/0==c?e=c:b.isPlainObject(c)&&f.isInteger(c.pick)?c=c.obj:b.isArray(c)?(c=new Date(c[0],c[1],c[2]),c=f.isDate(c)?c:g.create().obj):c=f.isInteger(c)||f.isDate(c)?g.normalize(new Date(c),d):g.now(a,c,d),{year:e||c.getFullYear(),month:e||c.getMonth(),date:e||c.getDate(),day:e||c.getDay(),obj:e||c,pick:e||c.getTime()}},c.prototype.createRange=function(a,c){var d=this,e=function(a){return a===!0||b.isArray(a)||f.isDate(a)?d.create(a):a};return f.isInteger(a)||(a=e(a)),f.isInteger(c)||(c=e(c)),f.isInteger(a)&&b.isPlainObject(c)?a=[c.year,c.month,c.date+a]:f.isInteger(c)&&b.isPlainObject(a)&&(c=[a.year,a.month,a.date+c]),{from:e(a),to:e(c)}},c.prototype.withinRange=function(a,b){return a=this.createRange(a.from,a.to),b.pick>=a.from.pick&&b.pick<=a.to.pick},c.prototype.overlapRanges=function(a,b){var c=this;return a=c.createRange(a.from,a.to),b=c.createRange(b.from,b.to),c.withinRange(a,b.from)||c.withinRange(a,b.to)||c.withinRange(b,a.from)||c.withinRange(b,a.to)},c.prototype.now=function(a,b,c){return b=new Date,c&&c.rel&&b.setDate(b.getDate()+c.rel),this.normalize(b,c)},c.prototype.navigate=function(a,c,d){var e,f,g,h,i=b.isArray(c),j=b.isPlainObject(c),k=this.item.view;if(i||j){for(j?(f=c.year,g=c.month,h=c.date):(f=+c[0],g=+c[1],h=+c[2]),d&&d.nav&&k&&k.month!==g&&(f=k.year,g=k.month),e=new Date(f,g+(d&&d.nav?d.nav:0),1),f=e.getFullYear(),g=e.getMonth();new Date(f,g,h).getMonth()!==g;)h-=1;c=[f,g,h]}return c},c.prototype.normalize=function(a){return a.setHours(0,0,0,0),a},c.prototype.measure=function(a,b){var c=this;return b?"string"==typeof b?b=c.parse(a,b):f.isInteger(b)&&(b=c.now(a,b,{rel:b})):b="min"==a?-1/0:1/0,b},c.prototype.viewset=function(a,b){return this.create([b.year,b.month,1])},c.prototype.validate=function(a,c,d){var e,g,h,i,j=this,k=c,l=d&&d.interval?d.interval:1,m=-1===j.item.enable,n=j.item.min,o=j.item.max,p=m&&j.item.disable.filter(function(a){if(b.isArray(a)){var d=j.create(a).pick;d<c.pick?e=!0:d>c.pick&&(g=!0)}return f.isInteger(a)}).length;if((!d||!d.nav&&!d.defaultValue)&&(!m&&j.disabled(c)||m&&j.disabled(c)&&(p||e||g)||!m&&(c.pick<=n.pick||c.pick>=o.pick)))for(m&&!p&&(!g&&l>0||!e&&0>l)&&(l*=-1);j.disabled(c)&&(Math.abs(l)>1&&(c.month<k.month||c.month>k.month)&&(c=k,l=l>0?1:-1),c.pick<=n.pick?(h=!0,l=1,c=j.create([n.year,n.month,n.date+(c.pick===n.pick?0:-1)])):c.pick>=o.pick&&(i=!0,l=-1,c=j.create([o.year,o.month,o.date+(c.pick===o.pick?0:1)])),!h||!i);)c=j.create([c.year,c.month,c.date+l]);return c},c.prototype.disabled=function(a){var c=this,d=c.item.disable.filter(function(d){return f.isInteger(d)?a.day===(c.settings.firstDay?d:d-1)%7:b.isArray(d)||f.isDate(d)?a.pick===c.create(d).pick:b.isPlainObject(d)?c.withinRange(d,a):void 0});return d=d.length&&!d.filter(function(a){return b.isArray(a)&&"inverted"==a[3]||b.isPlainObject(a)&&a.inverted}).length,-1===c.item.enable?!d:d||a.pick<c.item.min.pick||a.pick>c.item.max.pick},c.prototype.parse=function(a,b,c){var d=this,e={};return b&&"string"==typeof b?(c&&c.format||(c=c||{},c.format=d.settings.format),d.formats.toArray(c.format).map(function(a){var c=d.formats[a],g=c?f.trigger(c,d,[b,e]):a.replace(/^!/,"").length;c&&(e[a]=b.substr(0,g)),b=b.substr(g)}),[e.yyyy||e.yy,+(e.mm||e.m)-1,e.dd||e.d]):b},c.prototype.formats=function(){function a(a,b,c){var d=a.match(/[^\x00-\x7F]+|\w+/)[0];return c.mm||c.m||(c.m=b.indexOf(d)+1),d.length}function b(a){return a.match(/\w+/)[0].length}return{d:function(a,b){return a?f.digits(a):b.date},dd:function(a,b){return a?2:f.lead(b.date)},ddd:function(a,c){return a?b(a):this.settings.weekdaysShort[c.day]},dddd:function(a,c){return a?b(a):this.settings.weekdaysFull[c.day]},m:function(a,b){return a?f.digits(a):b.month+1},mm:function(a,b){return a?2:f.lead(b.month+1)},mmm:function(b,c){var d=this.settings.monthsShort;return b?a(b,d,c):d[c.month]},mmmm:function(b,c){var d=this.settings.monthsFull;return b?a(b,d,c):d[c.month]},yy:function(a,b){return a?2:(""+b.year).slice(2)},yyyy:function(a,b){return a?4:b.year},toArray:function(a){return a.split(/(d{1,4}|m{1,4}|y{4}|yy|!.)/g)},toString:function(a,b){var c=this;return c.formats.toArray(a).map(function(a){return f.trigger(c.formats[a],c,[0,b])||a.replace(/^!/,"")}).join("")}}}(),c.prototype.isDateExact=function(a,c){var d=this;return f.isInteger(a)&&f.isInteger(c)||"boolean"==typeof a&&"boolean"==typeof c?a===c:(f.isDate(a)||b.isArray(a))&&(f.isDate(c)||b.isArray(c))?d.create(a).pick===d.create(c).pick:b.isPlainObject(a)&&b.isPlainObject(c)?d.isDateExact(a.from,c.from)&&d.isDateExact(a.to,c.to):!1},c.prototype.isDateOverlap=function(a,c){var d=this,e=d.settings.firstDay?1:0;return f.isInteger(a)&&(f.isDate(c)||b.isArray(c))?(a=a%7+e,a===d.create(c).day+1):f.isInteger(c)&&(f.isDate(a)||b.isArray(a))?(c=c%7+e,c===d.create(a).day+1):b.isPlainObject(a)&&b.isPlainObject(c)?d.overlapRanges(a,c):!1},c.prototype.flipEnable=function(a){var b=this.item;b.enable=a||(-1==b.enable?1:-1)},c.prototype.deactivate=function(a,c){var d=this,e=d.item.disable.slice(0);return"flip"==c?d.flipEnable():c===!1?(d.flipEnable(1),e=[]):c===!0?(d.flipEnable(-1),e=[]):c.map(function(a){for(var c,g=0;g<e.length;g+=1)if(d.isDateExact(a,e[g])){c=!0;break}c||(f.isInteger(a)||f.isDate(a)||b.isArray(a)||b.isPlainObject(a)&&a.from&&a.to)&&e.push(a)}),e},c.prototype.activate=function(a,c){var d=this,e=d.item.disable,g=e.length;return"flip"==c?d.flipEnable():c===!0?(d.flipEnable(1),e=[]):c===!1?(d.flipEnable(-1),e=[]):c.map(function(a){var c,h,i,j;for(i=0;g>i;i+=1){if(h=e[i],d.isDateExact(h,a)){c=e[i]=null,j=!0;break}if(d.isDateOverlap(h,a)){b.isPlainObject(a)?(a.inverted=!0,c=a):b.isArray(a)?(c=a,c[3]||c.push("inverted")):f.isDate(a)&&(c=[a.getFullYear(),a.getMonth(),a.getDate(),"inverted"]);break}}if(c)for(i=0;g>i;i+=1)if(d.isDateExact(e[i],a)){e[i]=null;break}if(j)for(i=0;g>i;i+=1)if(d.isDateOverlap(e[i],a)){e[i]=null;break}c&&e.push(c)}),e.filter(function(a){return null!=a})},c.prototype.nodes=function(a){var b=this,c=b.settings,g=b.item,h=g.now,i=g.select,j=g.highlight,k=g.view,l=g.disable,m=g.min,n=g.max,o=function(a,b){return c.firstDay&&(a.push(a.shift()),b.push(b.shift())),f.node("thead",f.node("tr",f.group({min:0,max:d-1,i:1,node:"th",item:function(d){return[a[d],c.klass.weekdays,'scope=col title="'+b[d]+'"']}})))}((c.showWeekdaysFull?c.weekdaysFull:c.weekdaysShort).slice(0),c.weekdaysFull.slice(0)),p=function(a){return f.node("div"," ",c.klass["nav"+(a?"Next":"Prev")]+(a&&k.year>=n.year&&k.month>=n.month||!a&&k.year<=m.year&&k.month<=m.month?" "+c.klass.navDisabled:""),"data-nav="+(a||-1)+" "+f.ariaAttr({role:"button",controls:b.$node[0].id+"_table"})+' title="'+(a?c.labelMonthNext:c.labelMonthPrev)+'"')},q=function(){var d=c.showMonthsShort?c.monthsShort:c.monthsFull;return c.selectMonths?f.node("select",f.group({min:0,max:11,i:1,node:"option",item:function(a){return[d[a],0,"value="+a+(k.month==a?" selected":"")+(k.year==m.year&&a<m.month||k.year==n.year&&a>n.month?" disabled":"")]}}),c.klass.selectMonth,(a?"":"disabled")+" "+f.ariaAttr({controls:b.$node[0].id+"_table"})+' title="'+c.labelMonthSelect+'"'):f.node("div",d[k.month],c.klass.month)},r=function(){var d=k.year,e=c.selectYears===!0?5:~~(c.selectYears/2);if(e){var g=m.year,h=n.year,i=d-e,j=d+e;if(g>i&&(j+=g-i,i=g),j>h){var l=i-g,o=j-h;i-=l>o?o:l,j=h}return f.node("select",f.group({min:i,max:j,i:1,node:"option",item:function(a){return[a,0,"value="+a+(d==a?" selected":"")]}}),c.klass.selectYear,(a?"":"disabled")+" "+f.ariaAttr({controls:b.$node[0].id+"_table"})+' title="'+c.labelYearSelect+'"')}return f.node("div",d,c.klass.year)};return f.node("div",(c.selectYears?r()+q():q()+r())+p()+p(1),c.klass.header)+f.node("table",o+f.node("tbody",f.group({min:0,max:e-1,i:1,node:"tr",item:function(a){var e=c.firstDay&&0===b.create([k.year,k.month,1]).day?-7:0;return[f.group({min:d*a-k.day+e+1,max:function(){return this.min+d-1},i:1,node:"td",item:function(a){a=b.create([k.year,k.month,a+(c.firstDay?1:0)]);var d=i&&i.pick==a.pick,e=j&&j.pick==a.pick,g=l&&b.disabled(a)||a.pick<m.pick||a.pick>n.pick,o=f.trigger(b.formats.toString,b,[c.format,a]);return[f.node("div",a.date,function(b){return b.push(k.month==a.month?c.klass.infocus:c.klass.outfocus),h.pick==a.pick&&b.push(c.klass.now),d&&b.push(c.klass.selected),e&&b.push(c.klass.highlighted),g&&b.push(c.klass.disabled),b.join(" ")}([c.klass.day]),"data-pick="+a.pick+" "+f.ariaAttr({role:"gridcell",label:o,selected:d&&b.$node.val()===o?!0:null,activedescendant:e?!0:null,disabled:g?!0:null})),"",f.ariaAttr({role:"presentation"})]}})]}})),c.klass.table,'id="'+b.$node[0].id+'_table" '+f.ariaAttr({role:"grid",controls:b.$node[0].id,readonly:!0}))+f.node("div",f.node("button",c.today,c.klass.buttonToday,"type=button data-pick="+h.pick+(a&&!b.disabled(h)?"":" disabled")+" "+f.ariaAttr({controls:b.$node[0].id}))+f.node("button",c.clear,c.klass.buttonClear,"type=button data-clear=1"+(a?"":" disabled")+" "+f.ariaAttr({controls:b.$node[0].id}))+f.node("button",c.close,c.klass.buttonClose,"type=button data-close=true "+(a?"":" disabled")+" "+f.ariaAttr({controls:b.$node[0].id})),c.klass.footer)},c.defaults=function(a){return{labelMonthNext:"Next month",labelMonthPrev:"Previous month",labelMonthSelect:"Select a month",labelYearSelect:"Select a year",monthsFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],weekdaysFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],weekdaysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],today:"Today",clear:"Clear",close:"Close",closeOnSelect:!0,closeOnClear:!0,format:"d mmmm, yyyy",klass:{table:a+"table",header:a+"header",navPrev:a+"nav--prev",navNext:a+"nav--next",navDisabled:a+"nav--disabled",month:a+"month",year:a+"year",selectMonth:a+"select--month",selectYear:a+"select--year",weekdays:a+"weekday",day:a+"day",disabled:a+"day--disabled",selected:a+"day--selected",highlighted:a+"day--highlighted",now:a+"day--today",infocus:a+"day--infocus",outfocus:a+"day--outfocus",footer:a+"footer",buttonClear:a+"button--clear",buttonToday:a+"button--today",buttonClose:a+"button--close"}}}(a.klasses().picker+"__"),a.extend("pickadate",c)});define("native",["ext/underscore","lib/pickadate.min","$root"],function(_,pickadate,$root){var $=jQuery;var _navigate=function(hash){if(window.location.hash==hash){Backbone.history.loadUrl(hash)}else{window.location.hash=hash}window.localStorage.setItem("location",hash)};var _native={popupPreview:true,searchBarAdjust:0,height:function(){return $root.height()},width:function(){return $root.width()},start:function(callback){callback($root.data())},online:function(callback){callback(true)},preview:function(link){$(".loader").addClass("hidden");var $iframe=$("<iframe>").css({margin:"0 auto",display:"block",height:"600px"}).attr("src",link);$(".modal-dialog").css("width","800px");$(".modal-title").html("Document Preview");$(".modal-body").html($iframe);$(".modal").modal("show");$(".modal-dialog").css("margin-left",function(){return($(window).width()-$(this).width())/2})},setHeader:function(options){var message=_.pick(options,"title","nosearch");if(options.back){message.back=_.pick(options.back,"text","link")}message.actions=[];_.each(options.actions,function(action){message.actions.push(_.pick(action,"text","icon","link","target"))});handleHeader(message)},list:true,datepicker:function($el){$(".date",$el).pickadate({format:"dd mmm, yyyy",today:"",klass:{buttonClear:"btn",buttonClose:"btn"},onSet:function(context){var $dueTime=$(".time",$el);if(context.select){$dueTime.attr("disabled",false)}else{$dueTime.attr("disabled",true).val("")}}})}};var createLink=function(data){var a=$("<a>").attr("href","javascript:void(0);").data("target",data);if(data.icon){a.addClass("glyphicon glyphicon-"+data.icon).attr("title",data.text)}else{a.html(data.text)}return a};var $header=$(">.header",$root).removeClass("hidden").on("click","a",function(e){e.preventDefault();var data=$(this).data("target");if(data.target){$(data.target).trigger("action")}else if(data.link){_navigate(data.link)}else{$buttons.addClass("hidden");$search.removeClass("hidden").focus()}});var $buttons=$("span",$header);var $search=$("input",$header).keyup(function(e){if(e.keyCode==27){$buttons.removeClass("hidden");$search.addClass("hidden")}else if(e.keyCode==13){_navigate("#search/"+encodeURIComponent($search.val()));$buttons.removeClass("hidden");$search.addClass("hidden").val("")}});var handleHeader=function(options){var $left=$(".left",$header).empty();if(options.back){createLink(options.back).appendTo($left)}$left.append("<strong>"+options.title+"</strong>");var $action=$(".right",$header).empty();_.each(options.actions,function(action){createLink(action).appendTo($action)});if(!options.nosearch){createLink({text:"Search",icon:"search"}).appendTo($action)}};$(">.wrapper",$root).data("marginals",1).height(_native.height()-44);return _native});define("notifications",["ext/underscore","$root"],function(_,$root){var _navigate=function(hash){Backbone.history.loadUrl(hash);window.localStorage.setItem("location",hash)};var notificationUrls={};var $=jQuery;var $notifications=$(".notifications",$root);$notifications.off().click(function(e){e.preventDefault();var keys=_.keys(notificationUrls);var nextUrl=keys.pop();delete notificationUrls[nextUrl];_navigate(nextUrl);if(keys.length==0){$notifications.addClass("hidden")}else{$notifications.find("span").html(keys.length)}});return{addNotification:function(notification){notificationUrls[notification.target]=true;$notifications.removeClass("hidden").find("span").html(_.keys(notificationUrls).length)}}});define("messages",["ext/underscore"],function(_){var messages={m_last_updated:"Last updated",m_said:"said",m_comments:"Comments",m_comment:"Comment",m_share:"Share",m_shares:"Shared With",m_share_contact:"Share With Contact",m_new:"New",m_reply:"Reply",m_back:"Back",m_cancel:"Cancel",m_file:"File",m_page:"Note",m_discussion:"Discussion",m_event:"Event",m_task:"Task",m_edit:"Edit",m_post:"Post",m_save:"Save",m_preview:"Preview",m_download:"Download",m_search:"Search",m_on:"On",m_by:"by",m_all_day:"All day",m_to:"to",m_at:"at",m_version:"Version",m_size:"Size",m_today:"Today",m_tomorrow:"Tomorrow",m_assign:"Assign",m_mention:"Mention",m_mention_title:"Select A Person",m_make_comment:"Make A Comment",m_create_reply:"Create A Reply",m_create_discussion:"Create A Discussion",m_discussion_topic:"Enter Discussion Topic",m_discussion_first:"Enter First Comment",m_create_task:"Create A Task",m_update_task:"Update Task",m_task_title:"Enter Task Title",m_task_description:"Enter Task Description",m_task_duedate:"Select Due Date and Time, if applicable",m_task_status_NOT_STARTED:"Not Started",m_task_status_IN_PROGRESS:"In Progress",m_task_status_DEFERRED:"Deferred",m_task_status_WAITING:"Waiting",m_task_status_COMPLETED:"Complete",m_create_event:"Create An Event",m_update_event:"Update Event",m_event_title:"Enter Event Title",m_event_location:"Enter Event Location",m_event_startdate:"Select Start Date and Time, if applicable",m_event_enddate:"Select End Date and Time, if applicable",m_event_description:"Enter Event Description",m_actions_filter:"Filter",m_actions_sort:"Sort",m_actions_upload:"Upload",m_btn_context:"Groups",m_btn_updates:"Activity",m_btn_files:"Files",m_btn_notes:"Notes",m_btn_discussions:"Disc..",m_btn_events:"Events",m_btn_tasks:"Tasks",m_context_select_header:"Select group or account",m_context_signout:"Sign out",m_context_dashboard:"Dashboard",m_context_personal:"Personal",m_page_loading:"Loading..",m_updates_nothing:"Nothing yet..",m_files_nothing:"No files",m_notes_nothing:"No Notes",m_discussions_nothing:"No Discussions",m_events_nothing:"No Events",m_tasks_nothing:"No Tasks",m_comments_nothing:"No Comments",m_share_tokens_nothing:"Not Shared",m_share_input:"Start typing the email or name of your contact",m_email_input_error:"This is not a valid email address",m_search_nothing:"No Results",m_search_suggestions:"Did you mean",m_type_here:"Start typing here",m_file_uploader:"Uploaded by",m_file_preview_waiting:"Preview Generating ..",m_file_preview_failed:"No Preview Available",m_file_upload_header:"Upload A File",m_file_upload_failure:"Failed",m_file_upload_success:"Complete!",m_file_upload_add:"Add Files...",m_file_upload_start:"Start Upload",m_file_upload_cancel:"Cancel",m_file_upload_upload:"Upload",m_file_upload_retry:"Retry",m_file_upload_stop:"Stop",m_file_upload_remove:"Remove",m_file_native_header:"Select A File",m_file_native_failure:"There has been an error. Click to retry.",m_file_native_success:" has been uploaded",m_no_groups:"You do not have any groups",m_actions_sort_header:"Choose Sorting Option",m_actions_sort_latest:"Sort by most recent",m_actions_sort_name:"Sort by name",m_update_unknown:"Unknown Message",m_tasks_actions_header:"Choose Task Filter",m_tasks_actions_tbc:"Uncompleted",m_tasks_actions_all:"All Tasks",m_tasks_overdue:"Overdue",m_tasks_no_due_date:"No due date",m_tasks_requested_by:"Requested by",m_signin_title:"Sign in to Clinked",m_signin_domain:"Private Cloud Users Click Here",m_signin_username:"Enter username or email",m_signin_password:"Enter password",m_signin_signin:"Sign in",m_signin_linkedin:"Sign in using LinkedIn",m_signin_google:"Sign in using Google",m_signin_forgotten:"Forgotten Password?",m_signin_invalid:"Invalid username or password. Please try again.",m_signup_header:"Sign up to Clinked",m_signup_signup:"Sign up",m_reset_header:"Reset your Password",m_reset_reset:"Reset",m_input_signup:"Sign up",m_input_name:"Enter full name",m_input_error_name:"Please provide your full name",m_input_username:"Enter username",m_input_error_username:"Provide username",m_input_error_taken:"Username is taken, please choose again",m_input_password:"Enter password",m_input_error_password:"Provide password",m_input_error_minimum_6:"Minimum password length is 6 characters",m_input_confirm:"Re-enter password",m_input_error_mismatch:"Passwords do not match",m_input_error_confirm:"Confirm your password",m_input_telephone:"Enter phone number",m_input_organisation:"Enter organisation name",m_error_title:"Error",m_error_unexpected:"An unexpected error has occurred.",m_error_not_found:"The requested resource cannot be found.",m_error_dashboard:"Go To Dashboard",m_error_retry:"Retry",m_error_network:"Check your connection and try again.",m_error_invite:"This invitation has not been recognised.",m_error_startdate:"A start date must be given.",m_error_enddate:"An end date must be given.",m_error_time:"The time should be between 00:00 and 23:59.",m_error_date_range:'The date must be after "{0}"',m_domain_title:"Change Domain",m_domain_value:"Enter new domain",m_domain_change:"Change",m_domain_reset:"Reset",m_forgotten_title:"Forgotten Password Request",m_forgotten_email:"Please enter your email address",m_forgotten_request:"Request",m_forgotten_request_sent:"Password reset instructions have been sent to your email address.",m_forgotten_request_fail:"Sorry, there is no account registered with that email address.",m_list_pull_to_refresh:"Pull and release to refresh",m_event_location:"Location",m_event_places:"Places Taken",m_event_of:"out of",m_event_DECLINE:"Not attending",m_event_MAYBE:"Maybe attending",m_event_ACCEPT:"Attending",m_task_due:"Due",m_task_no_due:"No due date",m_task_progress:"Progress",m_task_REJECT:"Reject",m_task_ACCEPT:"Accept",m_request_event_NONE:"Awaiting reply",m_request_event_DECLINE:"Not attending",m_request_event_MAYBE:"Maybe attending",m_request_event_ACCEPT:"Attending",m_request_task_NONE:"Awaiting reply",m_request_task_REJECT:"Rejected",m_request_task_ACCEPT:"Accepted",m_message_placeholder:"Enter message","update.organisation.create":"{0} created account {1}","update.organisation.disable":"{0} disabled account {1}","update.organisation.enabled":"{0} enabled account {1}","update.user.private":"{0} said","update.user.profile":"{0} said to {4}","update.organisation.private":"{0} in {1} said","update.organisation.join":"{0} joined {1}","update.space.private":"{0} in {2} said","update.following.start":"{0} started following {3} in {2}","update.following.stop":"{0} stopped following {3} in {2}","update.discussion.create":"{0} created new discussion {3} in {2}","update.discussion.update":"{0} updated discussion {3} in {2}","update.discussion.createreply":"{0} replied to discussion {3} in {2}","update.space.create":"{0} created a new group {2}","update.space.join":"{0} joined {2} group","update.trash.remove":"{0} deleted group {2}","update.trash.restore":"{0} restored group {2}","update.trash.delete":"{0} deleted group {2} from {1} trash","update.filestore.create":"{0} uploaded file {3} in {2}","update.filestore.update":"{0} updated file {3} in {2}","update.filestore.folder":"{0} created folder {3} in {2}","update.filestore.rename":'{0} renamed folder "{5}" to {3} in {2}',"update.filestore.move":'{0} moved {3} to "{5}" in {2}',"update.filestore.copy":'{0} copied {3} to "{5}" in {2}',"update.filestore.approval.accept":"{0} approved file {3} in {2}","update.filestore.approval.reject":"{0} rejected file {3} in {2} ","update.event.create":"{0} created event {3} in {2}","update.event.createandassign":"{0} created event {3} in {2}","update.event.update":"{0} updated event {3} in {2}","update.event.updateandassign":"{0} updated event {3} in {2}","update.task.create":"{0} created task {3} in {2}","update.task.createandassign":"{0} created task {3} in {2}","update.task.update":"{0} updated task {3} in {2}","update.task.updateandassign":"{0} updated task {3} in {2}","update.task.complete":"{0} completed task {3} in {2}","update.task.reopen":"{0} marked task {3} as incomplete in {2}","update.attachment.create":"{0} attached file {5} to {3} in {2}","update.attachment.update":"{0} updated attachment {5} in {3}","update.comment.create":"{0} commented on {3} in {2}","update.comment.delete":"{0} deleted comment from {3} in {2}","update.comment.reply":"{0} replied on {3} in {2}","update.annotate.create":"{0} annotated {3} in {2}","update.annotate.delete":"{0} deleted annotation from {3} in {2}","update.page.create":"{0} created new page {3} in {2}","update.page.update":"{0} updated page {3} in {2}","update.page.restore":"{0} restored page {3} version {5} in {2}","update.page.renameandupdate":"{0} moved page {5} to {3} in {2}","update.space.trash.filerecord.create":"{0} deleted file {3} in {2}","update.space.trash.filerecord.attemptRestore":"{0} restored file {3} in {2}","update.space.trash.filerecord.delete":"{0} permanently deleted file {3} from {2} trash","update.space.trash.page.create":"{0} deleted page {3} in {2}","update.space.trash.page.attemptRestore":"{0} restored page {3} in {2}","update.space.trash.page.delete":"{0} permanently deleted page {3} from {2} trash","update.space.trash.discussion.create":"{0} deleted discussion {3} in {2}","update.space.trash.discussion.attemptRestore":"{0} restored discussion {3} in {2}","update.space.trash.discussion.delete":"{0} permanently deleted discussion {3} from {2} trash","update.space.trash.event.create":"{0} deleted event {3} in {2}","update.space.trash.event.attemptRestore":"{0} restored event {3} in {2}","update.space.trash.event.delete":"{0} permanently deleted event {3} from {2} trash","update.space.trash.task.create":"{0} deleted task {3} in {2}","update.space.trash.task.attemptRestore":"{0} restored task {3} in {2}","update.space.trash.task.delete":"{0} permanently deleted task {3} from {2} trash","update.space.rename":"{0} renamed group {5} to {2}","update.space.move":"{0} moved group {2} from {3}","update.space.remove":"{0} removed group {2}","update.space.restore":"{0} restored group {2} from trash","update.attachment.create.notify":"{0} attached the file {2} to {1} ","update.attachment.update.notify":"{0} updated the attachment {2} to {1}","update.discussion.createreply.notify":"{0} replied to discussion {1}","update.event.update.notify":"{0} edited the event {1}","update.event.updateandassign.notify":"{0} edited the event {1}","update.filestore.update.notify":"{0} edited the file {1}","update.filestore.folder.notify":"{0} created folder {1}","update.filestore.create.notify":"{0} created a new file {1}","update.page.update.notify":"{0} changed the page {1} ","update.page.renameandupdate.notify":"{0} changed the page {1}","update.space.trash.discussion.create.notify":"{0} deleted the discussion {1}","update.space.trash.event.create.notify":"{0} deleted the event {1}","update.space.trash.filerecord.create.notify":"{0} deleted the file {1}","update.space.trash.page.create.notify":"{0} deleted the page {1}","update.space.trash.task.create.notify":"{0} deleted the task {1}","update.space.trash.discussion.attemptRestore.notify":"{0} restored the discussion {1}","update.space.trash.event.attemptRestore.notify":"{0} restored the event {1}","update.space.trash.filerecord.attemptRestore.notify":"{0} restored the file {1}","update.space.trash.page.attemptRestore.notify":"{0} restored the page {1}","update.space.trash.task.attemptRestore.notify":"{0} restored the task {1}","update.task.complete.notify":"{0} completed the task {1}","update.task.reopen.notify":"{0} marked the task {1} as uncompleted ","update.task.update.notify":"{0} changed the task {1}","update.task.updateandassign.notify":"{0} changed the task {1}","update.comment.create.notify":"{0} commented on {1}","update.comment.reply.notify":"{0} commented on {1}"};var regional={};regional["tr"]={"update.user.private":"{0} söyledi","update.user.profile":"{0} {4} 'e söyledi","update.organisation.private":"{0} {1}'da söyledi","update.organisation.join":"{0} {1}'e katıldı","update.space.private":"{0} {2} grubunda söyledi","update.discussion.create":"{0} {2} grubunda {3} tartışmasını yarattı","update.discussion.update":"{0} {2} grubunda {3} tartışmasını güncelledi","update.discussion.createreply":"{0} {2} grubunda {3} tartışmasına yanıt verdi","update.space.create":"{0} {2} grubunu yarattı","update.space.join":"{0} {2} grubuna katıldı","update.trash.remove":"{0} {2} grubunu sildi","update.trash.restore":"{0} {2} grubunu geri getirdi","update.trash.delete":"{0} {2} grubunu {1} 'den sildi","update.filestore.create":"{0} {2} grubuna {3} dosyasını yükledi","update.filestore.update":"{0} {2} grubuna {3} dosyasını güncelledi","update.filestore.approval.accept":"{0} {2} grubunda {3} dosyasını onayladı","update.filestore.approval.reject":"{0} {2} grubunda {3} dosyasını reddetti ","update.event.create":"{0} {2} grubunda {3} etkinliğini yarattı","update.event.createandassign":"{0} {2} grubunda {3} etkinliğini yarattı","update.event.update":"{0} {2} grubunda {3} etkinliğini güncelledi","update.event.updateandassign":"{0} {2} grubunda {3} etkinliğini güncelledi","update.task.create":"{0} {2} grubunda {3} görevini yarattı","update.task.createandassign":"{0} {2} grubunda {3} görevini yarattı","update.task.update":"{0} {2} grubunda {3} görevini güncelledi","update.task.updateandassign":"{0} {2} grubunda {3} görevini güncelledi","update.task.complete":"{0} {2} grubunda {3} görevini tamamladı","update.task.reopen":"{0} {2} grubunda {3} görevini tamamladı","update.attachment.create":"{0} {5} dosyasını {2} grubunda {3} sayfasına ekledi ","update.attachment.update":"{0} {5} dosyasını {3}'de güncelledi","update.comment.create":"{0} {2} grubunda {3} sayfasına yorum yazdı ","update.comment.reply":"{0} {2} grubunda {3} yorumunu yanıtladı","update.page.create":"{0} {2} grubunda {3} sayfasını yarattı","update.page.update":"{0} {2} grubundaki {3} sayfasını güncelledi","update.page.restore":"{0} {2} grubundaki {3} sayfasının {5}. sürümünü geri yükledi","update.page.renameandupdate":"{0} {2} grubundaki {5} sayfasını {3} olarak değiştirdi","update.space.trash.filerecord.create":"{0} {3} dosyasını {2} grubundan sildi ","update.space.trash.filerecord.attemptRestore":"{0} {3} dosyasını {2} grubuna geri getirdi ","update.space.trash.filerecord.delete":"{0} {2} grubunda {3} dosyasını çöp kutusundan kalıcı olarak sildi","update.space.trash.page.create":"{0} {2} grubunda {3} sayfasını sildi","update.space.trash.page.attemptRestore":"{0} {2} grubunda {3} sayfasını geri getirdi ","update.space.trash.page.delete":"{0} {2} grubunda {3} sayfasını çöp kutusundan kalıcı olarak sildi","update.space.trash.discussion.create":"{0} {2} grubunda {3} tartışmasını sildi","update.space.trash.discussion.attemptRestore":"{0} {2} grubunda {3} tartışmasını geri getirdi","update.space.trash.discussion.delete":"{0} {2} grubunda {3} tartışmasını çöp kutusundan kalıcı olarak sildi","update.space.trash.event.create":"{0} {2} grubunda {3} etkinliğini sildi","update.space.trash.event.attemptRestore":"{0} {2} grubunda {3} etkinliğini geri getirdi","update.space.trash.event.delete":"{0} {2} grubunda {3} etkinliğini çöp kutusundan kalıcı olarak sildi","update.space.trash.task.create":"{0} {2} grubunda {3} görevini sildi","update.space.trash.task.attemptRestore":"{0} {2} grubunda {3} görevini geri getirdi","update.space.trash.task.delete":"{0} {2} grubunda {3} görevini çöp kutusundan kalıcı olarak sildi"};regional["ru"]={"update.user.private":"{0}сказал","update.user.profile":"{0}сказал{4}","update.organisation.private":"{0}в{1} указанном","update.organisation.join":"{0}регистрация {1}","update.space.private":"{0}в{2} указанном","update.discussion.create":"создал новую дискуссию {3} в","update.discussion.update":"обновление обсуждения {3} в {2}","update.discussion.createreply":"{0} ответил на обсуждении {3} в {2}","update.space.create":"{0} создана новая группа {2}","update.space.join":"{0} присоединился к {2} группе","update.trash.remove":"{0} удален из группы {2}","update.trash.restore":"{0} восстановлено группы {2}","update.trash.delete":"{0} удален группы {2} из {1} корзины","update.filestore.create":"{0} загруженный файл {3} в {2}","update.filestore.update":"{0} обновленный файл {3} в {2}","update.filestore.approval.accept":"утвержденный файл {3} в {2}","update.filestore.approval.reject":"{0} отклонил файл {3} в {2} ","update.event.create":"{0} создано событие {3} в {2}","update.event.createandassign":"{0} создано событие {3} в {2}","update.event.update":"{0} обновленно событие {3} в {2}","update.event.updateandassign":"обновленно событие {3} в {2}","update.task.create":"{0} созданной задачи {3} в {2}","update.task.createandassign":"{0} созданной задачи {3} в {2}","update.task.update":"обновленно задачи {3} в {2}","update.task.updateandassign":"обновленно задачи {3} в {2}","update.task.complete":"выполненная задача {3} в {2}","update.task.reopen":"отмечены задачи {3}, как неполное в {2}","update.attachment.create":"{0} прикрепленный файл {5} до {3} в {2}","update.attachment.update":"{0} обновленно вложение {5} в {3}","update.comment.create":"{0} прокомментировал {3} в {2}","update.comment.reply":"{0} ответил на {3} в {2}","update.page.create":"{0} создана новая страница {3} в {2}","update.page.update":"{0} обновленна страница {3} в {2}","update.page.restore":"{0} восстановлена страница {3} версии {5} в {2}","update.page.renameandupdate":"{0} переехала страница {5} в {3} в {2}",
     9"update.space.trash.filerecord.create":"{0} удаленный файл {3} в {2}","update.space.trash.filerecord.attemptRestore":"{0} восстановленный файл {3} в {2}","update.space.trash.filerecord.delete":"{0} постоянно удаляется файл {3} из {2} корзины","update.space.trash.page.create":"{0} удаленная страница {3} в {2}","update.space.trash.page.attemptRestore":"{0} восстановлена страница {3} в {2}","update.space.trash.page.delete":"{0} удалена страница {3} из {2} корзины","update.space.trash.discussion.create":"{0} удалена страница {3} из {2} корзины","update.space.trash.discussion.attemptRestore":"{0} восстановлено обсуждение {3} в {2}","update.space.trash.discussion.delete":"{0} постоянно удалено обсуждение {3} из {2} корзины","update.space.trash.event.create":"{0} удалено событие {3} в {2}","update.space.trash.event.attemptRestore":"{0} восстановлено событие {3} в {2}","update.space.trash.event.delete":"{0} постоянно удалено событие {3} из {2} корзины","update.space.trash.task.create":"удалена задача {3} в {2}","update.space.trash.task.attemptRestore":"{0} восстановлена задача {3} в {2}","update.space.trash.task.delete":"{0} постоянно удалена задача {3} из {2} корзины"};regional["it"]={"update.attachment.create":"{0} file allegati {5} di {3} in {2}","update.attachment.create.notify":"{0} ha allegato il file {2} di {1}","update.attachment.update":"{0} aggiornato file {5} di {3}","update.attachment.update.notify":"{0} aggiornato file {5} di {2}","update.comment.create":"{0} ha commentato su {3} di {2}","update.comment.create.notify":"{0} ha commentato su {1}","update.comment.delete":"{0} cancella commenti da {3} in {2}","update.comment.reply":"{0} risposte a {3} di {2}","update.comment.reply.notify":"{0} commenti su {1}","update.discussion.create":"{0} ha creato una nuova discussion {3} in {2}","update.discussion.createreply":"{0} ha risposto alla discussion {3} in {2}","update.discussion.createreply.notify":"{0} ha risposto alla discussion {1}","update.discussion.update":"{0} ha aggiornato la discussion {3} di {2}","update.event.create":"{0} ha creato l` event {3} in {2}","update.event.createandassign":"{0} {0} ha creato l` event {3} in {2}","update.event.update":"{0} event aggiornato {3} in {2}","update.event.update.notify":"{0} event modificati {1}","update.event.updateandassign":"{0} event aggiornato {3} in {2}","update.event.updateandassign.notify":"{0} event modificati {1}","update.filestore.approval.accept":"{0} file approvati {3} in {2}","update.filestore.approval.reject":"{0} file rifiutati {3} in {2}","update.filestore.copy":'{0} copiati {3} da "{5}" in {2}',"update.filestore.create":"{0} file caricati {3} in {2}","update.filestore.create.notify":"{0} nuovi file creati {3} in {2}","update.filestore.folder":"{0} cartelle create {3} in {2}","update.filestore.folder.notify":"{0} cartelle create {1}","update.filestore.move":'{0} spostato {3} da "{5}" a {2}',"update.filestore.rename":'{0} cartella rinominata "{5}" da {3} in {2}',"update.filestore.update":"{0} file caricati {3} in {2}","update.filestore.update.notify":"{0} modifca i file {1}","update.following.start":"{0} comincia a seguire {3} in {2}","update.following.stop":"{0} smette di seguire {3} in {2}","update.organisation.create":"{0} ha creato l`account {1} ","update.organisation.disable":"{0} ha disabilitato l`account {1}","update.organisation.enabled":"{0} ha abilitato l`account {1}","update.organisation.join":"{0} partecipa {1}","update.organisation.private":"{0} ha detto in {1} ","update.page.create":"{0} nuove page create {3} in {2}","update.page.renameandupdate":"{0} page spostate {5} da {3} in {2}","update.page.renameandupdate.notify":"{0} page cambiate {1}","update.page.restore":"{0} page aggiornate {3} in {2}","update.page.update":"{0} page aggiornate {3} in {2}","update.page.update.notify":"{0} page cambiate {1}","update.space.create":"{0} ha creato un nuovo gruppo {2}","update.space.join":"{0} si è unito al {2} gruppo","update.space.move":"{0} ha spostato il gruppo {2} da {3}","update.space.private":"{0} ha detto in {2}","update.space.remove":"{0} ha rimosso il gruppo {2}","update.space.rename":"{0} ha rinominato il gruppo {5} a {2}","update.space.restore":"{0} ha ripristinato il gruppo {2} dal cestino","update.space.trash.discussion.attemptRestore":"{0} ha ripristinato discussion  {3} in {2}","update.space.trash.discussion.attemptRestore.notify":"{0} ha ripristinato discussion  {1}","update.space.trash.discussion.create":"{0} ha cancellato la discussion {3} in {2}","update.space.trash.discussion.create.notify":"{0} ha cancellato la discussion {3} da {2} cestino","update.space.trash.discussion.delete":"{0} ha cancellato permanentemente la discussion {3} da {2} cestino","update.space.trash.event.attemptRestore":"{0} ha rispristinato event {3} di {2}","update.space.trash.event.attemptRestore.notify":"{0} ha ripristinato l` event {3} in {2}","update.space.trash.event.create":"{0} event ha cancellato {3} in {2}","update.space.trash.event.create.notify":"{0} ha cancellato l` event {1}","update.space.trash.event.delete":"{0} ha cancellato permanentemente event {3} da {2} cestino","update.space.trash.filerecord.attemptRestore":"{0} ha ripristinato file {3} in {2} ","update.space.trash.filerecord.attemptRestore.notify":"{0} ha ripristinato il file {1}","update.space.trash.filerecord.create":"{0} ha cancellato file {3} in {2}","update.space.trash.filerecord.create.notify":"{0} ha cancellato il file {1}","update.space.trash.filerecord.delete":"{0} ha cancellato permanentemente il/i file {3} da {2} cestino","update.space.trash.page.attemptRestore":"{0} ha ripristinato la/le page  {3} in {2}","update.space.trash.page.attemptRestore.notify":"{0} ha ripristinato la page {1}","update.space.trash.page.create":"{0} ha cancellato le page {3} in {2}","update.space.trash.page.create.notify":"{0} ha cancellato la page {1}","update.space.trash.page.delete":"{0} ha cancellato permanentemente le page {3} da {2} cestino","update.space.trash.task.attemptRestore":"{0} task ripristinato {3} in {2}","update.space.trash.task.attemptRestore.notify":"{0} ha ripristinato il compito task {1}","update.space.trash.task.create":"{0} task cancellati {3} in {2}","update.space.trash.task.create.notify":"{0} ha cancellato il compito task {1}","update.space.trash.task.delete":"{0} Cancellato permanentemente task {3} da {2}","update.task.complete":"{0} task completato {3} in {2}","update.task.complete.notify":"{0} completato il task {1}","update.task.create":"{0} task creati {3} in {2}","update.task.createandassign":"{0} task creati {3} in {2}","update.task.reopen":"{0} task segnati {3} come incompleti in {2}","update.task.reopen.notify":"{0} segnato il task come incompleto {1}","update.task.update":"{0} task aggiornati {3} in {2}","update.task.update.notify":"{0} ha cambiato il compito task {1}","update.task.updateandassign":"{0} task aggiornati {3} in {2}","update.task.updateandassign.notify":"{0} ha cambiato il compito task {1}","update.trash.delete":"{0} ha cancellato il gruppo {2} da {1} cestino","update.trash.remove":"{0} ha cancellato gruppo {2} da {1} cestino","update.trash.restore":"{0} ha cancellato gruppo {2}","update.user.private":"{0} ha detto","update.user.profile":"{0} ha detto a {4}"};regional["voxns"]={m_signin_title:"Sign in to VOXNS CXP",m_signup_header:"Sign up to VOXNS CXP"};regional["ruralco"]={m_signin_title:"Sign in to RuralcoLink",m_signup_header:"Sign up to RuralcoLink"};regional["botkeeper"]={m_signin_title:"Sign in to Botkeeper",m_signup_header:"Sign up to Botkeeper"};regional["stilettosociety"]={m_signin_title:"Sign in to Stiletto Society",m_signup_header:"Sign up to Stiletto Society"};return{messages:messages,template:function(template,data){return _.template(template,_.extend({},data,messages))},setLocale:function(locale){var regionalMessages=regional[locale];if(regionalMessages){this.messages=_.extend(messages,regionalMessages)}else{this.messages=messages}}}});define("app-context",["ext/underscore","$root","native","notifications","messages"],function(_,$root,_native,notifications,messages){var $=jQuery;var _credentials=null;var _getAppUrl=function(){return $root.data("appurl")};var appContext=_.extend({version:6,defaultThumb:_getAppUrl()+"/styles/images/default_thumbnail.png",environments:{prod:["https://api-p1.clinked.com","https://app.clinked.com","https://pubsub.clinked.com"],test:["https://test-api.clinked.com","https://test-app.clinked.com","https://test-pubsub.clinked.com"],dev:["http://localhost:18080/ROOT","http://localhost.localdomain:8080/ROOT","http://localhost:2222"],ip:["http://192.168.1.4:18080/ROOT","http://192.168.1.4:8080/ROOT","http://192.168.1.4:2222"],variants:{ruralco:{prod:["https://api.ruralcolink.com.au","https://ruralcolink.com.au","https://pubsub.ruralcolink.com.au"],test:["https://api-test.ruralcolink.com.au","https://test.ruralcolink.com.au","https://pubsub-test.ruralcolink.com.au"]}}},clientId:"clinked-mobile",pageSize:25,getAppUrl:_getAppUrl,setStartOptions:function(options){this.startOptions=options;if(options.variant){$root.addClass(options.variant);messages.setLocale(options.variant);if(this.environments.variants[options.variant]){this.environments=_.extend(this.environments,this.environments.variants[options.variant])}_native.thirdPartySignin=false}},start:function(callback){_native.start(function(options){appContext.setStartOptions(options);_updateConfig();if(options.location){}else{options.location=window.localStorage.getItem("location")}callback(options)})},getCredentials:function(callback){return _credentials},setCredentials:function(credentials){_credentials=credentials},removeCredentials:function(){_credentials=null},setAccessToken:function(token){if(token.expires_in){token.expires=(new Date).getTime()+token.expires_in*1e3}window.localStorage.setItem("accessToken",JSON.stringify(token));this.trigger("accessToken")},getAccessToken:function(){var json=window.localStorage.getItem("accessToken");if(json){var token=JSON.parse(json);var now=(new Date).getTime();if(!token.expires||token.expires>now){return token}}return null},removeAccessToken:function(){window.localStorage.removeItem("accessToken")},setTaskCompletedFilter:function(completed){window.localStorage.setItem("taskCompletedFilter",completed)},getTaskCompletedFilter:function(){return window.localStorage.getItem("taskCompletedFilter")=="true"},setFileSort:function(field){window.localStorage.setItem("fileSortField",field)},getFileSort:function(){var field=window.localStorage.getItem("fileSortField");return field?field:"lastModified"},setNoteSort:function(field){window.localStorage.setItem("noteSortField",field)},getNoteSort:function(){var field=window.localStorage.getItem("noteSortField");return field?field:"lastModified"},setPrinciple:function(principle){window.localStorage.setItem("me",JSON.stringify(principle));_updateLocale(principle.locale)},getPrinciple:function(){var principle=window.localStorage.getItem("me");if(principle){return JSON.parse(principle)}return null},removePrinciple:function(){window.localStorage.removeItem("me")},setDashboard:function(dashboard){window.localStorage.setItem("dashboard",dashboard)},getDashboard:function(){var dashboard=window.localStorage.getItem("dashboard");if(dashboard&&dashboard.indexOf(":@")==-1){dashboard=dashboard.replace(":",":@")}return dashboard},removeDashboard:function(){window.localStorage.removeItem("dashboard")},setEnvironment:function(environment){if(environment in this.environments){window.localStorage.setItem("environment",environment);_updateConfig()}},getEnvironment:function(){var environment=window.localStorage.getItem("environment");return environment?environment:_.keys(this.environments)[0]},resolveEndPoint:function(){return this.environments[this.getEnvironment()][0]},resolveAppEndPoint:function(){return this.environments[this.getEnvironment()][1]},resolvePubsubEndPoint:function(){return this.environments[this.getEnvironment()][2]},fullUrl:function(path){path+="?version="+this.version;var token=this.getAccessToken();if(token){path+="&access_token="+token.access_token}return this.resolveEndPoint()+path},preview:function(file,sessionNeeded){this.loading("show");if(sessionNeeded){$.get(this.fullUrl(file.url()+"session"),function(url){_native.preview(url,"text/html")})}else{_native.preview(this.fullUrl(file.url()+"preview"),file.get("contentType"),file.id+"."+file.get("versions"))}},loading:function(action){var $loader=$(".loader",$root);if(action=="show"){$loader.removeClass("hidden")}else if(action=="hide"){$loader.addClass("hidden");_native.pull&&_native.pull.cancel()}},setHeader:function(options){if(window.localStorage.getItem("features")=="limited"){options.nosearch=true}if(options.back){options.back.text=messages.messages[options.back.code]}if(!options.actions){options.actions=[]}if(options.action){options.actions.push(options.action)}_.each(options.actions,function(action){action.text=messages.messages[action.code]});_native.setHeader(options)},navigate:function(hash,force){if(window.location.hash==hash){force&&Backbone.history.loadUrl(hash)}else{window.location.hash=hash}window.localStorage.setItem("location",hash)}},Backbone.Events,notifications);var _updateLocale=function(locale){messages.setLocale(locale);var timeagoStrings=$.timeago.regional[locale];if(timeagoStrings){$.timeago.settings.strings=timeagoStrings}};var principle=appContext.getPrinciple();if(principle){_updateLocale(principle.locale)}var _updateConfig=function(){$.ajax({url:appContext.fullUrl("/config"),success:function(config){_.extend(appContext,config)},error:function(){appContext.navigate("#error",true)}})};$root.on("click","a",function(e){if(this.href!="javascript:void(0)"&&!_.isBlank(this.hash)){window.localStorage.setItem("location",this.hash)}});return appContext});define("router/base",["ext/underscore"],function(_){return Backbone.Router.extend({initialize:function(){_.bindToMethods(this)}})});define("api/cache",["ext/underscore"],function(_){return{defaultExpireIn:10,cache:{},putModel:function(model,expireIn){model._expiry=this.calcExpiry(expireIn);this.cache[model.getKey()]=model},calcExpiry:function(expireIn){if(!expireIn){expireIn=this.defaultExpireIn}return(new Date).getTime()+expireIn*6e4},get:function(contextKey){var model=this.cache[contextKey];if(model&&model._expiry>(new Date).getTime()){return model}return null},getFrom:function(model){var cached=this.get(model.getKey());return cached?cached:model},clear:function(pattern){if(pattern){_.each(_.keys(this.cache),function(key){if(key.indexOf(pattern)==0){delete this.cache[key]}},this)}else{this.cache={}}},put2:function(key,object){this.cache[key]={expiry:this.calcExpiry(),object:object}},get2:function(contextKey){var entry=this.cache[contextKey];if(entry&&entry.expiry>(new Date).getTime()){return entry.object}return null}}});define("api/sync",["ext/underscore","app-context"],function(_,appContext){var $=jQuery;var ajax=function(request){appContext.loading("show");var token=appContext.getAccessToken();if(token){request["headers"]={Authorization:"Bearer "+token.access_token}}var jqXHR=$.ajax(request);jqXHR.request=request};var requestTokenAndRetry=function(credentials,request){var params={scope:"read",grant_type:credentials.session?"session":credentials.password?"password":"refresh_token",client_id:appContext.clientId};$.ajax({type:"POST",url:appContext.resolveEndPoint()+"/oauth/token?"+$.param(params),data:credentials,success:function(data,textStatus,jqXHR){appContext.setAccessToken(data);ajax(request)},error:function(jqXHR,textStatus,errorThrown){console.log(JSON.stringify(jqXHR));console.log(JSON.stringify(textStatus));console.log(JSON.stringify(errorThrown));appContext.removeCredentials();appContext.navigate("#public/signin/m_signin_invalid",true)}})};var getCredentials=function(){var credentials=appContext.getCredentials();if(credentials){return credentials}else{var token=appContext.getAccessToken();if(token&&token.refresh_token){return{refresh_token:token.refresh_token}}}return null};var error=function(_error,jqXHR,textStatus,errorThrown){appContext.loading("hide");if(errorThrown=="Unauthorized"){var credentials=getCredentials();if(credentials){requestTokenAndRetry(credentials,jqXHR.request)}else{appContext.navigate("#public/signin",true)}}else{_error(jqXHR,textStatus,errorThrown);appContext.navigate("#error",true)}};var success=function(_success,data,textStatus,jqXHR){appContext.loading("hide");_success(data,textStatus,jqXHR)};var methodMap={create:"POST",update:"PUT","delete":"DELETE",read:"GET"};return{getKey:function(){var key=_.result(this,"url").replace(/\//g,":").substr(1);return this._getKey?this._getKey(key):key},sync:function(method,model,options){var params={type:methodMap[method],dataType:"json",cache:false,url:appContext.resolveEndPoint()+_.getProperty(model,"url")+"?version="+appContext.version};options.success=_.wrap(options.success,success);options.error=_.wrap(options.error,error);if(model.params){params.url+="&"+$.param(model.params,true)}if(model&&(method=="create"||method=="update")){params.contentType="application/json";params.data=JSON.stringify(model.toJSON())}if(params.type!=="GET"){params.processData=false}ajax(_.extend(params,options))}}});define("api/collection/base",["api/sync"],function(sync){return Backbone.Collection.extend(sync)});define("api/model/base",["ext/underscore","api/sync"],function(_,sync){return Backbone.Model.extend(sync)});define("api/model/user",["api/model/base"],function(BaseModel){return BaseModel.extend({})});define("api/collection/users",["api/collection/base","api/model/user"],function(BaseCollection,User){return BaseCollection.extend({model:User,url:"/users",initialize:function(models,options){this.context=options.context;this.params={};this.params[this.context.type+"Id"]=this.context.id;this.params["allowSelf"]=options.allowSelf},_getKey:function(key){return key+":"+this.context.getKey()}})});define("api/model/account",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(){this.type="account"},url:function(){return"/accounts/@"+this.id},isUser:function(){return this.get("name").indexOf("@")==0}})});define("api/collection/accounts",["api/collection/base","api/model/account"],function(BaseCollection,Account){return BaseCollection.extend({model:Account,url:"/accounts"})});define("api/model/group",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(){this.type="group"},url:function(){var id=this.id?"@"+this.id:this.get("name");return"/groups/"+id}})});define("api/collection/groups",["api/collection/base","api/model/group"],function(BaseCollection,Group){return BaseCollection.extend({model:Group,url:"/groups"})});define("api/collection/search",["ext/underscore","api/collection/base"],function(_,BaseCollection){return BaseCollection.extend({url:function(){return"/search/@"+this.account.id},initialize:function(models,options){options&&_.extend(this,options)},parse:function(response){if(response.suggestions.length>0){var suggestions=[];_.each(response.suggestions,function(suggestion){suggestions.push({suggestion:suggestion})});this.suggestions=true;return suggestions}this.more=response.nextPage;return response.page}})});define("api/model/principle",["api/model/user"],function(User){return User.extend({url:"/me"})});define("api/service/general",["ext/underscore","app-context","api/cache","api/collection/users","api/collection/accounts","api/collection/groups","api/collection/search","api/model/principle","api/model/account","api/model/group"],function(_,appContext,cache,Users,Accounts,Groups,Search,Principle,Account,Group){var $=jQuery;var _cacheIfNew=function(model){if(!model._expiry){cache.putModel(model)}};var _attachGroupsToAccounts=function(handler,accounts,groups){var catchall=new Account;accounts.unshift(catchall);var accountMap={};_cacheIfNew(accounts);accounts.each(function(account){_cacheIfNew(account);accountMap[account.getKey()]=account;account.groups=[]},this);_cacheIfNew(groups);groups.each(function(group){_cacheIfNew(group);var account=new Account(group.get("account"));account=accountMap[account.getKey()];if(!account){account=catchall}account.groups.push(group)},this);handler(accounts)};var _getSearchResults=function(account,query,page,handler){var search=new Search([],{account:account,search2:appContext.search2,params:{page:page,pageSize:appContext.pageSize,query:query}});search.once("sync",handler);search.fetch()};return{getUsers:function(context,handler,allowSelf){var users=cache.getFrom(new Users([],{context:context,allowSelf:allowSelf}));if(users._expiry){handler(users);return}users.once("sync",function(){cache.putModel(users);handler(users)});users.fetch()},fetchPrinciple:function(handler){var principle=new Principle;principle.once("change",function(){handler(principle)});principle.fetch()},getSearchResults:function(account,query,handler){_getSearchResults(account,query,1,handler)},getNextSearchResults:function(search,handler){_getSearchResults(search.account,search.params.query,search.params.page+1,function(next){search.add(next.models);search.params.page=next.params.page;search.more=next.more;handler(next)})},getAccountsWithGroups:function(handler){var accounts=cache.getFrom(new Accounts);var groups=cache.getFrom(new Groups);var attachGroupsToAccounts=_.bind(_.after(2,_attachGroupsToAccounts),this,handler,accounts,groups);if(accounts._expiry){attachGroupsToAccounts()}else{accounts.once("sync",attachGroupsToAccounts);accounts.fetch()}if(groups._expiry){attachGroupsToAccounts()}else{groups.once("sync",attachGroupsToAccounts);groups.fetch()}},getContext:function(contextKey,handler){var parts=contextKey.split(":@");var id=parseInt(parts[1]);if(parts[0]=="groups"){this.getGroup(id,handler)}else{this.getAccount(id,handler)}},getAccount:function(id,handler){var account=cache.getFrom(new Account({id:id}));if(account._expiry&&account.get("features")){handler(account)}else{account.once("change",function(){cache.putModel(account);handler(account)});account.fetch()}},getGroup:function(id,handler){var group=cache.getFrom(new Group({id:id}));if(group._expiry&&group.get("components")){handler(group)}else{group.once("change",function(){cache.putModel(group);handler(group)});group.fetch()}},getEmailFromInviteKey:function(inviteKey,handler){$.ajax({url:appContext.resolveAppEndPoint()+"/signup/invited",data:{inviteKey:inviteKey},success:function(response){if(response.form){handler(response.form.user.email)}else{handler()}},error:function(){handler()},dataType:"json"})},isUsernameTaken:function(username,handler){$.get(appContext.resolveAppEndPoint()+"/signup/taken",{username:username},function(response){handler(response.status)},"json")},createUser:function(user,handler){appContext.loading("show");$.ajax({type:"POST",url:appContext.resolveAppEndPoint()+"/signup/invited",data:user,success:function(){appContext.loading("hide");handler(true)},error:function(){appContext.loading("hide");handler(false)},dataType:"json"})},requestPasswordReset:function(email,handler){appContext.loading("show");$.ajax({type:"POST",url:appContext.resolveAppEndPoint()+"/password/forgotten",data:{email:email},success:function(response){appContext.loading("hide");handler(response._viewName=="organisation/password_forgotten_success")},error:function(){appContext.loading("hide");handler(false)},dataType:"json"})},resetPassword:function(username,tokenKey,password,handler){appContext.loading("show");$.ajax({type:"POST",url:appContext.resolveAppEndPoint()+"/password/reset/"+username+"/"+tokenKey,data:password,success:function(response){appContext.loading("hide");handler(true)},error:function(){appContext.loading("hide");handler(false)},dataType:"json"})},deleteModel:function(model,handler){model.destroy({wait:true});model.once("destroy",handler)}}});define("api/model/request",["api/model/base"],function(BaseModel){return BaseModel.extend({url:function(){var id="";if(this.id){id="/"+this.id}if(this.collection){return this.collection.url()+id}return"/requests"+id}})});!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define("moment",b):a.moment=b()}(this,function(){"use strict";function a(){return Dc.apply(null,arguments)}function b(a){Dc=a}function c(a){return"[object Array]"===Object.prototype.toString.call(a)}function d(a){return a instanceof Date||"[object Date]"===Object.prototype.toString.call(a)}function e(a,b){var c,d=[];for(c=0;c<a.length;++c)d.push(b(a[c],c));return d}function f(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function g(a,b){for(var c in b)f(b,c)&&(a[c]=b[c]);return f(b,"toString")&&(a.toString=b.toString),f(b,"valueOf")&&(a.valueOf=b.valueOf),a}function h(a,b,c,d){return za(a,b,c,d,!0).utc()}function i(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function j(a){return null==a._pf&&(a._pf=i()),a._pf}function k(a){if(null==a._isValid){var b=j(a);a._isValid=!isNaN(a._d.getTime())&&b.overflow<0&&!b.empty&&!b.invalidMonth&&!b.nullInput&&!b.invalidFormat&&!b.userInvalidated,a._strict&&(a._isValid=a._isValid&&0===b.charsLeftOver&&0===b.unusedTokens.length&&void 0===b.bigHour)}return a._isValid}function l(a){var b=h(0/0);return null!=a?g(j(b),a):j(b).userInvalidated=!0,b}function m(a,b){var c,d,e;if("undefined"!=typeof b._isAMomentObject&&(a._isAMomentObject=b._isAMomentObject),"undefined"!=typeof b._i&&(a._i=b._i),"undefined"!=typeof b._f&&(a._f=b._f),"undefined"!=typeof b._l&&(a._l=b._l),"undefined"!=typeof b._strict&&(a._strict=b._strict),"undefined"!=typeof b._tzm&&(a._tzm=b._tzm),"undefined"!=typeof b._isUTC&&(a._isUTC=b._isUTC),"undefined"!=typeof b._offset&&(a._offset=b._offset),"undefined"!=typeof b._pf&&(a._pf=j(b)),"undefined"!=typeof b._locale&&(a._locale=b._locale),Fc.length>0)for(c in Fc)d=Fc[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function n(b){m(this,b),this._d=new Date(+b._d),Gc===!1&&(Gc=!0,a.updateOffset(this),Gc=!1)}function o(a){return a instanceof n||null!=a&&null!=a._isAMomentObject}function p(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function q(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&p(a[d])!==p(b[d]))&&g++;return g+f}function r(){}function s(a){return a?a.toLowerCase().replace("_","-"):a}function t(a){for(var b,c,d,e,f=0;f<a.length;){for(e=s(a[f]).split("-"),b=e.length,c=s(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=u(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&q(e,c,!0)>=b-1)break;b--}f++}return null}function u(a){var b=null;if(!Hc[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=Ec._abbr,require("./locale/"+a),v(b)}catch(c){}return Hc[a]}function v(a,b){var c;return a&&(c="undefined"==typeof b?x(a):w(a,b),c&&(Ec=c)),Ec._abbr}function w(a,b){return null!==b?(b.abbr=a,Hc[a]||(Hc[a]=new r),Hc[a].set(b),v(a),Hc[a]):(delete Hc[a],null)}function x(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return Ec;if(!c(a)){if(b=u(a))return b;a=[a]}return t(a)}function y(a,b){var c=a.toLowerCase();Ic[c]=Ic[c+"s"]=Ic[b]=a}function z(a){return"string"==typeof a?Ic[a]||Ic[a.toLowerCase()]:void 0}function A(a){var b,c,d={};for(c in a)f(a,c)&&(b=z(c),b&&(d[b]=a[c]));return d}function B(b,c){return function(d){return null!=d?(D(this,b,d),a.updateOffset(this,c),this):C(this,b)}}function C(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function D(a,b,c){return a._d["set"+(a._isUTC?"UTC":"")+b](c)}function E(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=z(a),"function"==typeof this[a])return this[a](b);return this}function F(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.length<b;)d="0"+d;return(e?c?"+":"":"-")+d}function G(a,b,c,d){var e=d;"string"==typeof d&&(e=function(){return this[d]()}),a&&(Mc[a]=e),b&&(Mc[b[0]]=function(){return F(e.apply(this,arguments),b[1],b[2])}),c&&(Mc[c]=function(){return this.localeData().ordinal(e.apply(this,arguments),a)})}function H(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function I(a){var b,c,d=a.match(Jc);for(b=0,c=d.length;c>b;b++)Mc[d[b]]?d[b]=Mc[d[b]]:d[b]=H(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function J(a,b){return a.isValid()?(b=K(b,a.localeData()),Lc[b]||(Lc[b]=I(b)),Lc[b](a)):a.localeData().invalidDate()}function K(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Kc.lastIndex=0;d>=0&&Kc.test(a);)a=a.replace(Kc,c),Kc.lastIndex=0,d-=1;return a}function L(a,b,c){_c[a]="function"==typeof b?b:function(a){return a&&c?c:b}}function M(a,b){return f(_c,a)?_c[a](b._strict,b._locale):new RegExp(N(a))}function N(a){return a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function O(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=p(a)}),c=0;c<a.length;c++)ad[a[c]]=d}function P(a,b){O(a,function(a,c,d,e){d._w=d._w||{},b(a,d._w,d,e)})}function Q(a,b,c){null!=b&&f(ad,a)&&ad[a](b,c._a,c,a)}function R(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function S(a){return this._months[a.month()]}function T(a){return this._monthsShort[a.month()]}function U(a,b,c){var d,e,f;for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),d=0;12>d;d++){if(e=h([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function V(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),R(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function W(b){return null!=b?(V(this,b),a.updateOffset(this,!0),this):C(this,"Month")}function X(){return R(this.year(),this.month())}function Y(a){var b,c=a._a;return c&&-2===j(a).overflow&&(b=c[cd]<0||c[cd]>11?cd:c[dd]<1||c[dd]>R(c[bd],c[cd])?dd:c[ed]<0||c[ed]>24||24===c[ed]&&(0!==c[fd]||0!==c[gd]||0!==c[hd])?ed:c[fd]<0||c[fd]>59?fd:c[gd]<0||c[gd]>59?gd:c[hd]<0||c[hd]>999?hd:-1,j(a)._overflowDayOfYear&&(bd>b||b>dd)&&(b=dd),j(a).overflow=b),a}function Z(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function $(a,b){var c=!0,d=a+"\n"+(new Error).stack;return g(function(){return c&&(Z(d),c=!1),b.apply(this,arguments)},b)}function _(a,b){kd[a]||(Z(b),kd[a]=!0)}function aa(a){var b,c,d=a._i,e=ld.exec(d);if(e){for(j(a).iso=!0,b=0,c=md.length;c>b;b++)if(md[b][1].exec(d)){a._f=md[b][0]+(e[6]||" ");break}for(b=0,c=nd.length;c>b;b++)if(nd[b][1].exec(d)){a._f+=nd[b][0];break}d.match(Yc)&&(a._f+="Z"),ta(a)}else a._isValid=!1}function ba(b){var c=od.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(aa(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function ca(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function da(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function ea(a){return fa(a)?366:365}function fa(a){return a%4===0&&a%100!==0||a%400===0}function ga(){return fa(this.year())}function ha(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=Aa(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function ia(a){return ha(a,this._week.dow,this._week.doy).week}function ja(){return this._week.dow}function ka(){return this._week.doy}function la(a){
     10var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function ma(a){var b=ha(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function na(a,b,c,d,e){var f,g,h=da(a,0,1).getUTCDay();return h=0===h?7:h,c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:ea(a-1)+g}}function oa(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function pa(a,b,c){return null!=a?a:null!=b?b:c}function qa(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function ra(a){var b,c,d,e,f=[];if(!a._d){for(d=qa(a),a._w&&null==a._a[dd]&&null==a._a[cd]&&sa(a),a._dayOfYear&&(e=pa(a._a[bd],d[bd]),a._dayOfYear>ea(e)&&(j(a)._overflowDayOfYear=!0),c=da(e,0,a._dayOfYear),a._a[cd]=c.getUTCMonth(),a._a[dd]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[ed]&&0===a._a[fd]&&0===a._a[gd]&&0===a._a[hd]&&(a._nextDay=!0,a._a[ed]=0),a._d=(a._useUTC?da:ca).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[ed]=24)}}function sa(a){var b,c,d,e,f,g,h;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=pa(b.GG,a._a[bd],ha(Aa(),1,4).year),d=pa(b.W,1),e=pa(b.E,1)):(f=a._locale._week.dow,g=a._locale._week.doy,c=pa(b.gg,a._a[bd],ha(Aa(),f,g).year),d=pa(b.w,1),null!=b.d?(e=b.d,f>e&&++d):e=null!=b.e?b.e+f:f),h=na(c,d,e,g,f),a._a[bd]=h.year,a._dayOfYear=h.dayOfYear}function ta(b){if(b._f===a.ISO_8601)return void aa(b);b._a=[],j(b).empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,k=0;for(e=K(b._f,b._locale).match(Jc)||[],c=0;c<e.length;c++)f=e[c],d=(h.match(M(f,b))||[])[0],d&&(g=h.substr(0,h.indexOf(d)),g.length>0&&j(b).unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),k+=d.length),Mc[f]?(d?j(b).empty=!1:j(b).unusedTokens.push(f),Q(f,d,b)):b._strict&&!d&&j(b).unusedTokens.push(f);j(b).charsLeftOver=i-k,h.length>0&&j(b).unusedInput.push(h),j(b).bigHour===!0&&b._a[ed]<=12&&b._a[ed]>0&&(j(b).bigHour=void 0),b._a[ed]=ua(b._locale,b._a[ed],b._meridiem),ra(b),Y(b)}function ua(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function va(a){var b,c,d,e,f;if(0===a._f.length)return j(a).invalidFormat=!0,void(a._d=new Date(0/0));for(e=0;e<a._f.length;e++)f=0,b=m({},a),null!=a._useUTC&&(b._useUTC=a._useUTC),b._f=a._f[e],ta(b),k(b)&&(f+=j(b).charsLeftOver,f+=10*j(b).unusedTokens.length,j(b).score=f,(null==d||d>f)&&(d=f,c=b));g(a,c||b)}function wa(a){if(!a._d){var b=A(a._i);a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],ra(a)}}function xa(a){var b,e=a._i,f=a._f;return a._locale=a._locale||x(a._l),null===e||void 0===f&&""===e?l({nullInput:!0}):("string"==typeof e&&(a._i=e=a._locale.preparse(e)),o(e)?new n(Y(e)):(c(f)?va(a):f?ta(a):d(e)?a._d=e:ya(a),b=new n(Y(a)),b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b))}function ya(b){var f=b._i;void 0===f?b._d=new Date:d(f)?b._d=new Date(+f):"string"==typeof f?ba(b):c(f)?(b._a=e(f.slice(0),function(a){return parseInt(a,10)}),ra(b)):"object"==typeof f?wa(b):"number"==typeof f?b._d=new Date(f):a.createFromInputFallback(b)}function za(a,b,c,d,e){var f={};return"boolean"==typeof c&&(d=c,c=void 0),f._isAMomentObject=!0,f._useUTC=f._isUTC=e,f._l=c,f._i=a,f._f=b,f._strict=d,xa(f)}function Aa(a,b,c,d){return za(a,b,c,d,!1)}function Ba(a,b){var d,e;if(1===b.length&&c(b[0])&&(b=b[0]),!b.length)return Aa();for(d=b[0],e=1;e<b.length;++e)b[e][a](d)&&(d=b[e]);return d}function Ca(){var a=[].slice.call(arguments,0);return Ba("isBefore",a)}function Da(){var a=[].slice.call(arguments,0);return Ba("isAfter",a)}function Ea(a){var b=A(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+36e5*h,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=x(),this._bubble()}function Fa(a){return a instanceof Ea}function Ga(a,b){G(a,0,0,function(){var a=this.utcOffset(),c="+";return 0>a&&(a=-a,c="-"),c+F(~~(a/60),2)+b+F(~~a%60,2)})}function Ha(a){var b=(a||"").match(Yc)||[],c=b[b.length-1]||[],d=(c+"").match(td)||["-",0,0],e=+(60*d[1])+p(d[2]);return"+"===d[0]?e:-e}function Ia(b,c){var e,f;return c._isUTC?(e=c.clone(),f=(o(b)||d(b)?+b:+Aa(b))-+e,e._d.setTime(+e._d+f),a.updateOffset(e,!1),e):Aa(b).local();return c._isUTC?Aa(b).zone(c._offset||0):Aa(b).local()}function Ja(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Ka(b,c){var d,e=this._offset||0;return null!=b?("string"==typeof b&&(b=Ha(b)),Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ja(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?$a(this,Va(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ja(this)}function La(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function Ma(a){return this.utcOffset(0,a)}function Na(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ja(this),"m")),this}function Oa(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ha(this._i)),this}function Pa(a){return a=a?Aa(a).utcOffset():0,(this.utcOffset()-a)%60===0}function Qa(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Ra(){if(this._a){var a=this._isUTC?h(this._a):Aa(this._a);return this.isValid()&&q(this._a,a.toArray())>0}return!1}function Sa(){return!this._isUTC}function Ta(){return this._isUTC}function Ua(){return this._isUTC&&0===this._offset}function Va(a,b){var c,d,e,g=a,h=null;return Fa(a)?g={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(g={},b?g[b]=a:g.milliseconds=a):(h=ud.exec(a))?(c="-"===h[1]?-1:1,g={y:0,d:p(h[dd])*c,h:p(h[ed])*c,m:p(h[fd])*c,s:p(h[gd])*c,ms:p(h[hd])*c}):(h=vd.exec(a))?(c="-"===h[1]?-1:1,g={y:Wa(h[2],c),M:Wa(h[3],c),d:Wa(h[4],c),h:Wa(h[5],c),m:Wa(h[6],c),s:Wa(h[7],c),w:Wa(h[8],c)}):null==g?g={}:"object"==typeof g&&("from"in g||"to"in g)&&(e=Ya(Aa(g.from),Aa(g.to)),g={},g.ms=e.milliseconds,g.M=e.months),d=new Ea(g),Fa(a)&&f(a,"_locale")&&(d._locale=a._locale),d}function Wa(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function Xa(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function Ya(a,b){var c;return b=Ia(b,a),a.isBefore(b)?c=Xa(a,b):(c=Xa(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function Za(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(_(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Va(c,d),$a(this,e,a),this}}function $a(b,c,d,e){var f=c._milliseconds,g=c._days,h=c._months;e=null==e?!0:e,f&&b._d.setTime(+b._d+f*d),g&&D(b,"Date",C(b,"Date")+g*d),h&&V(b,C(b,"Month")+h*d),e&&a.updateOffset(b,g||h)}function _a(a){var b=a||Aa(),c=Ia(b,this).startOf("day"),d=this.diff(c,"days",!0),e=-6>d?"sameElse":-1>d?"lastWeek":0>d?"lastDay":1>d?"sameDay":2>d?"nextDay":7>d?"nextWeek":"sameElse";return this.format(this.localeData().calendar(e,this,Aa(b)))}function ab(){return new n(this)}function bb(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+this>+a):(c=o(a)?+a:+Aa(a),c<+this.clone().startOf(b))}function cb(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+a>+this):(c=o(a)?+a:+Aa(a),+this.clone().endOf(b)<c)}function db(a,b,c){return this.isAfter(a,c)&&this.isBefore(b,c)}function eb(a,b){var c;return b=z(b||"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+this===+a):(c=+Aa(a),+this.clone().startOf(b)<=c&&c<=+this.clone().endOf(b))}function fb(a){return 0>a?Math.ceil(a):Math.floor(a)}function gb(a,b,c){var d,e,f=Ia(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=z(b),"year"===b||"month"===b||"quarter"===b?(e=hb(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:fb(e)}function hb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function ib(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function jb(){var a=this.clone().utc();return 0<a.year()&&a.year()<=9999?"function"==typeof Date.prototype.toISOString?this.toDate().toISOString():J(a,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):J(a,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function kb(b){var c=J(this,b||a.defaultFormat);return this.localeData().postformat(c)}function lb(a,b){return this.isValid()?Va({to:this,from:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function mb(a){return this.from(Aa(),a)}function nb(a,b){return this.isValid()?Va({from:this,to:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function ob(a){return this.to(Aa(),a)}function pb(a){var b;return void 0===a?this._locale._abbr:(b=x(a),null!=b&&(this._locale=b),this)}function qb(){return this._locale}function rb(a){switch(a=z(a)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===a&&this.weekday(0),"isoWeek"===a&&this.isoWeekday(1),"quarter"===a&&this.month(3*Math.floor(this.month()/3)),this}function sb(a){return a=z(a),void 0===a||"millisecond"===a?this:this.startOf(a).add(1,"isoWeek"===a?"week":a).subtract(1,"ms")}function tb(){return+this._d-6e4*(this._offset||0)}function ub(){return Math.floor(+this/1e3)}function vb(){return this._offset?new Date(+this):this._d}function wb(){var a=this;return[a.year(),a.month(),a.date(),a.hour(),a.minute(),a.second(),a.millisecond()]}function xb(){return k(this)}function yb(){return g({},j(this))}function zb(){return j(this).overflow}function Ab(a,b){G(0,[a,a.length],0,b)}function Bb(a,b,c){return ha(Aa([a,11,31+b-c]),b,c).week}function Cb(a){var b=ha(this,this.localeData()._week.dow,this.localeData()._week.doy).year;return null==a?b:this.add(a-b,"y")}function Db(a){var b=ha(this,1,4).year;return null==a?b:this.add(a-b,"y")}function Eb(){return Bb(this.year(),1,4)}function Fb(){var a=this.localeData()._week;return Bb(this.year(),a.dow,a.doy)}function Gb(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)}function Hb(a,b){if("string"==typeof a)if(isNaN(a)){if(a=b.weekdaysParse(a),"number"!=typeof a)return null}else a=parseInt(a,10);return a}function Ib(a){return this._weekdays[a.day()]}function Jb(a){return this._weekdaysShort[a.day()]}function Kb(a){return this._weekdaysMin[a.day()]}function Lb(a){var b,c,d;for(this._weekdaysParse||(this._weekdaysParse=[]),b=0;7>b;b++)if(this._weekdaysParse[b]||(c=Aa([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b}function Mb(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Hb(a,this.localeData()),this.add(a-b,"d")):b}function Nb(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Ob(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)}function Pb(a,b){G(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function Qb(a,b){return b._meridiemParse}function Rb(a){return"p"===(a+"").toLowerCase().charAt(0)}function Sb(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Tb(a){G(0,[a,3],0,"millisecond")}function Ub(){return this._isUTC?"UTC":""}function Vb(){return this._isUTC?"Coordinated Universal Time":""}function Wb(a){return Aa(1e3*a)}function Xb(){return Aa.apply(null,arguments).parseZone()}function Yb(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.call(b,c):d}function Zb(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b}function $b(){return this._invalidDate}function _b(a){return this._ordinal.replace("%d",a)}function ac(a){return a}function bc(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)}function cc(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)}function dc(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function ec(a,b,c,d){var e=x(),f=h().set(d,b);return e[c](f,a)}function fc(a,b,c,d,e){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return ec(a,b,c,e);var f,g=[];for(f=0;d>f;f++)g[f]=ec(a,f,c,e);return g}function gc(a,b){return fc(a,b,"months",12,"month")}function hc(a,b){return fc(a,b,"monthsShort",12,"month")}function ic(a,b){return fc(a,b,"weekdays",7,"day")}function jc(a,b){return fc(a,b,"weekdaysShort",7,"day")}function kc(a,b){return fc(a,b,"weekdaysMin",7,"day")}function lc(){var a=this._data;return this._milliseconds=Rd(this._milliseconds),this._days=Rd(this._days),this._months=Rd(this._months),a.milliseconds=Rd(a.milliseconds),a.seconds=Rd(a.seconds),a.minutes=Rd(a.minutes),a.hours=Rd(a.hours),a.months=Rd(a.months),a.years=Rd(a.years),this}function mc(a,b,c,d){var e=Va(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function nc(a,b){return mc(this,a,b,1)}function oc(a,b){return mc(this,a,b,-1)}function pc(){var a,b,c,d=this._milliseconds,e=this._days,f=this._months,g=this._data,h=0;return g.milliseconds=d%1e3,a=fb(d/1e3),g.seconds=a%60,b=fb(a/60),g.minutes=b%60,c=fb(b/60),g.hours=c%24,e+=fb(c/24),h=fb(qc(e)),e-=fb(rc(h)),f+=fb(e/30),e%=30,h+=fb(f/12),f%=12,g.days=e,g.months=f,g.years=h,this}function qc(a){return 400*a/146097}function rc(a){return 146097*a/400}function sc(a){var b,c,d=this._milliseconds;if(a=z(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+12*qc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(rc(this._months/12)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 1440*b+d/6e4;case"second":return 86400*b+d/1e3;case"millisecond":return Math.floor(864e5*b)+d;default:throw new Error("Unknown unit "+a)}}function tc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*p(this._months/12)}function uc(a){return function(){return this.as(a)}}function vc(a){return a=z(a),this[a+"s"]()}function wc(a){return function(){return this._data[a]}}function xc(){return fb(this.days()/7)}function yc(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function zc(a,b,c){var d=Va(a).abs(),e=fe(d.as("s")),f=fe(d.as("m")),g=fe(d.as("h")),h=fe(d.as("d")),i=fe(d.as("M")),j=fe(d.as("y")),k=e<ge.s&&["s",e]||1===f&&["m"]||f<ge.m&&["mm",f]||1===g&&["h"]||g<ge.h&&["hh",g]||1===h&&["d"]||h<ge.d&&["dd",h]||1===i&&["M"]||i<ge.M&&["MM",i]||1===j&&["y"]||["yy",j];return k[2]=b,k[3]=+a>0,k[4]=c,yc.apply(null,k)}function Ac(a,b){return void 0===ge[a]?!1:void 0===b?ge[a]:(ge[a]=b,!0)}function Bc(a){var b=this.localeData(),c=zc(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function Cc(){var a=he(this.years()),b=he(this.months()),c=he(this.days()),d=he(this.hours()),e=he(this.minutes()),f=he(this.seconds()+this.milliseconds()/1e3),g=this.asSeconds();return g?(0>g?"-":"")+"P"+(a?a+"Y":"")+(b?b+"M":"")+(c?c+"D":"")+(d||e||f?"T":"")+(d?d+"H":"")+(e?e+"M":"")+(f?f+"S":""):"P0D"}var Dc,Ec,Fc=a.momentProperties=[],Gc=!1,Hc={},Ic={},Jc=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Kc=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Lc={},Mc={},Nc=/\d/,Oc=/\d\d/,Pc=/\d{3}/,Qc=/\d{4}/,Rc=/[+-]?\d{6}/,Sc=/\d\d?/,Tc=/\d{1,3}/,Uc=/\d{1,4}/,Vc=/[+-]?\d{1,6}/,Wc=/\d+/,Xc=/[+-]?\d+/,Yc=/Z|[+-]\d\d:?\d\d/gi,Zc=/[+-]?\d+(\.\d{1,3})?/,$c=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,_c={},ad={},bd=0,cd=1,dd=2,ed=3,fd=4,gd=5,hd=6;G("M",["MM",2],"Mo",function(){return this.month()+1}),G("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),G("MMMM",0,0,function(a){return this.localeData().months(this,a)}),y("month","M"),L("M",Sc),L("MM",Sc,Oc),L("MMM",$c),L("MMMM",$c),O(["M","MM"],function(a,b){b[cd]=p(a)-1}),O(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[cd]=e:j(c).invalidMonth=a});var id="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),jd="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),kd={};a.suppressDeprecationWarnings=!1;var ld=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,md=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],nd=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],od=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=$("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),G(0,["YY",2],0,function(){return this.year()%100}),G(0,["YYYY",4],0,"year"),G(0,["YYYYY",5],0,"year"),G(0,["YYYYYY",6,!0],0,"year"),y("year","y"),L("Y",Xc),L("YY",Sc,Oc),L("YYYY",Uc,Qc),L("YYYYY",Vc,Rc),L("YYYYYY",Vc,Rc),O(["YYYY","YYYYY","YYYYYY"],bd),O("YY",function(b,c){c[bd]=a.parseTwoDigitYear(b)}),a.parseTwoDigitYear=function(a){return p(a)+(p(a)>68?1900:2e3)};var pd=B("FullYear",!1);G("w",["ww",2],"wo","week"),G("W",["WW",2],"Wo","isoWeek"),y("week","w"),y("isoWeek","W"),L("w",Sc),L("ww",Sc,Oc),L("W",Sc),L("WW",Sc,Oc),P(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=p(a)});var qd={dow:0,doy:6};G("DDD",["DDDD",3],"DDDo","dayOfYear"),y("dayOfYear","DDD"),L("DDD",Tc),L("DDDD",Pc),O(["DDD","DDDD"],function(a,b,c){c._dayOfYear=p(a)}),a.ISO_8601=function(){};var rd=$("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=Aa.apply(null,arguments);return this>a?this:a}),sd=$("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=Aa.apply(null,arguments);return a>this?this:a});Ga("Z",":"),Ga("ZZ",""),L("Z",Yc),L("ZZ",Yc),O(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ha(a)});var td=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var ud=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,vd=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Va.fn=Ea.prototype;var wd=Za(1,"add"),xd=Za(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var yd=$("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});G(0,["gg",2],0,function(){return this.weekYear()%100}),G(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Ab("gggg","weekYear"),Ab("ggggg","weekYear"),Ab("GGGG","isoWeekYear"),Ab("GGGGG","isoWeekYear"),y("weekYear","gg"),y("isoWeekYear","GG"),L("G",Xc),L("g",Xc),L("GG",Sc,Oc),L("gg",Sc,Oc),L("GGGG",Uc,Qc),L("gggg",Uc,Qc),L("GGGGG",Vc,Rc),L("ggggg",Vc,Rc),P(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=p(a)}),P(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),G("Q",0,0,"quarter"),y("quarter","Q"),L("Q",Nc),O("Q",function(a,b){b[cd]=3*(p(a)-1)}),G("D",["DD",2],"Do","date"),y("date","D"),L("D",Sc),L("DD",Sc,Oc),L("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),O(["D","DD"],dd),O("Do",function(a,b){b[dd]=p(a.match(Sc)[0],10)});var zd=B("Date",!0);G("d",0,"do","day"),G("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),G("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),G("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),G("e",0,0,"weekday"),G("E",0,0,"isoWeekday"),y("day","d"),y("weekday","e"),y("isoWeekday","E"),L("d",Sc),L("e",Sc),L("E",Sc),L("dd",$c),L("ddd",$c),L("dddd",$c),P(["dd","ddd","dddd"],function(a,b,c){var d=c._locale.weekdaysParse(a);null!=d?b.d=d:j(c).invalidWeekday=a}),P(["d","e","E"],function(a,b,c,d){b[d]=p(a)});var Ad="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Bd="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Cd="Su_Mo_Tu_We_Th_Fr_Sa".split("_");G("H",["HH",2],0,"hour"),G("h",["hh",2],0,function(){return this.hours()%12||12}),Pb("a",!0),Pb("A",!1),y("hour","h"),L("a",Qb),L("A",Qb),L("H",Sc),L("h",Sc),L("HH",Sc,Oc),L("hh",Sc,Oc),O(["H","HH"],ed),O(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),O(["h","hh"],function(a,b,c){b[ed]=p(a),j(c).bigHour=!0});var Dd=/[ap]\.?m?\.?/i,Ed=B("Hours",!0);G("m",["mm",2],0,"minute"),y("minute","m"),L("m",Sc),L("mm",Sc,Oc),O(["m","mm"],fd);var Fd=B("Minutes",!1);G("s",["ss",2],0,"second"),y("second","s"),L("s",Sc),L("ss",Sc,Oc),O(["s","ss"],gd);var Gd=B("Seconds",!1);G("S",0,0,function(){return~~(this.millisecond()/100)}),G(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Tb("SSS"),Tb("SSSS"),y("millisecond","ms"),L("S",Tc,Nc),L("SS",Tc,Oc),L("SSS",Tc,Pc),L("SSSS",Wc),O(["S","SS","SSS","SSSS"],function(a,b){b[hd]=p(1e3*("0."+a))});var Hd=B("Milliseconds",!1);G("z",0,0,"zoneAbbr"),G("zz",0,0,"zoneName");var Id=n.prototype;Id.add=wd,Id.calendar=_a,Id.clone=ab,Id.diff=gb,Id.endOf=sb,Id.format=kb,Id.from=lb,Id.fromNow=mb,Id.to=nb,Id.toNow=ob,Id.get=E,Id.invalidAt=zb,Id.isAfter=bb,Id.isBefore=cb,Id.isBetween=db,Id.isSame=eb,Id.isValid=xb,Id.lang=yd,Id.locale=pb,Id.localeData=qb,Id.max=sd,Id.min=rd,Id.parsingFlags=yb,Id.set=E,Id.startOf=rb,Id.subtract=xd,Id.toArray=wb,Id.toDate=vb,Id.toISOString=jb,Id.toJSON=jb,Id.toString=ib,Id.unix=ub,Id.valueOf=tb,Id.year=pd,Id.isLeapYear=ga,Id.weekYear=Cb,Id.isoWeekYear=Db,Id.quarter=Id.quarters=Gb,Id.month=W,Id.daysInMonth=X,Id.week=Id.weeks=la,Id.isoWeek=Id.isoWeeks=ma,Id.weeksInYear=Fb,Id.isoWeeksInYear=Eb,Id.date=zd,Id.day=Id.days=Mb,Id.weekday=Nb,Id.isoWeekday=Ob,Id.dayOfYear=oa,Id.hour=Id.hours=Ed,Id.minute=Id.minutes=Fd,Id.second=Id.seconds=Gd,Id.millisecond=Id.milliseconds=Hd,Id.utcOffset=Ka,Id.utc=Ma,Id.local=Na,Id.parseZone=Oa,Id.hasAlignedHourOffset=Pa,Id.isDST=Qa,Id.isDSTShifted=Ra,Id.isLocal=Sa,Id.isUtcOffset=Ta,Id.isUtc=Ua,Id.isUTC=Ua,Id.zoneAbbr=Ub,Id.zoneName=Vb,Id.dates=$("dates accessor is deprecated. Use date instead.",zd),Id.months=$("months accessor is deprecated. Use month instead",W),Id.years=$("years accessor is deprecated. Use year instead",pd),Id.zone=$("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",La);var Jd=Id,Kd={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Ld={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},Md="Invalid date",Nd="%d",Od=/\d{1,2}/,Pd={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Qd=r.prototype;Qd._calendar=Kd,Qd.calendar=Yb,Qd._longDateFormat=Ld,Qd.longDateFormat=Zb,Qd._invalidDate=Md,Qd.invalidDate=$b,Qd._ordinal=Nd,Qd.ordinal=_b,Qd._ordinalParse=Od,Qd.preparse=ac,Qd.postformat=ac,Qd._relativeTime=Pd,Qd.relativeTime=bc,Qd.pastFuture=cc,Qd.set=dc,Qd.months=S,Qd._months=id,Qd.monthsShort=T,Qd._monthsShort=jd,Qd.monthsParse=U,Qd.week=ia,Qd._week=qd,Qd.firstDayOfYear=ka,Qd.firstDayOfWeek=ja,Qd.weekdays=Ib,Qd._weekdays=Ad,Qd.weekdaysMin=Kb,Qd._weekdaysMin=Cd,Qd.weekdaysShort=Jb,Qd._weekdaysShort=Bd,Qd.weekdaysParse=Lb,Qd.isPM=Rb,Qd._meridiemParse=Dd,Qd.meridiem=Sb,v("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===p(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=$("moment.lang is deprecated. Use moment.locale instead.",v),a.langData=$("moment.langData is deprecated. Use moment.localeData instead.",x);var Rd=Math.abs,Sd=uc("ms"),Td=uc("s"),Ud=uc("m"),Vd=uc("h"),Wd=uc("d"),Xd=uc("w"),Yd=uc("M"),Zd=uc("y"),$d=wc("milliseconds"),_d=wc("seconds"),ae=wc("minutes"),be=wc("hours"),ce=wc("days"),de=wc("months"),ee=wc("years"),fe=Math.round,ge={s:45,m:45,h:22,d:26,M:11},he=Math.abs,ie=Ea.prototype;ie.abs=lc,ie.add=nc,ie.subtract=oc,ie.as=sc,ie.asMilliseconds=Sd,ie.asSeconds=Td,ie.asMinutes=Ud,ie.asHours=Vd,ie.asDays=Wd,ie.asWeeks=Xd,ie.asMonths=Yd,ie.asYears=Zd,ie.valueOf=tc,ie._bubble=pc,ie.get=vc,ie.milliseconds=$d,ie.seconds=_d,ie.minutes=ae,ie.hours=be,ie.days=ce,ie.weeks=xc,ie.months=de,ie.years=ee,ie.humanize=Bc,ie.toISOString=Cc,ie.toString=Cc,ie.toJSON=Cc,ie.locale=pb,ie.localeData=qb,ie.toIsoString=$("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Cc),ie.lang=yd,G("X",0,0,"unix"),G("x",0,0,"valueOf"),L("x",Xc),L("X",Zc),O("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),O("x",function(a,b,c){c._d=new Date(p(a))}),a.version="2.10.3",b(Aa),a.fn=Jd,a.min=Ca,a.max=Da,a.utc=h,a.unix=Wb,a.months=gc,a.isDate=d,a.locale=v,a.invalid=l,a.duration=Va,a.isMoment=o,a.weekdays=ic,a.parseZone=Xb,a.localeData=x,a.isDuration=Fa,a.monthsShort=hc,a.weekdaysMin=kc,a.defineLocale=w,a.weekdaysShort=jc,a.normalizeUnits=z,a.relativeTimeThreshold=Ac;var je=a;return je});define("view/base",["ext/underscore","app-context","messages"],function(_,appContext,messages){var _message=function(code,args){var message=messages.messages[code];if(args){if(args.constructor!==Array){args=[args]}var parts=message.split(/[\{\}]+/);for(var i=1;i<parts.length;i+=2){parts[i]=args[parseInt(parts[i])]}return parts.join("")}return message};return Backbone.View.extend({initialize:function(options){_.bindToMethods(this);this.options=options},template:function(template,data){},template:function(template,data){if(data){var args=_.extend({messages:messages.messages,$:jQuery,appurl:appContext.getAppUrl()},data,messages.messages);return _.template(template,args)}return _.template(template,messages.messages)},getSearchQuery:function(){var parts=location.hash.split("?");if(parts.length>1){parts=parts[1].split("=");if(parts.length>1&&parts[0]=="search"){return parts[1]}}return null},formatQuery:function(query){if(!query){query=this.getSearchQuery()}if(!query){return""}return"?search="+encodeURIComponent(decodeURIComponent(query))},message:_message},{message:_message})});define("view/page",["ext/underscore","$root","view/base","native","app-context","api/service/general"],function(_,$root,BaseView,_native,appContext,service){var $=jQuery;var views={};return BaseView.extend({title:"Clinked",initialize:function(options){_.bindToMethods(this);this.options=options;this.$wrapper=$(">.wrapper",$root)},render:function(){_native.pull&&_native.pull.clear();var id=(new Date).getTime();views[id]=this;this.$view=$("<div>").addClass("view").attr("id",id).append(this.el);var $current=$(".view",$root);var viewId=$current.attr("id");if(viewId){views[viewId].remove();views[viewId]=null}$current.replaceWith(this.$view);if(this.navbar){this.$navigation=$("<div>").addClass("navigation");var self=this;this.navbar(function(navbar){self.$navigation.html(navbar.render().el);self.addFooter(self.$navigation)})}if(appContext.alert){this.$alert=$("<div>").addClass("alert alert-warning").html(appContext.alert);self.addHeader(this.$alert)}if(_native.pull&&_native.refreshable&&this.handleRefresh){_native.pull.init({text:this.message("m_list_pull_to_refresh"),$wrapper:this.$wrapper,success:this.handleRefresh})}if(this.action&&!this.action.link){this.action.target="#"+this.$view.attr("id");this.$view.on("action",this.action.view.doAction)}appContext.setHeader(this);return this},remove:function(){BaseView.prototype.remove.apply(this,arguments);if(this.$navigation){this.removeMarginal(this.$navigation)}if(this.$alert){this.removeMarginal(this.$alert)}},scroll:function(position){this.$view.animate({scrollTop:position},"fast")},addHeader:function($header){$(">.header",$root).after($header.addClass("marginal"));this.updateMarginalCount(+1)},addFooter:function($footer){this.$wrapper.after($footer.addClass("marginal"));this.updateMarginalCount(+1)},removeMarginal:function($marginal){$marginal.remove();this.updateMarginalCount(-1)},updateMarginalCount:function(sign){var marginalCount=this.$wrapper.data("marginals")+sign;var height=_native.height()-marginalCount*44;this.$wrapper.data("marginals",marginalCount).height(height)}})});define("view/extending-list",["ext/underscore","moment","view/page"],function(_,moment,PageView){var $=jQuery;return PageView.extend({tagName:"ul",className:"list-unstyled",initialize:function(options){PageView.prototype.initialize.apply(this,arguments);_(this.emptyMsgCode,"empty list message code required").assert();_(this.itemViewClass,"list item view class required").assert();_(this.handleEndOfList,"end of list handler required").assert();this.$loading=$("<li>").addClass("thin").html(this.message("m_page_loading"))},render:function(){PageView.prototype.render.apply(this,arguments);if(this.collection.length==0){$("<li>").addClass("thin").html(this.message(this.emptyMsgCode)).appendTo(this.$el)}else{this._renderPage(this.collection)}return this},refresh:function(){this.$el.empty();if(this.collection.length==0){$("<li>").addClass("thin").html(this.message(this.emptyMsgCode)).appendTo(this.$el)}else{this._renderPage(this.collection)}},renderPage:function(page){this.$loading.remove();this._renderPage(page)},_renderPage:function(page){page.each(function(model){var itemView=new this.itemViewClass({model:model,page:page});this.$el.append(itemView.render().el)},this);if(page.more){this.$loading.one("inview",this.handleEndOfList).appendTo(this.$el)}},extractDateLabel:function(date){var label;if(this.isToday(date)){label=this.message("m_today")}else if(this.isTomorrow(date)){label=this.message("m_tomorrow")}else{var format;if(this.isThisWeek(date)){format="dddd"}else if(this.isThisYear(date)){format="DD MMMM"}else{format="DD MMMM YYYY"}label=moment(date).format(format)}return label},isToday:function(date){var now=new Date;now.setHours(0,0,0,0);var date=new Date(date);date.setHours(0,0,0,0);return now.getTime()==date.getTime()},isTomorrow:function(date){var now=new Date;now.setHours(0,0,0,0);var date=new Date(date);date.setHours(0,0,0,0);return now.getTime()+864e5==date.getTime()},isThisWeek:function(date){var now=moment().format("YYYY ww");date=moment(date).format("YYYY ww");return now==date},isThisYear:function(date){return moment().format("YYYY")==moment(date).format("YYYY")}})});define("api/model/content",["api/model/base","api/model/group"],function(BaseModel,Group){return BaseModel.extend({url:function(){var id="";if(this.id){id="@"+this.id+"/"}else{var name=this.get("name");if(name){id=name+"/"}}return"/groups/@"+this.get("group").id+"/"+this.type+"s/"+id},getGroup:function(){return new Group(this.get("group"))}})});define("api/model/file",["api/model/content"],function(Content){
     11return Content.extend({initialize:function(){this.type="file"},isFolder:function(){return this.get("contentType")=="@folder"},getExtension:function(){if(this.isFolder()){return"folder"}var filename=this.get("friendlyName");var extensionPos=filename.lastIndexOf(".");if(filename.lastIndexOf("/")>extensionPos){return""}return filename.substring(extensionPos+1).toLowerCase()}},{type:"file"})});define("api/model/note",["api/model/content"],function(Content){return Content.extend({initialize:function(){this.type="page"}},{type:"page"})});define("api/model/discussion",["ext/underscore","api/model/content"],function(_,Content){return Content.extend({initialize:function(){this.type="discussion"}},{type:"discussion"})});define("api/model/event",["moment","api/model/content"],function(moment,Content){return Content.extend({initialize:function(){this.type="event"},getStartDate:function(){var startDate=moment(this.get("startDate"));if(this.get("allDay")){startDate.startOf("day")}return startDate},getEndDate:function(){var endDate=moment(this.get("endDate"));if(this.get("allDay")){endDate.subtract(1,"days").startOf("day")}return endDate},isSameDay:function(){var start=new Date(this.get("startDate"));start.setHours(0,0,0,0);var end=this.getEndDate().toDate();end.setHours(0,0,0,0);return start.getTime()==end.getTime()}},{type:"event"})});define("api/model/task",["api/model/content"],function(Content){return Content.extend({initialize:function(){this.type="task"},isOverdue:function(){return this.get("overdue")&&!this.get("completed")}},{type:"task"})});define("api/factory",["api/model/file","api/model/note","api/model/discussion","api/model/event","api/model/task"],function(File,Note,Discussion,Event,Task){return{createEntity:function(attributes){if(attributes.type=="page"){return new Note(attributes)}else if(attributes.type=="file"){return new File(attributes)}else if(attributes.type=="discussion"){return new Discussion(attributes)}else if(attributes.type=="event"){return new Event(attributes)}else if(attributes.type=="task"){return new Task(attributes)}return null}}});define("text",["module"],function(module){"use strict";var text,fs,progIds=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],xmlRegExp=/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,bodyRegExp=/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,hasLocation=typeof location!=="undefined"&&location.href,defaultProtocol=hasLocation&&location.protocol&&location.protocol.replace(/\:/,""),defaultHostName=hasLocation&&location.hostname,defaultPort=hasLocation&&(location.port||undefined),buildMap=[],masterConfig=module.config&&module.config()||{};text={version:"2.0.3",strip:function(content){if(content){content=content.replace(xmlRegExp,"");var matches=content.match(bodyRegExp);if(matches){content=matches[1]}}else{content=""}return content},jsEscape:function(content){return content.replace(/(['\\])/g,"\\$1").replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r").replace(/[\u2028]/g,"\\u2028").replace(/[\u2029]/g,"\\u2029")},createXhr:masterConfig.createXhr||function(){var xhr,i,progId;if(typeof XMLHttpRequest!=="undefined"){return new XMLHttpRequest}else if(typeof ActiveXObject!=="undefined"){for(i=0;i<3;i+=1){progId=progIds[i];try{xhr=new ActiveXObject(progId)}catch(e){}if(xhr){progIds=[progId];break}}}return xhr},parseName:function(name){var strip=false,index=name.indexOf("."),modName=name.substring(0,index),ext=name.substring(index+1,name.length);index=ext.indexOf("!");if(index!==-1){strip=ext.substring(index+1,ext.length);strip=strip==="strip";ext=ext.substring(0,index)}return{moduleName:modName,ext:ext,strip:strip}},xdRegExp:/^((\w+)\:)?\/\/([^\/\\]+)/,useXhr:function(url,protocol,hostname,port){var uProtocol,uHostName,uPort,match=text.xdRegExp.exec(url);if(!match){return true}uProtocol=match[2];uHostName=match[3];uHostName=uHostName.split(":");uPort=uHostName[1];uHostName=uHostName[0];return(!uProtocol||uProtocol===protocol)&&(!uHostName||uHostName.toLowerCase()===hostname.toLowerCase())&&(!uPort&&!uHostName||uPort===port)},finishLoad:function(name,strip,content,onLoad){content=strip?text.strip(content):content;if(masterConfig.isBuild){buildMap[name]=content}onLoad(content)},load:function(name,req,onLoad,config){if(config.isBuild&&!config.inlineText){onLoad();return}masterConfig.isBuild=config.isBuild;var parsed=text.parseName(name),nonStripName=parsed.moduleName+"."+parsed.ext,url=req.toUrl(nonStripName),useXhr=masterConfig.useXhr||text.useXhr;if(!hasLocation||useXhr(url,defaultProtocol,defaultHostName,defaultPort)){text.get(url,function(content){text.finishLoad(name,parsed.strip,content,onLoad)},function(err){if(onLoad.error){onLoad.error(err)}})}else{req([nonStripName],function(content){text.finishLoad(parsed.moduleName+"."+parsed.ext,parsed.strip,content,onLoad)})}},write:function(pluginName,moduleName,write,config){if(buildMap.hasOwnProperty(moduleName)){var content=text.jsEscape(buildMap[moduleName]);write.asModule(pluginName+"!"+moduleName,"define(function () { return '"+content+"';});\n")}},writeFile:function(pluginName,moduleName,req,write,config){var parsed=text.parseName(moduleName),nonStripName=parsed.moduleName+"."+parsed.ext,fileName=req.toUrl(parsed.moduleName+"."+parsed.ext)+".js";text.load(nonStripName,req,function(value){var textWrite=function(contents){return write(fileName,contents)};textWrite.asModule=function(moduleName,contents){return write.asModule(moduleName,fileName,contents)};text.write(pluginName,nonStripName,textWrite,config)},config)}};if(masterConfig.env==="node"||!masterConfig.env&&typeof process!=="undefined"&&process.versions&&!!process.versions.node){fs=require.nodeRequire("fs");text.get=function(url,callback){var file=fs.readFileSync(url,"utf8");if(file.indexOf("\ufeff")===0){file=file.substring(1)}callback(file)}}else if(masterConfig.env==="xhr"||!masterConfig.env&&text.createXhr()){text.get=function(url,callback,errback){var xhr=text.createXhr();xhr.open("GET",url,true);if(masterConfig.onXhr){masterConfig.onXhr(xhr,url)}xhr.onreadystatechange=function(evt){var status,err;if(xhr.readyState===4){status=xhr.status;if(status>399&&status<600){err=new Error(url+" HTTP status: "+status);err.xhr=xhr;errback(err)}else{callback(xhr.responseText)}}};xhr.send(null)}}else if(masterConfig.env==="rhino"||!masterConfig.env&&typeof Packages!=="undefined"&&typeof java!=="undefined"){text.get=function(url,callback){var stringBuffer,line,encoding="utf-8",file=new java.io.File(url),lineSeparator=java.lang.System.getProperty("line.separator"),input=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file),encoding)),content="";try{stringBuffer=new java.lang.StringBuffer;line=input.readLine();if(line&&line.length()&&line.charAt(0)===65279){line=line.substring(1)}stringBuffer.append(line);while((line=input.readLine())!==null){stringBuffer.append(lineSeparator);stringBuffer.append(line)}content=String(stringBuffer.toString())}finally{input.close()}callback(content)}}return text});define("text!text/search/item.html",[],function(){return"<a href=\"<%= link %>\">\n   <img src=\"<%= appurl %>/svg/<%= extension %>.svg\" onerror='this.onerror = null; this.src=\"<%= appurl %>/svg/file.svg\"'>\n   <p><b><%= get('name') %></b></p>\n  <abbr><%= m_last_updated %>: <%= $.timeago(new Date(get('timestamp'))) %></abbr>\n</a>\n"});define("view/search/item",["ext/underscore","view/base","api/factory","text!text/search/item.html"],function(_,BaseView,factory,template){return BaseView.extend({tagName:"li",className:"fat",initialize:function(options){BaseView.prototype.initialize.apply(this,arguments);this.page=options.page},render:function(){var extension=this.model.get("type");if(extension=="file"){var parts=this.model.get("name").split(".");extension=parts[parts.length-1]}this.model.set("group",{id:this.model.get("space")});var entity=factory.createEntity(this.model.toJSON());var args=_.extend({link:"#"+this.model.get("type")+"/"+entity.getKey()+this.formatQuery(this.page.params.query),extension:extension},this.model);this.$el.html(this.template(template,args));return this}})});define("view/search/list",["api/service/general","view/extending-list","view/search/item"],function(service,ExtendingListView,SearchItemView){var view=ExtendingListView.extend({back:{code:"m_context_dashboard",link:"#start"},title:ExtendingListView.message("m_search"),emptyMsgCode:"m_search_nothing",itemViewClass:SearchItemView,handleEndOfList:function(){service.getNextSearchResults(this.collection,this.renderPage)}});return view});define("text!text/search/suggestions.html",[],function(){return'&nbsp;&nbsp;<%= m_search_suggestions %>\n<% _.each(suggestions, function(suggestion, index) { %><!--\n \n --><% if (index != 0) { %>,<% } %>\n <a href="#search/<%= suggestion.suggestion %>"><%= suggestion.suggestion %></a><!-- \n  \n --><% }); %>?\n'});define("view/search/suggestions",["ext/underscore","view/page","text!text/search/suggestions.html"],function(_,PageView,template){return PageView.extend({tagName:"h4",back:{code:"m_context_dashboard",link:"#start"},title:PageView.message("m_search_nothing"),render:function(){PageView.prototype.render.apply(this,arguments);if(this.collection.length>0){var args={suggestions:this.collection.toJSON()};this.$el.html(this.template(template,args))}return this}})});define("view/public/branding",["app-context"],function(appContext){var $=jQuery;return{brand:function(){this.$view.addClass("wallpaper");var $logo=$("<div>").addClass("logo").prependTo(this.$el);if(appContext.startOptions.logo){$logo.css("background-image","url("+appContext.startOptions.logo+")");this.$view.css("background-image","none")}if(appContext.startOptions.wallpaper){this.$view.css("background-image","url("+appContext.startOptions.wallpaper+")")}}}});define("view/dialog",["ext/underscore","native","view/base"],function(_,_native,BaseView){var $=jQuery;return BaseView.extend({initialize:function(options){_.assert(options.callback,"callback required");_.assert(this.title,"title required");_.bindToMethods(this);this.options=options},render:function(){$(".modal-title").html(this.title);$(".modal-body").html(this.el);var $dialog=$(".modal-dialog").css({width:this.options.width?this.options.width:_native.width()-20+"px"});$(".modal").modal("show");$dialog.css("margin-left",function(){return($(window).width()-$(this).width())/2});return this},callback:function(){$(".modal").modal("hide");this.remove();this.options.callback.apply(this,arguments)}})});define("text!text/validated-input.html",[],function(){return'<input class="form-control" type="<%= type %>" name="<%= name %>" value="<%= value %>"   \n   <% if (maxlength) { print(\'maxlength=\' + maxlength) } %>\n    placeholder="<%= label ? messages[label] : \'\' %>"\n    autocorrect="<%= autocomplete ? \'on\' : \'off\' %>"\n    autocapitalize="<%= autocomplete ? \'on\' : \'off\' %>" >\n<p class="hidden invalid"></p>\n'});define("view/validated-input",["ext/underscore","view/base","text!text/validated-input.html"],function(_,BaseView,template){var $=jQuery;return BaseView.extend({events:{"keyup input":"keyup","blur input":"blur"},initialize:function(){BaseView.prototype.initialize.apply(this,arguments);_.assert(this.options.name,"name required");if(!this.options.validate){this.options.validate=function(text,handler){handler()}}},render:function(){var defs={type:"text",value:"",maxlength:null,autocomplete:true};this.$el.html(this.template(template,_.extend(defs,this.options)));return this},keyup:function(){if(this.options.keyup){this.options.keyup.call(this,$("input",this.$el).val())}},blur:function(){this.options.validate.call(this,$("input",this.$el).val(),this.displayValidation)},val:function(){return $("input",this.$el).val()},displayValidation:function(error){var $error=$("p",this.$el).html(this.message(error));if(error){$error.removeClass("hidden")}else{$error.addClass("hidden")}}})});define("view/validated-email",["ext/underscore","view/validated-input"],function(_,ValidatedInput){return ValidatedInput.extend({initialize:function(options){_.extend(options,{type:"text",name:"email",autocomplete:false,validate:function(text,handler){var re=/^([^\s\"\(\)\[\]\{\}])+@([\w-]+\.)+[A-Za-z]{2,4}$/;if(re.test(text)){handler()}else{handler("m_email_input_error")}}});ValidatedInput.prototype.initialize.apply(this,arguments)}})});define("text!text/public/forgotten.html",[],function(){return'<a href="javascript:void(0)" class="btn btn-primary">\n    <%= m_forgotten_request %>\n</a>\n'});define("view/public/forgotten",["view/dialog","view/validated-email","text!text/public/forgotten.html"],function(DialogView,ValidatedEmail,template){var $=jQuery;return DialogView.extend({tagName:"fieldset",title:DialogView.message("m_forgotten_title"),events:{"click a":"validate"},emailInput:new ValidatedEmail({label:"m_forgotten_email"}),render:function(){DialogView.prototype.render.apply(this,arguments);this.$el.html(this.template(template));$("a",this.$el).before(this.emailInput.render().el);return this},validate:function(){var self=this;this.emailInput.options.validate(this.emailInput.val(),function(error){self.emailInput.displayValidation(error);!error&&self.request()})},request:function(){var $email=$("input[name=email]",this.$el);this.callback($email.val())}})});define("text!text/public/signin.html",[],function(){return'<% if (error) { %>\n  <div class="alert alert-danger"><%= error %></div>\n<% } %>\n<input class="form-control" name="username" placeholder="<%= m_signin_username %>" type="text" autocorrect="off" autocapitalize="off">\n<input class="form-control" name="password" placeholder="<%= m_signin_password %>" type="password">\n<a href="javascript:void(0)" id="signin" class="btn btn-primary">\n   <%= m_signin_signin %>\n</a>\n<a href="javascript:void(0)" id="forgotten-link">\n   <%= m_signin_forgotten %>\n</a>\n<% if (thirdPartySignin) { %>\n    <a data-external class="btn btn-default linkedin" href="<%= appRoot %>/linkedin?referrer=mobile" >\n        <i class="fa fa-linkedin"></i>\n        <%= m_signin_linkedin %>\n  </a>\n  <a data-external class="btn btn-default google" href="<%= appRoot %>/google/oauth2?referrer=mobile" >\n     <i class="fa fa-google-plus"></i>\n     <%= m_signin_google %>\n    </a>\n<% } %>\n<% if (env != \'prod\') { %>\n   <div class="alert alert-success"><%= env %></div>\n<% } %>\n'});define("view/public/signin",["ext/underscore","view/page","native","app-context","api/service/general","view/public/branding","view/public/forgotten","text!text/public/signin.html"],function(_,PageView,native,appContext,service,branding,ForgottenView,template){return PageView.extend(_.extend(branding,{tagName:"fieldset",events:{"click #signin":"signin","click #forgotten-link":"openForgotten"},nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.title=PageView.message("m_signin_title")},render:function(){PageView.prototype.render.apply(this,arguments);var args={error:this.message(this.options.error),appRoot:appContext.resolveAppEndPoint(),env:appContext.getEnvironment(),thirdPartySignin:native.thirdPartySignin};this.$el.html(this.template(template,args));this.brand();return this},openForgotten:function(){var forgotten=new ForgottenView({callback:this.handleForgotten});forgotten.render()},handleForgotten:function(email){service.requestPasswordReset(email,function(success){success=success?"sent":"fail";appContext.navigate("#public/signin/m_forgotten_request_"+success,true)})},signin:function(){var $username=this.$el.find("input[name=username]");var $password=this.$el.find("input[name=password]");var credentials={username:$username.val(),password:$password.val()};if(credentials.username.indexOf("@")==0){appContext.setEnvironment(credentials.username.substr(1));appContext.navigate("#public/signin",true)}else{this.options.authenticate(credentials)}}}))});define("text!text/public/signup.html",[],function(){return'<p><b>Your Email: <%= email %></b></p>\n<a href="javascript:void(0)" id="signup" class="btn btn-primary">\n  <%= m_signup_signup %>\n</a>\n'});define("view/public/signup",["ext/underscore","view/page","app-context","api/service/general","view/public/branding","view/validated-input","text!text/public/signup.html"],function(_,PageView,appContext,service,branding,ValidatedInput,template){var $=jQuery;var _formatUsername=function(name){name=name.toLowerCase();var result=[];for(var i=0;i<name.length;i++){result.push(!name.charAt(i).match(/[a-z0-9_]/)?".":name.charAt(i))}return result.join("")};return PageView.extend(_.extend(branding,{tagName:"fieldset",events:{"click #signup":"validate"},nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.title=PageView.message("m_signup_header");var usernameView=new ValidatedInput({autocomplete:false,name:"user.username",label:"m_input_username",maxlength:32,validate:function(text,handler){if(!text){handler("m_input_error_username")}else if(text.length>2){service.isUsernameTaken(text,function(status){handler(status?"m_input_error_taken":null)})}else{handler()}},keyup:function(text){var name=$("input",nameView.$el).val();this.manual=_formatUsername(name)!=text}});var nameView=new ValidatedInput({name:"user.name",label:"m_input_name",maxlength:32,validate:function(text,handler){_.defer(usernameView.blur);handler(text?null:"m_input_error_name")},keyup:function(text){if(!usernameView.manual){var username=_formatUsername(text);$("input",usernameView.$el).val(username)}}});var passwordView=new ValidatedInput({type:"password",name:"user.password",label:"m_input_password",validate:function(text,handler){if(!text){handler("m_input_error_password")}else if(text.length<6){handler("m_input_error_minimum_6")}else{handler()}}});this.inputs=[nameView,usernameView,passwordView,new ValidatedInput({type:"password",name:"passwordConfirm",label:"m_input_confirm",validate:function(text,handler){if(!text){handler("m_input_error_confirm")}else{var password=$("input",passwordView.$el).val();handler(text==password?null:"m_input_error_mismatch")}}}),new ValidatedInput({name:"user.telephone",label:"m_input_telephone",maxlength:20}),new ValidatedInput({name:"user.organisation",label:"m_input_organisation",maxlength:100})]},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,this.options));this.brand();var $signup=$("#signup",this.$el);_.each(this.inputs,function(input){$signup.before(input.render().el)});return this},validate:function(){var allValid=true;var inputCount=this.inputs.length;var self=this;_.each(this.inputs,function(input){input.options.validate(input.val(),function(error){inputCount--;input.displayValidation(error);!error||(allValid=false);if(inputCount==0&&allValid){self.signup()}})})},signup:function(){var user=$("input",this.$el).serializeArray();user.push({name:"inviteKey",value:this.options.inviteKey});user.push({name:"user.email",value:this.options.email});var currentYear=(new Date).getFullYear();var rawOffset=Date.UTC(currentYear,0,1)-new Date(currentYear,0,1).getTime();user.push({name:"rawOffset",value:rawOffset});user.push({name:"dstSavings",value:Date.UTC(currentYear,6,1)-new Date(currentYear,6,1).getTime()-rawOffset});service.createUser(user,this.signupComplete)},signupComplete:function(success){if(success){var credentials={username:$("[name='user.username']",this.$el).val(),password:$("[name='user.password']",this.$el).val()};this.options.authenticate(credentials)}else{appContext.navigate("#public/signin/m_error_unexpected",true)}}}))});define("text!text/public/reset.html",[],function(){return'<a href="javascript:void(0)" id="reset" class="btn btn-primary">\n    <%= m_reset_reset %>\n</a>\n'});define("view/public/reset",["ext/underscore","view/page","app-context","api/service/general","view/public/branding","view/validated-input","text!text/public/reset.html"],function(_,PageView,appContext,service,branding,ValidatedInput,template){var $=jQuery;return PageView.extend(_.extend(branding,{tagName:"fieldset",events:{"click #reset":"validate"},title:PageView.message("m_reset_header"),nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var passwordView=this.passwordView=new ValidatedInput({type:"password",name:"password",label:"m_input_password",validate:function(text,handler){if(!text){handler("m_input_error_password")}else if(text.length<6){handler("m_input_error_minimum_6")}else{handler()}}});this.confirmView=new ValidatedInput({type:"password",name:"confirmedPassword",label:"m_input_confirm",validate:function(text,handler){if(!text){handler("m_input_error_confirm")}else{var password=$("input",passwordView.$el).val();handler(text==password?null:"m_input_error_mismatch")}}})},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,this.options));this.brand();var $reset=$("#reset",this.$el);$reset.before(this.passwordView.render().el);$reset.before(this.confirmView.render().el);return this},validate:function(){var self=this;var valid=0,count=0;var check=function(error){count++;if(!error){valid++}if(count==2&&valid==2){self.reset()}};this.passwordView.options.validate(this.passwordView.val(),function(error){self.passwordView.displayValidation(error);check(error)});this.confirmView.options.validate(this.confirmView.val(),function(error){self.confirmView.displayValidation(error);check(error)})},reset:function(){service.resetPassword(this.options.username,this.options.tokenKey,$("input",this.$el).serializeArray(),this.resetComplete)},resetComplete:function(success){if(success){var credentials={username:this.options.username,password:$("[name=password]",this.$el).val()};this.options.authenticate(credentials)}else{appContext.navigate("#public/signin/m_error_unexpected",true)}}}))});define("text!text/context-item.html",[],function(){return"<a href=\"javascript:void(0)\">\n  <% if (model.type == 'group') { %>\n        <img src=\"<%= cdn %>/customise/<%= model.get('hash') %>/@logo?_=<%= model.get('lastModified') %>\">\n  <% } %>\n   <%= _.escape(model.get('friendlyName')) %>\n</a>\n"});define("view/context/item",["ext/underscore","app-context","api/service/general","api/model/account","text!text/context-item.html"],function(_,appContext,service,Account,template){return Backbone.View.extend({tagName:"li",className:"context-item",events:{"click a":"onClick"},render:function(){if(!this.model.id){this.$el.addClass("hidden")}else if(this.model.type=="account"){this.$el.addClass("list-header")}var args={cdn:appContext.cdn,model:this.model};this.$el.html(_.template(template,args));return this},onClick:function(){appContext.setDashboard(this.model.getKey());var account=this.model.type=="group"?new Account(this.model.get("account")):this.model;service.getAccount(account.id,function(account){window.localStorage.setItem("features",account.get("features"));appContext.navigate("#start",true)})}})});define("view/context/select",["ext/underscore","view/page","view/context/item"],function(_,PageView,ContextItemView){return PageView.extend({title:PageView.message("m_context_select_header"),nosearch:true,action:{code:"m_context_signout",link:"#signout"},tagName:"ul",className:"list-unstyled",append:function(model){var view=new ContextItemView({model:model});this.$el.append(view.render().el)},render:function(){PageView.prototype.render.apply(this,arguments);this.collection.each(function(account){this.append(account);_.each(account.groups,function(group){this.append(group)},this)},this);return this}})});define("text!text/error.html",[],function(){return'<div class="alert alert-danger">\n   <%= online ? (!code ? m_error_unexpected : message) : m_error_network %>\n</div>\n<a href="#start" class="btn btn-primary">\n   <%= online ? m_error_dashboard : m_error_retry %>\n</a>\n'});define("view/error",["ext/underscore","view/page","text!text/error.html"],function(_,PageView,template){return PageView.extend({tagName:"fieldset",title:PageView.message("m_error_title"),nosearch:true,render:function(){PageView.prototype.render.apply(this,arguments);if(this.options.code){this.options.message=this.message(this.options.code)}this.$el.html(this.template(template,this.options));return this}})});define("router/default",["router/base","native","app-context","api/cache","api/service/general","api/model/account","api/model/group","api/model/request","view/search/list","view/search/suggestions","view/public/signin","view/public/signup","view/public/reset","view/context/select","view/error"],function(BaseRouter,_native,appContext,cache,service,Account,Group,Request,SearchListView,SearchSuggestionsView,SigninView,SignupView,ResetView,ContextSelectView,ErrorView){return BaseRouter.extend({routes:{"search/:query":"getSearch","defer/:organisation/requests/:id/:answer":"handleDeferredRequest","defer/:organisation/:group":"handleDeferredContent","defer/:organisation/:group/:type/:id":"handleDeferredContent","public/signup/:inviteKey":"showSignup","public/signin":"showSignin","public/signin/:error":"showSignin","public/reset/:username/:tokenKey":"showReset","public/auth/:session":"authenticateWithSession",signout:"actionSignout",start:"handleStart",context:"getAccounts",error:"showError","error/:code":"showError","*splat":"splat"},getSearch:function(query){var self=this;service.getContext(appContext.getDashboard(),function(context){var account=context.type=="group"?new Account(context.get("account")):context;service.getSearchResults(account,decodeURIComponent(query),self.showSearch)})},showSearch:function(results){if(results.suggestions){new SearchSuggestionsView({collection:results}).render()}else{new SearchListView({collection:results}).render()}},handleDeferredRequest:function(organisation,id,answer){var request=new Request({id:id});request.answer=answer;request.once("sync",this.answerRequest);request.fetch()},answerRequest:function(request){request.set("status",request.answer.toUpperCase());request.once("sync",function(){var key=request.get("contextKey");type=key.objectType.split(".")[4].toLowerCase();if(type=="space"){if(request.answer=="accept"){appContext.navigate("#updates/groups:@"+key.objectId,true)}else{appContext.navigate("#start",true)}}else{appContext.navigate("#"+type+"/"+type+":"+key.parent.objectId+":@"+key.objectId,true)}});request.save()},handleDeferredContent:function(organisation,group,type,id){group=new Group({name:organisation+":"+group});if(type){group.entity={type:type,id:id}}group.once("sync",this.redirectToGroupContent);group.fetch()},redirectToGroupContent:function(group){if(group.entity){var type=group.entity.type.substr(0,group.entity.type.length-1);appContext.navigate("#"+type+"/"+type+":"+group.id+":"+group.entity.id,true)}else{appContext.navigate("#updates/groups:@"+group.id,true)}},showSignin:function(error){var self=this;if(appContext.getCredentials()){appContext.navigate("#start",true)}else{new SigninView({authenticate:self.authenticate,error:error}).render()}},actionSignout:function(){appContext.removeDashboard();appContext.removeAccessToken();appContext.removePrinciple();cache.clear();appContext.removeCredentials();appContext.navigate("#public/signin",true)},handleStart:function(){var contextKey=appContext.getDashboard();if(contextKey){service.getContext(contextKey,function(context){if(context.type=="group"){var component=context.get("components")[0];if(component=="activity"){appContext.navigate("#updates/"+contextKey,true)}else{appContext.navigate("#"+component+"/"+contextKey,true)}}else{appContext.navigate("#updates/"+contextKey,true)}})}else{appContext.navigate("#context",true)}},getAccounts:function(){service.getAccountsWithGroups(this.showContextSelect)},showContextSelect:function(accounts){new ContextSelectView({collection:accounts}).render()},showError:function(code){_native.online(function(online){new ErrorView({code:code,online:online}).render()})},splat:function(){this.showError("m_error_not_found")},showSignup:function(inviteKey){var self=this;service.getEmailFromInviteKey(inviteKey,function(email){if(email){appContext.removeAccessToken();appContext.removePrinciple();cache.clear();new SignupView({authenticate:self.authenticate,email:email,inviteKey:inviteKey}).render()}else{appContext.navigate("#error/m_error_invite",true)}})},showReset:function(username,tokenKey){appContext.removeAccessToken();appContext.removePrinciple();cache.clear();new ResetView({authenticate:this.authenticate,username:username,tokenKey:tokenKey}).render()},authenticateWithSession:function(session){this.authenticate({session:session})},authenticate:function(credentials){appContext.setCredentials(credentials);service.fetchPrinciple(function(principle){appContext.setPrinciple(principle.toJSON());appContext.navigate("#start",true)})}})});define("api/model/update",["ext/underscore","api/model/base","api/model/account","api/model/group","api/factory"],function(_,BaseModel,Account,Group,factory){return BaseModel.extend({initialize:function(attributes){if(attributes.component){this.component=factory.createEntity(attributes.component)}},urlRoot:"/updates",isMicroblog:function(){return this.get("messageCode").search(/\.private$/)!=-1},getComponent:function(){return this.component},getAccount:function(){if(!this.account){this.account=this.get("account");if(this.account){this.account=new Account(this.account)}}return this.account},getGroup:function(){if(!this.group){this.group=this.get("group");if(this.group){this.group=new Group(this.group)}}return this.group},getContext:function(){if(this.getGroup()){return this.getGroup()}else if(this.getAccount()){return this.getAccount()}},format:function(template){var user=this.get("user");var account=this.get("account");var group=this.get("group");var args=[user?user.name:this.get("userName"),account?account.friendlyName:this.get("accountName"),group?group.friendlyName:this.get("groupName"),_.escape(this.get("componentName")),null,this.get("reservedName")];var parts=template.split(/[\{\}]+/);for(var i=1;i<parts.length;i+=2){parts[i]=args[parseInt(parts[i])]}var control={max:80};var description="";for(var i=0;i<parts.length&&!control.truncate;i++){var part=this.truncate(control,parts[i]);description+=i%2?part.bold():part}return description},truncate:function(control,part){if(!part){part=""}if(!control.current){control.current=0}control.current+=part.length;if(control.current>control.max){control.truncate=true;return part.substr(0,control.current-control.max)+".."}return part}})});define("api/collection/updates",["api/collection/base","api/model/update"],function(BaseCollection,Update){return BaseCollection.extend({model:Update,url:"/updates",initialize:function(models,options){this.context=options.context;this.params={currentPage:1,pageSize:25};if(options.current){if(options.current.offset){this.params.offset=options.current.offset}else{this.params.currentPage+=options.current.params.currentPage}}this.params[this.context.type+"Id"]=this.context.id},parse:function(response){if(response.page){this.more=response.nextPage;return response.page}this.offset=response.offset;this.more=response.more;return response.items},addPage:function(page){this.add(page.models);if(page.offset){this.offset=page.offset}else{this.params.currentPage=page.params.currentPage}this.more=page.more},_getKey:function(key){return key+":"+this.context.getKey()}})});define("api/model/microblog-reply",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(){this.reply=true},getComment:function(){return this.get("comment")},getCommenter:function(){return this.get("commenter")},getDateCreated:function(){return new Date(this.get("dateCreated"))}})});define("api/collection/microblog-replies",["api/collection/base","api/model/microblog-reply"],function(BaseCollection,Reply){return BaseCollection.extend({model:Reply,initialize:function(models,options){this.parent=options.parent},url:function(){return this.parent.url()+"/comments"}})});define("api/model/microblog",["ext/underscore","api/collection/microblog-replies","api/model/update"],function(_,Replies,Update){
     12return Update.extend({getComment:function(){return this.get("message")},getCommenter:function(){return this.get("user")},getDateCreated:function(){return new Date(this.get("lastModified"))},getReplies:function(){if(!this.replies){this.replies=new Replies(this.get("replies"),{parent:this})}return this.replies},_getKey:function(key){return key+":microblog"}})});define("api/model/base-comment",["api/model/base"],function(BaseModel){return BaseModel.extend({url:function(){var id=this.id?"/@"+this.id:"";return this.collection.url()+id},getComment:function(){return this.get("comment")},getCommenter:function(){var commenter=this.get("commenter");return commenter?commenter:{name:this.get("commenterName")}},getDateCreated:function(){return new Date(this.get("dateCreated"))}})});define("api/model/reply",["api/model/base-comment"],function(BaseComment){return BaseComment.extend({initialize:function(){this.reply=true}})});define("api/service/update",["ext/underscore","api/cache","api/service/general","api/collection/updates","api/model/microblog","api/model/reply"],function(_,cache,service,Updates,Microblog,Reply){var _getUpdatesPage=function(updates,handler){updates.once("sync",function(){updates.each(function(update){var component=update.getComponent();if(component){cache.putModel(component)}});handler(updates)});updates.fetch()};return{getUpdates:function(contextKey,handler,force){service.getContext(contextKey,function(context){var updates=new Updates([],{context:context});if(!force){updates=cache.getFrom(updates);if(updates._expiry){handler(updates);return}}_getUpdatesPage(updates,function(updates){cache.putModel(updates);handler(updates)})})},getCachedUpdates:function(contextKey,handler){service.getContext(contextKey,function(context){var updates=new Updates([],{context:context});handler(cache.getFrom(updates))})},getNextUpdates:function(updates,handler){_getUpdatesPage(new Updates([],{context:updates.context,current:updates}),function(next){updates.addPage(next);handler(next)})},getMicroblog:function(id,handler,force){var microblog=new Microblog({id:id});if(!force){microblog=cache.getFrom(microblog);if(microblog._expiry){handler(microblog);return}}microblog.once("change",function(){handler(microblog)});microblog.fetch()},createMicroblog:function(context,text,handler){var attributes={message:text};attributes[context.type]={id:context.id};var microblog=new Microblog(attributes);microblog.save();microblog.once("change",_.bind(handler,this,microblog))},createMicroblogReply:function(microblog,text,handler){var replies=microblog.getReplies();var reply=new Reply({comment:text});replies.once("change",_.bind(handler,this,reply));replies.add(reply);reply.save()}}});define("text!text/navbar.html",[],function(){return"<% _.each(btns, function(btn, i) { %>\n   <div class=\"btn-group <%= btn.name %>\">\n     <a href=\"<%= btn.link %>\" class=\"btn btn-default <%= btn.name == focus ? 'selected' : '' %>\">\n         <img src=\"<%= appurl %>/svg/components/<%= btn.name %><%= btn.name == focus ? '-white' : '' %>.svg\" />\n      </a>\n  </div>\n<% }); %>\n"});define("view/navbar",["ext/underscore","view/base","text!text/navbar.html"],function(_,BaseView,template){return BaseView.extend({className:"btn-group btn-group-justified",initialize:function(options){_.assert(options.btns,"btns required");_.assert(options.focus,"focus required");this.options=options},render:function(){this.$el.html(this.template(template,this.options));return this}})});define("view/navbar-factory",["ext/underscore","api/service/general","view/navbar"],function(_,service,NavBar){return{navbarCreate:function(focus,groupId,callback){service.getGroup(groupId,function(group){var choiceMap={activity:{name:"activity",link:"#updates/"+group.getKey()},pages:{name:"notes",link:"#notes/"+group.getKey()},files:{name:"files",link:"#files/"+group.getKey()},discussions:{name:"discussions",link:"#discussions/"+group.getKey()},events:{name:"events",link:"#events/"+group.getKey()},tasks:{name:"tasks",link:"#tasks/"+group.getKey()},chat:{name:"messages",link:"#messages/"+group.getKey()}};var btns=[];_.each(group.get("components"),function(component){if(choiceMap[component]){btns.push(choiceMap[component])}});callback(new NavBar({focus:focus,btns:btns}))})}}});define("text!text/update-item.html",[],function(){return"<img class=\"svg-1default <%= sprite %>\" src=\"<%= image %>\" \n  onerror='this.onerror = null; this.src=\"<%= appurl %>/styles/images/default_thumbnail.png\"'>\n<% var template = messages[model.get('messageCode')]; %>\n<p><%= template ? model.format(template) : m_update_unknown %></p>\n<abbr><%= $.timeago(new Date(model.get('lastModified'))) %></abbr>\n"});define("view/update/item",["ext/underscore","view/base","app-context","api/cache","text!text/update-item.html"],function(_,BaseView,appContext,cache,template){var $=jQuery;return BaseView.extend({tagName:"li",className:"fat update-item",render:function(){var args=this.addImageArgs({model:this.model});var parent=null;var link=this.createLink();if(link){parent=$("<a>").attr("href",link).appendTo(this.el)}else{parent=this.$el}parent.addClass("list-parent").append(this.template(template,args));return this},createLink:function(){if(this.model.isMicroblog()){cache.putModel(this.model);return"#microblog/"+this.model.getKey()}else if(this.model.get("component")){var component=this.model.getComponent();if(component){if(this.model.get("message")){var root="#comments/";if(this.model.get("messageCode")=="update.discussion.createreply"){root="#discussion/"}return root+component.getKey()+"/"+this.model.get("lastModified")}return"#"+component.type+"/"+component.getKey()}}else if(this.model.getContext()){var contextKey=this.model.getContext().getKey();if(contextKey!=this.model.collection.context.getKey()){return"#updates/"+contextKey}}return null},addImageArgs:function(args){if(this.model.isMicroblog()){args.sprite="";var blogger=this.model.get("user");if(blogger.logo){args.image=appContext.cdn+"/users/"+blogger.id+"/thumbnail"}else{args.image=appContext.defaultThumb}}else{args.sprite="svg-"+this.model.get("messageCode").replace(/\./g,"");var component=this.model.getComponent();if(component&&component.isFolder&&component.isFolder()){args.sprite+=" folder"}args.image=appContext.getAppUrl()+"/styles/images/transparent.gif"}return args}})});define("view/update/list",["ext/underscore","api/service/update","view/navbar-factory","view/extending-list","view/update/item"],function(_,service,navbarFactory,ExtendingListView,UpdateItemView){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);this.title=_.escape(this.options.context.get("friendlyName"));this.action={code:"m_comment",icon:"comment",link:"#updates/"+this.options.context.getKey()+"/create"};if(this.options.context.type=="group"){this.navbar=this._navbar}},emptyMsgCode:"m_updates_nothing",itemViewClass:UpdateItemView,handleEndOfList:function(){service.getNextUpdates(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getUpdates(this.collection.context.getKey(),function(updates){self.collection=updates;self.refresh()},true)},_navbar:function(callback){this.navbarCreate("activity",this.options.context.id,callback)}}).extend(navbarFactory)});define("text!text/people-item.html",[],function(){return'<a class="item-with-icon" href="javascript:void(0)">\n   <img src="<%= thumb %>">\n  <h4><%= name %></h4>\n</a>\n'});define("view/people/item",["ext/underscore","app-context","text!text/people-item.html"],function(_,appContext,template){return Backbone.View.extend({tagName:"li",className:"fat",events:{"click a":"select"},initialize:function(options){_.assert(options.callback,"callback required");this.options=options},render:function(){var thumb=appContext.getAppUrl()+"/styles/images/default_thumbnail.png";if(this.model.get("logo")){thumb=appContext.cdn+"/users/"+this.model.id+"/thumbnail"}var args={name:this.model.get("name"),thumb:thumb};this.$el.html(_.template(template,args));return this},select:function(){this.options.callback(this.model)}})});define("view/people/list",["ext/underscore","view/dialog","view/people/item"],function(_,DialogView,PeopleItemView){return DialogView.extend({tagName:"ul",className:"list-unstyled",title:DialogView.message("m_mention_title"),render:function(){DialogView.prototype.render.apply(this,arguments);var keys={};this.options.filter&&_.each(this.options.filter,function(id){keys[id]=true});this.collection.each(function(user){if(!keys[user.id]){var view=new PeopleItemView({model:user,callback:this.callback});this.$el.append(view.render().el)}},this);return this}})});define("view/editor",["ext/underscore","native","api/service/general","view/people/list"],function(_,native,generalService,PeopleListView){var $=jQuery;return Backbone.View.extend({tagName:"iframe",attributes:{scrolling:"no",frameBorder:"0"},initialize:function(options){_.bindToMethods(this);this.context=options.context;this.$page=options.$page;this.content=options.content},render:function(){var $target=$("textarea.editor",this.$page);this.placeholder='<span style="color:gray;">'+$target.attr("placeholder")+"</span>";$target.replaceWith(this.el);this.frameWin=this.el.contentWindow;this.frameDoc=this.frameWin.document;this.frameDoc.designMode="on";this.$frameBody=$(this.frameDoc.body);this.$frameBody.css("font-family","Helvetica,Arial,sans-serif");if(_.isBlank(this.content)){this.$frameBody.html(this.placeholder)}else{this.$frameBody.html(this.content)}$(this.frameDoc).keydown(this.onKeydown);var self=this;$(this.frameDoc).keyup(function(e){self.$el.trigger("_change")});$(this.frameWin).focus(this.onFocus).blur(this.onBlur);native.keyboardCancelRequired&&this.frameDoc.body.blur()},render_delayed:function(focus){_.delay(function(self){self.render();focus&&self.frameWin.focus()},100,this)},onFocus:function(){if(this.getText()==""){this.$frameBody.html("")}},onBlur:function(){if(_.isBlank(_.stripTags(this.getText()))){this.$frameBody.html(this.placeholder)}},onKeydown:function(e){if(e.keyCode==13){e.preventDefault();var br=$("<br>").addClass("new-line").appendTo(this.frameDoc.body);var space=$(document.createTextNode(String.fromCharCode(160))).insertAfter(br);var selection=this.frameWin.getSelection();var range=this.frameDoc.createRange();range.selectNode(selection.anchorNode);range.setStartBefore(space[0]);range.collapse(true);selection.removeAllRanges();selection.addRange(range)}},doAction:function(){var self=this;generalService.getUsers(this.context,function(users){self.users=users;var people=new PeopleListView({collection:users,callback:function(user){self.insertMention(user)}});people.render()})},insertMention:function(user){this.frameDoc.body.focus();var anchor=$("<a/>").css({"background-color":"grey"}).text("@"+user.get("username"));anchor.appendTo(this.frameDoc.body);var space=$(document.createTextNode(String.fromCharCode(160))).insertAfter(anchor);var selection=this.frameWin.getSelection();var range=this.frameDoc.createRange();range.selectNode(selection.anchorNode);range.setStartAfter(space[0]);range.collapse(true);selection.removeAllRanges();selection.addRange(range);native.keyboardCancelRequired&&this.frameDoc.body.blur()},getText:function(){var text=this.$frameBody.html();return text==this.placeholder?"":text}})});define("text!text/editor.html",[],function(){return'<textarea class="editor hidden" placeholder="<%= m_type_here %>"></textarea>\n<fieldset>\n  <a href="javascript:void(0)" id="post" class="btn btn-primary" disabled="disabled">\n       <%= m_post %>\n </a>\n</fieldset>\n'});define("view/editor-page",["ext/underscore","view/page","view/editor","text!text/editor.html"],function(_,PageView,EditorView,template){var $=jQuery;return PageView.extend({events:{"_change iframe":"onChange","click #post":"post"},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);_.assert(this.post,"title post");this.editor=new EditorView({context:this.options.context,$page:this.$el});this.action={code:"m_mention",view:this.editor}},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template));this.editor.render_delayed(true);return this},onChange:function(){$("#post",this.$el).attr("disabled",_.isBlank(this.editor.getText()))}})});define("view/update/create",["app-context","view/editor-page","api/service/update"],function(appContext,EditorPageView,service){return EditorPageView.extend({title:EditorPageView.message("m_make_comment"),nosearch:true,initialize:function(){EditorPageView.prototype.initialize.apply(this,arguments);this.back={code:"m_btn_updates",link:"#updates/"+this.options.context.getKey()}},post:function(){service.createMicroblog(this.options.context,this.editor.getText(),this.microblogCreated)},microblogCreated:function(microblog){appContext.navigate("#microblog/"+microblog.getKey());service.getUpdates(this.options.context.getKey(),function(updates){updates.unshift(microblog)})}})});define("view/update/reply",["app-context","view/editor-page","api/service/update"],function(appContext,EditorPageView,service){return EditorPageView.extend({title:EditorPageView.message("m_reply"),nosearch:true,initialize:function(){EditorPageView.prototype.initialize.apply(this,arguments);this.back={code:"m_comment",link:"#microblog/"+this.options.update.getKey()}},post:function(){var microblog=this.options.update;service.createMicroblogReply(microblog,this.editor.getText(),function(microblogReply){appContext.navigate("#microblog/"+microblog.getKey())})}})});define("text!text/comment-item.html",[],function(){return'<div>\n <img src="<%= cdn %>/users/<%= commenter.id %>/thumbnail" \n        onerror=\'this.onerror = null; this.src="<%= appurl %>/styles/images/default_thumbnail.png"\'>\n    <p><%= model.getComment() %></p>\n  <p class="who-when"><%= commenter.name %> (<%= $.timeago(model.getDateCreated()) %>)</p>\n  \n  <% if (!model.reply) { %>\n     <a href="javascript:void(0)" class="comment-reply">\n           <span class="glyphicon glyphicon-repeat"></span>\n      </a>\n  <% } %>\n   <% if (me.id == commenter.id) { %>\n        <a href="javascript:void(0)" class="comment-delete">\n          <span class="glyphicon glyphicon-trash"></span>\n       </a>\n  <% } %>\n</div>\n'});define("view/comment/item",["ext/underscore","view/base","app-context","text!text/comment-item.html"],function(_,BaseView,appContext,template){return BaseView.extend({className:"comment",events:{"click .comment-delete":"onDelete","click .comment-reply":"onReply"},initialize:function(options){BaseView.prototype.initialize.apply(this,arguments);this.replyViews=[]},render:function(){var args={model:this.model,commenter:this.model.getCommenter(),selected:this.options.selected,cdn:appContext.cdn,me:appContext.getPrinciple()};this.$el.html(this.template(template,args));if(this.options.selected){this.$el.addClass("selected")}if(this.model.reply){this.$el.addClass("reply")}return this},onReply:function(){this.options.onReply(this.model)},onDelete:function(){this.options.onDelete(this.model,this.onDeleted)},onDeleted:function(){this.$el.remove();_.each(this.replyViews,function(view){view.$el.remove()})}})});define("view/comment/list",["ext/underscore","view/page","view/comment/item"],function(_,PageView,CommentItemView){var $=jQuery;return PageView.extend({className:"comments",initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.collection.on("remove",this.onRemove);var context=this.collection.context;this.back={code:"m_"+context.type,link:"#"+context.type+"/"+context.getKey()+this.formatQuery()};this.title=_.escape(context.get("friendlyName"));this.action={code:"m_new",link:"#comments/"+context.getKey()+"/create"}},render:function(){PageView.prototype.render.apply(this,arguments);var selectedId=this.getSelectedComment();this.collection.each(function(comment){var commentView=this.createAndRender(comment,selectedId==comment.id);comment.getReplies().each(function(reply){var replyView=this.createAndRender(reply,selectedId==reply.id);commentView.replyViews.push(replyView)},this)},this);this.onRemove();return this},createAndRender:function(comment,selected){var view=new CommentItemView({model:comment,selected:selected,onDelete:this.options.onDelete,onReply:this.options.onReply});this.$el.append(view.render().el);selected&&this.scroll(view.$el.offset().top-52);return view},getSelectedComment:function(){if(!this.options.dateOfSelection){return-1}var flattened=[];this.collection.each(function(comment){flattened.push(comment);comment.getReplies().each(function(reply){flattened.push(reply)})});flattened=_.sortBy(flattened,function(comment){return-comment.get("dateCreated")});var selected=_.find(flattened,function(comment){return comment.get("dateCreated")<=this.options.dateOfSelection},this);return selected?selected.id:-1},remove:function(){this.collection.off("remove",this.onRemove);this.$el.remove();return this},onRemove:function(){if(this.collection.length==0){$("<div>").addClass("ui-body-d ui-corner-all").html(this.message("m_comments_nothing")).appendTo(this.el)}}})});define("view/update/microblog",["view/page","view/comment/list","messages"],function(PageView,CommentListView,messages){return CommentListView.extend({initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var microblog=options.microblog;this.back={code:"m_btn_updates",link:"#updates/"+microblog.getContext().getKey()};this.title=microblog.format(messages.messages[microblog.get("messageCode")]);this.collection=new Backbone.Collection([microblog]);this.collection.on("remove",this.onRemove)}})});define("router/update",["app-context","router/base","api/service/general","api/service/update","view/update/list","view/update/create","view/update/reply","view/update/microblog"],function(appContext,BaseRouter,generalService,updateService,UpdateListView,UpdateCreateView,UpdateReplyView,UpdateMicroblogView){return BaseRouter.extend({routes:{"updates/:contextKey/create":"createMicroblog","updates/:contextKey":"getUpdates","microblog/:microblogKey/create":"createMicroblogReply","microblog/:microblogKey":"getMicroblog"},getUpdates:function(contextKey){updateService.getCachedUpdates(contextKey,this.showUpdates)},showUpdates:function(updates){var view=new UpdateListView({context:updates.context,collection:updates});view.render();view.handleRefresh()},createMicroblog:function(contextKey){generalService.getContext(contextKey,this.showCreateMicroblog)},showCreateMicroblog:function(context){new UpdateCreateView({context:context}).render()},getMicroblog:function(microblogKey){var parts=microblogKey.split(":");updateService.getMicroblog(parts[1],this.showMicroblog,true)},showMicroblog:function(microblog){var view=new UpdateMicroblogView({microblog:microblog,onDelete:function(target,onDeleted){generalService.deleteModel(target,onDeleted);if(!target.reply){updateService.getUpdates(target.getContext().getKey(),function(updates){updates.remove(target,{silent:true})})}},onReply:function(microblog){appContext.navigate("#microblog/"+microblog.getKey()+"/create")}});view.render()},createMicroblogReply:function(microblogKey){var parts=microblogKey.split(":");updateService.getMicroblog(parts[1],this.showCreateMicroblogReply)},showCreateMicroblogReply:function(microblog){new UpdateReplyView({context:microblog.getContext(),update:microblog}).render()}})});define("api/model/permission",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(attributes,options){this.context=options.context},url:function(){return this.context.url()+"/permission"},canEdit:function(){return(18&this.get("mask"))>0},canCreate:function(){return(20&this.get("mask"))>0}})});define("api/service/base",["ext/underscore","api/model/permission"],function(_,Permission){return{getCollection:function(collection,handler){collection.once("sync",function(){handler(collection)});collection.fetch()},getPermission:function(model,handler){if(model.permission){handler(model)}else{var permission=new Permission({},{context:model});permission.once("sync",function(){model.permission=permission;handler(model)});permission.fetch()}}}});define("api/collection/more",["ext/underscore","api/collection/base"],function(_,BaseCollection){return BaseCollection.extend({initialize:function(models,options){if(options){this.params=options.params}this.params=this.params||{}},parse:function(response){this.more=response.nextPage;return response.page}})});define("api/collection/files",["api/collection/more","api/model/file"],function(MoreCollection,File){return MoreCollection.extend({model:File,initialize:function(models,options){MoreCollection.prototype.initialize.apply(this,arguments);if(options){this.context=options.context}},url:function(){var base="/groups/@"+this.getGroup().id+"/files";if(this.context.type=="group"){return base}var id=this.context.id?"@"+this.context.id:this.context.get("name");return base+"/"+id},_getKey:function(key){return key+":"+this.params.orderBy},parse:function(response){if(this.context.type=="file"){response=response.children}this.more=response.nextPage;return response.page},getGroup:function(){if(this.context.type=="group"){return this.context}return this.context.get("group")}})});define("api/service/file",["ext/underscore","app-context","api/cache","api/service/base","api/service/general","api/collection/files","api/model/file"],function(_,appContext,cache,base,service,Files,File){return _.extend({getFiles:function(contextKey,handler,force){var self=this;this.getContextWithPermission(contextKey,function(context){var files=new Files([],{context:context,params:self.createFileParams(1)});if(!force){files=cache.getFrom(files);if(files){handler(files);return}}self.getCollection(files,function(files){cache.putModel(files);files.each(function(file){cache.putModel(file)});handler(files)})})},getCachedFiles:function(contextKey,handler){var self=this;this.getContextWithPermission(contextKey,function(context){var files=new Files([],{context:context,params:self.createFileParams(1)});handler(cache.getFrom(files))})},getContextWithPermission:function(contextKey,handler){var self=this;this.getContext(contextKey,function(context){self.getPermission(context,handler)})},getContext:function(contextKey,handler){var parts=contextKey.split(":");if(parts.length==2){service.getGroup(parseInt(parts[1].substr(1)),handler)}else{this.getFile({id:parts[1].substr(1)},parts[3],handler)}},getNextFiles:function(files,handler){var next=new Files([],{context:files.context,params:this.createFileParams(files.params.currentPage+1)});this.getCollection(next,function(next){files.add(next.models);files.params.currentPage=next.params.currentPage;files.more=next.more;handler(next)})},getFile:function(group,id,handler){var self=this;this.getFileOnly(group,id,function(file){self.getPermission(file,handler)})},getFileOnly:function(group,id,handler){var file=new File({name:id});if(id.charAt(0)=="@"){file=new File({id:parseInt(id.slice(1))})}file.set("group",group);file.params=this.createFileParams(1);file=cache.getFrom(file);if(file._expiry){handler(file);return}cache.putModel(file);file.once("change",handler);file.fetch()},createFileParams:function(currentPage){var orderBy=appContext.getFileSort();return{currentPage:currentPage,pageSize:appContext.pageSize,orderBy:orderBy,ascending:orderBy=="name"}}},base)});define("text!text/file/item.html",[],function(){return"<a href=\"#file/<%= getKey() %>\">\n    <img src=\"<%= appurl %>/svg/<%= getExtension() %>.svg\" onerror='this.onerror = null; this.src=\"<%= appurl %>/svg/file.svg\"'>\n  <p><b><%= get('friendlyName') %></b></p>\n  <abbr><%= m_last_updated %>: <%= $.timeago(new Date(get('lastModified'))) %></abbr>\n</a>\n"});define("view/file/item",["view/base","text!text/file/item.html"],function(BaseView,template){return BaseView.extend({tagName:"li",className:"fat",render:function(){this.$el.html(this.template(template,this.model));return this}})});define("view/file/list",["ext/underscore","api/service/file","view/navbar-factory","view/extending-list","view/file/item"],function(_,service,navbarFactory,ExtendingListView,FileItemView){return ExtendingListView.extend({initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);this.title=_.escape(this.collection.context.get("friendlyName"));this.back=this.options.back;this.action=this.options.action},emptyMsgCode:"m_files_nothing",itemViewClass:FileItemView,handleEndOfList:function(){service.getNextFiles(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getFiles(this.collection.context.getKey(),function(files){self.collection=files;self.refresh()},true)},navbar:function(callback){this.navbarCreate("files",this.collection.getGroup().id,callback)}}).extend(navbarFactory)});define("text!text/sort-action.html",[],function(){return'<div>\n   <input type="radio" name="sort_by" id="lastModified" value="lastModified" \n        <% if (sort == \'lastModified\') { print(\'checked\') } %> >\n  <label for="lastModified"><%= m_actions_sort_latest %></label>\n</div>\n<div>\n <input type="radio" name="sort_by" id="name" value="name" \n        <% if (sort == \'name\') { print(\'checked\') } %> >\n  <label for="name"><%= m_actions_sort_name %></label>\n</div>\n'});define("view/sort-action",["view/dialog","text!text/sort-action.html"],function(DialogView,template){return DialogView.extend({className:"choice-list",title:DialogView.message("m_actions_sort_header"),events:{"change input[type=radio]":"select"},render:function(){DialogView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,this.options));return this},doAction:function(){this.render()},select:function(event){this.callback(this.options.context,event.target.value)}})});define("text!text/file/upload.html",[],function(){return'<ul>\n  <li>\n      <span class="btn btn-success add" id="complex-flash-wrapper">\n         <%= m_file_upload_add %>\n      </span>\n       <input type="file" name="file" multiple />\n    </li>\n <li><a href="javascript:void(0)" class="btn btn-primary upload-all"><%= m_file_upload_start %></a></li>\n   <li><a href="javascript:void(0)" class="btn btn-default cancel-all"><%= m_file_upload_cancel %></a></li>\n</ul>\n<table class="table">\n    <tbody>\n       <tr class="template">\n         <td class="name">&nbsp;</td>\n          <td class="size">&nbsp;</td>\n          <td class="progress-container">\n               <div class="progress progress-striped">\n                   <div class="progress-bar">&nbsp;</div>\n                </div>\n            </td>\n         <td class="buttons">\n              <a href="javascript:void(0)" class="btn btn-xs btn-primary submit"><%= m_file_upload_upload %></a>\n                <a href="javascript:void(0)" class="btn btn-xs btn-primary retry"><%= m_file_upload_retry %></a>\n              <a href="javascript:void(0)" class="btn btn-xs btn-danger cancel"><%= m_file_upload_stop %></a>\n               <a href="javascript:void(0)" class="btn btn-xs btn-default remove"><%= m_file_upload_remove %></a>\n            </td>\n     </tr>\n </tbody>\n</table>\n'});define("view/file/upload",["view/dialog","app-context","text!text/file/upload.html"],function(DialogView,appContext,template){var $=jQuery;return DialogView.extend({tagName:"form",className:"upload-container",title:DialogView.message("m_file_upload_header"),events:{"click a.cancel-all":"cancel"},initialize:function(options){DialogView.prototype.initialize.apply(this,arguments);this.options.width="600px"},doAction:function(){$(".modal").on("hidden.bs.modal",this.close);var endpoint=this.getEndpoint();if(this.options.context.type=="file"){endpoint+="/"+this.options.context.id}$.get(appContext.fullUrl(endpoint+"/index"),this.retrievePath)},retrievePath:function(index){this.index=JSON.parse($.base64.atob(index));if(this.options.context.type=="file"){if(this.index.fileSystem.length==0){var endpoint=this.options.context.url()+"path";$.get(appContext.fullUrl(endpoint),this.setPath)}else{var aFile=this.index.fileSystem[0];this.setPath(aFile.substring(1,aFile.lastIndexOf("/")))}}else{this.render()}},setPath:function(path){this.path=path;this.render()},render:function(){DialogView.prototype.render.apply(this,arguments);this.$el.html(this.template(template));var endpoint=appContext.resolveEndPoint()+this.getEndpoint();var path="";if(this.path){path="&path="+encodeURIComponent(this.path)}var token=appContext.getAccessToken().access_token;this.$el.fileupload({beforeFinalSend:this.beforeFinalSend,chunkEndpoint:endpoint+"/upload/data?access_token="+token,finalEndpoint:endpoint+"/upload/complete?success=True&access_token="+token+"&forwardContext="+encodeURIComponent(endpoint)+path,layout:"Complex",ajaxLoader:appContext.getAppUrl()+"/styles/images/ajax-loader.gif",defaultContentType:"application/json; charset=UTF-8",fileComplete:this.message("m_file_upload_success"),filefinish:this.filefinish});return this},beforeFinalSend:function(xhr,options){xhr.setRequestHeader("X-File-Id",options.file.fuid);xhr.setRequestHeader("X-File-Name",options.file.name);xhr.setRequestHeader("X-File-Size",options.file.size);xhr.setRequestHeader("X-File-Type",options.file.type);var data={sharing:"MEMBERS",memberPermission:8};var file=this.index.metadata["/"+(this.path?this.path+"/":"")+options.file.name];if(file){data.id=file.ID}options.data=JSON.stringify(data)},filefinish:function(file,success,isError){if(isError){var bar=$("tr#file_"+file.fuid+" .progress-bar",this.$el);bar.text(this.message("m_file_upload_failure"))}},getEndpoint:function(){var context=this.options.context;var group=context.toJSON();if(context.type=="file"){group=context.get("group")}var accountId=group.contextKey.parent.objectId;return"/v2/accounts/"+accountId+"/groups/"+group.id+"/files"},cancel:function(){$(".modal").modal("hide")},close:function(){$(".modal").off("hidden.bs.modal",this.close);this.options.callback(this.options.context)}})});define("text!text/file/native-item.html",[],function(){return"<a class='item' href=\"javascript:void(0)\">\n  <img src=\"<%= appurl %>/svg/<%= extension %>.svg\" onerror='this.onerror = null; this.src=\"<%= appurl %>/svg/file.svg\"'>\n   <%= _.escape(file.name) %>\n</a>\n<div class='item progress hidden'>\n  <div class='progress-bar progress-bar-striped progress-bar-info'></div>\n</div>\n<div class='item failure hidden'>\n    <div class='progress-bar progress-bar-striped progress-bar-danger'>\n       <span><%= m_file_native_failure %></span>\n </div>\n</div>\n<div class='item success hidden'>\n <div class='progress-bar progress-bar-striped progress-bar-success'>\n      <span><b><%= _.escape(file.name) %></b><%= m_file_native_success %></span>\n    </div>\n</div>\n"});define("view/file/native-item",["ext/underscore","view/base","native","app-context","api/service/file","text!text/file/native-item.html"],function(_,BaseView,native,appContext,service,template){return BaseView.extend({tagName:"li",className:"native-item",events:{"click .failure, a":"select","click .success":"dismiss"},initialize:function(options){_.bindToMethods(this);this.options=options},render:function(){var args=_.extend({extension:this.getExtension(this.options.file)},this.options);this.$el.html(this.template(template,args));return this},getExtension:function(file){if(file.folder){return"folder"}var extensionPos=file.name.lastIndexOf(".");if(file.name.lastIndexOf("/")>extensionPos){return""}return file.name.substring(extensionPos+1).toLowerCase()},dismiss:function(){$(".item",this.$el).addClass("hidden");$("a",this.$el).removeClass("hidden")},select:function(){if(this.options.list.uploading){return}if(this.options.file.folder){var path=(this.options.path?this.options.path+"/":"")+this.options.file.name;var link="#native/"+this.options.context.getKey()+"/"+encodeURIComponent(path);appContext.navigate(link,true)}else{var self=this;this.retrievePath(function(path){self.retrieveFileId(path,function(fileId){self.upload(path,fileId)})});$(".item",this.$el).addClass("hidden");$(".progress",this.$el).removeClass("hidden")}},retrievePath:function(handler){if(this.options.context.type=="file"){$.get(appContext.fullUrl(this.options.context.url()+"path"),handler);
     13
     14}else{handler(null)}},retrieveFileId:function(path,handler){var endpoint=this.getEndpoint();if(this.options.context.type=="file"){endpoint+="/"+this.options.context.id}var self=this;$.get(appContext.fullUrl(endpoint+"/index"),function(index){index=JSON.parse($.base64.atob(index));var existing=index.metadata["/"+(path?path+"/":"")+self.options.file.name];var fileId=null;if(existing){fileId=existing.ID}handler(fileId)})},upload:function(path,fileId){var file=(this.options.path?this.options.path+"/":"")+this.options.file.name;this.options.list.uploading=true;var token=appContext.getAccessToken().access_token;var endpoint=appContext.resolveEndPoint()+this.getEndpoint();native.upload(file,endpoint,token,path,fileId,this.progress)},getEndpoint:function(){var context=this.options.context;var group=context.toJSON();if(context.type=="file"){group=context.get("group")}var accountId=group.contextKey.parent.objectId;return"/v2/accounts/"+accountId+"/groups/"+group.id+"/files"},progress:function(percent){if(percent==-1){this.finish();$(".failure",this.$el).removeClass("hidden")}else if(percent==100){this.finish();$(".success",this.$el).removeClass("hidden")}else{$(".progress-bar-info",this.$el).css("width",percent+"%").html("<span>"+percent+"%</span>")}},finish:function(){this.options.list.uploading=false;$(".item",this.$el).addClass("hidden");$(".progress-bar-info",this.$el).css("width",0).html("")}})});define("view/file/native-list",["ext/underscore","view/page","view/file/native-item"],function(_,PageView,NativeItemView){return PageView.extend({tagName:"ul",className:"list-unstyled",title:PageView.message("m_file_native_header"),nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.action={code:"m_cancel",link:"#files/"+this.options.context.getKey()};if(this.options.path){this.title=this.options.path;var path="";var last=this.options.path.lastIndexOf("/");if(last!=-1){path=this.options.path.substr(0,last);path="/"+encodeURIComponent(path);this.title=this.options.path.substr(last+1)}this.back={code:"m_back",link:"#native/"+this.options.context.getKey()+path}}},render:function(){PageView.prototype.render.apply(this,arguments);_.each(this.options.files,function(file){var view=new NativeItemView({list:this,context:this.options.context,path:this.options.path,file:file});this.$el.append(view.render().el)},this);return this}})});define("text!text/file/view.html",[],function(){return"<% if (type == 'image') { %>\n   <img class=\"sized\" src=\"<%= preview %>\">\n<% } %>\n<div class=\"entity-info\" >\n   <p><%= m_file_uploader %>: <%= model.get('uploaded').name %></p>\n  <p>\n       <img src=\"<%= cdn %>/users/<%= model.get('uploaded').id %>/thumbnail\" \n          onerror='this.onerror = null; this.src=\"<%= appurl %>/styles/images/default_thumbnail.png\"'>\n    </p>\n  <p><%= m_on %>: <%= lastModified.format('ddd, DD MMM YYYY, HH:mm') %></p>\n <p><%= m_version %>: <%= model.get('versions') %></p>\n <p><%= m_size %>: <%= size %></p>\n <p>\n       <img src=\"<%= appurl %>/svg/<%= model.getExtension() %>.svg\" \n           onerror='this.onerror = null; this.src=\"<%= appurl %>/svg/file.svg\"'>\n   </p>\n  <% if (type != 'document' && type != 'image') { %>\n        <p><%= m_file_preview_failed %></p>\n   <% } %>\n</div>\n<% if (type == 'document') { %>\n  <a href=\"javascript:void(0)\" class=\"btn btn-primary preview\">\n     <%= m_preview %>\n  </a>\n<% } %>\n"});define("view/file/view",["ext/underscore","native","view/page","moment","app-context","view/navbar-factory","text!text/file/view.html"],function(_,native,PageView,moment,appContext,navbarFactory,template){return PageView.extend({KB:1024,MB:1024*1024,GB:1024*1024*1024,tagName:"fieldset",events:{"click a.preview":"preview"},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var query=this.getSearchQuery();if(query){this.back={code:"m_back",link:"#search/"+query}}else{this.back=this.options.back}this.title=this.model.get("friendlyName");this.actions=[{code:"m_comments",icon:"comment",link:"#comments/"+this.model.getKey()+this.formatQuery(query)}];if(this.model.permission.canEdit()&&window.localStorage.getItem("features")!="limited"){this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()+this.formatQuery(query)})}if(native.list&&!native.upload){this.actions.unshift({code:"m_download",link:appContext.fullUrl(this.model.url()+"download")})}},render:function(){PageView.prototype.render.apply(this,arguments);var args={type:this.options.type,model:this.model,lastModified:moment(this.model.get("lastModified")),size:this.formatSize(),cdn:appContext.cdn,preview:appContext.fullUrl(this.model.url()+"preview")};this.$el.html(this.template(template,args));return this},formatSize:function(){var size=this.model.get("size");var unit="bytes";var divisor=1;if(size>this.GB){unit="GB";divisor=this.GB}else if(size>this.MB){unit="MB";divisor=this.MB}else if(size>this.KB){unit="KB";divisor=this.KB}return Math.round(size*10/divisor)/10+" "+unit},navbar:function(callback){this.navbarCreate("files",this.model.getGroup().id,callback)},preview:function(){appContext.preview(this.model,this.options.type=="document")}}).extend(navbarFactory)});define("router/file",["ext/underscore","app-context","api/cache","native","router/base","api/service/file","api/collection/files","view/file/list","view/sort-action","view/file/upload","view/file/native-list","view/file/view"],function(_,appContext,cache,native,BaseRouter,service,Files,FileListView,SortActionView,FileUploadView,NativeListView,FileViewView){return BaseRouter.extend({routes:{"files/:contextKey":"getFiles","file/:fileKey":"getFile","native/:contextKey/:path":"getNative","native/:contextKey":"getNative"},getFiles:function(contextKey){service.getCachedFiles(contextKey,this.showFiles)},showFiles:function(files){var view=this.createFileListView(files.context,files);view.render();view.handleRefresh()},getFile:function(fileKey){var parts=fileKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getFile(group,parts[3],this.handleFile)},handleFile:function(file){if(file.isFolder()){var children=file.get("children");if(children){var files=new Files(children.page,{context:file,params:service.createFileParams(1)});files.more=children.nextPage;cache.putModel(files);files.each(function(file){cache.putModel(file)});var view=this.createFileListView(file,files);view.render()}else{this.getFiles(file.getKey())}}else{this.showFile(file)}},showFile:function(file){var type=this.getFileType(file);var view=new FileViewView({back:this.createFileBack(file),model:file,type:type});if(type=="unknown"||type=="image"||native.popupPreview){view.render()}else{appContext.setHeader(view);_.defer(function(){appContext.preview(file,type=="document")})}},getFileType:function(file){var contentType=file.get("contentType");if(_.startsWith(contentType,"image/")){return"image"}if(_.startsWith(contentType,"video/")){return"video"}if(_.startsWith(contentType,"audio/")&&native.audioPreview){return"video"}if(_.find(appContext.mimetypes,function(mimetype){return this==mimetype},contentType)){return"document"}return"unknown"},createFileListView:function(context,collection){var canCreate=context.permission.canCreate();if(native.upload&&canCreate){var action={code:"m_actions_upload",link:"#native/"+context.getKey()}}else if(native.list&&canCreate){var action={code:"m_actions_upload",view:new FileUploadView({context:context,callback:this.refresh})}}else{var action={code:"m_actions_sort",view:new SortActionView({context:context,sort:appContext.getFileSort(),callback:this.sortFiles})}}return new FileListView({back:this.createFileBack(context),action:action,collection:collection})},sortFiles:function(context,field){appContext.setFileSort(field);this.refresh(context)},refresh:function(context){appContext.navigate("#files/"+context.getKey(),true)},createFileBack:function(context){if(context.type=="group"){return{code:"m_btn_context",link:"#context"}}var parent=context.get("parent");if(parent.type=="group"){return{code:"m_btn_files",link:"#files/groups:@"+parent.id}}return{code:"m_back",link:"#file/groups:@"+context.get("group").id+":files:@"+parent.id}},getNative:function(contextKey,path){service.getContext(contextKey,function(context){native.list(path,function(files){var view=new NativeListView({context:context,path:path,files:files});view.render()})})}})});define("router/group",["router/base","api/cache","api/model/group","api/model/permission"],function(BaseRouter,cache,Group,Permission){return BaseRouter.extend({execute:function(callback,args){var groupId=this.getGroupId(args);if(groupId){args.unshift(cache.getFrom(new Group({id:groupId})));this.retrieveGroupWithPermission(callback,args)}else{callback.apply(this,args)}},getGroupId:function(args){if(args.length>0){var key=args[0].split(":");if(key.length==2&&key[0]=="groups"){return key[1].substr(1)}}return null},retrieveGroupWithPermission:function(callback,args){var group=args[0];this.retrieveGroup(group,function(){if(group.permission){callback.apply(self,args)}else{var permission=new Permission({},{context:group});permission.once("sync",function(){group.permission=permission;callback.apply(self,args)});permission.fetch()}})},retrieveGroup:function(group,handler){if(group.get("components")){handler()}else{group.once("change",function(){cache.putModel(group);handler()});group.fetch()}}})});define("api/collection/content",["api/collection/more","api/model/file"],function(MoreCollection,File){return MoreCollection.extend({initialize:function(models,options){MoreCollection.prototype.initialize.apply(this,arguments);if(options){this.group=options.group}},url:function(){return"/groups/@"+this.group.id+"/"+this.model.type+"s"}})});define("api/collection/notes",["api/collection/content","api/model/note"],function(ContentCollection,Note){return ContentCollection.extend({model:Note,_getKey:function(key){return key+":"+this.params.orderBy}})});define("api/service/note",["ext/underscore","app-context","api/cache","api/service/base","api/collection/notes","api/model/note"],function(_,appContext,cache,base,Notes,Note){return _.extend({getNotes:function(group,handler){var notes=this.createNotes(group,1);cache.putModel(notes);this.getCollection(notes,handler)},getNextNotes:function(notes,handler){var next=this.createNotes(notes.group,notes.params.currentPage+1);this.getCollection(next,function(next){notes.add(next.models);notes.params.currentPage=next.params.currentPage;notes.more=next.more;handler(next)})},getNote:function(group,id,handler){var self=this;this.getNoteOnly(group,id,function(note){self.getPermission(note,handler)})},getNoteOnly:function(group,id,handler){var note=new Note({name:id});if(id.charAt(0)=="@"){note=new Note({id:parseInt(id.slice(1))})}note.set("group",group);note=cache.getFrom(note);if(note._expiry&&note.get("content")){handler(note);return}cache.putModel(note);note.once("change",handler);note.fetch()},createNotes:function(group,currentPage){var orderBy=appContext.getNoteSort();return new Notes([],{group:group,params:{type:"page",currentPage:currentPage,pageSize:appContext.pageSize,orderBy:orderBy,ascending:orderBy=="name"}})}},base)});define("text!text/note-item.html",[],function(){return"<a class=\"no-icon\" href=\"#note/<%= getKey() %>\">\n    <p><b><%= _.escape(get('friendlyName')) %></b></p>\n    <abbr><%= m_last_updated %>: <%= $.timeago(new Date(get('lastModified'))) %></abbr>\n</a>\n"});define("view/note/item",["view/base","text!text/note-item.html"],function(BaseView,template){return BaseView.extend({tagName:"li",className:"fat",render:function(){this.$el.html(this.template(template,this.model));return this}})});define("view/note/list",["ext/underscore","app-context","view/navbar-factory","view/extending-list","view/sort-action","view/note/item","api/service/note"],function(_,appContext,navbarFactory,ExtendingListView,SortActionView,NoteItemView,service){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);this.title=_.escape(this.collection.group.get("friendlyName"));this.action={code:"m_actions_sort",view:new SortActionView({context:this.collection.group,sort:appContext.getNoteSort(),callback:this.sortNotes})}},sortNotes:function(context,field){appContext.setNoteSort(field);appContext.navigate("#notes/"+context.getKey(),true)},emptyMsgCode:"m_notes_nothing",itemViewClass:NoteItemView,handleEndOfList:function(){service.getNextNotes(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getNotes(this.collection.group,function(pages){self.collection=pages;self.refresh()})},navbar:function(callback){this.navbarCreate("notes",this.collection.group.id,callback)}}).extend(navbarFactory)});define("api/model/attachment",["api/model/base"],function(BaseModel){return BaseModel.extend({url:function(){var container=this.get("parent");var id=this.id?"@"+this.id:this.get("name");return"/groups/@"+container.group.id+"/"+container.type+"s/@"+container.id+"/attachments/"+id+"/"}})});define("view/link-resolver",["ext/underscore","app-context","api/factory","api/model/attachment"],function(_,appContext,factory,Attachment){var $=jQuery;var linkResolver={handleImage:function(element,parts){element.src=appContext.fullUrl("/groups/@"+this.model.getGroup().id+"/pages/"+this.model.get("name")+"/attachments/"+parts[0]+"/preview")},handleDocument:function(element,parts){var link=$("<a>").attr("href","javascript:void(0)").html(parts[0]).click(_.bind(this.showAttachment,this,parts[0]));$(element).replaceWith(link)},showAttachment:function(fileName){var attachment=new Attachment({name:fileName,parent:this.model.toJSON()});attachment.on("change",function(){appContext.preview(this)});attachment.fetch()},handleVideo:function(element){element.src=appContext.getAppUrl()+"/styles/images/video_preview.png"},handleLinks:function(element,parts){if(parts[0]=="url"){$(element).attr("data-external",true);return}var entity=factory.createEntity({type:parts[0],group:this.model.getGroup().toJSON(),name:parts[1]});if(entity){element.href="#"+parts[0]+"/"+entity.getKey()}else{$(element).removeAttr("href")}},resolveLinks:function(){_.each($("[media_link]",this.$el),function(element){var parts=$(element).attr("media_link").split(":");var handler=this.handlers[parts[0]];handler&&handler.apply(this,[element,_.rest(parts)])},this)}};linkResolver.handlers={attachment:linkResolver.handleImage,attachment_document:linkResolver.handleDocument,video:linkResolver.handleVideo,attachment_video:linkResolver.handleVideo,link:linkResolver.handleLinks};return linkResolver});(function(window,doc){var m=Math,dummyStyle=doc.createElement("div").style,vendor=function(){var vendors="t,webkitT,MozT,msT,OT".split(","),t,i=0,l=vendors.length;for(;i<l;i++){t=vendors[i]+"ransform";if(t in dummyStyle){return vendors[i].substr(0,vendors[i].length-1)}}return false}(),cssVendor=vendor?"-"+vendor.toLowerCase()+"-":"",transform=prefixStyle("transform"),transitionProperty=prefixStyle("transitionProperty"),transitionDuration=prefixStyle("transitionDuration"),transformOrigin=prefixStyle("transformOrigin"),transitionTimingFunction=prefixStyle("transitionTimingFunction"),transitionDelay=prefixStyle("transitionDelay"),isAndroid=/android/gi.test(navigator.appVersion),isIDevice=/iphone|ipad/gi.test(navigator.appVersion),isTouchPad=/hp-tablet/gi.test(navigator.appVersion),has3d=prefixStyle("perspective")in dummyStyle,hasTouch="ontouchstart"in window&&!isTouchPad,hasTransform=vendor!==false,hasTransitionEnd=prefixStyle("transition")in dummyStyle,RESIZE_EV="onorientationchange"in window?"orientationchange":"resize",START_EV=hasTouch?"touchstart":"mousedown",MOVE_EV=hasTouch?"touchmove":"mousemove",END_EV=hasTouch?"touchend":"mouseup",CANCEL_EV=hasTouch?"touchcancel":"mouseup",WHEEL_EV=vendor=="Moz"?"DOMMouseScroll":"mousewheel",TRNEND_EV=function(){if(vendor===false)return false;var transitionEnd={"":"transitionend",webkit:"webkitTransitionEnd",Moz:"transitionend",O:"otransitionend",ms:"MSTransitionEnd"};return transitionEnd[vendor]}(),nextFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){return setTimeout(callback,1)}}(),cancelFrame=function(){return window.cancelRequestAnimationFrame||window.webkitCancelAnimationFrame||window.webkitCancelRequestAnimationFrame||window.mozCancelRequestAnimationFrame||window.oCancelRequestAnimationFrame||window.msCancelRequestAnimationFrame||clearTimeout}(),translateZ=has3d?" translateZ(0)":"",iScroll=function(el,options){var that=this,i;that.wrapper=typeof el=="object"?el:doc.getElementById(el);that.wrapper.style.overflow="hidden";that.scroller=that.wrapper.children[0];that.options={hScroll:true,vScroll:true,x:0,y:0,bounce:true,bounceLock:false,momentum:true,lockDirection:true,useTransform:true,useTransition:false,topOffset:0,checkDOMChanges:false,handleClick:true,hScrollbar:true,vScrollbar:true,fixedScrollbar:isAndroid,hideScrollbar:isIDevice,fadeScrollbar:isIDevice&&has3d,scrollbarClass:"",zoom:false,zoomMin:1,zoomMax:4,doubleTapZoom:2,wheelAction:"scroll",snap:false,snapThreshold:1,onRefresh:null,onBeforeScrollStart:function(e){e.preventDefault()},onScrollStart:null,onBeforeScrollMove:null,onScrollMove:null,onBeforeScrollEnd:null,onScrollEnd:null,onTouchEnd:null,onDestroy:null,onZoomStart:null,onZoom:null,onZoomEnd:null};for(i in options)that.options[i]=options[i];that.x=that.options.x;that.y=that.options.y;that.options.useTransform=hasTransform&&that.options.useTransform;that.options.hScrollbar=that.options.hScroll&&that.options.hScrollbar;that.options.vScrollbar=that.options.vScroll&&that.options.vScrollbar;that.options.zoom=that.options.useTransform&&that.options.zoom;that.options.useTransition=hasTransitionEnd&&that.options.useTransition;if(that.options.zoom&&isAndroid){translateZ=""}that.scroller.style[transitionProperty]=that.options.useTransform?cssVendor+"transform":"top left";that.scroller.style[transitionDuration]="0";that.scroller.style[transformOrigin]="0 0";if(that.options.useTransition)that.scroller.style[transitionTimingFunction]="cubic-bezier(0.33,0.66,0.66,1)";if(that.options.useTransform)that.scroller.style[transform]="translate("+that.x+"px,"+that.y+"px)"+translateZ;else that.scroller.style.cssText+=";position:absolute;top:"+that.y+"px;left:"+that.x+"px";if(that.options.useTransition)that.options.fixedScrollbar=true;that.refresh();that._bind(RESIZE_EV,window);that._bind(START_EV);if(!hasTouch){if(that.options.wheelAction!="none")that._bind(WHEEL_EV)}if(that.options.checkDOMChanges)that.checkDOMTime=setInterval(function(){that._checkDOMChanges()},500)};iScroll.prototype={enabled:true,x:0,y:0,steps:[],scale:1,currPageX:0,currPageY:0,pagesX:[],pagesY:[],aniTime:null,wheelZoomCount:0,handleEvent:function(e){var that=this;switch(e.type){case START_EV:if(!hasTouch&&e.button!==0)return;that._start(e);break;case MOVE_EV:that._move(e);break;case END_EV:case CANCEL_EV:that._end(e);break;case RESIZE_EV:that._resize();break;case WHEEL_EV:that._wheel(e);break;case TRNEND_EV:that._transitionEnd(e);break}},_checkDOMChanges:function(){if(this.moved||this.zoomed||this.animating||this.scrollerW==this.scroller.offsetWidth*this.scale&&this.scrollerH==this.scroller.offsetHeight*this.scale)return;this.refresh()},_scrollbar:function(dir){var that=this,bar;if(!that[dir+"Scrollbar"]){if(that[dir+"ScrollbarWrapper"]){if(hasTransform)that[dir+"ScrollbarIndicator"].style[transform]="";that[dir+"ScrollbarWrapper"].parentNode.removeChild(that[dir+"ScrollbarWrapper"]);that[dir+"ScrollbarWrapper"]=null;that[dir+"ScrollbarIndicator"]=null}return}if(!that[dir+"ScrollbarWrapper"]){bar=doc.createElement("div");if(that.options.scrollbarClass)bar.className=that.options.scrollbarClass+dir.toUpperCase();else bar.style.cssText="position:absolute;z-index:100;"+(dir=="h"?"height:7px;bottom:1px;left:2px;right:"+(that.vScrollbar?"7":"2")+"px":"width:7px;bottom:"+(that.hScrollbar?"7":"2")+"px;top:2px;right:1px");bar.style.cssText+=";pointer-events:none;"+cssVendor+"transition-property:opacity;"+cssVendor+"transition-duration:"+(that.options.fadeScrollbar?"350ms":"0")+";overflow:hidden;opacity:"+(that.options.hideScrollbar?"0":"1");that.wrapper.appendChild(bar);that[dir+"ScrollbarWrapper"]=bar;bar=doc.createElement("div");if(!that.options.scrollbarClass){bar.style.cssText="position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);"+cssVendor+"background-clip:padding-box;"+cssVendor+"box-sizing:border-box;"+(dir=="h"?"height:100%":"width:100%")+";"+cssVendor+"border-radius:3px;border-radius:3px"}bar.style.cssText+=";pointer-events:none;"+cssVendor+"transition-property:"+cssVendor+"transform;"+cssVendor+"transition-timing-function:cubic-bezier(0.33,0.66,0.66,1);"+cssVendor+"transition-duration:0;"+cssVendor+"transform: translate(0,0)"+translateZ;if(that.options.useTransition)bar.style.cssText+=";"+cssVendor+"transition-timing-function:cubic-bezier(0.33,0.66,0.66,1)";that[dir+"ScrollbarWrapper"].appendChild(bar);that[dir+"ScrollbarIndicator"]=bar}if(dir=="h"){that.hScrollbarSize=that.hScrollbarWrapper.clientWidth;that.hScrollbarIndicatorSize=m.max(m.round(that.hScrollbarSize*that.hScrollbarSize/that.scrollerW),8);that.hScrollbarIndicator.style.width=that.hScrollbarIndicatorSize+"px";that.hScrollbarMaxScroll=that.hScrollbarSize-that.hScrollbarIndicatorSize;that.hScrollbarProp=that.hScrollbarMaxScroll/that.maxScrollX}else{that.vScrollbarSize=that.vScrollbarWrapper.clientHeight;that.vScrollbarIndicatorSize=m.max(m.round(that.vScrollbarSize*that.vScrollbarSize/that.scrollerH),8);that.vScrollbarIndicator.style.height=that.vScrollbarIndicatorSize+"px";that.vScrollbarMaxScroll=that.vScrollbarSize-that.vScrollbarIndicatorSize;that.vScrollbarProp=that.vScrollbarMaxScroll/that.maxScrollY}that._scrollbarPos(dir,true)},_resize:function(){var that=this;setTimeout(function(){that.refresh()},isAndroid?200:0)},_pos:function(x,y){if(this.zoomed)return;x=this.hScroll?x:0;y=this.vScroll?y:0;if(this.options.useTransform){this.scroller.style[transform]="translate("+x+"px,"+y+"px) scale("+this.scale+")"+translateZ}else{x=m.round(x);y=m.round(y);this.scroller.style.left=x+"px";this.scroller.style.top=y+"px"}this.x=x;this.y=y;this._scrollbarPos("h");this._scrollbarPos("v")},_scrollbarPos:function(dir,hidden){var that=this,pos=dir=="h"?that.x:that.y,size;if(!that[dir+"Scrollbar"])return;pos=that[dir+"ScrollbarProp"]*pos;if(pos<0){if(!that.options.fixedScrollbar){size=that[dir+"ScrollbarIndicatorSize"]+m.round(pos*3);if(size<8)size=8;that[dir+"ScrollbarIndicator"].style[dir=="h"?"width":"height"]=size+"px"}pos=0}else if(pos>that[dir+"ScrollbarMaxScroll"]){if(!that.options.fixedScrollbar){size=that[dir+"ScrollbarIndicatorSize"]-m.round((pos-that[dir+"ScrollbarMaxScroll"])*3);if(size<8)size=8;that[dir+"ScrollbarIndicator"].style[dir=="h"?"width":"height"]=size+"px";pos=that[dir+"ScrollbarMaxScroll"]+(that[dir+"ScrollbarIndicatorSize"]-size)}else{pos=that[dir+"ScrollbarMaxScroll"]}}that[dir+"ScrollbarWrapper"].style[transitionDelay]="0";that[dir+"ScrollbarWrapper"].style.opacity=hidden&&that.options.hideScrollbar?"0":"1";that[dir+"ScrollbarIndicator"].style[transform]="translate("+(dir=="h"?pos+"px,0)":"0,"+pos+"px)")+translateZ},_start:function(e){var that=this,point=hasTouch?e.touches[0]:e,matrix,x,y,c1,c2;if(!that.enabled)return;if(that.options.onBeforeScrollStart)that.options.onBeforeScrollStart.call(that,e);if(that.options.useTransition||that.options.zoom)that._transitionTime(0);that.moved=false;that.animating=false;that.zoomed=false;that.distX=0;that.distY=0;that.absDistX=0;that.absDistY=0;that.dirX=0;that.dirY=0;if(that.options.zoom&&hasTouch&&e.touches.length>1){c1=m.abs(e.touches[0].pageX-e.touches[1].pageX);c2=m.abs(e.touches[0].pageY-e.touches[1].pageY);that.touchesDistStart=m.sqrt(c1*c1+c2*c2);that.originX=m.abs(e.touches[0].pageX+e.touches[1].pageX-that.wrapperOffsetLeft*2)/2-that.x;that.originY=m.abs(e.touches[0].pageY+e.touches[1].pageY-that.wrapperOffsetTop*2)/2-that.y;if(that.options.onZoomStart)that.options.onZoomStart.call(that,e)}if(that.options.momentum){if(that.options.useTransform){matrix=getComputedStyle(that.scroller,null)[transform].replace(/[^0-9\-.,]/g,"").split(",");x=+matrix[4];y=+matrix[5]}else{x=+getComputedStyle(that.scroller,null).left.replace(/[^0-9-]/g,"");y=+getComputedStyle(that.scroller,null).top.replace(/[^0-9-]/g,"")}if(x!=that.x||y!=that.y){if(that.options.useTransition)that._unbind(TRNEND_EV);else cancelFrame(that.aniTime);that.steps=[];that._pos(x,y);if(that.options.onScrollEnd)that.options.onScrollEnd.call(that)}}that.absStartX=that.x;that.absStartY=that.y;that.startX=that.x;that.startY=that.y;that.pointX=point.pageX;that.pointY=point.pageY;that.startTime=e.timeStamp||Date.now();if(that.options.onScrollStart)that.options.onScrollStart.call(that,e);that._bind(MOVE_EV,window);that._bind(END_EV,window);that._bind(CANCEL_EV,window)},_move:function(e){var that=this,point=hasTouch?e.touches[0]:e,deltaX=point.pageX-that.pointX,deltaY=point.pageY-that.pointY,newX=that.x+deltaX,newY=that.y+deltaY,c1,c2,scale,timestamp=e.timeStamp||Date.now();if(that.options.onBeforeScrollMove)that.options.onBeforeScrollMove.call(that,e);if(that.options.zoom&&hasTouch&&e.touches.length>1){c1=m.abs(e.touches[0].pageX-e.touches[1].pageX);c2=m.abs(e.touches[0].pageY-e.touches[1].pageY);that.touchesDist=m.sqrt(c1*c1+c2*c2);that.zoomed=true;scale=1/that.touchesDistStart*that.touchesDist*this.scale;if(scale<that.options.zoomMin)scale=.5*that.options.zoomMin*Math.pow(2,scale/that.options.zoomMin);else if(scale>that.options.zoomMax)scale=2*that.options.zoomMax*Math.pow(.5,that.options.zoomMax/scale);that.lastScale=scale/this.scale;newX=this.originX-this.originX*that.lastScale+this.x,newY=this.originY-this.originY*that.lastScale+this.y;this.scroller.style[transform]="translate("+newX+"px,"+newY+"px) scale("+scale+")"+translateZ;if(that.options.onZoom)that.options.onZoom.call(that,e);return}that.pointX=point.pageX;that.pointY=point.pageY;if(newX>0||newX<that.maxScrollX){newX=that.options.bounce?that.x+deltaX/2:newX>=0||that.maxScrollX>=0?0:that.maxScrollX}if(newY>that.minScrollY||newY<that.maxScrollY){newY=that.options.bounce?that.y+deltaY/2:newY>=that.minScrollY||that.maxScrollY>=0?that.minScrollY:that.maxScrollY}that.distX+=deltaX;that.distY+=deltaY;that.absDistX=m.abs(that.distX);that.absDistY=m.abs(that.distY);if(that.absDistX<6&&that.absDistY<6){return}if(that.options.lockDirection){if(that.absDistX>that.absDistY+5){newY=that.y;deltaY=0}else if(that.absDistY>that.absDistX+5){newX=that.x;deltaX=0}}that.moved=true;that._pos(newX,newY);that.dirX=deltaX>0?-1:deltaX<0?1:0;that.dirY=deltaY>0?-1:deltaY<0?1:0;if(timestamp-that.startTime>300){that.startTime=timestamp;that.startX=that.x;that.startY=that.y}if(that.options.onScrollMove)that.options.onScrollMove.call(that,e)},_end:function(e){if(hasTouch&&e.touches.length!==0)return;var that=this,point=hasTouch?e.changedTouches[0]:e,target,ev,momentumX={dist:0,time:0},momentumY={dist:0,time:0},duration=(e.timeStamp||Date.now())-that.startTime,newPosX=that.x,newPosY=that.y,distX,distY,newDuration,snap,scale;that._unbind(MOVE_EV,window);that._unbind(END_EV,window);that._unbind(CANCEL_EV,window);if(that.options.onBeforeScrollEnd)that.options.onBeforeScrollEnd.call(that,e);if(that.zoomed){scale=that.scale*that.lastScale;scale=Math.max(that.options.zoomMin,scale);scale=Math.min(that.options.zoomMax,scale);that.lastScale=scale/that.scale;that.scale=scale;that.x=that.originX-that.originX*that.lastScale+that.x;that.y=that.originY-that.originY*that.lastScale+that.y;that.scroller.style[transitionDuration]="200ms";that.scroller.style[transform]="translate("+that.x+"px,"+that.y+"px) scale("+that.scale+")"+translateZ;that.zoomed=false;that.refresh();if(that.options.onZoomEnd)that.options.onZoomEnd.call(that,e);return}if(!that.moved){if(hasTouch){if(that.doubleTapTimer&&that.options.zoom){clearTimeout(that.doubleTapTimer);that.doubleTapTimer=null;if(that.options.onZoomStart)that.options.onZoomStart.call(that,e);that.zoom(that.pointX,that.pointY,that.scale==1?that.options.doubleTapZoom:1);if(that.options.onZoomEnd){setTimeout(function(){that.options.onZoomEnd.call(that,e)},200)}}else if(this.options.handleClick){that.doubleTapTimer=setTimeout(function(){that.doubleTapTimer=null;target=point.target;while(target.nodeType!=1)target=target.parentNode;if(target.tagName!="SELECT"&&target.tagName!="INPUT"&&target.tagName!="TEXTAREA"){ev=doc.createEvent("MouseEvents");ev.initMouseEvent("click",true,true,e.view,1,point.screenX,point.screenY,point.clientX,point.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,0,null);ev._fake=true;target.dispatchEvent(ev)}},that.options.zoom?250:0)}}that._resetPos(400);if(that.options.onTouchEnd)that.options.onTouchEnd.call(that,e);return}if(duration<300&&that.options.momentum){momentumX=newPosX?that._momentum(newPosX-that.startX,duration,-that.x,that.scrollerW-that.wrapperW+that.x,that.options.bounce?that.wrapperW:0):momentumX;momentumY=newPosY?that._momentum(newPosY-that.startY,duration,-that.y,that.maxScrollY<0?that.scrollerH-that.wrapperH+that.y-that.minScrollY:0,that.options.bounce?that.wrapperH:0):momentumY;newPosX=that.x+momentumX.dist;newPosY=that.y+momentumY.dist;if(that.x>0&&newPosX>0||that.x<that.maxScrollX&&newPosX<that.maxScrollX)momentumX={dist:0,time:0};if(that.y>that.minScrollY&&newPosY>that.minScrollY||that.y<that.maxScrollY&&newPosY<that.maxScrollY)momentumY={dist:0,time:0}}if(momentumX.dist||momentumY.dist){newDuration=m.max(m.max(momentumX.time,momentumY.time),10);if(that.options.snap){distX=newPosX-that.absStartX;distY=newPosY-that.absStartY;if(m.abs(distX)<that.options.snapThreshold&&m.abs(distY)<that.options.snapThreshold){that.scrollTo(that.absStartX,that.absStartY,200)}else{snap=that._snap(newPosX,newPosY);newPosX=snap.x;newPosY=snap.y;newDuration=m.max(snap.time,newDuration)}}that.scrollTo(m.round(newPosX),m.round(newPosY),newDuration);if(that.options.onTouchEnd)that.options.onTouchEnd.call(that,e);return}if(that.options.snap){distX=newPosX-that.absStartX;distY=newPosY-that.absStartY;if(m.abs(distX)<that.options.snapThreshold&&m.abs(distY)<that.options.snapThreshold)that.scrollTo(that.absStartX,that.absStartY,200);else{snap=that._snap(that.x,that.y);if(snap.x!=that.x||snap.y!=that.y)that.scrollTo(snap.x,snap.y,snap.time)}if(that.options.onTouchEnd)that.options.onTouchEnd.call(that,e);return}that._resetPos(200);if(that.options.onTouchEnd)that.options.onTouchEnd.call(that,e)},_resetPos:function(time){var that=this,resetX=that.x>=0?0:that.x<that.maxScrollX?that.maxScrollX:that.x,resetY=that.y>=that.minScrollY||that.maxScrollY>0?that.minScrollY:that.y<that.maxScrollY?that.maxScrollY:that.y;if(resetX==that.x&&resetY==that.y){if(that.moved){that.moved=false;if(that.options.onScrollEnd)that.options.onScrollEnd.call(that)}if(that.hScrollbar&&that.options.hideScrollbar){if(vendor=="webkit")that.hScrollbarWrapper.style[transitionDelay]="300ms";that.hScrollbarWrapper.style.opacity="0"}if(that.vScrollbar&&that.options.hideScrollbar){if(vendor=="webkit")that.vScrollbarWrapper.style[transitionDelay]="300ms";that.vScrollbarWrapper.style.opacity="0"}return}that.scrollTo(resetX,resetY,time||0)},_wheel:function(e){var that=this,wheelDeltaX,wheelDeltaY,deltaX,deltaY,deltaScale;if("wheelDeltaX"in e){wheelDeltaX=e.wheelDeltaX/12;wheelDeltaY=e.wheelDeltaY/12}else if("wheelDelta"in e){wheelDeltaX=wheelDeltaY=e.wheelDelta/12}else if("detail"in e){wheelDeltaX=wheelDeltaY=-e.detail*3}else{return}if(that.options.wheelAction=="zoom"){deltaScale=that.scale*Math.pow(2,1/3*(wheelDeltaY?wheelDeltaY/Math.abs(wheelDeltaY):0));if(deltaScale<that.options.zoomMin)deltaScale=that.options.zoomMin;if(deltaScale>that.options.zoomMax)deltaScale=that.options.zoomMax;if(deltaScale!=that.scale){
     15if(!that.wheelZoomCount&&that.options.onZoomStart)that.options.onZoomStart.call(that,e);that.wheelZoomCount++;that.zoom(e.pageX,e.pageY,deltaScale,400);setTimeout(function(){that.wheelZoomCount--;if(!that.wheelZoomCount&&that.options.onZoomEnd)that.options.onZoomEnd.call(that,e)},400)}return}deltaX=that.x+wheelDeltaX;deltaY=that.y+wheelDeltaY;if(deltaX>0)deltaX=0;else if(deltaX<that.maxScrollX)deltaX=that.maxScrollX;if(deltaY>that.minScrollY)deltaY=that.minScrollY;else if(deltaY<that.maxScrollY)deltaY=that.maxScrollY;if(that.maxScrollY<0){that.scrollTo(deltaX,deltaY,0)}},_transitionEnd:function(e){var that=this;if(e.target!=that.scroller)return;that._unbind(TRNEND_EV);that._startAni()},_startAni:function(){var that=this,startX=that.x,startY=that.y,startTime=Date.now(),step,easeOut,animate;if(that.animating)return;if(!that.steps.length){that._resetPos(400);return}step=that.steps.shift();if(step.x==startX&&step.y==startY)step.time=0;that.animating=true;that.moved=true;if(that.options.useTransition){that._transitionTime(step.time);that._pos(step.x,step.y);that.animating=false;if(step.time)that._bind(TRNEND_EV);else that._resetPos(0);return}animate=function(){var now=Date.now(),newX,newY;if(now>=startTime+step.time){that._pos(step.x,step.y);that.animating=false;if(that.options.onAnimationEnd)that.options.onAnimationEnd.call(that);that._startAni();return}now=(now-startTime)/step.time-1;easeOut=m.sqrt(1-now*now);newX=(step.x-startX)*easeOut+startX;newY=(step.y-startY)*easeOut+startY;that._pos(newX,newY);if(that.animating)that.aniTime=nextFrame(animate)};animate()},_transitionTime:function(time){time+="ms";this.scroller.style[transitionDuration]=time;if(this.hScrollbar)this.hScrollbarIndicator.style[transitionDuration]=time;if(this.vScrollbar)this.vScrollbarIndicator.style[transitionDuration]=time},_momentum:function(dist,time,maxDistUpper,maxDistLower,size){var deceleration=6e-4,speed=m.abs(dist)/time,newDist=speed*speed/(2*deceleration),newTime=0,outsideDist=0;if(dist>0&&newDist>maxDistUpper){outsideDist=size/(6/(newDist/speed*deceleration));maxDistUpper=maxDistUpper+outsideDist;speed=speed*maxDistUpper/newDist;newDist=maxDistUpper}else if(dist<0&&newDist>maxDistLower){outsideDist=size/(6/(newDist/speed*deceleration));maxDistLower=maxDistLower+outsideDist;speed=speed*maxDistLower/newDist;newDist=maxDistLower}newDist=newDist*(dist<0?-1:1);newTime=speed/deceleration;return{dist:newDist,time:m.round(newTime)}},_offset:function(el){var left=-el.offsetLeft,top=-el.offsetTop;while(el=el.offsetParent){left-=el.offsetLeft;top-=el.offsetTop}if(el!=this.wrapper){left*=this.scale;top*=this.scale}return{left:left,top:top}},_snap:function(x,y){var that=this,i,l,page,time,sizeX,sizeY;page=that.pagesX.length-1;for(i=0,l=that.pagesX.length;i<l;i++){if(x>=that.pagesX[i]){page=i;break}}if(page==that.currPageX&&page>0&&that.dirX<0)page--;x=that.pagesX[page];sizeX=m.abs(x-that.pagesX[that.currPageX]);sizeX=sizeX?m.abs(that.x-x)/sizeX*500:0;that.currPageX=page;page=that.pagesY.length-1;for(i=0;i<page;i++){if(y>=that.pagesY[i]){page=i;break}}if(page==that.currPageY&&page>0&&that.dirY<0)page--;y=that.pagesY[page];sizeY=m.abs(y-that.pagesY[that.currPageY]);sizeY=sizeY?m.abs(that.y-y)/sizeY*500:0;that.currPageY=page;time=m.round(m.max(sizeX,sizeY))||200;return{x:x,y:y,time:time}},_bind:function(type,el,bubble){(el||this.scroller).addEventListener(type,this,!!bubble)},_unbind:function(type,el,bubble){(el||this.scroller).removeEventListener(type,this,!!bubble)},destroy:function(){var that=this;that.scroller.style[transform]="";that.hScrollbar=false;that.vScrollbar=false;that._scrollbar("h");that._scrollbar("v");that._unbind(RESIZE_EV,window);that._unbind(START_EV);that._unbind(MOVE_EV,window);that._unbind(END_EV,window);that._unbind(CANCEL_EV,window);if(!that.options.hasTouch){that._unbind(WHEEL_EV)}if(that.options.useTransition)that._unbind(TRNEND_EV);if(that.options.checkDOMChanges)clearInterval(that.checkDOMTime);if(that.options.onDestroy)that.options.onDestroy.call(that)},refresh:function(){var that=this,offset,i,l,els,pos=0,page=0;if(that.scale<that.options.zoomMin)that.scale=that.options.zoomMin;that.wrapperW=that.wrapper.clientWidth||1;that.wrapperH=that.wrapper.clientHeight||1;that.minScrollY=-that.options.topOffset||0;that.scrollerW=m.round(that.scroller.offsetWidth*that.scale);that.scrollerH=m.round((that.scroller.offsetHeight+that.minScrollY)*that.scale);that.maxScrollX=that.wrapperW-that.scrollerW;that.maxScrollY=that.wrapperH-that.scrollerH+that.minScrollY;that.dirX=0;that.dirY=0;if(that.options.onRefresh)that.options.onRefresh.call(that);that.hScroll=that.options.hScroll&&that.maxScrollX<0;that.vScroll=that.options.vScroll&&(!that.options.bounceLock&&!that.hScroll||that.scrollerH>that.wrapperH);that.hScrollbar=that.hScroll&&that.options.hScrollbar;that.vScrollbar=that.vScroll&&that.options.vScrollbar&&that.scrollerH>that.wrapperH;offset=that._offset(that.wrapper);that.wrapperOffsetLeft=-offset.left;that.wrapperOffsetTop=-offset.top;if(typeof that.options.snap=="string"){that.pagesX=[];that.pagesY=[];els=that.scroller.querySelectorAll(that.options.snap);for(i=0,l=els.length;i<l;i++){pos=that._offset(els[i]);pos.left+=that.wrapperOffsetLeft;pos.top+=that.wrapperOffsetTop;that.pagesX[i]=pos.left<that.maxScrollX?that.maxScrollX:pos.left*that.scale;that.pagesY[i]=pos.top<that.maxScrollY?that.maxScrollY:pos.top*that.scale}}else if(that.options.snap){that.pagesX=[];while(pos>=that.maxScrollX){that.pagesX[page]=pos;pos=pos-that.wrapperW;page++}if(that.maxScrollX%that.wrapperW)that.pagesX[that.pagesX.length]=that.maxScrollX-that.pagesX[that.pagesX.length-1]+that.pagesX[that.pagesX.length-1];pos=0;page=0;that.pagesY=[];while(pos>=that.maxScrollY){that.pagesY[page]=pos;pos=pos-that.wrapperH;page++}if(that.maxScrollY%that.wrapperH)that.pagesY[that.pagesY.length]=that.maxScrollY-that.pagesY[that.pagesY.length-1]+that.pagesY[that.pagesY.length-1]}that._scrollbar("h");that._scrollbar("v");if(!that.zoomed){that.scroller.style[transitionDuration]="0";that._resetPos(400)}},scrollTo:function(x,y,time,relative){var that=this,step=x,i,l;that.stop();if(!step.length)step=[{x:x,y:y,time:time,relative:relative}];for(i=0,l=step.length;i<l;i++){if(step[i].relative){step[i].x=that.x-step[i].x;step[i].y=that.y-step[i].y}that.steps.push({x:step[i].x,y:step[i].y,time:step[i].time||0})}that._startAni()},scrollToElement:function(el,time){var that=this,pos;el=el.nodeType?el:that.scroller.querySelector(el);if(!el)return;pos=that._offset(el);pos.left+=that.wrapperOffsetLeft;pos.top+=that.wrapperOffsetTop;pos.left=pos.left>0?0:pos.left<that.maxScrollX?that.maxScrollX:pos.left;pos.top=pos.top>that.minScrollY?that.minScrollY:pos.top<that.maxScrollY?that.maxScrollY:pos.top;time=time===undefined?m.max(m.abs(pos.left)*2,m.abs(pos.top)*2):time;that.scrollTo(pos.left,pos.top,time)},scrollToPage:function(pageX,pageY,time){var that=this,x,y;time=time===undefined?400:time;if(that.options.onScrollStart)that.options.onScrollStart.call(that);if(that.options.snap){pageX=pageX=="next"?that.currPageX+1:pageX=="prev"?that.currPageX-1:pageX;pageY=pageY=="next"?that.currPageY+1:pageY=="prev"?that.currPageY-1:pageY;pageX=pageX<0?0:pageX>that.pagesX.length-1?that.pagesX.length-1:pageX;pageY=pageY<0?0:pageY>that.pagesY.length-1?that.pagesY.length-1:pageY;that.currPageX=pageX;that.currPageY=pageY;x=that.pagesX[pageX];y=that.pagesY[pageY]}else{x=-that.wrapperW*pageX;y=-that.wrapperH*pageY;if(x<that.maxScrollX)x=that.maxScrollX;if(y<that.maxScrollY)y=that.maxScrollY}that.scrollTo(x,y,time)},disable:function(){this.stop();this._resetPos(0);this.enabled=false;this._unbind(MOVE_EV,window);this._unbind(END_EV,window);this._unbind(CANCEL_EV,window)},enable:function(){this.enabled=true},stop:function(){if(this.options.useTransition)this._unbind(TRNEND_EV);else cancelFrame(this.aniTime);this.steps=[];this.moved=false;this.animating=false},zoom:function(x,y,scale,time){var that=this,relScale=scale/that.scale;if(!that.options.useTransform)return;that.zoomed=true;time=time===undefined?200:time;x=x-that.wrapperOffsetLeft-that.x;y=y-that.wrapperOffsetTop-that.y;that.x=x-x*relScale+that.x;that.y=y-y*relScale+that.y;that.scale=scale;that.refresh();that.x=that.x>0?0:that.x<that.maxScrollX?that.maxScrollX:that.x;that.y=that.y>that.minScrollY?that.minScrollY:that.y<that.maxScrollY?that.maxScrollY:that.y;that.scroller.style[transitionDuration]=time+"ms";that.scroller.style[transform]="translate("+that.x+"px,"+that.y+"px) scale("+scale+")"+translateZ;that.zoomed=false},isReady:function(){return!this.moved&&!this.zoomed&&!this.animating}};function prefixStyle(style){if(vendor==="")return style;style=style.charAt(0).toUpperCase()+style.substr(1);return vendor+style}dummyStyle=null;if(typeof exports!=="undefined")exports.iScroll=iScroll;else window.iScroll=iScroll})(window,document);define("lib/iscroll",function(global){return function(){var ret,fn;return ret||global.iScroll}}(this));define("view/note/view",["ext/underscore","$root","view/page","view/link-resolver","lib/iscroll","view/navbar-factory"],function(_,$root,PageView,linkResolver,iScroll,navbarFactory){var $=jQuery;return PageView.extend({attributes:{id:"scroll-wrapper"},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.group=this.model.getGroup();var query=this.getSearchQuery();if(query){this.back={code:"m_back",link:"#search/"+query}}else{this.back={code:"m_btn_notes",link:"#notes/"+this.group.getKey()}}this.title=_.escape(this.model.get("friendlyName")),this.actions=[{code:"m_comments",icon:"comment",link:"#comments/"+this.model.getKey()+this.formatQuery(query)}];if(this.model.permission.canEdit()&&window.localStorage.getItem("features")!="limited"){this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()+this.formatQuery(query)})}},render:function(){PageView.prototype.render.apply(this,arguments);$("<div>").addClass("html-content").html(this.model.get("content")).appendTo(this.$el);this.resolveLinks();var fudge=30;var zoomMin=$root.width()/($("div.html-content",this.$el).width()+fudge);var iscroll=new iScroll(this.el,{zoom:true,zoomMin:zoomMin});iscroll.zoom(0,0,zoomMin,0);iscroll.refresh();return this},navbar:function(callback){this.navbarCreate("pages",this.group.id,callback)}}).extend(navbarFactory).extend(linkResolver)});define("router/note",["router/group","api/cache","api/service/note","view/note/list","view/note/view"],function(GroupRouter,cache,service,NoteListView,NoteViewView){return GroupRouter.extend({routes:{"notes/:groupKey":"showNotes","note/:noteKey":"getNote","page/:noteKey":"getNote"},showNotes:function(group){var notes=cache.getFrom(service.createNotes(group,1));var view=new NoteListView({collection:notes});view.render();view.handleRefresh()},getNote:function(noteKey){var parts=noteKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getNote(group,parts[3],this.showNote)},showNote:function(note){new NoteViewView({model:note}).render()}})});define("api/collection/discussions",["api/collection/content","api/model/discussion"],function(ContentCollection,Discussion){return ContentCollection.extend({model:Discussion})});define("api/model/discussion-reply",["api/model/base"],function(BaseModel){return BaseModel.extend({url:function(){var id=this.id?"/@"+this.id:"";return this.collection.url()+id}})});define("api/collection/discussion-replies",["api/collection/base","api/model/discussion-reply"],function(BaseCollection,DiscussionReply){return BaseCollection.extend({model:DiscussionReply,initialize:function(models,options){this.discussion=options.discussion},url:function(){return this.discussion.url()+"/replies"}})});define("api/service/discussion",["ext/underscore","app-context","api/cache","api/service/base","api/collection/discussions","api/collection/discussion-replies","api/model/discussion-reply","api/model/discussion"],function(_,appContext,cache,base,Discussions,DiscussionReplies,DiscussionReply,Discussion){return _.extend({getDiscussions:function(group,handler){var discussions=this.createDiscussions(group,1);cache.putModel(discussions);this.getCollection(discussions,handler)},getNextDiscussions:function(discussions,handler){var next=this.createDiscussions(group,discussions.params.currentPage+1);this.getCollection(next,function(next){discussions.add(next.models);discussions.params.currentPage=next.params.currentPage;discussions.more=next.more;handler(next)})},getDiscussion:function(group,id,handler){var self=this;this.getDiscussionOnly(group,id,function(discussion){self.getPermission(discussion,handler)})},getDiscussionOnly:function(group,id,handler){var discussion=new Discussion({name:id});if(id.charAt(0)=="@"){discussion=new Discussion({id:parseInt(id.slice(1))})}discussion.set("group",group);discussion=cache.getFrom(discussion);if(discussion._expiry){if(discussion.replies){handler(discussion)}else{this._getReplies(discussion,handler)}return}cache.putModel(discussion);var _handler=_.after(2,handler);discussion.once("change",_handler);discussion.fetch();this._getReplies(discussion,_handler)},_getReplies:function(discussion,handler){discussion.replies=new DiscussionReplies([],{discussion:discussion});discussion.replies.once("sync",function(){handler(discussion)});discussion.replies.fetch()},createDiscussion:function(discussions,discussion,handler){discussion["group"]={id:discussions.group.id};var model=new Discussion(discussion);discussions.add(model);model.save();model.once("change",_.bind(handler,this,model))},createReply:function(replies,text,handler){var reply=new DiscussionReply({reply:text});replies.add(reply);reply.save();reply.once("change",_.bind(handler,this,reply))},createDiscussions:function(group,currentPage){return new Discussions([],{group:group,params:{currentPage:currentPage,pageSize:appContext.pageSize}})}},base)});define("text!text/discussion/item.html",[],function(){return"<a class=\"no-icon\" href=\"#discussion/<%= getKey() %>\">\n <p><b><%= _.escape(get('friendlyName')) %></b></p>\n    <abbr><%= m_last_updated %>: <%= $.timeago(new Date(get('lastModified'))) %></abbr>\n   <span class=\"badge\"><%= get('replies') %></span>\n</a>\n"});define("view/discussion/item",["view/base","text!text/discussion/item.html"],function(BaseView,template){return BaseView.extend({tagName:"li",className:"fat",render:function(){this.$el.html(this.template(template,this.model));return this}})});define("view/discussion/list",["ext/underscore","view/navbar-factory","view/extending-list","view/discussion/item","api/service/discussion"],function(_,navbarFactory,ExtendingListView,DiscussionItemView,service){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);var group=this.collection.group;this.title=_.escape(group.get("friendlyName"));if(group.permission.canCreate()){this.action={code:"m_new",link:"#discussions/"+group.getKey()+"/create"}}},emptyMsgCode:"m_discussions_nothing",itemViewClass:DiscussionItemView,handleEndOfList:function(){service.getNextDiscussions(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getDiscussions(this.collection.group,function(discussions){self.collection=discussions;self.refresh()})},navbar:function(callback){this.navbarCreate("discussions",this.collection.group.id,callback)}}).extend(navbarFactory)});define("text!text/discussion/create.html",[],function(){return'<input class="form-control" name="topic" placeholder="<%= m_discussion_topic %>" type="text" maxlength="128">\n<textarea class="editor hidden" placeholder="<%= m_discussion_first %>"></textarea>\n<a href="javascript:void(0)" id="post" class="btn btn-primary" disabled="disabled">\n  <%= m_post %>\n</a>\n'});define("view/discussion/create",["ext/underscore","app-context","view/page","view/editor","api/service/discussion","text!text/discussion/create.html"],function(_,appContext,PageView,EditorView,service,template){var $=jQuery;return PageView.extend({tagName:"fieldset",events:{"keyup [name=topic]":"onKeyup","click #post":"post"},title:PageView.message("m_create_discussion"),nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.editor=new EditorView({context:this.options.discussions.group,$page:this.$el});this.action={code:"m_mention",view:this.editor};this.back={code:"m_btn_discussions",link:"#discussions/"+this.options.discussions.group.getKey()}},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template));this.editor.render_delayed();return this},onKeyup:function(){$("#post",this.$el).attr("disabled",_.isBlank($("[name=topic]",this.el).val()))},post:function(){service.createDiscussion(this.options.discussions,{friendlyName:$("[name=topic]",this.el).val(),description:this.editor.getText()},function(discussion){appContext.navigate("#discussion/"+discussion.getKey())})}})});define("text!text/discussion/reply.html",[],function(){return"<div>\n    <img src=\"<%= cdn %>/users/<%= model.get('author').id %>/thumbnail\"\n     onerror='this.onerror = null; this.src=\"<%= appurl %>/styles/images/default_thumbnail.png\"'>\n    <p><%= _.isBlank(model.get('reply')) ? '&nbsp;' : model.get('reply') %></p>\n   <p class=\"who-when\"><%= model.get('author').name %> (<%= $.timeago(new Date(model.get('dateCreated'))) %>)</p>\n  <% if ((me.id == model.get('author').id) && !readonly) { %>\n       <a href=\"javascript:void(0)\" class=\"comment-delete\">\n          <span class=\"glyphicon glyphicon-trash\"></span>\n     </a>\n  <% } %>\n</div>\n"});define("view/discussion/reply",["ext/underscore","view/base","app-context","api/service/general","text!text/discussion/reply.html"],function(_,BaseView,appContext,service,template){return BaseView.extend({attributes:{"class":"comment"},events:{"click .comment-delete":"onDelete"},initialize:function(options){_.bindToMethods(this);this.replyViews=[];this.options=options},render:function(){var args={readonly:this.options.readonly,model:this.model,cdn:appContext.cdn,me:appContext.getPrinciple()};this.$el.html(this.template(template,args));return this},onDelete:function(){service.deleteModel(this.model,this.onDeleted)},onDeleted:function(){this.$el.remove()}})});define("view/discussion/view",["ext/underscore","view/page","api/model/discussion-reply","view/navbar-factory","view/discussion/reply"],function(_,PageView,DiscussionReply,navbarFactory,DiscussionReplyView){return PageView.extend({className:"comments",initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.group=this.model.getGroup();var query=this.getSearchQuery();if(query){this.back={code:"m_back",link:"#search/"+query}}else{this.back={code:"m_btn_discussions",link:"#discussions/"+this.group.getKey()}}this.title=_.escape(this.model.get("friendlyName"));this.actions=[{code:"m_reply",link:"#discussion/"+this.model.getKey()+"/create"}];if(this.model.permission.canEdit()){this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()+this.formatQuery(query)})}},render:function(){PageView.prototype.render.apply(this,arguments);var view=new DiscussionReplyView({model:new DiscussionReply({author:this.model.get("author"),reply:this.model.get("description"),dateCreated:this.model.get("dateCreated")}),readonly:true});this.$el.append(view.render().el);var selectedId=this.getSelectedReply();this.model.replies.each(function(reply){var view=new DiscussionReplyView({model:reply});var $item=view.render().$el;this.$el.append($item);if(selectedId==reply.id){$item.addClass("selected");this.scroll($item.offset().top-52)}},this);return this},getSelectedReply:function(){var reversed=_.sortBy(this.model.replies.toJSON(),function(reply){return-reply.dateCreated});var selected=_.find(reversed,function(reply){return reply.dateCreated<=this.options.dateOfSelection},this);return selected?selected.id:-1},navbar:function(callback){this.navbarCreate("discussions",this.group.id,callback)}}).extend(navbarFactory)});define("view/discussion/create-reply",["app-context","view/editor-page","api/service/discussion"],function(appContext,EditorPageView,service){return EditorPageView.extend({title:EditorPageView.message("m_create_reply"),nosearch:true,initialize:function(){EditorPageView.prototype.initialize.apply(this,arguments);this.back={code:"m_discussion",link:"#discussion/"+this.options.replies.discussion.getKey()}},post:function(){var backLink=this.back.link;service.createReply(this.options.replies,this.editor.getText(),function(reply){appContext.navigate(backLink+"/"+reply.get("dateCreated"))})}})});define("router/discussion",["router/group","api/cache","api/service/discussion","view/discussion/list","view/discussion/create","view/discussion/view","view/discussion/create-reply"],function(GroupRouter,cache,service,DiscussionListView,DiscussionCreateView,DiscussionViewView,ReplyCreateView){return GroupRouter.extend({routes:{"discussions/:groupKey/create":"createDiscussion","discussions/:groupKey":"showDiscussions","discussion/:discussionKey/create":"createReply","discussion/:discussionKey/:dateOfSelection":"getDiscussion","discussion/:discussionKey":"getDiscussion"},showDiscussions:function(group){var discussions=cache.getFrom(service.createDiscussions(group,1));var view=new DiscussionListView({collection:discussions});view.render();view.handleRefresh()},createDiscussion:function(group){var discussions=cache.getFrom(service.createDiscussions(group,1));new DiscussionCreateView({discussions:discussions}).render()},getDiscussion:function(discussionKey,dateOfSelection){var parts=discussionKey.split(":");var group={id:parseInt(parts[1].substr(1))};var self=this;service.getDiscussion(group,parts[3],function(discussion){var options={model:discussion};if(dateOfSelection){options.dateOfSelection=parseInt(dateOfSelection)}new DiscussionViewView(options).render()})},createReply:function(discussionKey){var self=this;var parts=discussionKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getDiscussion(group,parts[3],function(discussion){self.showReplyCreate(discussion.replies)})},showReplyCreate:function(replies){new ReplyCreateView({context:replies.discussion.getGroup(),replies:replies}).render()}})});define("api/collection/requests",["api/collection/base","api/model/request"],function(BaseCollection,Request){return BaseCollection.extend({model:Request,initialize:function(models,options){if(options&&options.context){this.context=options.context}},url:function(){return this.context.url()+"/requests"}})});define("api/service/request",["ext/underscore","app-context","api/service/base","api/collection/requests","api/model/request"],function(_,appContext,base,Requests,Request){return _.extend({getRequests:function(model,handler){model.requests=new Requests([],{context:model});model.requests.once("sync",function(){handler(model)});model.requests.fetch()},saveRequests:function(model,requests,handler){requests["context"]=model;var requestMap={};requests.each(function(request){requestMap[request.get("target").id]=request});model.requests&&model.requests.each(function(request){if(requestMap[request.get("target").id]){delete requestMap[request.get("target").id]}else{request.destroy()}});var newRequests=_.values(requestMap);if(newRequests.length==0){handler()}else{var _handler=_.after(newRequests.length,handler);var me=appContext.getPrinciple();_.each(newRequests,function(request){model.requests&&model.requests.add(request);request.set("source",{id:me.id});request.once("sync",_handler);request.save()})}},createRequests:function(existingRequests){var requests=new Requests;if(existingRequests){existingRequests.each(function(request){requests.add(new Request(request.toJSON()))})}else{requests.add(this.createRequest(appContext.getPrinciple()))}return requests},createRequest:function(user){return new Request({target:user.toJSON?user.toJSON():user,status:appContext.getPrinciple().id==user.id?"ACCEPT":"NONE"})}},base)});define("api/collection/events",["api/collection/content","api/model/event"],function(ContentCollection,Event){return ContentCollection.extend({model:Event})});define("api/service/event",["ext/underscore","app-context","api/cache","api/service/base","api/service/request","api/collection/events","api/model/event"],function(_,appContext,cache,base,requestService,Events,Event){return _.extend({getEvents:function(group,handler){var events=this.createEvents(group,1);cache.putModel(events);this.getCollection(events,handler)},getNextEvents:function(events,handler){var next=this.createEvents(events.group,events.params.currentPage+1);this.getCollection(next,function(next){events.add(next.models);events.params.currentPage=next.params.currentPage;events.more=next.more;handler(next)})},getEvent:function(group,id,handler){var self=this;this.getEventOnly(group,id,function(event){self.getPermission(event,handler)})},getEventOnly:function(group,id,handler){var event=new Event({name:id});if(id.charAt(0)=="@"){event=new Event({id:parseInt(id.slice(1))})}event.set("group",group);event=cache.getFrom(event);if(event._expiry){if(event.requests){handler(event)}else{requestService.getRequests(event,handler)}return}cache.putModel(event);var _handler=_.after(2,handler);event.once("change",_handler);event.fetch();requestService.getRequests(event,_handler)},saveEvent:function(context,attributes,requests,handler){var event;if(context.type){event=context;event.set(attributes)}else{attributes["group"]=context.group;event=new Event(attributes);context.add(event)}var self=this;event.once("sync",function(){requestService.saveRequests(event,requests,_.bind(handler,self,event))});event.save()},createEvents:function(group,currentPage){return new Events([],{group:group,params:{currentPage:currentPage,pageSize:appContext.pageSize}})}},base)});define("text!text/event/item.html",[],function(){return"<a class=\"no-icon\" href=\"#event/<%= getKey() %>\">\n <p><b><%= _.escape(get('friendlyName')) %></b></p>\n    <abbr><%= when %>, <%= m_by %> <%= get('author').name %></abbr>\n   <span class=\"badge\"><%= get('attendees') %></span>\n</a>\n"});define("view/event/item",["ext/underscore","moment","view/base","text!text/event/item.html"],function(_,moment,BaseView,template){return BaseView.extend({tagName:"li",render:function(){var dateLabel=this.model.get("dateLabel");if(dateLabel){this.$el.addClass("list-divider").html(dateLabel)}else{this.$el.addClass("fat");var args=_.extend({when:this.getTime()},this.model);this.$el.html(this.template(template,args))}return this},getTime:function(){if(this.model.get("allDay")){if(this.model.isSameDay()){return this.message("m_all_day")}else{return this.message("m_all_day")+" "+this.message("m_to")+this.model.getEndDate().format(" DD/MM/YY")}}else{var startDate=moment(this.model.get("startDate")).format("HH:mm ");var endDate=moment(this.model.get("endDate"));if(this.model.isSameDay()){return startDate+this.message("m_to")+endDate.format(" HH:mm")}else{return startDate+this.message("m_to")+endDate.format(" DD/MM/YY, HH:mm")}}}})});define("view/event/list",["ext/underscore","api/service/event","api/collection/events","api/model/event","view/navbar-factory","view/extending-list","view/event/item"],function(_,service,Events,Event,navbarFactory,ExtendingListView,EventItemView){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);var group=this.collection.group;this.title=_.escape(group.get("friendlyName"));if(group.permission.canCreate()){this.action={code:"m_new",link:"#events/"+group.getKey()+"/create"}}this.groupEvents()},groupEvents:function(){var eventMap=_.groupBy(this.collection.models,function(event){return this.extractDateLabel(event.get("startDate"))},this);this.collection=new Events([],{group:this.collection.group});_.each(_.keys(eventMap),function(dateLabel){this.collection.add(new Event({dateLabel:dateLabel}));this.collection.add(eventMap[dateLabel])},this)},emptyMsgCode:"m_events_nothing",itemViewClass:EventItemView,handleEndOfList:function(){service.getNextEvents(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getEvents(this.collection.group,function(events){self.collection=events;self.groupEvents();self.refresh()})},navbar:function(callback){this.navbarCreate("events",this.collection.group.id,callback)}}).extend(navbarFactory)});define("text!text/request/item.html",[],function(){return'<% if (request.get(\'target\').logo) { %>\n  <img src="<%= appContext.cdn %>/users/<%= request.get(\'target\').id %>/thumbnail">\n<% } else { %>\n   <img src="<%= appContext.defaultThumb %>">\n<% } %>\n<span><%= request.get(\'target\').name %></span>\n<% if (deletable) { %>\n <a href="javascript:void(0)" class="comment-delete">\n      <span class="glyphicon glyphicon-trash"></span>\n   </a>\n<% } %>\n'});define("view/request/item",["ext/underscore","app-context","text!text/request/item.html"],function(_,appContext,template){return Backbone.View.extend({tagName:"li",events:{"click .comment-delete":"onDelete"},initialize:function(options){this.options=options},render:function(){var args=_.extend({appContext:appContext,deletable:false},this.options);this.$el.html(_.template(template,args));return this},onDelete:function(){this.options.collection.remove(this.options.request)}})});define("text!text/request/group.html",[],function(){return"<h5 class=\"request-<%= status %>\">\n   <%= messages['m_request_' + type + '_' + status] %>\n</h5>\n<ul class=\"list-unstyled\"></ul>\n"});define("view/request/group",["ext/underscore","view/base","view/request/item","text!text/request/group.html"],function(_,BaseView,RequestItemView,template){var $=jQuery;return BaseView.extend({initialize:function(options){this.options=options},render:function(){this.$el.html(this.template(template,this.options));var $list=$("ul",this.$el);_.each(this.options.requestGroup,function(request){var options=_.extend({request:request},this.options);var view=new RequestItemView(options);$list.append(view.render().el)},this);return this}})});define("view/request/list",["ext/underscore","view/request/group"],function(_,RequestGroupView){return Backbone.View.extend({className:"requests",initialize:function(options){this.options=options},render:function(){var requestMap=_.groupBy(this.collection.models,function(request){return request.get("status")});this.$el.empty();_.each(["ACCEPT","REJECT","DECLINE","MAYBE","NONE"],function(status){if(!requestMap[status]){return}var options=_.extend({status:status,requestGroup:requestMap[status]},this.options);var view=new RequestGroupView(options);this.$el.append(view.render().el)},this);return this}})});define("text!text/date-time.html",[],function(){return"<input name=\"date\" class=\"form-control date\" type=\"text\"\n   placeholder=\"<%= messages[placeholder] %>\" \n value=\"<%= date ? date.format('DD MMM, YYYY') : '' %>\" >\n\n<% var time = date ? date.format('HH:mm') : ''; %>\n\n<input name=\"time\" class=\"form-control time\" type=\"text\" \n   placeholder=\"<%= time == '00:00' || time == '' ? 'hh:mm' : '' %>\" \n  value=\"<%= time == '00:00' ? '' : time %>\" <%= date ? '' : 'disabled=\"disabled\"' %> >\n\n<p class=\"invalid hidden\"></p>\n"});define("view/date-time",["ext/underscore","native","view/base","moment","text!text/date-time.html"],function(_,_native,BaseView,moment,template){var $=jQuery;return BaseView.extend({className:"date-time",render:function(){BaseView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,this.options));_native.datepicker(this.$el);return this},isTimeSet:function(){var dueTime=$("[name=time]",this.$el).val();return!_.isBlank(dueTime)},val:function(previousDate){this.error();var date=$("[name=date]",this.$el).val();if(_.isBlank(date)){if(this.options.required){this.error(this.message(this.options.required));throw"invalid"}}else{var time=$("[name=time]",this.$el).val();if(!_.isBlank(time)&&time.search(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/)==-1){
     16this.error(this.message("m_error_time"));throw"invalid"}var format="DD MMM, YYYY HH:mm Z";var datetime=moment(date+" "+time+" +0000",format).valueOf();if(previousDate&&previousDate>datetime){this.error(this.message("m_error_date_range",moment(previousDate).format(format)));throw"invalid"}return datetime}return null},error:function(message){var $error=$("p.invalid",this.$el);if(message){$error.html(message).removeClass("hidden")}else{$error.addClass("hidden")}}})});define("text!text/event/save.html",[],function(){return'<input class="form-control" name="friendlyName" placeholder="<%= m_event_title %>" \n  type="text" maxlength="108" value="<%= event ? event.get(\'friendlyName\') : \'\' %>">\n<div id="startDate"></div>\n<div id="endDate"></div>\n<input class="form-control" name="location" placeholder="<%= m_event_location %>" \n  type="text" maxlength="128" value="<%= event ? event.get(\'location\') : \'\' %>">\n<textarea class="editor hidden" placeholder="<%= m_event_description %>"></textarea>\n<div id="requests"></div>\n<a href="javascript:void(0)" id="save" class="btn btn-primary" <%= event ? \'\' : \'disabled="disabled"\' %>>\n    <%= m_save %>\n</a>\n'});define("view/event/save",["ext/underscore","view/page","view/editor","app-context","moment","api/service/general","api/service/request","api/service/event","view/people/list","view/request/list","view/date-time","text!text/event/save.html"],function(_,PageView,EditorView,appContext,moment,generalService,requestService,eventService,PeopleListView,RequestListView,DateTimeView,template){var $=jQuery;return PageView.extend({tagName:"fieldset",events:{"keyup [name=friendlyName]":"onKeyup","click #save":"save"},nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var group=this.resolveGroup();this.editor=new EditorView({context:group,$page:this.$el,content:options.model?options.model.get("description"):null});this.back={code:options.model?"m_event":"m_btn_events",link:options.model?"#event/"+options.model.getKey():"#events/"+group.getKey()};this.action={code:"m_assign",view:this};this.title=this.message(options.model?"m_update_event":"m_create_event");this.requestList=new RequestListView({collection:requestService.createRequests(options.model?options.model.requests:null),type:"event",deletable:true});this.requestList.collection.on("remove",this.renderRequests);this.startDate=new DateTimeView({date:options.model?options.model.getStartDate():null,placeholder:"m_event_startdate",required:"m_error_startdate"});this.endDate=new DateTimeView({date:options.model?options.model.getEndDate():null,placeholder:"m_event_enddate",required:"m_error_enddate"})},resolveGroup:function(){if(this.options.model){return this.options.model.getGroup()}return this.options.collection.group},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,{statuses:["NOT_STARTED","IN_PROGRESS","DEFERRED","WAITING","COMPLETED"],event:this.options.model}));$("#startDate",this.$el).replaceWith(this.startDate.render().$el);$("#endDate",this.$el).replaceWith(this.endDate.render().$el);this.renderRequests();this.editor.render_delayed();return this},renderRequests:function(){var $requests=$("#requests",this.$el).empty();if(this.requestList.collection.length>0){$requests.append(this.requestList.render().el)}},onKeyup:function(){$("#save",this.$el).attr("disabled",_.isBlank($("[name=friendlyName]",this.el).val()))},doAction:function(container){var filter=this.requestList.collection.map(function(request){return request.get("target").id});var self=this;generalService.getUsers(this.resolveGroup(),function(users){var people=new PeopleListView({collection:users,callback:self.addRequest,filter:filter});people.render()},true)},addRequest:function(user){this.requestList.collection.add(requestService.createRequest(user));this.renderRequests()},save:function(){this.requestList.collection.off("remove",this.renderRequests);var attributes={friendlyName:$("[name=friendlyName]",this.el).val(),location:$("[name=location]",this.el).val(),description:this.editor.getText(),allDay:!(this.startDate.isTimeSet()||this.endDate.isTimeSet())};var valid=true;try{attributes.startDate=this.startDate.val()}catch(e){valid=false}try{attributes.endDate=this.endDate.val(attributes.startDate)}catch(e){valid=false}if(attributes.allDay){attributes.startDate+=432e5;attributes.endDate+=432e5;if(this.startDate!=this.endDate){attributes.endDate+=864e5}}valid&&eventService.saveEvent(this.options.model?this.options.model:this.options.collection,attributes,this.requestList.collection,function(event){appContext.navigate("#event/"+event.getKey())})}})});define("text!text/event/view.html",[],function(){return"<div class=\"entity-info\" >\n   <% if (!_.isBlank(get('description'))) { %>\n       <div class=\"description\">\n           <%= get('description') %>\n     </div>\n    <% } %>\n   <% if (get('location')) { %>\n      <p>\n           <%= m_event_location %>: <%= _.escape(get('location')) %>\n     </p>\n  <% } %>\n   <%= when %>\n   <% if (get('attendeeLimit')) { %>\n     <p>\n           <%= m_event_places %>: <%= get('attendees') %> <%= m_event_of %> <%= get('attendeeLimit') %>\n      </p>\n  <% } %>\n</div>\n<% if (answer) { %>\n  <a href='javascript:void(0)' class='btn btn-success'>\n     <%= m_event_ACCEPT %>\n </a>\n  <a href='javascript:void(0)' class='btn btn-danger'>\n      <%= m_event_DECLINE %>\n    </a>\n  <a href='javascript:void(0)' class='btn btn-warning'>\n     <%= m_event_MAYBE %>\n  </a>\n<% } %>\n<div id=\"requests\"></div>\n"});define("view/event/view",["ext/underscore","view/page","view/link-resolver","app-context","moment","view/navbar-factory","view/request/list","text!text/event/view.html"],function(_,PageView,linkResolver,appContext,moment,navbarFactory,RequestListView,template){var DATEF="dddd, DD MMMM YYYY";var TIMEF="HH:mm";var FULLF=DATEF+", "+TIMEF;return PageView.extend({tagName:"fieldset",events:{"click a.btn-success":function(){this.update("ACCEPT")},"click a.btn-danger":function(){this.update("DECLINE")},"click a.btn-warning":function(){this.update("MAYBE")}},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.group=this.model.getGroup();var query=this.getSearchQuery();if(query){this.back={code:"m_back",link:"#search/"+query}}else{this.back={code:"m_btn_events",link:"#events/"+this.group.getKey()}}this.title=_.escape(this.model.get("friendlyName"));this.actions=[{code:"m_comments",icon:"comment",link:"#comments/"+this.model.getKey()+this.formatQuery(query)}];if(this.model.permission.canEdit()){this.actions.unshift({code:"m_edit",link:"#event/"+this.model.getKey()+"/edit"});this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()+this.formatQuery(query)})}},update:function(status){this.answer.set("status",status);this.answer.once("sync",this.success);this.answer.save()},success:function(){appContext.navigate("#event/"+this.model.getKey(),true)},render:function(){PageView.prototype.render.apply(this,arguments);this.answer=this.model.requests.find(function(request){return request.get("target").id==appContext.getPrinciple().id&&request.get("status")=="NONE"});var args=_.extend({answer:this.answer,when:this.getTime()},this.model);this.$el.html(this.template(template,args));this.resolveLinks();if(this.model.requests.size()>0){var view=new RequestListView({collection:this.model.requests,type:"event"});view.render().$el.appendTo($("#requests",this.$el))}return this},getTime:function(){var startDate=moment(this.model.get("startDate"));if(this.model.get("allDay")){if(this.model.isSameDay()){return this.p(startDate.format(DATEF))}else{return this.p(startDate.format(DATEF))+this.p(this.message("m_to"))+this.p(this.model.getEndDate().format(DATEF))}}else{var endDate=moment(this.model.get("endDate"));if(this.model.isSameDay()){return this.p(startDate.format(DATEF))+this.p(startDate.format(TIMEF)+" "+this.message("m_to")+" "+endDate.format(TIMEF))}else{return this.p(startDate.format(FULLF))+this.p(this.message("m_to"))+this.p(endDate.format(FULLF))}}},p:function(text){return"<p>"+text+"</p>"},navbar:function(callback){this.navbarCreate("events",this.group.id,callback)}}).extend(navbarFactory).extend(linkResolver)});define("router/event",["ext/underscore","router/group","api/cache","api/service/event","view/event/list","view/event/save","view/event/view"],function(_,GroupRouter,cache,service,EventListView,EventSaveView,EventViewView){return GroupRouter.extend({routes:{"events/:groupKey/create":"createEvent","events/:groupKey":"showEvents","event/:eventKey/edit":"editEvent","event/:eventKey":"getEvent"},createEvent:function(group){var events=cache.getFrom(service.createEvents(group,1));new EventSaveView({collection:events}).render()},showEvents:function(group){var events=cache.getFrom(service.createEvents(group,1));var view=new EventListView({collection:events});view.render();view.handleRefresh()},getEvent:function(eventKey){var parts=eventKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getEvent(group,parts[3],this.showEvent)},showEvent:function(event){new EventViewView({model:event}).render()},editEvent:function(eventKey){var parts=eventKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getEvent(group,parts[3],function(event){new EventSaveView({model:event}).render()})}})});define("api/collection/tasks",["api/collection/content","api/model/task"],function(ContentCollection,Task){return ContentCollection.extend({model:Task,_getKey:function(key){return key+":"+this.params.completed}})});define("api/service/task",["ext/underscore","app-context","api/cache","api/service/base","api/service/request","api/collection/tasks","api/model/task"],function(_,appContext,cache,base,requestService,Tasks,Task){return _.extend({getTasks:function(group,handler){var tasks=this.createTasks(group,1);cache.putModel(tasks);this.getCollection(tasks,handler)},getNextTasks:function(tasks,handler){var next=this.createTasks(tasks.group,tasks.params.currentPage+1);this.getCollection(next,function(next){tasks.add(next.models);tasks.params.currentPage=next.params.currentPage;tasks.more=next.more;handler(next)})},getTask:function(group,id,handler){var self=this;this.getTaskOnly(group,id,function(task){self.getPermission(task,handler)})},getTaskOnly:function(group,id,handler){var task=new Task({name:id});if(id.charAt(0)=="@"){task=new Task({id:parseInt(id.slice(1))})}task.set("group",group);task=cache.getFrom(task);if(task._expiry){if(task.requests){handler(task)}else{requestService.getRequests(task,handler)}return}cache.putModel(task);var _handler=_.after(2,handler);task.once("change",_handler);task.fetch();requestService.getRequests(task,_handler)},saveTask:function(context,attributes,requests,handler){var task;if(context.type){task=context;task.set(attributes)}else{attributes["group"]=context.group;task=new Task(attributes);context.add(task)}var self=this;task.once("sync",function(){requestService.saveRequests(task,requests,_.bind(handler,self,task))});task.save()},createTasks:function(group,currentPage){return new Tasks([],{group:group,params:{currentPage:currentPage,pageSize:appContext.pageSize,completed:false}})}},base)});define("text!text/task/item.html",[],function(){return"<div class=\"task-status <%= model.isOverdue() ? 'OVERDUE' : model.get('status') %>\">\n    <span><%= messages['m_task_status_' + model.get('status')] %></span>\n</div>\n<a href=\"#task/<%= getKey() %>\" class=\"task-item\">\n  <p><b><%= _.escape(get('friendlyName')) %></b></p>\n    <abbr>\n        <%= m_tasks_requested_by %>\n       <%= get('author').name %><%= when %>\n  </abbr>\n</a>\n"});define("view/task/item",["ext/underscore","moment","view/base","text!text/task/item.html"],function(_,moment,BaseView,template){return BaseView.extend({tagName:"li",render:function(){var dateLabel=this.model.get("dateLabel");if(dateLabel){this.$el.addClass("list-divider").html(dateLabel)}else{this.$el.addClass("fat");var args=_.extend({model:this.model,when:this.getTime()},this.model);this.$el.html(this.template(template,args))}return this},getTime:function(){var dueDate=this.model.get("dueDate");if(!dueDate){return""}var dueDate=moment(dueDate);var dateString=dueDate.format(", DD/MM/YY");if(this.model.get("timeSet")){dateString+=" "+this.message("m_at")+" "+dueDate.format("HH:mm")}return dateString}})});define("view/task/list",["ext/underscore","api/service/task","api/collection/tasks","api/model/task","view/navbar-factory","view/extending-list","view/task/item"],function(_,service,Tasks,Task,navbarFactory,ExtendingListView,TaskItemView){return ExtendingListView.extend({back:{code:"m_btn_context",link:"#context"},initialize:function(){ExtendingListView.prototype.initialize.apply(this,arguments);var group=this.collection.group;this.title=_.escape(group.get("friendlyName"));if(group.permission.canCreate()){this.action={code:"m_new",link:"#tasks/"+group.getKey()+"/create"}}this.groupTasks()},groupTasks:function(){var taskMap=_.groupBy(this.collection.models,this.extractDueDateLabel);this.collection=new Tasks([],{group:this.collection.group});_.each(_.keys(taskMap),function(dateLabel){this.collection.add(new Task({dateLabel:dateLabel}));this.collection.add(taskMap[dateLabel])},this)},extractDueDateLabel:function(task){if(task.isOverdue()){return this.message("m_tasks_overdue")}var dueDate=task.get("dueDate");if(!dueDate){return this.message("m_tasks_no_due_date")}return this.extractDateLabel(dueDate)},emptyMsgCode:"m_tasks_nothing",itemViewClass:TaskItemView,handleEndOfList:function(){service.getNextTasks(this.collection,this.renderPage)},handleRefresh:function(){var self=this;service.getTasks(this.collection.group,function(tasks){self.collection=tasks;self.groupTasks();self.refresh()})},navbar:function(callback){this.navbarCreate("tasks",this.collection.group.id,callback)}}).extend(navbarFactory)});define("text!text/task/save.html",[],function(){return'<input class="form-control" name="friendlyName" placeholder="<%= m_task_title %>" \n  type="text" maxlength="108" value="<%= task ? task.get(\'friendlyName\') : \'\' %>">\n<textarea class="editor hidden" placeholder="<%= m_task_description %>"></textarea>\n<div class="select">\n   <select name="status">\n        <% var status = task ? task.get(\'status\') : "NOT_STARTED"; %>\n       <% for (i = 0; i < statuses.length; i++) { %>\n         <option value="<%= statuses[i] %>" <%= statuses[i] == status ? \'selected="selected"\' : \'\' %> >\n                <%= messages[\'m_task_status_\' + statuses[i]] %>\n         </option>\n     <% } %>\n   </select>\n</div>\n<div id="dueDate"></div>\n<div id="requests"></div>\n<a href="javascript:void(0)" id="save" class="btn btn-primary" <%= task ? \'\' : \'disabled="disabled"\' %>>\n  <%= m_save %>\n</a>\n'});define("view/task/save",["ext/underscore","moment","view/page","view/editor","app-context","api/service/general","api/service/request","api/service/task","view/people/list","view/request/list","view/date-time","text!text/task/save.html"],function(_,moment,PageView,EditorView,appContext,generalService,requestService,taskService,PeopleListView,RequestListView,DateTimeView,template){var $=jQuery;return PageView.extend({tagName:"fieldset",events:{"keyup [name=friendlyName]":"onKeyup","click #save":"save"},nosearch:true,initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var group=this.resolveGroup();this.editor=new EditorView({context:group,$page:this.$el,content:options.model?options.model.get("description"):null});this.back={code:options.model?"m_task":"m_btn_tasks",link:options.model?"#task/"+options.model.getKey():"#tasks/"+group.getKey()};this.action={code:"m_assign",view:this};this.title=this.message(options.model?"m_update_task":"m_create_task");this.requestList=new RequestListView({collection:requestService.createRequests(options.model?options.model.requests:null),type:"task",deletable:true});this.requestList.collection.on("remove",this.renderRequests);var dueDate=null;if(options.model){dueDate=options.model.get("dueDate")}this.dueDate=new DateTimeView({date:dueDate?moment(dueDate):null,placeholder:"m_task_duedate"})},resolveGroup:function(){if(this.options.model){return this.options.model.getGroup()}return this.options.collection.group},render:function(){PageView.prototype.render.apply(this,arguments);this.$el.html(this.template(template,{statuses:["NOT_STARTED","IN_PROGRESS","DEFERRED","WAITING","COMPLETED"],task:this.options.model}));$("#dueDate",this.$el).replaceWith(this.dueDate.render().$el);this.renderRequests();this.editor.render_delayed();return this},renderRequests:function(){var $requests=$("#requests",this.$el).empty();if(this.requestList.collection.length>0){$requests.append(this.requestList.render().el)}},onKeyup:function(){$("#save",this.$el).attr("disabled",_.isBlank($("[name=friendlyName]",this.el).val()))},doAction:function(container){var filter=this.requestList.collection.map(function(request){return request.get("target").id});var self=this;generalService.getUsers(this.resolveGroup(),function(users){var people=new PeopleListView({collection:users,callback:self.addRequest,filter:filter});people.render()},true)},addRequest:function(user){this.requestList.collection.add(requestService.createRequest(user));this.renderRequests()},save:function(){this.requestList.collection.off("remove",this.renderRequests);try{var attributes={friendlyName:$("[name=friendlyName]",this.el).val(),description:this.editor.getText(),status:$("[name=status]",this.el).val(),dueDate:this.dueDate.val()};taskService.saveTask(this.options.model?this.options.model:this.options.collection,attributes,this.requestList.collection,function(task){appContext.navigate("#task/"+task.getKey())})}catch(e){}}})});define("text!text/task/view.html",[],function(){return"<div></div>\n<div class=\"task-status <%= isOverdue() ? 'OVERDUE' : get('status') %>\">\n   <span><%= messages['m_task_status_' + get('status')] %></span>\n</div>\n<div class=\"entity-info\" >\n  <% if (!_.isBlank(get('description'))) { %>\n       <div class=\"description\">\n           <%= get('description') %>\n     </div>\n    <% } %>\n   <p><%= when %></p>\n    <% if (get('status') == 'IN_PROGRESS') { %>\n       <p><%= m_task_progress %>: <%= get('progress') %>%</p>\n    <% } %>\n</div>\n<% if (answer) { %>\n  <a href='javascript:void(0)' class='btn btn-success'>\n     <%= m_task_ACCEPT %>\n  </a>\n  <a href='javascript:void(0)' class='btn btn-danger'>\n      <%= m_task_REJECT %>\n  </a>\n<% } %>\n<div id=\"requests\"></div>\n"});define("view/task/view",["ext/underscore","view/page","view/link-resolver","app-context","moment","view/navbar-factory","view/request/list","text!text/task/view.html"],function(_,PageView,linkResolver,appContext,moment,navbarFactory,RequestListView,template){return PageView.extend({tagName:"fieldset",events:{"click a.btn-success":function(){this.update("ACCEPT")},"click a.btn-danger":function(){this.update("REJECT")}},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.group=this.model.getGroup();var query=this.getSearchQuery();if(query){this.back={code:"m_back",link:"#search/"+query}}else{this.back={code:"m_btn_tasks",link:"#tasks/"+this.group.getKey()}}this.title=_.escape(this.model.get("friendlyName"));this.actions=[{code:"m_comments",icon:"comment",link:"#comments/"+this.model.getKey()+this.formatQuery(query)}];if(this.model.permission.canEdit()){this.actions.unshift({code:"m_edit",link:"#task/"+this.model.getKey()+"/edit"});this.actions.push({code:"m_shares",icon:"share",link:"#shares/"+this.model.getKey()+this.formatQuery(query)})}},update:function(status){this.answer.set("status",status);this.answer.once("sync",this.success);this.answer.save()},success:function(){appContext.navigate("#task/"+this.model.getKey(),true)},render:function(){PageView.prototype.render.apply(this,arguments);this.answer=this.model.requests.find(function(request){return request.get("target").id==appContext.getPrinciple().id&&request.get("status")=="NONE"});var args=_.extend({answer:this.answer,when:this.getTime()},this.model);this.$el.html(this.template(template,args));this.resolveLinks();if(this.model.requests.size()>0){var view=new RequestListView({collection:this.model.requests,type:"task"});view.render().$el.appendTo($("#requests",this.$el))}return this},getTime:function(){var dueDate=this.model.get("dueDate");if(!dueDate){return this.message("m_task_no_due")}dueDate=moment(dueDate);var dateString=dueDate.format("DD/MM/YY");if(this.model.get("timeSet")){dateString+=" "+this.message("m_at")+" "+dueDate.format("HH:mm")}return this.message("m_task_due")+": "+dateString},navbar:function(callback){this.navbarCreate("tasks",this.group.id,callback)}}).extend(navbarFactory).extend(linkResolver)});define("router/task",["ext/underscore","router/group","app-context","api/cache","api/service/task","view/task/list","view/task/save","view/task/view"],function(_,GroupRouter,appContext,cache,service,TaskListView,TaskSaveView,TaskViewView){return GroupRouter.extend({routes:{"tasks/:groupKey/create":"createTask","tasks/:groupKey":"showTasks","task/:taskKey/edit":"editTask","task/:taskKey":"getTask"},createTask:function(group){var tasks=cache.getFrom(service.createTasks(group,1));new TaskSaveView({collection:tasks}).render()},showTasks:function(group){var tasks=cache.getFrom(service.createTasks(group,1));var view=new TaskListView({collection:tasks});view.render();view.handleRefresh()},getTask:function(taskKey){var parts=taskKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getTask(group,parts[3],this.showTask)},showTask:function(task){new TaskViewView({model:task}).render()},editTask:function(taskKey){var parts=taskKey.split(":");var group={id:parseInt(parts[1].substr(1))};service.getTask(group,parts[3],function(task){new TaskSaveView({model:task}).render()})}})});define("router/entity",["router/base","api/cache","api/service/file","api/service/note","api/service/discussion","api/service/event","api/service/task"],function(BaseRouter,cache,fileService,noteService,discussionService,eventService,taskService){return BaseRouter.extend({execute:function(callback,args){var keyParts=null;if(args.length>0){keyParts=args[0].split(":");if(keyParts.length!=5){keyParts=null}}var self=this;var handler=function(entity){args.unshift(entity);callback.apply(self,args)};if(keyParts){args.shift();var group={id:parseInt(keyParts[1].substr(1))};if(keyParts[2]=="files"){fileService.getFile(group,keyParts[3],handler)}else if(keyParts[2]=="pages"){noteService.getNote(group,keyParts[3],handler)}else if(keyParts[2]=="discussions"){discussionService.getDiscussion(group,keyParts[3],handler)}else if(keyParts[2]=="events"){eventService.getEvent(group,keyParts[3],handler)}else if(keyParts[2]=="tasks"){taskService.getTask(group,keyParts[3],handler)}}else{callback.apply(this,args)}}})});define("api/collection/replies",["api/collection/base","api/model/reply"],function(BaseCollection,Reply){return BaseCollection.extend({model:Reply,initialize:function(models,options){this.parent=options.parent},url:function(){return this.parent.url()}})});define("api/model/comment",["api/model/base-comment","api/collection/replies"],function(BaseComment,Replies){return BaseComment.extend({initialize:function(attributes){this.replies=new Replies(attributes.replies,{parent:this})},getReplies:function(){return this.replies}})});define("api/collection/comments",["api/collection/base","api/model/comment"],function(BaseCollection,Comment){return BaseCollection.extend({model:Comment,initialize:function(models,options){this.context=options.context},url:function(){return this.context.url()+"/comments"}})});define("api/service/comment",["ext/underscore","api/cache","api/collection/comments"],function(_,cache,Comments){return{getComments:function(context,handler){var comments=cache.getFrom(new Comments([],{context:context}));if(comments._expiry){handler(comments)}else{comments.fetch();comments.once("sync",function(){cache.putModel(comments);handler(comments)})}},createComment:function(comments,text,handler){var comment=new comments.model({comment:text});comments.add(comment);comment.save();comment.once("change",handler)}}});define("view/comment/create",["app-context","view/editor-page","api/service/comment"],function(appContext,EditorPageView,service){return EditorPageView.extend({title:EditorPageView.message("m_make_comment"),nosearch:true,initialize:function(){EditorPageView.prototype.initialize.apply(this,arguments);this.back={code:"m_comments",link:"#comments/"+this.options.entity.getKey()}},post:function(){var backLink=this.back.link;service.createComment(this.options.comments,this.editor.getText(),function(comment){appContext.navigate(backLink+"/"+comment.get("dateCreated"))})}})});define("router/comment",["ext/underscore","app-context","router/entity","api/cache","api/service/general","api/service/comment","view/comment/list","view/comment/create"],function(_,appContext,EntityRouter,cache,generalService,commentService,CommentListView,CommentCreateView){return EntityRouter.extend({routes:{"comments/:contextKey/create":"createComment","comments/:contextKey/:dateOfSelection":"getComments","comments/:contextKey":"getComments","replies/:commentKey/create":"createReply"},getComments:function(context,dateOfSelection){commentService.getComments(context,function(comments){comments.each(function(comment){cache.putModel(comment)});var options={collection:comments,onDelete:function(comment,onDeleted){generalService.deleteModel(comment,onDeleted)},onReply:function(comment){appContext.navigate("#replies/"+comment.getKey()+"/create")}};if(dateOfSelection){options["dateOfSelection"]=parseInt(dateOfSelection)}var view=new CommentListView(options);view.render()})},createComment:function(context){commentService.getComments(context,this.showCommentCreate)},createReply:function(commentKey){var comment=cache.get(commentKey);this.showCommentCreate(comment.getReplies(),comment.collection)},showCommentCreate:function(comments,parent){if(!parent){parent=comments}new CommentCreateView({context:parent.context.getGroup(),comments:comments,entity:parent.context}).render()}})});define("api/collection/base2",["ext/underscore","api/sync","api/cache"],function(_,sync,cache){var BaseCollection=_.extend({initialize:function(){this.on("remove",function(){cache.put2(this.getKey(),this.toJSON())},this)},add:function(model){var models=_.isArray(model)?model:[model];_.each(models,function(model){model.once("change",function(){cache.put2(this.getKey(),this.toJSON())},this)},this);Backbone.Collection.prototype.add.apply(this,arguments)},fetch:function(){var cached=cache.get2(this.getKey());if(cached){_.each(cached,function(attributes){this.add(new this.model(attributes))},this);this.trigger("sync",this)}else{Backbone.Collection.prototype.fetch.apply(this,arguments);this.once("sync",function(){cache.put2(this.getKey(),this.toJSON())},this)}}},sync);return Backbone.Collection.extend(BaseCollection)});define("api/model/share-token",["api/model/base"],function(BaseModel){return BaseModel.extend({idAttribute:"tokenKey"})});define("api/collection/share-tokens",["api/collection/base2","api/model/share-token"],function(BaseCollection,ShareToken){return BaseCollection.extend({model:ShareToken,initialize:function(models,options){BaseCollection.prototype.initialize.apply(this,arguments);this.context=options.context},url:function(){return this.context.url()+"/shares"}})});define("text!text/share-token/item.html",[],function(){return"<p>\n  <%= get('email') %>\n   <% if (get('name') && get('name') != get('email') ) { %>\n      (<%= get('name') %>)\n  <% } %>\n</p>\n\n<a href=\"javascript:void(0)\">\n  <span class=\"glyphicon glyphicon-trash\"></span>\n</a>\n"});define("view/share-token/item",["ext/underscore","view/base","text!text/share-token/item.html"],function(_,BaseView,template){return BaseView.extend({className:"share-token",events:{"click a":"onDelete"},render:function(){this.$el.html(this.template(template,this.model));return this},onDelete:function(){this.model.destroy({wait:true});this.model.once("destroy",this.onDeleted)},onDeleted:function(){this.$el.remove()}})});define("view/share-token/list",["ext/underscore","view/page","view/share-token/item"],function(_,PageView,ShareTokenItemView){var $=jQuery;return PageView.extend({className:"share-tokens",initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.collection.on("remove",this.onRemove);var context=this.collection.context;this.back={code:"m_"+context.type,link:"#"+context.type+"/"+context.getKey()+this.formatQuery()};this.title=_.escape(context.get("friendlyName"));this.action={code:"m_new",link:"#shares/"+context.getKey()+"/create"}},render:function(){PageView.prototype.render.apply(this,arguments);this.collection.once("sync",this.renderList);this.collection.fetch();return this},renderList:function(){var contactMap={};_.each(this.options.contacts,function(contact){contactMap[contact.email.toLowerCase()]=contact});this.collection.each(function(shareToken){var contact=contactMap[shareToken.get("email").toLowerCase()];if(contact){shareToken.set("name",contact.name)}var itemView=new ShareTokenItemView({model:shareToken,collection:this.collection});this.$el.append(itemView.render().el)},this);this.onRemove()},remove:function(){this.collection.off("remove",this.onRemove);this.$el.remove();return this},onRemove:function(){if(this.collection.length==0){$("<div>").addClass("ui-body-d ui-corner-all").html(this.message("m_share_tokens_nothing")).appendTo(this.el)}}})});define("text!text/share-token/create.html",[],function(){return'<a href="javascript:void(0)" id="share" class="btn btn-primary">\n   <%= m_share %>\n</a>\n'});define("view/share-token/create",["ext/underscore","app-context","view/page","view/validated-email","text!text/share-token/create.html"],function(_,appContext,PageView,ValidatedEmail,template){var $=jQuery;return PageView.extend({tagName:"fieldset",events:{"click #share":"validate"},title:PageView.message("m_share_contact"),nosearch:true,emailInput:new ValidatedEmail({label:"m_share_input"}),initialize:function(options){PageView.prototype.initialize.apply(this,arguments);var context=this.collection.context;this.back={code:"m_back",link:"#shares/"+this.collection.context.getKey()}},render:function(){PageView.prototype.render.apply(this,arguments);this.collection.fetch();this.$el.html(this.template(template,{}));$("#share",this.$el).before(this.emailInput.render().el);var self=this;var $input=this.$el.find("input");$input.autocomplete({appendTo:"#clinked-portal",source:function(request,response){var contacts=_.filter(self.options.contacts,function(contact){var term=request.term.toLowerCase();return contact.name.toLowerCase().indexOf(term)!=-1||contact.email.toLowerCase().indexOf(term)!=-1});response(contacts.slice(0,4))},select:function(event,ui){event.preventDefault()},focus:function(event,ui){$input.val(ui.item.email);event.preventDefault()}}).data("ui-autocomplete")._renderItem=function(ul,contact){var text=contact.email;if(contact.email!=contact.name){text+=" ("+contact.name+")"}return $("<li>").data("contact",contact).outerWidth($input.outerWidth()-3).append(text).appendTo(ul)};return this},validate:function(){var self=this;this.emailInput.options.validate(this.emailInput.val(),function(error){self.emailInput.displayValidation(error);!error&&self.share()})},share:function(){var shareToken=new this.collection.model({email:this.emailInput.val()});this.collection.add(shareToken);shareToken.save();var backLink=this.back.link;shareToken.once("change",function(){appContext.navigate(backLink)})}})});define("router/share-token",["ext/underscore","router/entity","native","api/cache","api/collection/share-tokens","view/share-token/list","view/share-token/create"],function(_,EntityRouter,native,cache,ShareTokens,ShareTokenListView,ShareTokenCreateView){return EntityRouter.extend({routes:{"shares/:contextKey/create":"createShareToken","shares/:contextKey":"getShareTokens"},getShareTokens:function(context){
     17this.getContacts(function(contacts){var shareTokens=new ShareTokens([],{context:context});new ShareTokenListView({collection:shareTokens,contacts:contacts}).render()})},createShareToken:function(context){this.getContacts(function(contacts){var shareTokens=new ShareTokens([],{context:context});new ShareTokenCreateView({collection:shareTokens,contacts:contacts}).render()})},getContacts:function(handler){if(!native.contacts){handler([]);return}var contacts=cache.get2("contacts");if(contacts){handler(contacts)}else{native.contacts(function(contacts){cache.put2("contacts",contacts);handler(contacts)})}}})});!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define("io",[],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module,exports){module.exports=_dereq_("./lib/")},{"./lib/":2}],2:[function(_dereq_,module,exports){var url=_dereq_("./url");var parser=_dereq_("socket.io-parser");var Manager=_dereq_("./manager");var debug=_dereq_("debug")("socket.io-client");module.exports=exports=lookup;var cache=exports.managers={};function lookup(uri,opts){if(typeof uri=="object"){opts=uri;uri=undefined}opts=opts||{};var parsed=url(uri);var source=parsed.source;var id=parsed.id;var io;if(opts.forceNew||opts["force new connection"]||false===opts.multiplex){debug("ignoring socket cache for %s",source);io=Manager(source,opts)}else{if(!cache[id]){debug("new io instance for %s",source);cache[id]=Manager(source,opts)}io=cache[id]}return io.socket(parsed.path)}exports.protocol=parser.protocol;exports.connect=lookup;exports.Manager=_dereq_("./manager");exports.Socket=_dereq_("./socket")},{"./manager":3,"./socket":5,"./url":6,debug:10,"socket.io-parser":46}],3:[function(_dereq_,module,exports){var url=_dereq_("./url");var eio=_dereq_("engine.io-client");var Socket=_dereq_("./socket");var Emitter=_dereq_("component-emitter");var parser=_dereq_("socket.io-parser");var on=_dereq_("./on");var bind=_dereq_("component-bind");var object=_dereq_("object-component");var debug=_dereq_("debug")("socket.io-client:manager");var indexOf=_dereq_("indexof");var Backoff=_dereq_("backo2");module.exports=Manager;function Manager(uri,opts){if(!(this instanceof Manager))return new Manager(uri,opts);if(uri&&"object"==typeof uri){opts=uri;uri=undefined}opts=opts||{};opts.path=opts.path||"/socket.io";this.nsps={};this.subs=[];this.opts=opts;this.reconnection(opts.reconnection!==false);this.reconnectionAttempts(opts.reconnectionAttempts||Infinity);this.reconnectionDelay(opts.reconnectionDelay||1e3);this.reconnectionDelayMax(opts.reconnectionDelayMax||5e3);this.randomizationFactor(opts.randomizationFactor||.5);this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()});this.timeout(null==opts.timeout?2e4:opts.timeout);this.readyState="closed";this.uri=uri;this.connected=[];this.encoding=false;this.packetBuffer=[];this.encoder=new parser.Encoder;this.decoder=new parser.Decoder;this.autoConnect=opts.autoConnect!==false;if(this.autoConnect)this.open()}Manager.prototype.emitAll=function(){this.emit.apply(this,arguments);for(var nsp in this.nsps){this.nsps[nsp].emit.apply(this.nsps[nsp],arguments)}};Manager.prototype.updateSocketIds=function(){for(var nsp in this.nsps){this.nsps[nsp].id=this.engine.id}};Emitter(Manager.prototype);Manager.prototype.reconnection=function(v){if(!arguments.length)return this._reconnection;this._reconnection=!!v;return this};Manager.prototype.reconnectionAttempts=function(v){if(!arguments.length)return this._reconnectionAttempts;this._reconnectionAttempts=v;return this};Manager.prototype.reconnectionDelay=function(v){if(!arguments.length)return this._reconnectionDelay;this._reconnectionDelay=v;this.backoff&&this.backoff.setMin(v);return this};Manager.prototype.randomizationFactor=function(v){if(!arguments.length)return this._randomizationFactor;this._randomizationFactor=v;this.backoff&&this.backoff.setJitter(v);return this};Manager.prototype.reconnectionDelayMax=function(v){if(!arguments.length)return this._reconnectionDelayMax;this._reconnectionDelayMax=v;this.backoff&&this.backoff.setMax(v);return this};Manager.prototype.timeout=function(v){if(!arguments.length)return this._timeout;this._timeout=v;return this};Manager.prototype.maybeReconnectOnOpen=function(){if(!this.reconnecting&&this._reconnection&&this.backoff.attempts===0){this.reconnect()}};Manager.prototype.open=Manager.prototype.connect=function(fn){debug("readyState %s",this.readyState);if(~this.readyState.indexOf("open"))return this;debug("opening %s",this.uri);this.engine=eio(this.uri,this.opts);var socket=this.engine;var self=this;this.readyState="opening";this.skipReconnect=false;var openSub=on(socket,"open",function(){self.onopen();fn&&fn()});var errorSub=on(socket,"error",function(data){debug("connect_error");self.cleanup();self.readyState="closed";self.emitAll("connect_error",data);if(fn){var err=new Error("Connection error");err.data=data;fn(err)}else{self.maybeReconnectOnOpen()}});if(false!==this._timeout){var timeout=this._timeout;debug("connect attempt will timeout after %d",timeout);var timer=setTimeout(function(){debug("connect attempt timed out after %d",timeout);openSub.destroy();socket.close();socket.emit("error","timeout");self.emitAll("connect_timeout",timeout)},timeout);this.subs.push({destroy:function(){clearTimeout(timer)}})}this.subs.push(openSub);this.subs.push(errorSub);return this};Manager.prototype.onopen=function(){debug("open");this.cleanup();this.readyState="open";this.emit("open");var socket=this.engine;this.subs.push(on(socket,"data",bind(this,"ondata")));this.subs.push(on(this.decoder,"decoded",bind(this,"ondecoded")));this.subs.push(on(socket,"error",bind(this,"onerror")));this.subs.push(on(socket,"close",bind(this,"onclose")))};Manager.prototype.ondata=function(data){this.decoder.add(data)};Manager.prototype.ondecoded=function(packet){this.emit("packet",packet)};Manager.prototype.onerror=function(err){debug("error",err);this.emitAll("error",err)};Manager.prototype.socket=function(nsp){var socket=this.nsps[nsp];if(!socket){socket=new Socket(this,nsp);this.nsps[nsp]=socket;var self=this;socket.on("connect",function(){socket.id=self.engine.id;if(!~indexOf(self.connected,socket)){self.connected.push(socket)}})}return socket};Manager.prototype.destroy=function(socket){var index=indexOf(this.connected,socket);if(~index)this.connected.splice(index,1);if(this.connected.length)return;this.close()};Manager.prototype.packet=function(packet){debug("writing packet %j",packet);var self=this;if(!self.encoding){self.encoding=true;this.encoder.encode(packet,function(encodedPackets){for(var i=0;i<encodedPackets.length;i++){self.engine.write(encodedPackets[i])}self.encoding=false;self.processPacketQueue()})}else{self.packetBuffer.push(packet)}};Manager.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var pack=this.packetBuffer.shift();this.packet(pack)}};Manager.prototype.cleanup=function(){var sub;while(sub=this.subs.shift())sub.destroy();this.packetBuffer=[];this.encoding=false;this.decoder.destroy()};Manager.prototype.close=Manager.prototype.disconnect=function(){this.skipReconnect=true;this.backoff.reset();this.readyState="closed";this.engine&&this.engine.close()};Manager.prototype.onclose=function(reason){debug("close");this.cleanup();this.backoff.reset();this.readyState="closed";this.emit("close",reason);if(this._reconnection&&!this.skipReconnect){this.reconnect()}};Manager.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var self=this;if(this.backoff.attempts>=this._reconnectionAttempts){debug("reconnect failed");this.backoff.reset();this.emitAll("reconnect_failed");this.reconnecting=false}else{var delay=this.backoff.duration();debug("will wait %dms before reconnect attempt",delay);this.reconnecting=true;var timer=setTimeout(function(){if(self.skipReconnect)return;debug("attempting reconnect");self.emitAll("reconnect_attempt",self.backoff.attempts);self.emitAll("reconnecting",self.backoff.attempts);if(self.skipReconnect)return;self.open(function(err){if(err){debug("reconnect attempt error");self.reconnecting=false;self.reconnect();self.emitAll("reconnect_error",err.data)}else{debug("reconnect success");self.onreconnect()}})},delay);this.subs.push({destroy:function(){clearTimeout(timer)}})}};Manager.prototype.onreconnect=function(){var attempt=this.backoff.attempts;this.reconnecting=false;this.backoff.reset();this.updateSocketIds();this.emitAll("reconnect",attempt)}},{"./on":4,"./socket":5,"./url":6,backo2:7,"component-bind":8,"component-emitter":9,debug:10,"engine.io-client":11,indexof:42,"object-component":43,"socket.io-parser":46}],4:[function(_dereq_,module,exports){module.exports=on;function on(obj,ev,fn){obj.on(ev,fn);return{destroy:function(){obj.removeListener(ev,fn)}}}},{}],5:[function(_dereq_,module,exports){var parser=_dereq_("socket.io-parser");var Emitter=_dereq_("component-emitter");var toArray=_dereq_("to-array");var on=_dereq_("./on");var bind=_dereq_("component-bind");var debug=_dereq_("debug")("socket.io-client:socket");var hasBin=_dereq_("has-binary");module.exports=exports=Socket;var events={connect:1,connect_error:1,connect_timeout:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1};var emit=Emitter.prototype.emit;function Socket(io,nsp){this.io=io;this.nsp=nsp;this.json=this;this.ids=0;this.acks={};if(this.io.autoConnect)this.open();this.receiveBuffer=[];this.sendBuffer=[];this.connected=false;this.disconnected=true}Emitter(Socket.prototype);Socket.prototype.subEvents=function(){if(this.subs)return;var io=this.io;this.subs=[on(io,"open",bind(this,"onopen")),on(io,"packet",bind(this,"onpacket")),on(io,"close",bind(this,"onclose"))]};Socket.prototype.open=Socket.prototype.connect=function(){if(this.connected)return this;this.subEvents();this.io.open();if("open"==this.io.readyState)this.onopen();return this};Socket.prototype.send=function(){var args=toArray(arguments);args.unshift("message");this.emit.apply(this,args);return this};Socket.prototype.emit=function(ev){if(events.hasOwnProperty(ev)){emit.apply(this,arguments);return this}var args=toArray(arguments);var parserType=parser.EVENT;if(hasBin(args)){parserType=parser.BINARY_EVENT}var packet={type:parserType,data:args};if("function"==typeof args[args.length-1]){debug("emitting packet with ack id %d",this.ids);this.acks[this.ids]=args.pop();packet.id=this.ids++}if(this.connected){this.packet(packet)}else{this.sendBuffer.push(packet)}return this};Socket.prototype.packet=function(packet){packet.nsp=this.nsp;this.io.packet(packet)};Socket.prototype.onopen=function(){debug("transport is open - connecting");if("/"!=this.nsp){this.packet({type:parser.CONNECT})}};Socket.prototype.onclose=function(reason){debug("close (%s)",reason);this.connected=false;this.disconnected=true;delete this.id;this.emit("disconnect",reason)};Socket.prototype.onpacket=function(packet){if(packet.nsp!=this.nsp)return;switch(packet.type){case parser.CONNECT:this.onconnect();break;case parser.EVENT:this.onevent(packet);break;case parser.BINARY_EVENT:this.onevent(packet);break;case parser.ACK:this.onack(packet);break;case parser.BINARY_ACK:this.onack(packet);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.emit("error",packet.data);break}};Socket.prototype.onevent=function(packet){var args=packet.data||[];debug("emitting event %j",args);if(null!=packet.id){debug("attaching ack callback to event");args.push(this.ack(packet.id))}if(this.connected){emit.apply(this,args)}else{this.receiveBuffer.push(args)}};Socket.prototype.ack=function(id){var self=this;var sent=false;return function(){if(sent)return;sent=true;var args=toArray(arguments);debug("sending ack %j",args);var type=hasBin(args)?parser.BINARY_ACK:parser.ACK;self.packet({type:type,id:id,data:args})}};Socket.prototype.onack=function(packet){debug("calling ack %s with %j",packet.id,packet.data);var fn=this.acks[packet.id];fn.apply(this,packet.data);delete this.acks[packet.id]};Socket.prototype.onconnect=function(){this.connected=true;this.disconnected=false;this.emit("connect");this.emitBuffered()};Socket.prototype.emitBuffered=function(){var i;for(i=0;i<this.receiveBuffer.length;i++){emit.apply(this,this.receiveBuffer[i])}this.receiveBuffer=[];for(i=0;i<this.sendBuffer.length;i++){this.packet(this.sendBuffer[i])}this.sendBuffer=[]};Socket.prototype.ondisconnect=function(){debug("server disconnect (%s)",this.nsp);this.destroy();this.onclose("io server disconnect")};Socket.prototype.destroy=function(){if(this.subs){for(var i=0;i<this.subs.length;i++){this.subs[i].destroy()}this.subs=null}this.io.destroy(this)};Socket.prototype.close=Socket.prototype.disconnect=function(){if(this.connected){debug("performing disconnect (%s)",this.nsp);this.packet({type:parser.DISCONNECT})}this.destroy();if(this.connected){this.onclose("io client disconnect")}return this}},{"./on":4,"component-bind":8,"component-emitter":9,debug:10,"has-binary":38,"socket.io-parser":46,"to-array":50}],6:[function(_dereq_,module,exports){(function(global){var parseuri=_dereq_("parseuri");var debug=_dereq_("debug")("socket.io-client:url");module.exports=url;function url(uri,loc){var obj=uri;var loc=loc||global.location;if(null==uri)uri=loc.protocol+"//"+loc.host;if("string"==typeof uri){if("/"==uri.charAt(0)){if("/"==uri.charAt(1)){uri=loc.protocol+uri}else{uri=loc.hostname+uri}}if(!/^(https?|wss?):\/\//.test(uri)){debug("protocol-less url %s",uri);if("undefined"!=typeof loc){uri=loc.protocol+"//"+uri}else{uri="https://"+uri}}debug("parse %s",uri);obj=parseuri(uri)}if(!obj.port){if(/^(http|ws)$/.test(obj.protocol)){obj.port="80"}else if(/^(http|ws)s$/.test(obj.protocol)){obj.port="443"}}obj.path=obj.path||"/";obj.id=obj.protocol+"://"+obj.host+":"+obj.port;obj.href=obj.protocol+"://"+obj.host+(loc&&loc.port==obj.port?"":":"+obj.port);return obj}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{debug:10,parseuri:44}],7:[function(_dereq_,module,exports){module.exports=Backoff;function Backoff(opts){opts=opts||{};this.ms=opts.min||100;this.max=opts.max||1e4;this.factor=opts.factor||2;this.jitter=opts.jitter>0&&opts.jitter<=1?opts.jitter:0;this.attempts=0}Backoff.prototype.duration=function(){var ms=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.jitter*ms);ms=(Math.floor(rand*10)&1)==0?ms-deviation:ms+deviation}return Math.min(ms,this.max)|0};Backoff.prototype.reset=function(){this.attempts=0};Backoff.prototype.setMin=function(min){this.ms=min};Backoff.prototype.setMax=function(max){this.max=max};Backoff.prototype.setJitter=function(jitter){this.jitter=jitter}},{}],8:[function(_dereq_,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],9:[function(_dereq_,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],10:[function(_dereq_,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],11:[function(_dereq_,module,exports){module.exports=_dereq_("./lib/")},{"./lib/":12}],12:[function(_dereq_,module,exports){module.exports=_dereq_("./socket");module.exports.parser=_dereq_("engine.io-parser")},{"./socket":13,"engine.io-parser":25}],13:[function(_dereq_,module,exports){(function(global){var transports=_dereq_("./transports");var Emitter=_dereq_("component-emitter");var debug=_dereq_("debug")("engine.io-client:socket");var index=_dereq_("indexof");var parser=_dereq_("engine.io-parser");var parseuri=_dereq_("parseuri");var parsejson=_dereq_("parsejson");var parseqs=_dereq_("parseqs");module.exports=Socket;function noop(){}function Socket(uri,opts){if(!(this instanceof Socket))return new Socket(uri,opts);opts=opts||{};if(uri&&"object"==typeof uri){opts=uri;uri=null}if(uri){uri=parseuri(uri);opts.host=uri.host;opts.secure=uri.protocol=="https"||uri.protocol=="wss";opts.port=uri.port;if(uri.query)opts.query=uri.query}this.secure=null!=opts.secure?opts.secure:global.location&&"https:"==location.protocol;if(opts.host){var pieces=opts.host.split(":");opts.hostname=pieces.shift();if(pieces.length){opts.port=pieces.pop()}else if(!opts.port){opts.port=this.secure?"443":"80"}}this.agent=opts.agent||false;this.hostname=opts.hostname||(global.location?location.hostname:"localhost");this.port=opts.port||(global.location&&location.port?location.port:this.secure?443:80);this.query=opts.query||{};if("string"==typeof this.query)this.query=parseqs.decode(this.query);this.upgrade=false!==opts.upgrade;this.path=(opts.path||"/engine.io").replace(/\/$/,"")+"/";this.forceJSONP=!!opts.forceJSONP;this.jsonp=false!==opts.jsonp;this.forceBase64=!!opts.forceBase64;this.enablesXDR=!!opts.enablesXDR;this.timestampParam=opts.timestampParam||"t";this.timestampRequests=opts.timestampRequests;this.transports=opts.transports||["polling","websocket"];this.readyState="";this.writeBuffer=[];this.callbackBuffer=[];this.policyPort=opts.policyPort||843;this.rememberUpgrade=opts.rememberUpgrade||false;this.binaryType=null;this.onlyBinaryUpgrades=opts.onlyBinaryUpgrades;this.pfx=opts.pfx||null;this.key=opts.key||null;this.passphrase=opts.passphrase||null;this.cert=opts.cert||null;this.ca=opts.ca||null;this.ciphers=opts.ciphers||null;this.rejectUnauthorized=opts.rejectUnauthorized||null;this.open()}Socket.priorWebsocketSuccess=false;Emitter(Socket.prototype);Socket.protocol=parser.protocol;Socket.Socket=Socket;Socket.Transport=_dereq_("./transport");Socket.transports=_dereq_("./transports");Socket.parser=_dereq_("engine.io-parser");Socket.prototype.createTransport=function(name){debug('creating transport "%s"',name);var query=clone(this.query);query.EIO=parser.protocol;query.transport=name;if(this.id)query.sid=this.id;var transport=new transports[name]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:query,forceJSONP:this.forceJSONP,jsonp:this.jsonp,forceBase64:this.forceBase64,enablesXDR:this.enablesXDR,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this,pfx:this.pfx,key:this.key,passphrase:this.passphrase,cert:this.cert,ca:this.ca,ciphers:this.ciphers,rejectUnauthorized:this.rejectUnauthorized});return transport};function clone(obj){var o={};for(var i in obj){if(obj.hasOwnProperty(i)){o[i]=obj[i]}}return o}Socket.prototype.open=function(){var transport;if(this.rememberUpgrade&&Socket.priorWebsocketSuccess&&this.transports.indexOf("websocket")!=-1){transport="websocket"}else if(0==this.transports.length){var self=this;setTimeout(function(){self.emit("error","No transports available")},0);return}else{transport=this.transports[0]}this.readyState="opening";var transport;try{transport=this.createTransport(transport)}catch(e){this.transports.shift();this.open();return}transport.open();this.setTransport(transport)};Socket.prototype.setTransport=function(transport){debug("setting transport %s",transport.name);var self=this;if(this.transport){debug("clearing existing transport %s",this.transport.name);this.transport.removeAllListeners()}this.transport=transport;transport.on("drain",function(){self.onDrain()}).on("packet",function(packet){self.onPacket(packet)}).on("error",function(e){self.onError(e)}).on("close",function(){self.onClose("transport close")})};Socket.prototype.probe=function(name){debug('probing transport "%s"',name);var transport=this.createTransport(name,{probe:1}),failed=false,self=this;Socket.priorWebsocketSuccess=false;function onTransportOpen(){if(self.onlyBinaryUpgrades){var upgradeLosesBinary=!this.supportsBinary&&self.transport.supportsBinary;failed=failed||upgradeLosesBinary}if(failed)return;debug('probe transport "%s" opened',name);transport.send([{type:"ping",data:"probe"}]);transport.once("packet",function(msg){if(failed)return;if("pong"==msg.type&&"probe"==msg.data){debug('probe transport "%s" pong',name);self.upgrading=true;self.emit("upgrading",transport);if(!transport)return;Socket.priorWebsocketSuccess="websocket"==transport.name;debug('pausing current transport "%s"',self.transport.name);self.transport.pause(function(){if(failed)return;if("closed"==self.readyState)return;debug("changing transport and sending upgrade packet");cleanup();self.setTransport(transport);transport.send([{type:"upgrade"}]);self.emit("upgrade",transport);transport=null;self.upgrading=false;self.flush()})}else{debug('probe transport "%s" failed',name);var err=new Error("probe error");err.transport=transport.name;self.emit("upgradeError",err)}})}function freezeTransport(){if(failed)return;failed=true;cleanup();transport.close();transport=null}function onerror(err){var error=new Error("probe error: "+err);error.transport=transport.name;freezeTransport();debug('probe transport "%s" failed because of error: %s',name,err);self.emit("upgradeError",error)}function onTransportClose(){onerror("transport closed")}function onclose(){onerror("socket closed")}function onupgrade(to){if(transport&&to.name!=transport.name){debug('"%s" works - aborting "%s"',to.name,transport.name);freezeTransport()}}function cleanup(){transport.removeListener("open",onTransportOpen);transport.removeListener("error",onerror);transport.removeListener("close",onTransportClose);self.removeListener("close",onclose);self.removeListener("upgrading",onupgrade)}transport.once("open",onTransportOpen);transport.once("error",onerror);transport.once("close",onTransportClose);this.once("close",onclose);this.once("upgrading",onupgrade);transport.open()};Socket.prototype.onOpen=function(){debug("socket open");this.readyState="open";Socket.priorWebsocketSuccess="websocket"==this.transport.name;this.emit("open");this.flush();if("open"==this.readyState&&this.upgrade&&this.transport.pause){debug("starting upgrade probes");for(var i=0,l=this.upgrades.length;i<l;i++){this.probe(this.upgrades[i])}}};Socket.prototype.onPacket=function(packet){if("opening"==this.readyState||"open"==this.readyState){debug('socket receive: type "%s", data "%s"',packet.type,packet.data);this.emit("packet",packet);this.emit("heartbeat");switch(packet.type){case"open":this.onHandshake(parsejson(packet.data));break;case"pong":this.setPing();break;case"error":var err=new Error("server error");err.code=packet.data;this.emit("error",err);break;case"message":this.emit("data",packet.data);this.emit("message",packet.data);break}}else{debug('packet received with socket readyState "%s"',this.readyState)}};Socket.prototype.onHandshake=function(data){this.emit("handshake",data);this.id=data.sid;this.transport.query.sid=data.sid;this.upgrades=this.filterUpgrades(data.upgrades);this.pingInterval=data.pingInterval;this.pingTimeout=data.pingTimeout;this.onOpen();if("closed"==this.readyState)return;this.setPing();this.removeListener("heartbeat",this.onHeartbeat);this.on("heartbeat",this.onHeartbeat)};Socket.prototype.onHeartbeat=function(timeout){clearTimeout(this.pingTimeoutTimer);var self=this;self.pingTimeoutTimer=setTimeout(function(){if("closed"==self.readyState)return;self.onClose("ping timeout")},timeout||self.pingInterval+self.pingTimeout)};Socket.prototype.setPing=function(){var self=this;clearTimeout(self.pingIntervalTimer);self.pingIntervalTimer=setTimeout(function(){debug("writing ping packet - expecting pong within %sms",self.pingTimeout);self.ping();self.onHeartbeat(self.pingTimeout)},self.pingInterval)};Socket.prototype.ping=function(){this.sendPacket("ping")};Socket.prototype.onDrain=function(){for(var i=0;i<this.prevBufferLen;i++){if(this.callbackBuffer[i]){this.callbackBuffer[i]()}}this.writeBuffer.splice(0,this.prevBufferLen);this.callbackBuffer.splice(0,this.prevBufferLen);this.prevBufferLen=0;if(this.writeBuffer.length==0){this.emit("drain")}else{this.flush()}};Socket.prototype.flush=function(){if("closed"!=this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){debug("flushing %d packets in socket",this.writeBuffer.length);this.transport.send(this.writeBuffer);this.prevBufferLen=this.writeBuffer.length;this.emit("flush")}};Socket.prototype.write=Socket.prototype.send=function(msg,fn){this.sendPacket("message",msg,fn);return this};Socket.prototype.sendPacket=function(type,data,fn){if("closing"==this.readyState||"closed"==this.readyState){return}var packet={type:type,data:data};this.emit("packetCreate",packet);this.writeBuffer.push(packet);this.callbackBuffer.push(fn);this.flush()};Socket.prototype.close=function(){if("opening"==this.readyState||"open"==this.readyState){this.readyState="closing";var self=this;function close(){self.onClose("forced close");debug("socket closing - telling transport to close");self.transport.close()}function cleanupAndClose(){self.removeListener("upgrade",cleanupAndClose);self.removeListener("upgradeError",cleanupAndClose);close()}function waitForUpgrade(){self.once("upgrade",cleanupAndClose);self.once("upgradeError",cleanupAndClose)}if(this.writeBuffer.length){this.once("drain",function(){if(this.upgrading){waitForUpgrade()}else{close()}})}else if(this.upgrading){waitForUpgrade()}else{close()}}return this};Socket.prototype.onError=function(err){debug("socket error %j",err);Socket.priorWebsocketSuccess=false;this.emit("error",err);this.onClose("transport error",err)};Socket.prototype.onClose=function(reason,desc){if("opening"==this.readyState||"open"==this.readyState||"closing"==this.readyState){debug('socket close with reason: "%s"',reason);var self=this;clearTimeout(this.pingIntervalTimer);clearTimeout(this.pingTimeoutTimer);setTimeout(function(){self.writeBuffer=[];self.callbackBuffer=[];self.prevBufferLen=0},0);this.transport.removeAllListeners("close");this.transport.close();this.transport.removeAllListeners();this.readyState="closed";this.id=null;this.emit("close",reason,desc)}};Socket.prototype.filterUpgrades=function(upgrades){var filteredUpgrades=[];for(var i=0,j=upgrades.length;i<j;i++){if(~index(this.transports,upgrades[i]))filteredUpgrades.push(upgrades[i])}return filteredUpgrades}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transport":14,"./transports":15,"component-emitter":9,debug:22,"engine.io-parser":25,indexof:42,parsejson:34,parseqs:35,parseuri:36}],14:[function(_dereq_,module,exports){var parser=_dereq_("engine.io-parser");var Emitter=_dereq_("component-emitter");module.exports=Transport;function Transport(opts){this.path=opts.path;this.hostname=opts.hostname;this.port=opts.port;this.secure=opts.secure;this.query=opts.query;this.timestampParam=opts.timestampParam;this.timestampRequests=opts.timestampRequests;this.readyState="";this.agent=opts.agent||false;this.socket=opts.socket;this.enablesXDR=opts.enablesXDR;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized}Emitter(Transport.prototype);Transport.timestamps=0;Transport.prototype.onError=function(msg,desc){var err=new Error(msg);err.type="TransportError";err.description=desc;this.emit("error",err);return this};Transport.prototype.open=function(){if("closed"==this.readyState||""==this.readyState){this.readyState="opening";this.doOpen()}return this};Transport.prototype.close=function(){if("opening"==this.readyState||"open"==this.readyState){this.doClose();this.onClose()}return this};Transport.prototype.send=function(packets){if("open"==this.readyState){this.write(packets)}else{throw new Error("Transport not open")}};Transport.prototype.onOpen=function(){this.readyState="open";this.writable=true;this.emit("open")};Transport.prototype.onData=function(data){var packet=parser.decodePacket(data,this.socket.binaryType);this.onPacket(packet)};Transport.prototype.onPacket=function(packet){this.emit("packet",packet)};Transport.prototype.onClose=function(){this.readyState="closed";this.emit("close")}},{"component-emitter":9,"engine.io-parser":25}],15:[function(_dereq_,module,exports){(function(global){var XMLHttpRequest=_dereq_("xmlhttprequest");var XHR=_dereq_("./polling-xhr");var JSONP=_dereq_("./polling-jsonp");var websocket=_dereq_("./websocket");exports.polling=polling;exports.websocket=websocket;function polling(opts){var xhr;var xd=false;var xs=false;var jsonp=false!==opts.jsonp;if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}xd=opts.hostname!=location.hostname||port!=opts.port;xs=opts.secure!=isSSL}opts.xdomain=xd;
     18
     19opts.xscheme=xs;xhr=new XMLHttpRequest(opts);if("open"in xhr&&!opts.forceJSONP){return new XHR(opts)}else{if(!jsonp)throw new Error("JSONP disabled");return new JSONP(opts)}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling-jsonp":16,"./polling-xhr":17,"./websocket":19,xmlhttprequest:20}],16:[function(_dereq_,module,exports){(function(global){var Polling=_dereq_("./polling");var inherit=_dereq_("component-inherit");module.exports=JSONPPolling;var rNewline=/\n/g;var rEscapedNewline=/\\n/g;var callbacks;var index=0;function empty(){}function JSONPPolling(opts){Polling.call(this,opts);this.query=this.query||{};if(!callbacks){if(!global.___eio)global.___eio=[];callbacks=global.___eio}this.index=callbacks.length;var self=this;callbacks.push(function(msg){self.onData(msg)});this.query.j=this.index;if(global.document&&global.addEventListener){global.addEventListener("beforeunload",function(){if(self.script)self.script.onerror=empty},false)}}inherit(JSONPPolling,Polling);JSONPPolling.prototype.supportsBinary=false;JSONPPolling.prototype.doClose=function(){if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}if(this.form){this.form.parentNode.removeChild(this.form);this.form=null;this.iframe=null}Polling.prototype.doClose.call(this)};JSONPPolling.prototype.doPoll=function(){var self=this;var script=document.createElement("script");if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}script.async=true;script.src=this.uri();script.onerror=function(e){self.onError("jsonp poll error",e)};var insertAt=document.getElementsByTagName("script")[0];insertAt.parentNode.insertBefore(script,insertAt);this.script=script;var isUAgecko="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);if(isUAgecko){setTimeout(function(){var iframe=document.createElement("iframe");document.body.appendChild(iframe);document.body.removeChild(iframe)},100)}};JSONPPolling.prototype.doWrite=function(data,fn){var self=this;if(!this.form){var form=document.createElement("form");var area=document.createElement("textarea");var id=this.iframeId="eio_iframe_"+this.index;var iframe;form.className="socketio";form.style.position="absolute";form.style.top="-1000px";form.style.left="-1000px";form.target=id;form.method="POST";form.setAttribute("accept-charset","utf-8");area.name="d";form.appendChild(area);document.body.appendChild(form);this.form=form;this.area=area}this.form.action=this.uri();function complete(){initIframe();fn()}function initIframe(){if(self.iframe){try{self.form.removeChild(self.iframe)}catch(e){self.onError("jsonp polling iframe removal error",e)}}try{var html='<iframe src="javascript:0" name="'+self.iframeId+'">';iframe=document.createElement(html)}catch(e){iframe=document.createElement("iframe");iframe.name=self.iframeId;iframe.src="javascript:0"}iframe.id=self.iframeId;self.form.appendChild(iframe);self.iframe=iframe}initIframe();data=data.replace(rEscapedNewline,"\\\n");this.area.value=data.replace(rNewline,"\\n");try{this.form.submit()}catch(e){}if(this.iframe.attachEvent){this.iframe.onreadystatechange=function(){if(self.iframe.readyState=="complete"){complete()}}}else{this.iframe.onload=complete}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling":18,"component-inherit":21}],17:[function(_dereq_,module,exports){(function(global){var XMLHttpRequest=_dereq_("xmlhttprequest");var Polling=_dereq_("./polling");var Emitter=_dereq_("component-emitter");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:polling-xhr");module.exports=XHR;module.exports.Request=Request;function empty(){}function XHR(opts){Polling.call(this,opts);if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}this.xd=opts.hostname!=global.location.hostname||port!=opts.port;this.xs=opts.secure!=isSSL}}inherit(XHR,Polling);XHR.prototype.supportsBinary=true;XHR.prototype.request=function(opts){opts=opts||{};opts.uri=this.uri();opts.xd=this.xd;opts.xs=this.xs;opts.agent=this.agent||false;opts.supportsBinary=this.supportsBinary;opts.enablesXDR=this.enablesXDR;opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;return new Request(opts)};XHR.prototype.doWrite=function(data,fn){var isBinary=typeof data!=="string"&&data!==undefined;var req=this.request({method:"POST",data:data,isBinary:isBinary});var self=this;req.on("success",fn);req.on("error",function(err){self.onError("xhr post error",err)});this.sendXhr=req};XHR.prototype.doPoll=function(){debug("xhr poll");var req=this.request();var self=this;req.on("data",function(data){self.onData(data)});req.on("error",function(err){self.onError("xhr poll error",err)});this.pollXhr=req};function Request(opts){this.method=opts.method||"GET";this.uri=opts.uri;this.xd=!!opts.xd;this.xs=!!opts.xs;this.async=false!==opts.async;this.data=undefined!=opts.data?opts.data:null;this.agent=opts.agent;this.isBinary=opts.isBinary;this.supportsBinary=opts.supportsBinary;this.enablesXDR=opts.enablesXDR;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized;this.create()}Emitter(Request.prototype);Request.prototype.create=function(){var opts={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;var xhr=this.xhr=new XMLHttpRequest(opts);var self=this;try{debug("xhr open %s: %s",this.method,this.uri);xhr.open(this.method,this.uri,this.async);if(this.supportsBinary){xhr.responseType="arraybuffer"}if("POST"==this.method){try{if(this.isBinary){xhr.setRequestHeader("Content-type","application/octet-stream")}else{xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}}catch(e){}}if("withCredentials"in xhr){xhr.withCredentials=true}if(this.hasXDR()){xhr.onload=function(){self.onLoad()};xhr.onerror=function(){self.onError(xhr.responseText)}}else{xhr.onreadystatechange=function(){if(4!=xhr.readyState)return;if(200==xhr.status||1223==xhr.status){self.onLoad()}else{setTimeout(function(){self.onError(xhr.status)},0)}}}debug("xhr data %s",this.data);xhr.send(this.data)}catch(e){setTimeout(function(){self.onError(e)},0);return}if(global.document){this.index=Request.requestsCount++;Request.requests[this.index]=this}};Request.prototype.onSuccess=function(){this.emit("success");this.cleanup()};Request.prototype.onData=function(data){this.emit("data",data);this.onSuccess()};Request.prototype.onError=function(err){this.emit("error",err);this.cleanup(true)};Request.prototype.cleanup=function(fromError){if("undefined"==typeof this.xhr||null===this.xhr){return}if(this.hasXDR()){this.xhr.onload=this.xhr.onerror=empty}else{this.xhr.onreadystatechange=empty}if(fromError){try{this.xhr.abort()}catch(e){}}if(global.document){delete Request.requests[this.index]}this.xhr=null};Request.prototype.onLoad=function(){var data;try{var contentType;try{contentType=this.xhr.getResponseHeader("Content-Type").split(";")[0]}catch(e){}if(contentType==="application/octet-stream"){data=this.xhr.response}else{if(!this.supportsBinary){data=this.xhr.responseText}else{data="ok"}}}catch(e){this.onError(e)}if(null!=data){this.onData(data)}};Request.prototype.hasXDR=function(){return"undefined"!==typeof global.XDomainRequest&&!this.xs&&this.enablesXDR};Request.prototype.abort=function(){this.cleanup()};if(global.document){Request.requestsCount=0;Request.requests={};if(global.attachEvent){global.attachEvent("onunload",unloadHandler)}else if(global.addEventListener){global.addEventListener("beforeunload",unloadHandler,false)}}function unloadHandler(){for(var i in Request.requests){if(Request.requests.hasOwnProperty(i)){Request.requests[i].abort()}}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling":18,"component-emitter":9,"component-inherit":21,debug:22,xmlhttprequest:20}],18:[function(_dereq_,module,exports){var Transport=_dereq_("../transport");var parseqs=_dereq_("parseqs");var parser=_dereq_("engine.io-parser");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:polling");module.exports=Polling;var hasXHR2=function(){var XMLHttpRequest=_dereq_("xmlhttprequest");var xhr=new XMLHttpRequest({xdomain:false});return null!=xhr.responseType}();function Polling(opts){var forceBase64=opts&&opts.forceBase64;if(!hasXHR2||forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(Polling,Transport);Polling.prototype.name="polling";Polling.prototype.doOpen=function(){this.poll()};Polling.prototype.pause=function(onPause){var pending=0;var self=this;this.readyState="pausing";function pause(){debug("paused");self.readyState="paused";onPause()}if(this.polling||!this.writable){var total=0;if(this.polling){debug("we are currently polling - waiting to pause");total++;this.once("pollComplete",function(){debug("pre-pause polling complete");--total||pause()})}if(!this.writable){debug("we are currently writing - waiting to pause");total++;this.once("drain",function(){debug("pre-pause writing complete");--total||pause()})}}else{pause()}};Polling.prototype.poll=function(){debug("polling");this.polling=true;this.doPoll();this.emit("poll")};Polling.prototype.onData=function(data){var self=this;debug("polling got data %s",data);var callback=function(packet,index,total){if("opening"==self.readyState){self.onOpen()}if("close"==packet.type){self.onClose();return false}self.onPacket(packet)};parser.decodePayload(data,this.socket.binaryType,callback);if("closed"!=this.readyState){this.polling=false;this.emit("pollComplete");if("open"==this.readyState){this.poll()}else{debug('ignoring poll - transport state "%s"',this.readyState)}}};Polling.prototype.doClose=function(){var self=this;function close(){debug("writing close packet");self.write([{type:"close"}])}if("open"==this.readyState){debug("transport open - closing");close()}else{debug("transport not open - deferring close");this.once("open",close)}};Polling.prototype.write=function(packets){var self=this;this.writable=false;var callbackfn=function(){self.writable=true;self.emit("drain")};var self=this;parser.encodePayload(packets,this.supportsBinary,function(data){self.doWrite(data,callbackfn)})};Polling.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"https":"http";var port="";if(false!==this.timestampRequests){query[this.timestampParam]=+new Date+"-"+Transport.timestamps++}if(!this.supportsBinary&&!query.sid){query.b64=1}query=parseqs.encode(query);if(this.port&&("https"==schema&&this.port!=443||"http"==schema&&this.port!=80)){port=":"+this.port}if(query.length){query="?"+query}return schema+"://"+this.hostname+port+this.path+query}},{"../transport":14,"component-inherit":21,debug:22,"engine.io-parser":25,parseqs:35,xmlhttprequest:20}],19:[function(_dereq_,module,exports){var Transport=_dereq_("../transport");var parser=_dereq_("engine.io-parser");var parseqs=_dereq_("parseqs");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:websocket");var WebSocket=_dereq_("ws");module.exports=WS;function WS(opts){var forceBase64=opts&&opts.forceBase64;if(forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(WS,Transport);WS.prototype.name="websocket";WS.prototype.supportsBinary=true;WS.prototype.doOpen=function(){if(!this.check()){return}var self=this;var uri=this.uri();var protocols=void 0;var opts={agent:this.agent};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;this.ws=new WebSocket(uri,protocols,opts);if(this.ws.binaryType===undefined){this.supportsBinary=false}this.ws.binaryType="arraybuffer";this.addEventListeners()};WS.prototype.addEventListeners=function(){var self=this;this.ws.onopen=function(){self.onOpen()};this.ws.onclose=function(){self.onClose()};this.ws.onmessage=function(ev){self.onData(ev.data)};this.ws.onerror=function(e){self.onError("websocket error",e)}};if("undefined"!=typeof navigator&&/iPad|iPhone|iPod/i.test(navigator.userAgent)){WS.prototype.onData=function(data){var self=this;setTimeout(function(){Transport.prototype.onData.call(self,data)},0)}}WS.prototype.write=function(packets){var self=this;this.writable=false;for(var i=0,l=packets.length;i<l;i++){parser.encodePacket(packets[i],this.supportsBinary,function(data){try{self.ws.send(data)}catch(e){debug("websocket closed before onclose event")}})}function ondrain(){self.writable=true;self.emit("drain")}setTimeout(ondrain,0)};WS.prototype.onClose=function(){Transport.prototype.onClose.call(this)};WS.prototype.doClose=function(){if(typeof this.ws!=="undefined"){this.ws.close()}};WS.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"wss":"ws";var port="";if(this.port&&("wss"==schema&&this.port!=443||"ws"==schema&&this.port!=80)){port=":"+this.port}if(this.timestampRequests){query[this.timestampParam]=+new Date}if(!this.supportsBinary){query.b64=1}query=parseqs.encode(query);if(query.length){query="?"+query}return schema+"://"+this.hostname+port+this.path+query};WS.prototype.check=function(){return!!WebSocket&&!("__initialize"in WebSocket&&this.name===WS.prototype.name)}},{"../transport":14,"component-inherit":21,debug:22,"engine.io-parser":25,parseqs:35,ws:37}],20:[function(_dereq_,module,exports){var hasCORS=_dereq_("has-cors");module.exports=function(opts){var xdomain=opts.xdomain;var xscheme=opts.xscheme;var enablesXDR=opts.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!xdomain||hasCORS)){return new XMLHttpRequest}}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!xscheme&&enablesXDR){return new XDomainRequest}}catch(e){}if(!xdomain){try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}},{"has-cors":40}],21:[function(_dereq_,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],22:[function(_dereq_,module,exports){exports=module.exports=_dereq_("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function useColors(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"==typeof console&&"function"==typeof console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){localStorage.removeItem("debug")}else{localStorage.debug=namespaces}}catch(e){}}function load(){var r;try{r=localStorage.debug}catch(e){}return r}exports.enable(load())},{"./debug":23}],23:[function(_dereq_,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=_dereq_("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{exports.names.push(new RegExp("^"+namespaces+"$"))}}}function disable(){exports.enable("")}function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++){if(exports.skips[i].test(name)){return false}}for(i=0,len=exports.names.length;i<len;i++){if(exports.names[i].test(name)){return true}}return false}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{ms:24}],24:[function(_dereq_,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){var match=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"h":return n*h;case"minutes":case"minute":case"m":return n*m;case"seconds":case"second":case"s":return n*s;case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+" "+name;return Math.ceil(ms/n)+" "+name+"s"}},{}],25:[function(_dereq_,module,exports){(function(global){var keys=_dereq_("./keys");var hasBinary=_dereq_("has-binary");var sliceBuffer=_dereq_("arraybuffer.slice");var base64encoder=_dereq_("base64-arraybuffer");var after=_dereq_("after");var utf8=_dereq_("utf8");var isAndroid=navigator.userAgent.match(/Android/i);var isPhantomJS=/PhantomJS/i.test(navigator.userAgent);var dontSendBlobs=isAndroid||isPhantomJS;exports.protocol=3;var packets=exports.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6};var packetslist=keys(packets);var err={type:"error",data:"parser error"};var Blob=_dereq_("blob");exports.encodePacket=function(packet,supportsBinary,utf8encode,callback){if("function"==typeof supportsBinary){callback=supportsBinary;supportsBinary=false}if("function"==typeof utf8encode){callback=utf8encode;utf8encode=null}var data=packet.data===undefined?undefined:packet.data.buffer||packet.data;if(global.ArrayBuffer&&data instanceof ArrayBuffer){return encodeArrayBuffer(packet,supportsBinary,callback)}else if(Blob&&data instanceof global.Blob){return encodeBlob(packet,supportsBinary,callback)}if(data&&data.base64){return encodeBase64Object(packet,callback)}var encoded=packets[packet.type];if(undefined!==packet.data){encoded+=utf8encode?utf8.encode(String(packet.data)):String(packet.data)}return callback(""+encoded)};function encodeBase64Object(packet,callback){var message="b"+exports.packets[packet.type]+packet.data.data;return callback(message)}function encodeArrayBuffer(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}var data=packet.data;var contentArray=new Uint8Array(data);var resultBuffer=new Uint8Array(1+data.byteLength);resultBuffer[0]=packets[packet.type];for(var i=0;i<contentArray.length;i++){resultBuffer[i+1]=contentArray[i]}return callback(resultBuffer.buffer)}function encodeBlobAsArrayBuffer(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}var fr=new FileReader;fr.onload=function(){packet.data=fr.result;exports.encodePacket(packet,supportsBinary,true,callback)};return fr.readAsArrayBuffer(packet.data)}function encodeBlob(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}if(dontSendBlobs){return encodeBlobAsArrayBuffer(packet,supportsBinary,callback)}var length=new Uint8Array(1);length[0]=packets[packet.type];var blob=new Blob([length.buffer,packet.data]);return callback(blob)}exports.encodeBase64Packet=function(packet,callback){var message="b"+exports.packets[packet.type];if(Blob&&packet.data instanceof Blob){var fr=new FileReader;fr.onload=function(){var b64=fr.result.split(",")[1];callback(message+b64)};return fr.readAsDataURL(packet.data)}var b64data;try{b64data=String.fromCharCode.apply(null,new Uint8Array(packet.data))}catch(e){var typed=new Uint8Array(packet.data);var basic=new Array(typed.length);for(var i=0;i<typed.length;i++){basic[i]=typed[i]}b64data=String.fromCharCode.apply(null,basic)}message+=global.btoa(b64data);return callback(message)};exports.decodePacket=function(data,binaryType,utf8decode){if(typeof data=="string"||data===undefined){if(data.charAt(0)=="b"){return exports.decodeBase64Packet(data.substr(1),binaryType)}if(utf8decode){try{data=utf8.decode(data)}catch(e){return err}}var type=data.charAt(0);if(Number(type)!=type||!packetslist[type]){return err}if(data.length>1){return{type:packetslist[type],data:data.substring(1)}}else{return{type:packetslist[type]}}}var asArray=new Uint8Array(data);var type=asArray[0];var rest=sliceBuffer(data,1);if(Blob&&binaryType==="blob"){rest=new Blob([rest])}return{type:packetslist[type],data:rest}};exports.decodeBase64Packet=function(msg,binaryType){var type=packetslist[msg.charAt(0)];if(!global.ArrayBuffer){return{type:type,data:{base64:true,data:msg.substr(1)}}}var data=base64encoder.decode(msg.substr(1));if(binaryType==="blob"&&Blob){data=new Blob([data])}return{type:type,data:data}};exports.encodePayload=function(packets,supportsBinary,callback){if(typeof supportsBinary=="function"){callback=supportsBinary;supportsBinary=null}var isBinary=hasBinary(packets);if(supportsBinary&&isBinary){if(Blob&&!dontSendBlobs){return exports.encodePayloadAsBlob(packets,callback)}return exports.encodePayloadAsArrayBuffer(packets,callback)}if(!packets.length){return callback("0:")}function setLengthHeader(message){return message.length+":"+message}function encodeOne(packet,doneCallback){exports.encodePacket(packet,!isBinary?false:supportsBinary,true,function(message){doneCallback(null,setLengthHeader(message))})}map(packets,encodeOne,function(err,results){return callback(results.join(""))})};function map(ary,each,done){var result=new Array(ary.length);var next=after(ary.length,done);var eachWithIndex=function(i,el,cb){each(el,function(error,msg){result[i]=msg;cb(error,result)})};for(var i=0;i<ary.length;i++){eachWithIndex(i,ary[i],next)}}exports.decodePayload=function(data,binaryType,callback){if(typeof data!="string"){return exports.decodePayloadAsBinary(data,binaryType,callback)}if(typeof binaryType==="function"){callback=binaryType;binaryType=null}var packet;if(data==""){return callback(err,0,1)}var length="",n,msg;for(var i=0,l=data.length;i<l;i++){var chr=data.charAt(i);if(":"!=chr){length+=chr}else{if(""==length||length!=(n=Number(length))){return callback(err,0,1)}msg=data.substr(i+1,n);if(length!=msg.length){return callback(err,0,1)}if(msg.length){packet=exports.decodePacket(msg,binaryType,true);if(err.type==packet.type&&err.data==packet.data){return callback(err,0,1)}var ret=callback(packet,i+n,l);if(false===ret)return}i+=n;length=""}}if(length!=""){return callback(err,0,1)}};exports.encodePayloadAsArrayBuffer=function(packets,callback){if(!packets.length){return callback(new ArrayBuffer(0))}function encodeOne(packet,doneCallback){exports.encodePacket(packet,true,true,function(data){return doneCallback(null,data)})}map(packets,encodeOne,function(err,encodedPackets){var totalLength=encodedPackets.reduce(function(acc,p){var len;if(typeof p==="string"){len=p.length}else{len=p.byteLength}return acc+len.toString().length+len+2},0);var resultArray=new Uint8Array(totalLength);var bufferIndex=0;encodedPackets.forEach(function(p){var isString=typeof p==="string";var ab=p;if(isString){var view=new Uint8Array(p.length);for(var i=0;i<p.length;i++){view[i]=p.charCodeAt(i)}ab=view.buffer}if(isString){resultArray[bufferIndex++]=0}else{resultArray[bufferIndex++]=1}var lenStr=ab.byteLength.toString();for(var i=0;i<lenStr.length;i++){resultArray[bufferIndex++]=parseInt(lenStr[i])}resultArray[bufferIndex++]=255;var view=new Uint8Array(ab);for(var i=0;i<view.length;i++){resultArray[bufferIndex++]=view[i]}});return callback(resultArray.buffer)})};exports.encodePayloadAsBlob=function(packets,callback){function encodeOne(packet,doneCallback){exports.encodePacket(packet,true,true,function(encoded){var binaryIdentifier=new Uint8Array(1);binaryIdentifier[0]=1;if(typeof encoded==="string"){var view=new Uint8Array(encoded.length);for(var i=0;i<encoded.length;i++){view[i]=encoded.charCodeAt(i)}encoded=view.buffer;binaryIdentifier[0]=0}var len=encoded instanceof ArrayBuffer?encoded.byteLength:encoded.size;var lenStr=len.toString();var lengthAry=new Uint8Array(lenStr.length+1);for(var i=0;i<lenStr.length;i++){lengthAry[i]=parseInt(lenStr[i])}lengthAry[lenStr.length]=255;if(Blob){var blob=new Blob([binaryIdentifier.buffer,lengthAry.buffer,encoded]);doneCallback(null,blob)}})}map(packets,encodeOne,function(err,results){return callback(new Blob(results))})};exports.decodePayloadAsBinary=function(data,binaryType,callback){if(typeof binaryType==="function"){callback=binaryType;binaryType=null}var bufferTail=data;var buffers=[];var numberTooLong=false;while(bufferTail.byteLength>0){var tailArray=new Uint8Array(bufferTail);var isString=tailArray[0]===0;var msgLength="";for(var i=1;;i++){if(tailArray[i]==255)break;if(msgLength.length>310){numberTooLong=true;break}msgLength+=tailArray[i]}if(numberTooLong)return callback(err,0,1);bufferTail=sliceBuffer(bufferTail,2+msgLength.length);msgLength=parseInt(msgLength);var msg=sliceBuffer(bufferTail,0,msgLength);if(isString){try{msg=String.fromCharCode.apply(null,new Uint8Array(msg))}catch(e){var typed=new Uint8Array(msg);msg="";for(var i=0;i<typed.length;i++){msg+=String.fromCharCode(typed[i])}}}buffers.push(msg);bufferTail=sliceBuffer(bufferTail,msgLength)}var total=buffers.length;buffers.forEach(function(buffer,i){callback(exports.decodePacket(buffer,binaryType,true),i,total)})}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./keys":26,after:27,"arraybuffer.slice":28,"base64-arraybuffer":29,blob:30,"has-binary":31,utf8:33}],26:[function(_dereq_,module,exports){module.exports=Object.keys||function keys(obj){var arr=[];var has=Object.prototype.hasOwnProperty;for(var i in obj){if(has.call(obj,i)){arr.push(i)}}return arr}},{}],27:[function(_dereq_,module,exports){module.exports=after;function after(count,callback,err_cb){var bail=false;err_cb=err_cb||noop;proxy.count=count;return count===0?callback():proxy;function proxy(err,result){if(proxy.count<=0){throw new Error("after called too many times")}--proxy.count;if(err){bail=true;callback(err);callback=err_cb}else if(proxy.count===0&&!bail){callback(null,result)}}}function noop(){}},{}],28:[function(_dereq_,module,exports){module.exports=function(arraybuffer,start,end){var bytes=arraybuffer.byteLength;start=start||0;end=end||bytes;if(arraybuffer.slice){return arraybuffer.slice(start,end)}if(start<0){start+=bytes}if(end<0){end+=bytes}if(end>bytes){end=bytes}if(start>=bytes||start>=end||bytes===0){return new ArrayBuffer(0)}var abv=new Uint8Array(arraybuffer);var result=new Uint8Array(end-start);for(var i=start,ii=0;i<end;i++,ii++){result[ii]=abv[i]}return result.buffer}},{}],29:[function(_dereq_,module,exports){(function(chars){"use strict";exports.encode=function(arraybuffer){var bytes=new Uint8Array(arraybuffer),i,len=bytes.length,base64="";for(i=0;i<len;i+=3){base64+=chars[bytes[i]>>2];base64+=chars[(bytes[i]&3)<<4|bytes[i+1]>>4];base64+=chars[(bytes[i+1]&15)<<2|bytes[i+2]>>6];base64+=chars[bytes[i+2]&63]}if(len%3===2){base64=base64.substring(0,base64.length-1)+"="}else if(len%3===1){base64=base64.substring(0,base64.length-2)+"=="}return base64};exports.decode=function(base64){var bufferLength=base64.length*.75,len=base64.length,i,p=0,encoded1,encoded2,encoded3,encoded4;if(base64[base64.length-1]==="="){bufferLength--;if(base64[base64.length-2]==="="){bufferLength--}}var arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer);for(i=0;i<len;i+=4){encoded1=chars.indexOf(base64[i]);encoded2=chars.indexOf(base64[i+1]);encoded3=chars.indexOf(base64[i+2]);encoded4=chars.indexOf(base64[i+3]);bytes[p++]=encoded1<<2|encoded2>>4;bytes[p++]=(encoded2&15)<<4|encoded3>>2;bytes[p++]=(encoded3&3)<<6|encoded4&63}return arraybuffer}})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},{}],30:[function(_dereq_,module,exports){(function(global){var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MSBlobBuilder||global.MozBlobBuilder;var blobSupported=function(){try{var b=new Blob(["hi"]);return b.size==2}catch(e){return false}}();var blobBuilderSupported=BlobBuilder&&BlobBuilder.prototype.append&&BlobBuilder.prototype.getBlob;function BlobBuilderConstructor(ary,options){options=options||{};var bb=new BlobBuilder;for(var i=0;i<ary.length;i++){bb.append(ary[i])}return options.type?bb.getBlob(options.type):bb.getBlob()}module.exports=function(){if(blobSupported){return global.Blob}else if(blobBuilderSupported){return BlobBuilderConstructor}else{return undefined}}()}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],31:[function(_dereq_,module,exports){(function(global){var isArray=_dereq_("isarray");module.exports=hasBinary;function hasBinary(data){function _hasBinary(obj){if(!obj)return false;if(global.Buffer&&global.Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer||global.Blob&&obj instanceof Blob||global.File&&obj instanceof File){return true}if(isArray(obj)){for(var i=0;i<obj.length;i++){if(_hasBinary(obj[i])){return true}}}else if(obj&&"object"==typeof obj){if(obj.toJSON){obj=obj.toJSON()}for(var key in obj){if(obj.hasOwnProperty(key)&&_hasBinary(obj[key])){return true}}}return false}return _hasBinary(data)}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{isarray:32}],32:[function(_dereq_,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],33:[function(_dereq_,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){
     20root=freeGlobal}var stringFromCharCode=String.fromCharCode;function ucs2decode(string){var output=[];var counter=0;var length=string.length;var value;var extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){var length=array.length;var index=-1;var value;var output="";while(++index<length){value=array[index];if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value)}return output}function createByte(codePoint,shift){return stringFromCharCode(codePoint>>shift&63|128)}function encodeCodePoint(codePoint){if((codePoint&4294967168)==0){return stringFromCharCode(codePoint)}var symbol="";if((codePoint&4294965248)==0){symbol=stringFromCharCode(codePoint>>6&31|192)}else if((codePoint&4294901760)==0){symbol=stringFromCharCode(codePoint>>12&15|224);symbol+=createByte(codePoint,6)}else if((codePoint&4292870144)==0){symbol=stringFromCharCode(codePoint>>18&7|240);symbol+=createByte(codePoint,12);symbol+=createByte(codePoint,6)}symbol+=stringFromCharCode(codePoint&63|128);return symbol}function utf8encode(string){var codePoints=ucs2decode(string);var length=codePoints.length;var index=-1;var codePoint;var byteString="";while(++index<length){codePoint=codePoints[index];byteString+=encodeCodePoint(codePoint)}return byteString}function readContinuationByte(){if(byteIndex>=byteCount){throw Error("Invalid byte index")}var continuationByte=byteArray[byteIndex]&255;byteIndex++;if((continuationByte&192)==128){return continuationByte&63}throw Error("Invalid continuation byte")}function decodeSymbol(){var byte1;var byte2;var byte3;var byte4;var codePoint;if(byteIndex>byteCount){throw Error("Invalid byte index")}if(byteIndex==byteCount){return false}byte1=byteArray[byteIndex]&255;byteIndex++;if((byte1&128)==0){return byte1}if((byte1&224)==192){var byte2=readContinuationByte();codePoint=(byte1&31)<<6|byte2;if(codePoint>=128){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&240)==224){byte2=readContinuationByte();byte3=readContinuationByte();codePoint=(byte1&15)<<12|byte2<<6|byte3;if(codePoint>=2048){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&248)==240){byte2=readContinuationByte();byte3=readContinuationByte();byte4=readContinuationByte();codePoint=(byte1&15)<<18|byte2<<12|byte3<<6|byte4;if(codePoint>=65536&&codePoint<=1114111){return codePoint}}throw Error("Invalid UTF-8 detected")}var byteArray;var byteCount;var byteIndex;function utf8decode(byteString){byteArray=ucs2decode(byteString);byteCount=byteArray.length;byteIndex=0;var codePoints=[];var tmp;while((tmp=decodeSymbol())!==false){codePoints.push(tmp)}return ucs2encode(codePoints)}var utf8={version:"2.0.0",encode:utf8encode,decode:utf8decode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return utf8})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=utf8}else{var object={};var hasOwnProperty=object.hasOwnProperty;for(var key in utf8){hasOwnProperty.call(utf8,key)&&(freeExports[key]=utf8[key])}}}else{root.utf8=utf8}})(this)}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],34:[function(_dereq_,module,exports){(function(global){var rvalidchars=/^[\],:{}\s]*$/;var rvalidescape=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;var rvalidtokens=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;var rvalidbraces=/(?:^|:|,)(?:\s*\[)+/g;var rtrimLeft=/^\s+/;var rtrimRight=/\s+$/;module.exports=function parsejson(data){if("string"!=typeof data||!data){return null}data=data.replace(rtrimLeft,"").replace(rtrimRight,"");if(global.JSON&&JSON.parse){return JSON.parse(data)}if(rvalidchars.test(data.replace(rvalidescape,"@").replace(rvalidtokens,"]").replace(rvalidbraces,""))){return new Function("return "+data)()}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],35:[function(_dereq_,module,exports){exports.encode=function(obj){var str="";for(var i in obj){if(obj.hasOwnProperty(i)){if(str.length)str+="&";str+=encodeURIComponent(i)+"="+encodeURIComponent(obj[i])}}return str};exports.decode=function(qs){var qry={};var pairs=qs.split("&");for(var i=0,l=pairs.length;i<l;i++){var pair=pairs[i].split("=");qry[decodeURIComponent(pair[0])]=decodeURIComponent(pair[1])}return qry}},{}],36:[function(_dereq_,module,exports){var re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;var parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];module.exports=function parseuri(str){var src=str,b=str.indexOf("["),e=str.indexOf("]");if(b!=-1&&e!=-1){str=str.substring(0,b)+str.substring(b,e).replace(/:/g,";")+str.substring(e,str.length)}var m=re.exec(str||""),uri={},i=14;while(i--){uri[parts[i]]=m[i]||""}if(b!=-1&&e!=-1){uri.source=src;uri.host=uri.host.substring(1,uri.host.length-1).replace(/;/g,":");uri.authority=uri.authority.replace("[","").replace("]","").replace(/;/g,":");uri.ipv6uri=true}return uri}},{}],37:[function(_dereq_,module,exports){var global=function(){return this}();var WebSocket=global.WebSocket||global.MozWebSocket;module.exports=WebSocket?ws:null;function ws(uri,protocols,opts){var instance;if(protocols){instance=new WebSocket(uri,protocols)}else{instance=new WebSocket(uri)}return instance}if(WebSocket)ws.prototype=WebSocket.prototype},{}],38:[function(_dereq_,module,exports){(function(global){var isArray=_dereq_("isarray");module.exports=hasBinary;function hasBinary(data){function _hasBinary(obj){if(!obj)return false;if(global.Buffer&&global.Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer||global.Blob&&obj instanceof Blob||global.File&&obj instanceof File){return true}if(isArray(obj)){for(var i=0;i<obj.length;i++){if(_hasBinary(obj[i])){return true}}}else if(obj&&"object"==typeof obj){if(obj.toJSON){obj=obj.toJSON()}for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key)&&_hasBinary(obj[key])){return true}}}return false}return _hasBinary(data)}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{isarray:39}],39:[function(_dereq_,module,exports){module.exports=_dereq_(32)},{}],40:[function(_dereq_,module,exports){var global=_dereq_("global");try{module.exports="XMLHttpRequest"in global&&"withCredentials"in new global.XMLHttpRequest}catch(err){module.exports=false}},{global:41}],41:[function(_dereq_,module,exports){module.exports=function(){return this}()},{}],42:[function(_dereq_,module,exports){var indexOf=[].indexOf;module.exports=function(arr,obj){if(indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],43:[function(_dereq_,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],44:[function(_dereq_,module,exports){var re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;var parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];module.exports=function parseuri(str){var m=re.exec(str||""),uri={},i=14;while(i--){uri[parts[i]]=m[i]||""}return uri}},{}],45:[function(_dereq_,module,exports){(function(global){var isArray=_dereq_("isarray");var isBuf=_dereq_("./is-buffer");exports.deconstructPacket=function(packet){var buffers=[];var packetData=packet.data;function _deconstructPacket(data){if(!data)return data;if(isBuf(data)){var placeholder={_placeholder:true,num:buffers.length};buffers.push(data);return placeholder}else if(isArray(data)){var newData=new Array(data.length);for(var i=0;i<data.length;i++){newData[i]=_deconstructPacket(data[i])}return newData}else if("object"==typeof data&&!(data instanceof Date)){var newData={};for(var key in data){newData[key]=_deconstructPacket(data[key])}return newData}return data}var pack=packet;pack.data=_deconstructPacket(packetData);pack.attachments=buffers.length;return{packet:pack,buffers:buffers}};exports.reconstructPacket=function(packet,buffers){var curPlaceHolder=0;function _reconstructPacket(data){if(data&&data._placeholder){var buf=buffers[data.num];return buf}else if(isArray(data)){for(var i=0;i<data.length;i++){data[i]=_reconstructPacket(data[i])}return data}else if(data&&"object"==typeof data){for(var key in data){data[key]=_reconstructPacket(data[key])}return data}return data}packet.data=_reconstructPacket(packet.data);packet.attachments=undefined;return packet};exports.removeBlobs=function(data,callback){function _removeBlobs(obj,curKey,containingObject){if(!obj)return obj;if(global.Blob&&obj instanceof Blob||global.File&&obj instanceof File){pendingBlobs++;var fileReader=new FileReader;fileReader.onload=function(){if(containingObject){containingObject[curKey]=this.result}else{bloblessData=this.result}if(!--pendingBlobs){callback(bloblessData)}};fileReader.readAsArrayBuffer(obj)}else if(isArray(obj)){for(var i=0;i<obj.length;i++){_removeBlobs(obj[i],i,obj)}}else if(obj&&"object"==typeof obj&&!isBuf(obj)){for(var key in obj){_removeBlobs(obj[key],key,obj)}}}var pendingBlobs=0;var bloblessData=data;_removeBlobs(bloblessData);if(!pendingBlobs){callback(bloblessData)}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./is-buffer":47,isarray:48}],46:[function(_dereq_,module,exports){var debug=_dereq_("debug")("socket.io-parser");var json=_dereq_("json3");var isArray=_dereq_("isarray");var Emitter=_dereq_("component-emitter");var binary=_dereq_("./binary");var isBuf=_dereq_("./is-buffer");exports.protocol=4;exports.types=["CONNECT","DISCONNECT","EVENT","BINARY_EVENT","ACK","BINARY_ACK","ERROR"];exports.CONNECT=0;exports.DISCONNECT=1;exports.EVENT=2;exports.ACK=3;exports.ERROR=4;exports.BINARY_EVENT=5;exports.BINARY_ACK=6;exports.Encoder=Encoder;exports.Decoder=Decoder;function Encoder(){}Encoder.prototype.encode=function(obj,callback){debug("encoding packet %j",obj);if(exports.BINARY_EVENT==obj.type||exports.BINARY_ACK==obj.type){encodeAsBinary(obj,callback)}else{var encoding=encodeAsString(obj);callback([encoding])}};function encodeAsString(obj){var str="";var nsp=false;str+=obj.type;if(exports.BINARY_EVENT==obj.type||exports.BINARY_ACK==obj.type){str+=obj.attachments;str+="-"}if(obj.nsp&&"/"!=obj.nsp){nsp=true;str+=obj.nsp}if(null!=obj.id){if(nsp){str+=",";nsp=false}str+=obj.id}if(null!=obj.data){if(nsp)str+=",";str+=json.stringify(obj.data)}debug("encoded %j as %s",obj,str);return str}function encodeAsBinary(obj,callback){function writeEncoding(bloblessData){var deconstruction=binary.deconstructPacket(bloblessData);var pack=encodeAsString(deconstruction.packet);var buffers=deconstruction.buffers;buffers.unshift(pack);callback(buffers)}binary.removeBlobs(obj,writeEncoding)}function Decoder(){this.reconstructor=null}Emitter(Decoder.prototype);Decoder.prototype.add=function(obj){var packet;if("string"==typeof obj){packet=decodeString(obj);if(exports.BINARY_EVENT==packet.type||exports.BINARY_ACK==packet.type){this.reconstructor=new BinaryReconstructor(packet);if(this.reconstructor.reconPack.attachments===0){this.emit("decoded",packet)}}else{this.emit("decoded",packet)}}else if(isBuf(obj)||obj.base64){if(!this.reconstructor){throw new Error("got binary data when not reconstructing a packet")}else{packet=this.reconstructor.takeBinaryData(obj);if(packet){this.reconstructor=null;this.emit("decoded",packet)}}}else{throw new Error("Unknown type: "+obj)}};function decodeString(str){var p={};var i=0;p.type=Number(str.charAt(0));if(null==exports.types[p.type])return error();if(exports.BINARY_EVENT==p.type||exports.BINARY_ACK==p.type){var buf="";while(str.charAt(++i)!="-"){buf+=str.charAt(i);if(i==str.length)break}if(buf!=Number(buf)||str.charAt(i)!="-"){throw new Error("Illegal attachments")}p.attachments=Number(buf)}if("/"==str.charAt(i+1)){p.nsp="";while(++i){var c=str.charAt(i);if(","==c)break;p.nsp+=c;if(i==str.length)break}}else{p.nsp="/"}var next=str.charAt(i+1);if(""!==next&&Number(next)==next){p.id="";while(++i){var c=str.charAt(i);if(null==c||Number(c)!=c){--i;break}p.id+=str.charAt(i);if(i==str.length)break}p.id=Number(p.id)}if(str.charAt(++i)){try{p.data=json.parse(str.substr(i))}catch(e){return error()}}debug("decoded %s as %j",str,p);return p}Decoder.prototype.destroy=function(){if(this.reconstructor){this.reconstructor.finishedReconstruction()}};function BinaryReconstructor(packet){this.reconPack=packet;this.buffers=[]}BinaryReconstructor.prototype.takeBinaryData=function(binData){this.buffers.push(binData);if(this.buffers.length==this.reconPack.attachments){var packet=binary.reconstructPacket(this.reconPack,this.buffers);this.finishedReconstruction();return packet}return null};BinaryReconstructor.prototype.finishedReconstruction=function(){this.reconPack=null;this.buffers=[]};function error(data){return{type:exports.ERROR,data:"parser error"}}},{"./binary":45,"./is-buffer":47,"component-emitter":9,debug:10,isarray:48,json3:49}],47:[function(_dereq_,module,exports){(function(global){module.exports=isBuf;function isBuf(obj){return global.Buffer&&global.Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],48:[function(_dereq_,module,exports){module.exports=_dereq_(32)},{}],49:[function(_dereq_,module,exports){(function(window){var getClass={}.toString,isProperty,forEach,undef;var isLoader=typeof define==="function"&&define.amd;var nativeJSON=typeof JSON=="object"&&JSON;var JSON3=typeof exports=="object"&&exports&&!exports.nodeType&&exports;if(JSON3&&nativeJSON){JSON3.stringify=nativeJSON.stringify;JSON3.parse=nativeJSON.parse}else{JSON3=window.JSON=nativeJSON||{}}var isExtended=new Date(-0xc782b5b800cec);try{isExtended=isExtended.getUTCFullYear()==-109252&&isExtended.getUTCMonth()===0&&isExtended.getUTCDate()===1&&isExtended.getUTCHours()==10&&isExtended.getUTCMinutes()==37&&isExtended.getUTCSeconds()==6&&isExtended.getUTCMilliseconds()==708}catch(exception){}function has(name){if(has[name]!==undef){return has[name]}var isSupported;if(name=="bug-string-char-index"){isSupported="a"[0]!="a"}else if(name=="json"){isSupported=has("json-stringify")&&has("json-parse")}else{var value,serialized='{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';if(name=="json-stringify"){var stringify=JSON3.stringify,stringifySupported=typeof stringify=="function"&&isExtended;if(stringifySupported){(value=function(){return 1}).toJSON=value;try{stringifySupported=stringify(0)==="0"&&stringify(new Number)==="0"&&stringify(new String)=='""'&&stringify(getClass)===undef&&stringify(undef)===undef&&stringify()===undef&&stringify(value)==="1"&&stringify([value])=="[1]"&&stringify([undef])=="[null]"&&stringify(null)=="null"&&stringify([undef,getClass,null])=="[null,null,null]"&&stringify({a:[value,true,false,null,"\x00\b\n\f\r    "]})==serialized&&stringify(null,value)==="1"&&stringify([1,2],null,1)=="[\n 1,\n 2\n]"&&stringify(new Date(-864e13))=='"-271821-04-20T00:00:00.000Z"'&&stringify(new Date(864e13))=='"+275760-09-13T00:00:00.000Z"'&&stringify(new Date(-621987552e5))=='"-000001-01-01T00:00:00.000Z"'&&stringify(new Date(-1))=='"1969-12-31T23:59:59.999Z"'}catch(exception){stringifySupported=false}}isSupported=stringifySupported}if(name=="json-parse"){var parse=JSON3.parse;if(typeof parse=="function"){try{if(parse("0")===0&&!parse(false)){value=parse(serialized);var parseSupported=value["a"].length==5&&value["a"][0]===1;if(parseSupported){try{parseSupported=!parse('"    "')}catch(exception){}if(parseSupported){try{parseSupported=parse("01")!==1}catch(exception){}}if(parseSupported){try{parseSupported=parse("1.")!==1}catch(exception){}}}}}catch(exception){parseSupported=false}}isSupported=parseSupported}}return has[name]=!!isSupported}if(!has("json")){var functionClass="[object Function]";var dateClass="[object Date]";var numberClass="[object Number]";var stringClass="[object String]";var arrayClass="[object Array]";var booleanClass="[object Boolean]";var charIndexBuggy=has("bug-string-char-index");if(!isExtended){var floor=Math.floor;var Months=[0,31,59,90,120,151,181,212,243,273,304,334];var getDay=function(year,month){return Months[month]+365*(year-1970)+floor((year-1969+(month=+(month>1)))/4)-floor((year-1901+month)/100)+floor((year-1601+month)/400)}}if(!(isProperty={}.hasOwnProperty)){isProperty=function(property){var members={},constructor;if((members.__proto__=null,members.__proto__={toString:1},members).toString!=getClass){isProperty=function(property){var original=this.__proto__,result=property in(this.__proto__=null,this);this.__proto__=original;return result}}else{constructor=members.constructor;isProperty=function(property){var parent=(this.constructor||constructor).prototype;return property in this&&!(property in parent&&this[property]===parent[property])}}members=null;return isProperty.call(this,property)}}var PrimitiveTypes={"boolean":1,number:1,string:1,undefined:1};var isHostType=function(object,property){var type=typeof object[property];return type=="object"?!!object[property]:!PrimitiveTypes[type]};forEach=function(object,callback){var size=0,Properties,members,property;(Properties=function(){this.valueOf=0}).prototype.valueOf=0;members=new Properties;for(property in members){if(isProperty.call(members,property)){size++}}Properties=members=null;if(!size){members=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,length;var hasProperty=!isFunction&&typeof object.constructor!="function"&&isHostType(object,"hasOwnProperty")?object.hasOwnProperty:isProperty;for(property in object){if(!(isFunction&&property=="prototype")&&hasProperty.call(object,property)){callback(property)}}for(length=members.length;property=members[--length];hasProperty.call(object,property)&&callback(property));}}else if(size==2){forEach=function(object,callback){var members={},isFunction=getClass.call(object)==functionClass,property;for(property in object){if(!(isFunction&&property=="prototype")&&!isProperty.call(members,property)&&(members[property]=1)&&isProperty.call(object,property)){callback(property)}}}}else{forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,isConstructor;for(property in object){if(!(isFunction&&property=="prototype")&&isProperty.call(object,property)&&!(isConstructor=property==="constructor")){callback(property)}}if(isConstructor||isProperty.call(object,property="constructor")){callback(property)}}}return forEach(object,callback)};if(!has("json-stringify")){var Escapes={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var leadingZeroes="000000";var toPaddedString=function(width,value){return(leadingZeroes+(value||0)).slice(-width)};var unicodePrefix="\\u00";var quote=function(value){var result='"',index=0,length=value.length,isLarge=length>10&&charIndexBuggy,symbols;if(isLarge){symbols=value.split("")}for(;index<length;index++){var charCode=value.charCodeAt(index);switch(charCode){case 8:case 9:case 10:case 12:case 13:case 34:case 92:result+=Escapes[charCode];break;default:if(charCode<32){result+=unicodePrefix+toPaddedString(2,charCode.toString(16));break}result+=isLarge?symbols[index]:charIndexBuggy?value.charAt(index):value[index]}}return result+'"'};var serialize=function(property,object,callback,properties,whitespace,indentation,stack){var value,className,year,month,date,time,hours,minutes,seconds,milliseconds,results,element,index,length,prefix,result;try{value=object[property]}catch(exception){}if(typeof value=="object"&&value){className=getClass.call(value);if(className==dateClass&&!isProperty.call(value,"toJSON")){if(value>-1/0&&value<1/0){if(getDay){date=floor(value/864e5);for(year=floor(date/365.2425)+1970-1;getDay(year+1,0)<=date;year++);for(month=floor((date-getDay(year,0))/30.42);getDay(year,month+1)<=date;month++);date=1+date-getDay(year,month);time=(value%864e5+864e5)%864e5;hours=floor(time/36e5)%24;minutes=floor(time/6e4)%60;seconds=floor(time/1e3)%60;milliseconds=time%1e3}else{year=value.getUTCFullYear();month=value.getUTCMonth();date=value.getUTCDate();hours=value.getUTCHours();minutes=value.getUTCMinutes();seconds=value.getUTCSeconds();milliseconds=value.getUTCMilliseconds()}value=(year<=0||year>=1e4?(year<0?"-":"+")+toPaddedString(6,year<0?-year:year):toPaddedString(4,year))+"-"+toPaddedString(2,month+1)+"-"+toPaddedString(2,date)+"T"+toPaddedString(2,hours)+":"+toPaddedString(2,minutes)+":"+toPaddedString(2,seconds)+"."+toPaddedString(3,milliseconds)+"Z"}else{value=null}}else if(typeof value.toJSON=="function"&&(className!=numberClass&&className!=stringClass&&className!=arrayClass||isProperty.call(value,"toJSON"))){value=value.toJSON(property)}}if(callback){value=callback.call(object,property,value)}if(value===null){return"null"}className=getClass.call(value);if(className==booleanClass){return""+value}else if(className==numberClass){return value>-1/0&&value<1/0?""+value:"null"}else if(className==stringClass){return quote(""+value)}if(typeof value=="object"){for(length=stack.length;length--;){if(stack[length]===value){throw TypeError()}}stack.push(value);results=[];prefix=indentation;indentation+=whitespace;if(className==arrayClass){for(index=0,length=value.length;index<length;index++){element=serialize(index,value,callback,properties,whitespace,indentation,stack);results.push(element===undef?"null":element)}result=results.length?whitespace?"[\n"+indentation+results.join(",\n"+indentation)+"\n"+prefix+"]":"["+results.join(",")+"]":"[]"}else{forEach(properties||value,function(property){var element=serialize(property,value,callback,properties,whitespace,indentation,stack);if(element!==undef){results.push(quote(property)+":"+(whitespace?" ":"")+element)}});result=results.length?whitespace?"{\n"+indentation+results.join(",\n"+indentation)+"\n"+prefix+"}":"{"+results.join(",")+"}":"{}"}stack.pop();return result}};JSON3.stringify=function(source,filter,width){var whitespace,callback,properties,className;if(typeof filter=="function"||typeof filter=="object"&&filter){if((className=getClass.call(filter))==functionClass){callback=filter}else if(className==arrayClass){properties={};for(var index=0,length=filter.length,value;index<length;value=filter[index++],(className=getClass.call(value),className==stringClass||className==numberClass)&&(properties[value]=1));}}if(width){if((className=getClass.call(width))==numberClass){if((width-=width%1)>0){for(whitespace="",width>10&&(width=10);whitespace.length<width;whitespace+=" ");}}else if(className==stringClass){whitespace=width.length<=10?width:width.slice(0,10)}}return serialize("",(value={},value[""]=source,value),callback,properties,whitespace,"",[])}}if(!has("json-parse")){var fromCharCode=String.fromCharCode;var Unescapes={92:"\\",34:'"',47:"/",98:"\b",116:"  ",110:"\n",102:"\f",114:"\r"};var Index,Source;var abort=function(){Index=Source=null;throw SyntaxError()};var lex=function(){var source=Source,length=source.length,value,begin,position,isSigned,charCode;while(Index<length){charCode=source.charCodeAt(Index);switch(charCode){case 9:case 10:case 13:case 32:Index++;break;case 123:case 125:case 91:case 93:case 58:case 44:value=charIndexBuggy?source.charAt(Index):source[Index];Index++;return value;case 34:for(value="@",Index++;Index<length;){charCode=source.charCodeAt(Index);if(charCode<32){abort()}else if(charCode==92){charCode=source.charCodeAt(++Index);switch(charCode){case 92:case 34:case 47:case 98:case 116:case 110:case 102:case 114:value+=Unescapes[charCode];Index++;break;case 117:begin=++Index;for(position=Index+4;Index<position;Index++){charCode=source.charCodeAt(Index);if(!(charCode>=48&&charCode<=57||charCode>=97&&charCode<=102||charCode>=65&&charCode<=70)){abort()}}value+=fromCharCode("0x"+source.slice(begin,Index));break;default:abort()}}else{if(charCode==34){break}charCode=source.charCodeAt(Index);begin=Index;while(charCode>=32&&charCode!=92&&charCode!=34){charCode=source.charCodeAt(++Index)}value+=source.slice(begin,Index)}}if(source.charCodeAt(Index)==34){Index++;return value}abort();default:begin=Index;if(charCode==45){isSigned=true;charCode=source.charCodeAt(++Index)}if(charCode>=48&&charCode<=57){if(charCode==48&&(charCode=source.charCodeAt(Index+1),charCode>=48&&charCode<=57)){abort()}isSigned=false;for(;Index<length&&(charCode=source.charCodeAt(Index),charCode>=48&&charCode<=57);Index++);if(source.charCodeAt(Index)==46){position=++Index;for(;position<length&&(charCode=source.charCodeAt(position),charCode>=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}charCode=source.charCodeAt(Index);if(charCode==101||charCode==69){charCode=source.charCodeAt(++Index);if(charCode==43||charCode==45){Index++}for(position=Index;position<length&&(charCode=source.charCodeAt(position),charCode>=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}return+source.slice(begin,Index)}if(isSigned){abort()}if(source.slice(Index,Index+4)=="true"){Index+=4;return true}else if(source.slice(Index,Index+5)=="false"){Index+=5;return false}else if(source.slice(Index,Index+4)=="null"){Index+=4;return null}abort()}}return"$"};var get=function(value){var results,hasMembers;if(value=="$"){abort()}if(typeof value=="string"){if((charIndexBuggy?value.charAt(0):value[0])=="@"){return value.slice(1)}if(value=="["){results=[];for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="]"){break}if(hasMembers){if(value==","){value=lex();if(value=="]"){abort()}}else{abort()}}if(value==","){abort()}results.push(get(value))}return results}else if(value=="{"){results={};for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="}"){break}if(hasMembers){if(value==","){value=lex();if(value=="}"){abort()}}else{abort()}}if(value==","||typeof value!="string"||(charIndexBuggy?value.charAt(0):value[0])!="@"||lex()!=":"){abort()}results[value.slice(1)]=get(lex())}return results}abort()}return value};var update=function(source,property,callback){var element=walk(source,property,callback);if(element===undef){delete source[property]}else{source[property]=element}};var walk=function(source,property,callback){var value=source[property],length;if(typeof value=="object"&&value){if(getClass.call(value)==arrayClass){for(length=value.length;length--;){update(value,length,callback)}}else{forEach(value,function(property){update(value,property,callback)})}}return callback.call(source,property,value)};JSON3.parse=function(source,callback){var result,value;Index=0;Source=""+source;result=get(lex());if(lex()!="$"){abort()}Index=Source=null;return callback&&getClass.call(callback)==functionClass?walk((value={},value[""]=result,value),"",callback):result}}}if(isLoader){define(function(){return JSON3})}})(this)},{}],50:[function(_dereq_,module,exports){module.exports=toArray;function toArray(list,index){var array=[];index=index||0;for(var i=index||0;i<list.length;i++){array[i-index]=list[i]}return array}},{}]},{},[1])(1)});define("pubsub",["ext/underscore","app-context","io"],function(_,appContext,io){var $=jQuery;var groupIdMap={};var getGroupId=function(conversationId,callback){if(groupIdMap[conversationId]){callback(groupIdMap[conversationId])}else{$.ajax({url:appContext.fullUrl("/v2/messages/"+conversationId+"/participants"),success:function(participants){_.assert(participants.length==1,"only 1 participant expected");var idParts=participants[0].id.split(":");_.assert(idParts[1]=="group","not a group participant: "+idParts[1]);groupIdMap[conversationId]={id:idParts[3],name:participants[0].name};callback(groupIdMap[conversationId])},error:function(jqXHR,textStatus,errorThrown){console.log(JSON.stringify(jqXHR));console.log(JSON.stringify(textStatus));console.log(JSON.stringify(errorThrown));appContext.navigate("#error",true)}})}};var createSocket=function(accessToken){console.log("creating socket ..");var socket=io.connect(appContext.resolvePubsubEndPoint()+"?auth_type=token&token="+accessToken.access_token+"&subscribe=chat");socket.on("connect",function(){setInterval(function(){socket.emit("ping")},3e4)});socket.on("buddies",function(conversation,buddies){$(".receiver-"+conversation).trigger("buddies",buddies)});socket.on("chat-message",function(message){var receiver=$(".receiver-"+message.conversation);if(receiver.length==1){receiver.trigger("chatmsg",message)}else{if(message.type=="text"){getGroupId(message.conversation,function(group){appContext.addNotification({title:'Chat message in group "'+group.name+'"',target:"#messages/groups:@"+group.id,text:message.body})})}}});socket.on("unread",function(conversations){_.each(conversations,function(conversation){getGroupId(conversation.id,function(group){appContext.addNotification({title:'Chat message in group "'+group.name+'"',target:"#messages/groups:@"+group.id})})})});return socket};var socket=null;var accessToken=appContext.getAccessToken();if(accessToken){socket=createSocket(accessToken)}appContext.on("accessToken",function(){if(socket){socket.removeAllListeners("unread");socket.removeAllListeners("chat-message");socket.removeAllListeners("buddies");socket.removeAllListeners("connect")}socket=createSocket(appContext.getAccessToken())});return{emit:function(event,data){if(!socket){throw"no socket available"}socket.emit(event,data)}}});define("api/model/message",["ext/underscore","moment","api/model/base"],function(_,moment,BaseModel){return BaseModel.extend({initialize:function(attributes,options){this.principle=options.principle;this.created=new Date},getSourceId:function(){var source=this.get("source");return source?source.id.split(":")[3]:this.principle.id},getSourceName:function(){var source=this.get("source");return source?source.name:this.principle.name},getDateReceived:function(){var date=moment(this.get("dateReceived"));return date?new Date(moment(date,"YYYY-MM-DDTHH:mm:ss.SSSZ").valueOf()):this.created},isType:function(){return this.get("type")=="type"},isTyping:function(){_.assert(this.isType(),"not a type message");return this.get("body")=="yes"},noThumb:function(){var noThumb=_.find(this.get("properties"),function(property){return property=="nothumb"});return!!noThumb}})});define("api/collection/messages",["api/collection/base","api/model/message"],function(BaseCollection,Message){return BaseCollection.extend({model:Message,initialize:function(models,options){if(options.current){this.conversation=options.current.conversation;if(options.current.offset){this.params={offset:options.current.offset}}else if(options.current.length>0){this.params={"condition.offset":options.current.length}}}else{this.conversation=options.conversation}},url:function(){return"/v2/messages/"+this.conversation.id+"/history"},parse:function(response){if(response instanceof Array){this.more=response.length>0;return response}this.offset=response.offset;this.more=response.more;return response.items;
     21
     22},addPage:function(page){this.add(page.models);this.offset=page.offset;this.more=page.more},comparator:function(model){return-model.getDateReceived().getTime()}})});define("text!text/message/item.html",[],function(){return'\n<% if (noThumb()) { %>\n   <img src="<%= appurl %>/styles/images/default_thumbnail.png">\n<% } else { %>\n <img src="<%= cdn %>/users/<%= getSourceId() %>/thumbnail">\n<% } %>\n<div class="info <% if (getSourceId() == me.id) { print(\'self\') } %>">\n    <p>\n       <strong class="name"><%= getSourceName() %></strong>\n      <abbr data-time="<%= getDateReceived().getTime() %>" class="timeago">\n         <%= $.timeago(getDateReceived()) %>\n       </abbr>\n   </p>\n  <p class="body"><%= get(\'body\') %></p>\n</div>    \n'});define("view/message/item",["ext/underscore","app-context","view/base","text!text/message/item.html"],function(_,appContext,BaseView,template){var $=jQuery;return BaseView.extend({tagName:"li",events:{"click div.self":"update"},initialize:function(options){_.bindToMethods(this);this.options=options;this.model.on("change",this.change)},render:function(){var args=_.extend({cdn:appContext.cdn,me:appContext.getPrinciple()},this.model);this.$el.html(this.template(template,args));return this},change:function(){$(".body",this.$el).html(this.model.get("body"))},update:function(){this.options.inputView.update(this.model)}})});define("text!text/message/input.html",[],function(){return'<textarea placeholder="<%= m_message_placeholder %>"></textarea>\n<a href="javascript:void(0)" class="send hidden">\n <span class="glyphicon glyphicon-send"></span>\n</a>\n<div class="update-btns hidden">\n    <a href="javascript:void(0)" class="update">\n      <span class="glyphicon glyphicon-ok"></span>\n  </a>\n  <a href="javascript:void(0)" class="cancel">\n      <span class="glyphicon glyphicon-remove"></span>\n  </a>\n</div>\n'});define("view/message/input",["ext/underscore","view/base","app-context","pubsub","text!text/message/input.html"],function(_,BaseView,appContext,pubsub,template){var $=jQuery;return BaseView.extend({back:{code:"m_btn_context",link:"#context"},className:"messages-input",events:{"keyup textarea":"keyup","click .send,.update":"send","click .cancel":"cancel"},initialize:function(options){_.bindToMethods(this);this.options=options},render:function(){this.$el.html(this.template(template));this.$input=$("textarea",this.$el);this.$send=$(".send",this.$el);return this},keyup:function(){if(_.trim(this.$input.val()).length==0){if(this.target){this.cancel()}else{this.stopTyping;this.sendBtn(false)}}else{if(!this.typing){this.emitMessage("type","yes")}this.typing=true;this.stopTyping_debounced();if(!this.target){this.sendBtn(true)}}},send:function(){var body=_.trim(this.$input.val()).replace(/\n/gm,"<br/>");if(this.target){this.emitMessage("update",body,this.target);this.cancel()}else{this.emitMessage("text",body);this.$input.val("");this.stopTyping();this.sendBtn(false)}},cancel:function(){this.target=null;this.$input.val("");this.updateBtns(false);this.stopTyping()},emitMessage:function(type,body,target){var conversationId=this.options.conversation.id;var message={conversation:conversationId,deliveryId:conversationId+Math.random().toString(36).substr(2),body:body,type:type,properties:[]};if(typeof target!="undefined"){message.id=target.id;message.deliveryId=target.get("deliveryId")}if(!appContext.getPrinciple().logo){message.properties.push("nothumb")}pubsub.emit("chat-message",message);$(".receiver-"+conversationId).trigger("chatmsg",message)},stopTyping:function(){this.emitMessage("type","no");this.typing=false},stopTyping_debounced:_.debounce(function(){this.stopTyping()},5e3),update:function(message){this.target=message;this.$input.val(message.get("body").replace(/<br ?\/>/g,"\n")).focus();this.sendBtn(false);this.updateBtns(true)},updateBtns:function(show){var $btns=$(".update-btns",this.$el);if(show){$btns.removeClass("hidden");this.$input.width(this.$el.width()-65)}else{$btns.addClass("hidden");this.$input.css("width","100%")}},sendBtn:function(show){if(show){this.$send.removeClass("hidden");this.$input.width(this.$el.width()-40)}else{this.$send.addClass("hidden");this.$input.css("width","100%")}}})});define("view/message/list",["ext/underscore","app-context","view/page","api/collection/messages","api/model/message","view/navbar-factory","view/message/item","view/message/input"],function(_,appContext,PageView,Messages,Message,navbarFactory,MessageItemView,MessageInputView){var $=jQuery;return PageView.extend({back:{code:"m_btn_context",link:"#context"},tagName:"ul",className:"messages list-unstyled",events:{buddies:"receiveBuddies",chatmsg:"receiveMessage"},initialize:function(options){PageView.prototype.initialize.apply(this,arguments);this.title=_.escape(this.collection.conversation.group.get("friendlyName"));this.timer=setInterval(this.updateTime,6e4)},render:function(){PageView.prototype.render.apply(this,arguments);this.inputView=new MessageInputView({conversation:this.collection.conversation});this.addFooter(this.inputView.render().$el);this.$el.addClass("receiver-"+this.collection.conversation.id);this.$header=$("<div>").addClass("messages-header");this.addHeader(this.$header);this.retrievePage();return this},receiveBuddies:function(){$("img",this.$header).remove();for(var i=1;i<arguments.length;i++){var src=appContext.defaultThumb;if(arguments[i].logo){src=appContext.cdn+"/users/"+arguments[i].id+"/thumbnail"}$("<img>").addClass("user-"+arguments[i].id).attr("src",src).appendTo(this.$header)}},receiveMessage:function(e,message){message=new Message(message,{principle:appContext.getPrinciple()});if(message.isType()){if(message.isTyping()){if(message.get("source")){var html=message.get("source").name+" typing..";$("<li>").addClass("typing").html(html).appendTo(this.$el)}}else{$("li.typing",this.$el).remove()}}else{var target=this.collection.findWhere({deliveryId:message.get("deliveryId")});if(target){target.set("body",message.get("body"))}else{var itemView=new MessageItemView({model:message,inputView:this.inputView});this.$el.append(itemView.render().el);this.collection.add(message)}}this.scrollToEnd()},retrievePage:function(){var messages=new Messages([],{current:this.collection});messages.once("sync",this.renderPage);messages.fetch()},renderPage:function(messages){var $first=$("li",this.$el).first();messages.each(function(message){var itemView=new MessageItemView({model:message,inputView:this.inputView});this.$el.prepend(itemView.render().el)},this);if(this.collection.length==0){this.scrollToEnd()}else{this.scroll($first.position().top-1)}messages.more&&_.defer(_.bind(function(){$("li",this.$el).first().one("inview",this.retrievePage)},this));this.collection.addPage(messages)},scrollToEnd:function(){var last=$("li",this.$el).last();if(last.length>0){this.scroll(last.position().top+last.height())}},updateTime:function(){$("abbr.timeago",this.$el).each(function(){var $abbr=$(this);$abbr.html($.timeago(new Date($abbr.data("time"))))})},remove:function(){PageView.prototype.remove.apply(this,arguments);clearInterval(this.timer);this.removeMarginal(this.$header);this.removeMarginal(this.inputView.$el)},navbar:function(callback){this.navbarCreate("messages",this.collection.conversation.group.id,callback)}}).extend(navbarFactory)});define("api/model/conversation",["api/model/base"],function(BaseModel){return BaseModel.extend({initialize:function(attributes,options){this.group=options.group},url:function(){return this.group.url()+"/conversation"}})});define("router/message",["ext/underscore","router/group","app-context","pubsub","view/message/list","api/model/conversation","api/collection/messages"],function(_,GroupRouter,appContext,pubsub,MessageListView,Conversation,Messages){var $=jQuery;var showMessages=function(conversation){var view=new MessageListView({collection:new Messages([],{conversation:conversation})});view.render();pubsub.emit("buddies-notify",conversation.id);$.ajax({type:"POST",url:appContext.fullUrl("/v2/messages"),data:JSON.stringify({conversations:[conversation.id]}),error:function(){appContext.navigate("#error",true)},contentType:"application/json"})};return GroupRouter.extend({routes:{"messages/:groupKey":"getConversation"},getConversation:function(group){var conversation=new Conversation({},{group:group});conversation.once("sync",showMessages);conversation.fetch()}})});requirejs.config({baseUrl:"app",paths:{io:"lib/socket.io","native":"../native","underscore.string":"lib/underscore.string",moment:"lib/moment.min"},shim:{"lib/iscroll":{exports:"iScroll"}}});define("$root",[],function(){return jQuery("#clinked-portal")});require(["app-context","router/default","router/update","router/file","router/note","router/discussion","router/event","router/task","router/comment","router/share-token","router/message"],function(appContext,DefaultRouter,UpdateRouter,FileRouter,NoteRouter,DiscussionRouter,EventRouter,TaskRouter,CommentRouter,ShareTokenRouter,MessageRouter){new DefaultRouter;new UpdateRouter;new FileRouter;new NoteRouter;new DiscussionRouter;new EventRouter;new TaskRouter;new CommentRouter;new ShareTokenRouter;new MessageRouter;Backbone.history.start({silent:true});appContext.start(function(options){console.log("initialising: "+JSON.stringify(options));appContext.navigate(options.location?options.location:"#start",true)})});define("main",function(){});
  • clinked-client-portal/trunk/clinked-portal.php

    r1209081 r1355844  
    55Description: The Clinked Client Portal plugin is a great addition to the popular <a href="http://clinked.com">Clinked application</a> - a branded, feature rich client portal. Using the plugin couldn't be easier. Simply include the shortcode <strong>[clinked_portal]</strong> in the desired page and you're done. If you don't already have an account visit our website and <a href="http://clinked.com/packages">sign up</a> for a free trial.
    66Author: Clinked
    7 Version: 1.3
     7Version: 1.4
    88Author URI: http://clinked.com
    99License: GPLv2
  • clinked-client-portal/trunk/readme.txt

    r1209077 r1355844  
    44Requires at least: 3.0
    55Tested up to: 4.1
    6 Stable tag: 1.3
     6Stable tag: 1.4
    77License: GPLv2
    88License URI: http://www.gnu.org/licenses/gpl-2.0.html
     
    9393== Changelog ==
    9494
     95= 1.4 =
     96* Fix for Navbar not showing under some installations.
     97* Fixed chat module.
     98
    9599= 1.3 =
    96100* Custom branding feature.
     
    107111== Upgrade Notice ==
    108112
     113= 1.4 =
     114This upgrade includes a fix for the Navbar not showing under some installations.
     115
    109116= 1.3 =
    110117This upgrade allows for custom branding.
Note: See TracChangeset for help on using the changeset viewer.