json-object-editor 0.10.653 → 0.10.657

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/js/joe.min.js CHANGED
@@ -1 +1 @@
1
- $c.isMobile()?document.getElementsByTagName("html")[0].className+=" touch joesmall-size":document.getElementsByTagName("html")[0].className+=" no-touch joelarge-size",window._joeEditingHash=!1;var _webworkers=!1,_joeworker;window.Worker&&(_webworkers=!0);var joe_web_dir="//"+location.hostname+":"+(location.port||("https:"==location.protocol?443:80))+"/JsonObjectEditor/",__gotoJoeSection;function __require(file,callback){var head=document.getElementsByTagName("head")[0],script=document.createElement("script");script.src=file,script.type="text/javascript",script.onload=callback,script.onreadystatechange=function(){"complete"==this.readyState&&callback()},head.appendChild(script)}function JsonObjectEditor(specs){var self=this,htmlRef=document.getElementsByTagName("html")[0];self.initialDocumentTitle=document.title,$c.TEMPLATE_VARS.push({variable:"/textarea",value:"</textarea>"},{variable:"textarea",value:"<textarea>"},{variable:"SERVER",value:"//"+$c.SERVER});var initialized=!1,colCount=1,listMode=!1,gridMode=!1,tableMode=!1,tableSpecs,multiEdit=!1;this.VERSION="1.0.1",window._joes=window._joes||[],this.joe_index=window._joes.length,window._joes.length||(window._joe=this),this.Error={log:[],add:function(message,error,data){var payload={caller:arguments.callee.caller,callerargs:arguments.callee.caller.arguments,message:message,error:error,stack:new Error(error).stack,data:data,timestamp:(new Date).toISOString(),_id:cuid()};self.Error.log.push(payload),logit("[error]: "+message)},show:function(){self.show(self.Error.log,{schema:{title:"${message}",idprop:"_id",listView:{title:"<joe-title>${message}</joe-title><joe-subtitle>${timestamp}</joe-subtitle>",listWindowTitle:"Errors"},fields:["error:code","message","stack:code",{name:"data",type:"content",run:function(data,obj){return"<div><pre>"+tryEval(data)+"</pre></div>"}},"callerargs:code","timestamp:guid","_id"]}})}},window._joes.push(this),this.Cache={static:{},list:[],lookup:{},clear:function(){self.Cache.lookup={},self.Cache.list=[]},remove:function(id){},get:function(id,specs){var cacheitem=self.Cache.lookup[id];if(cacheitem&&"function"==typeof cacheitem.value&&"callback"==cacheitem.type)return cacheitem.value(cacheitem.data,cacheitem.id);if(!cacheitem){var obj=self.search(id)[0]||!1;return!!obj&&(self.Cache.add(obj,{id:id}),obj)}return cacheitem.value},callback:function(id){var cacheitem=self.Cache.lookup[id];if("function"==typeof cacheitem.value)return cacheitem.value(cacheitem.data,cacheitem.id);logit("cache item is not a function")},add:function(value,specs){specs=specs||{};var obj=$.extend({id:specs.id||cuid(),value:value,parent:self.joe_index},specs);return self.Cache.list.push(obj.id),self.Cache.lookup[obj.id]=obj,obj}},this.Cache.set=this.Cache.add,this.history=[];var defaults={localStorage:!1,container:"body",joeprofile:{lockedFields:["joeUpdated"],hiddenFields:[]},profiles:{},fields:{},schemas:{rendering:{title:"HTML Rendering",callback:function(){alert("yo")}}},compact:!1,useControlEnter:!0,useEscapeKey:!1,autoInit:!1,autosave:1e4,dynamicDisplay:$(window).height()<800&&$c.isMobile()?12:20,sans:!1,listSubMenu:!0,documentTitle:!1,style:{inset:!0,cards:!1},speechRecognition:!1},goingBackFromID,goingBackQuery;for(var s in this.specs=$.extend({},defaults,specs||{}),this.specs.localStorage&&"undefined"==typeof Storage&&(alert("no local storage"),this.specs.LocalStorage=!1),this.Indexes={_add:function(idprop,dataitem){self.Indexes[idprop]=self.Indexes[idprop]||{},self.Indexes[idprop][dataitem[idprop]]=dataitem},_usage:0},this.Printer={init:function(){document.querySelector("print-joe")||document.body.appendChild(document.createElement("print-joe"))},print:function(){self.Printer.init();var cln=document.getElementsByTagName("joe-panel-content")[0].cloneNode(!0);document.querySelector("print-joe").innerHTML="",document.querySelector("print-joe").appendChild(cln);var panelContent=document.querySelector("print-joe joe-panel-content");panelContent.className="joe-panel-content";var activeNodes=document.querySelectorAll("print-joe joe-panel-content .joe-content-section.active");if(activeNodes.length){panelContent.innerHTML="";for(var i=0;i<activeNodes.length;i++)panelContent.appendChild(activeNodes[i])}window.print(),document.querySelector("print-joe").innerHTML=""}},this.Data={},this.Render={schema_icon:function(schema,classes){var icon=self.schemas[schema]&&self.schemas[schema].menuicon||"";return icon&&(icon=`<joe-icon class="${classes||""}">${icon}</joe-icon>`),icon},ref_chip:function(things,specs){specs="string"==typeof specs?{cssclass:specs}:specs||{};const items=Array.isArray(things)?things:things?.tags||[];if(!items.length)return"";const labelProp=specs.labelProp||"name",tooltipProp=!1===specs.tooltipProp?null:specs.tooltipProp||"info";let html=`<joe-chips class="${specs.cssclass||""}">`;return items.forEach(ref=>{const obj="object"==typeof ref?ref:$J.get(ref);if(!obj)return;const label=obj[labelProp]||"",title=tooltipProp&&obj[tooltipProp]?` title="${obj[tooltipProp]}"`:"";let style="";if(specs.useStatusColor&&obj.status){const statusObj=_joe.Cache.get(obj.status);statusObj?.color&&(style=` style="border-left:4px solid ${statusObj.color}"`)}else obj.color&&(style=` style="background:${obj.color}"`);html+=`<joe-chip data-id="${obj._id}"${title}${style}>${label}</joe-chip>`}),html+="</joe-chips>",html}},this.container=$(this.specs.container),this.fields=this.specs.fields,this.Fields={reset:function(propname){var field=self.Fields.get(propname);self.current.object[propname]=field.reset,self.Fields.rerender(propname)},onPanelShow:function(cur){cur=cur||_jco();var currentFields=self.current.fields;logit("current fields",currentFields),currentFields.map(f=>{f.onPanelShow&&f.onPanelShow(cur)})}},this.schemas=this.specs.schemas,_joe.schemas)_joe.schemas[s].__schemaname=_joe.schemas[s].name=s,_joe.schemas[s]._id=cuid();function createTitleObject(specs){specs=specs||{};var titleObj=$.extend({},self.current.object),list=specs.list||self.current.list;if(list){var lcount=list.length;self.current.subset&&(lcount=list.where(self.current.subset.filter).length),titleObj._listCount=lcount||"0",titleObj._subsetName=self.current.subset&&self.current.subset.name+" "||""}self.current.title=specs.title||self.getCascadingProp("title")||self.current.schema&&"new "+self.current.schema.__schemaname||"Json Object Editor",self.current.subtitle=specs.subtitle||self.getCascadingProp("subtitle");var title=fillTemplate(self.propAsFuncOrValue(self.current.title),titleObj),subtitle=fillTemplate(self.propAsFuncOrValue(self.current.subtitle),titleObj);return titleObj.docTitle=title,titleObj.subTitle=subtitle,titleObj}function renderSubmenuButtons(buttons){var content,html="";if(buttons=self.propAsFuncOrValue(buttons||listMode&&self.getCascadingProp("headerListMenu")||!listMode&&self.getCascadingProp("headerMenu"))){var h=self.renderMenuButtons(buttons,"joe-submenu-button");h&&(content=!0),html+=h}return{html:html,content:content}}function renderSectionAnchors(){var anchorhtml='<joe-submenu-section-anchors><joe-panel-button class="sections-toggle" onclick="'+getSelfStr+'.Sections.toggle(this);">'+self.SVG.icon.sections+" <joe-button-label>"+(self.current.sections&&self.current.sections.count()||"")+" sections</joe-button-label></joe-panel-button>";anchorhtml+='<div class="joe-submenu-section" onclick="_joe.Sections.gotoTop('+self.joe_index+')">^ top</div>';var section,scount=0,template='<joe-submenu-section class="joe-submenu-section f${renderTo}" data-section="${name}" data-panel="${renderTo}" '+('onclick="getJoe('+self.joe_index+").gotoSection('${id}');\"")+" "+('ondblclick="getJoe('+self.joe_index+").gotoSection('${id}',{focus:'${id}'});\"")+">${${anchor}||${name}}</joe-submenu-section>";for(var secname in self.current.sections)(section=_getSection(secname)).hidden||(anchorhtml+=fillTemplate(template,section),scount++);return{count:scount,code:anchorhtml+="<div class='clear'></div></joe-submenu-section-anchors>"}}this.current={},this.current.clear=function(){self.current.list=null,self.current.subsets=null,self.current.subset=null,self.current.filters={},self.current.fields=[],self.current.schema=null,self.current.object=null,self.current.reset={},self.current.cache={},self.current.title=null,self.current.keyword="",1==_joes.length&&(document.title=self.initialDocumentTitle)},this.defaultProfile=this.specs.defaultProfile||this.specs.joeprofile,this.current.profile=this.defaultProfile,this.ace_editors={},this.Render.stripeColor=function(opt,colorfunc){var color=self.propAsFuncOrValue(colorfunc||opt.stripecolor,opt,null,_jco()),title="";return color&&$c.isObject(color)&&(title=' title="'+color.title+'" ',color=color.color),"<joe-stripe-color "+title+(color&&'style="background-color:'+color+';"'||"")+"></joe-stripe-color>"},this.Render.bgColor=function(opt,colorfunc){var color=self.propAsFuncOrValue(colorfunc||opt.bgcolor,opt,null,_jco());return color&&$c.isObject(color)&&(color=color.color),"<joe-bg-color "+(color&&'style="background-color:'+color+';"'||"")+"></joe-bg-color>"},this.Render.itemCheckbox=function(listItem,schema,specs){specs=specs||{};var checkbox=self.propAsFuncOrValue(self.getCascadingProp("checkbox",schema),listItem),idprop=specs.idprop||self.getIDProp();if(checkbox){var cbox_prop=checkbox,cbox_percentage=null,cbox_title="";"object"==$.type(checkbox)&&(cbox_prop=checkbox.prop,cbox_title=checkbox.title||cbox_prop,cbox_percentage=self.propAsFuncOrValue(checkbox.percentage,listItem));var cb_label=self.propAsFuncOrValue(checkbox.label,listItem);checkbox='<joe-checkbox title="'+cbox_title+'" class="'+([!0,"true"].contains(listItem[cbox_prop])?"checked":"")+'"onclick="_joe.checkItem(\''+listItem[idprop]+"','"+cbox_prop+"',null,this)\">"+(!1!==cbox_percentage&&checkbox.hasOwnProperty("percentage")?"<joe-checkbox-percentage>"+Math.round(100*cbox_percentage)+"%</joe-checkbox-percentage>":"")+(cb_label&&"<joe-checkbox-label>"+cb_label+"</joe-checkbox-label>"||"")+"</joe-checkbox>"}else checkbox="";return checkbox},this.init=function(callback){if(initialized)return!1;beginLogGroup("JOE init"),self.current.clear();var respond_timeout,html=self.renderFramework(self.renderEditorHeader()+self.renderEditorContent()+self.renderEditorFooter());self.container.append(html),self.overlay=$(".joe-overlay[data-joeindex="+self.joe_index+"]"),self.panel=self.overlay.find(".joe-overlay-panel"),self.initKeyHandlers(),self.Speech.init(),self.readHashLink(),window.addEventListener("hashchange",function(newH,oldH){if(!($GET("!")||location.hash)||0!=self.joe_index||!specs.useHashlink)return!1;window._joeEditingHash||self.readHashLink()},!1),$(window).on("resize",function(){self.resizeOk()&&(clearTimeout(respond_timeout),respond_timeout=setTimeout(self.respond,200))}),self.initButtons(),initialized=!0,self.respond(),endLogGroup(),self.Components.init(),callback&&callback()},this.initButtons=function(){$(document).on("click","joe-button",function(e){e.preventDefault();var actionName=$(this).attr("action");if(actionName){var currentObject=_joe.current?_joe.current.object:null,currentSchema=_joe.current&&_joe.current.schema,currentSchemaMethods=currentSchema?currentSchema.methods:null;JOE.async&&"function"==typeof JOE.async[actionName]?JOE.async[actionName](currentObject,e):currentSchemaMethods&&"function"==typeof currentSchemaMethods[actionName]?currentSchemaMethods[actionName](currentObject,e):console.warn("No method found for joe-button action:",actionName)}else console.warn("No action defined for joe-button")})},this.resizeOk=function(){return!$c.isMobile()||"INPUT"!=document.activeElement.tagName},this.initKeyHandlers=function(){self.specs.useBackButton&&(window.onkeydown=function(e){var code=e.keyCode,isInputElement=-1!=["input","select","textarea"].indexOf(e.target&&e.target.tagName&&e.target.tagName.toLowerCase()||""),isEditable=e.target.isContentEditable||$(e.target).closest("joe-ai-chatbox").length||$(e.target).closest("joe-ai-widget").length;if(8==code)return isInputElement||isEditable?void 0:(self.goBack(),!1);if(-1==[37,39,38,40,13,16,17,27].indexOf(code)){if(e.altKey)switch(code){case 70:self.quickFind(),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault();break;case 78:self.quickAdd(),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault();break;case 80:self.Printer.print(),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()}else if(listMode){$(document.activeElement)&&$(document.activeElement)[0]!=$(".joe-submenu-search-field")[0]&&(self.overlay.find(".joe-submenu-search-field").focus(),$(".joe-panel-content-option.keyboard-selected").removeClass("keyboard-selected"))}else if((e.ctrlKey||e.metaKey)&&83===code)self.container.find(".joe-button.joe-quicksave-button").length&&(self.updateObject(null,null,!0),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault())}else{if($(".joe-text-autocomplete.active").length){var sel=".joe-text-autocomplete-option.visible.keyboard-selected",keyboardSelected=$(sel)[0],keyboardSelectedIndex=$(sel).length?$(sel).index():-1;switch(code){case 38:--keyboardSelectedIndex>-1&&keyboardSelectOption(".joe-text-autocomplete-option.visible");break;case 40:++keyboardSelectedIndex<$(".joe-text-autocomplete-option.visible").length&&keyboardSelectOption(".joe-text-autocomplete-option.visible");break;case 13:-1!=keyboardSelectedIndex&&keyboardSelected.click()}}if(listMode)if(e.altKey){if(self.current.subsets){var subindex=self.current.subsets.indexOf(self.current.subset)+1;switch(code){case 38:$("joe-subset-option").eq(subindex-1).click();break;case 40:$("joe-subset-option").eq(subindex+1).click()}}}else{keyboardSelectedIndex=$(".joe-panel-content-option.keyboard-selected").length?$(".joe-panel-content-option.keyboard-selected").index():-1;switch(code){case 38:--keyboardSelectedIndex>-1&&keyboardSelectOption(".joe-panel-content-option",top);break;case 40:++keyboardSelectedIndex<currentListItems.length&&keyboardSelectOption(".joe-panel-content-option",top);break;case 13:-1!=keyboardSelectedIndex&&$(".joe-panel-content-option.keyboard-selected").find(".joe-panel-content-option-content").click()}}else if(e.altKey)switch(code){case 219:case 221:var sside=219==code?"left":"right";self.current.sidebars[sside].content&&!self.current.sidebars[sside].hidden&&self.toggleSidebar(sside)}else if(e.ctrlKey)switch(code){case 37:self.previous();break;case 39:self.next()}else if(13==code){var ae=$(document.activeElement);if(ae&&ae.is("input")){var fieldobj=ae.parents(".joe-object-field");if(fieldobj.length)try{fieldobj.find(".joe-plus-button").click()}catch(e){self.Error.add("adding new row to objectlist",e)}}}function keyboardSelectOption(selector,top){$(selector+".keyboard-selected").toggleClass("keyboard-selected");var el=$(selector).eq(keyboardSelectedIndex);el.addClass("keyboard-selected"),self.overlay.find(".joe-submenu-search-field").blur(),el[0].scrollIntoView(top)}}})},this.getMode=function(){return listMode&&self.current.list?"list":self.current.object?"details":!!self.current.list&&"list"},this.renderFramework=function(content){return'<joe-overlay class="joe-overlay sans cols-'+colCount+" style-variant1 "+(self.specs.compact?" compact ":"")+(self.specs.sans?" sans ":"")+'" data-joeindex="'+this.joe_index+'"><joe-panel class="joe-overlay-panel">'+(content||"")+'</joe-panel><div class="joe-mini-panel"></div></joe-overlay>'},this.populateFramework=function(data,setts){self.current.cache={},self.overlay.removeClass("multi-edit");var joePopulateBenchmarker=new Benchmarker;self.current.reset=self.current.reset||{},beginLogGroup("JOE population");var specs=setts||{};self.current.specs=setts,self.current.data=data,self.current.userSpecs=$.extend({},setts),gridMode="grid"==self.current.specs.viewMode,tableMode="table"==self.current.specs.viewMode,self.current.specs.noHistory||self.history.push({specs:self.current.userSpecs,data:self.current.data});var currentSubsets,schema=setts.schema||"",profile=setts.profile||null,callback=setts.callback||null,datatype=setts.datatype||"",title=setts.title||"";(self.current.callback=callback||null,"string"==$.type(data)&&"string"!=datatype&&self.getDataset(data,{boolean:!0})&&(!specs.schema&&self.schemas[data]&&(schema=data),data=self.getDataset(data)),specs.schema=this.setSchema(schema),colCount=self.current.specs.colCount||specs.schema&&specs.schema.colCount||1,"small-size"==self.sizeClass&&(colCount=1),specs.preformat=specs.schema&&specs.schema.preformat||specs.preformat||function(d){return d},data=specs.preformat(data),"object"!=$.type(data)&&"object"!=datatype||(specs.object=data,specs.menu=specs.menu||specs.schema&&specs.schema.menu||self.specs.menu||specs.multiedit&&__defaultMultiButtons||__defaultObjectButtons,specs.mode="object",self.current.object=data),self.toggleMultiEditMode(specs,data),listMode=!1,"array"==$.type(data)||"array"==datatype)&&(listMode=!0,specs.list=data,specs.menu=specs.listMenu||specs.schema&&specs.schema.listMenu||__defaultButtons,specs.mode="list",self.current.list=data,"function"==typeof(currentSubsets=setts.subsets||specs.schema&&specs.schema.subsets||null)&&(currentSubsets=currentSubsets()),self.current.specs.subset&&currentSubsets&&currentSubsets.where({$or:[{name:specs.subset},{id:specs.subset},{group_start:specs.subset}]}).length?self.current.subset=currentSubsets.where({$or:[{name:specs.subset},{id:specs.subset},{group_start:specs.subset}]})[0]||!1:"All"==self.current.specs.subset?self.current.subset={name:"All",filter:{}}:self.current.subset=currentSubsets&&currentSubsets.where({default:!0})[0]||null,self.current.subsets=currentSubsets,self.current.sorter=setts.sorter||self.current.subset&&self.current.subset.sorter||specs.schema&&specs.schema.sorter||"name","string"==$.type(self.current.sorter)&&(self.current.sorter=[self.current.sorter]));"list"==specs.mode?self.current.submenu=self.current.specs.listsubmenu||self.current.specs.submenu||specs.schema&&specs.schema.listSubMenu||self.specs.listSubMenu:self.current.submenu=self.current.specs.submenu||specs.schema&&specs.schema.subMenu||self.specs.subMenu,"none"==self.current.submenu&&(self.current.submenu=null),"string"==$.type(data)&&"rendering"==datatype?(specs.rendering=data,specs.menu=[__replaceBtn__],specs.mode="rendering",self.current.rendering=specs.rendering):"string"!=$.type(data)&&"string"!=datatype||(specs.text=data,specs.menu=__defaultButtons,specs.mode="text",self.current.text=specs.text),specs.listWindowTitle=specs.list&&(specs._listMenuTitle||specs._listWindowTitle||self.getCascadingProp("listWindowTitle")||getProperty("specs.list.windowTitle")||specs.schema&&(specs.schema._listMenuTitle||specs.schema._listWindowTitle))||!1,specs.title=specs.listWindowTitle||title||specs.schema&&(specs.schema.title||specs.schema._title)||"Viewing "+(self.current.schema&&self.current.schema.__schemaname||"string"==typeof self.current.userSpecs.schema&&self.current.userSpecs.schema||specs.mode).capitalize(),specs.profile=profile&&self.specs.profiles[profile]||self.specs.joeprofile,self.current.profile=specs.profile,self.cleanUp(),tableSpecs=self.current.schema&&(self.current.schema.table||self.current.schema.tableView)?$.extend({cols:["name",self.getIDProp()]},self.current.schema&&(self.current.schema.table||self.current.schema.tableView)||{}):null;var contentBM=new Benchmarker;beginLogGroup("Content");var content=self.renderEditorContent(specs);endLogGroup(),_bmResponse(contentBM,"JOE [Content]");var chromeBM=new Benchmarker,html=self.renderEditorHeader(specs)+self.renderEditorSubmenu(specs)+content+self.renderEditorFooter(specs)+self.renderMessageContainer();return _bmResponse(chromeBM,"JOE [overlay-chrome]"),self.overlay.find(".joe-overlay-panel").html(html),!self.current.specs.noHistory&&self.history.length&&$.extend(self.history[self.history.length-1],{_joeHistoryTitle:self.overlay.find(".joe-panel-title").html()}),self.updateHashLink(),_bmResponse(joePopulateBenchmarker,"----Joe Populated"),endLogGroup(),html},this.toggleMultiEditMode=function(specs,data){multiEdit=self.current.userSpecs&&self.current.userSpecs.multiedit||!1},this.Header={},this.toggleHelpMenu=function(show,target){},this.listUnsavedChanges=function(){},this.Header.Render=this.renderEditorHeader=function(specs){var BM=new Benchmarker,titleObj=createTitleObject(specs=specs||{}),title=titleObj.docTitle||self.current.schema&&"new "+self.current.schema.__schemaname;titleObj.subTitle;if(self.specs.documentTitle){var doctitle=!0===self.specs.documentTitle?self.current.title:self.propAsFuncOrValue(self.specs.documentTitle,self.current.title);document.title=fillTemplate(self.propAsFuncOrValue(doctitle),titleObj)}var close_action=specs.close_action||'onclick="getJoe('+self.joe_index+').closeButtonAction()"',reload_action=specs.reload_action||'onclick="getJoe('+self.joe_index+').reload()"';!function(){var html="";specs.minimode||(html+='<div class="jif-panel-header-button joe-panel-help" onclick="_joe.toggleHelpMenu()" title="help">'+self.SVG.icon.help+"</div>")}();var unsaved_icon=function(){var html="";return specs.minimode?"":html+='<div class="jif-panel-header-button joe-panel-unsaved" onclick="_joe.updateObject(this,null,true);" title="unsaved changes">'+self.SVG.icon.unsaved+"</div>"}(),reload_button=(specs.speech_action||self.joe_index,specs.minimode?"":'<div class="jif-panel-header-button joe-panel-reload" title="reload" '+reload_action+'><span class="jif-reload"></span></div>'),mic_button=!self.specs.speechRecognition||specs.minimode?"":'<div class="jif-panel-header-button joe-panel-speech" title="speech" id="speech-button-'+self.joe_index+'">M</div>',close_button='<div class="jif-panel-header-button joe-panel-close" title="close" '+close_action+">"+self.SVG.icon.close+"</div>",schema_button=!specs.minimode&&self.current.schema&&self.current.schema.menuicon&&'<joe-schema-icon class="clickable" title="'+self.current.schema.__schemaname+'" onclick="goJoe(\''+self.current.schema.__schemaname+"')\">"+self.current.schema.menuicon+"</joe-schema-icon>"||"",back_button=!specs.minimode&&function(){var html="";return self.history.length>1&&(html+='<div class="jif-header-back-btn jif-panel-header-button standard-button" onclick="window.history.back()" title="back">'+self.SVG.icon.left+"</div>"),html}()||"",left_buttons=[back_button,schema_button],right_buttons=[close_button,mic_button,reload_button,unsaved_icon],html="<joe-panel-header >"+(specs.schema&&specs.schema.subsets&&self.renderSubsetselector(specs.schema)||specs.subsets&&self.renderSubsetselector(specs)||"")+left_buttons.join(" ")+'<div class="joe-vcenter joe-panel-title-holder"><span class="joe-panel-title">'+(("<div>"+title+"</div>").toDomElement().innerText||title||"Json Object Editor")+'</span></div><joe-panel-header-buttons class="right-side">'+right_buttons.join(" ")+'<div class="clear"></div></joe-panel-header-buttons><div class="clear"></div></joe-panel-header>';return _bmResponse(BM,"[Header] rendered"),html},this.closeButtonAction=function(prechecked){if(this.checkChanges()){self.history=[],self.panel.addClass("centerscreen-collapse"),self.hide(500),self.current.clear(),$(self.container).trigger({type:"hideJoe",index:self.joe_index}),self.updateHashLink();var closeAction=self.getCascadingProp("onPanelHide");closeAction&&closeAction(self.getState()),self.Autosave.deactivate()}},this.goBack=function(obj){if(this.checkChanges()){if(self.current.object){var gobackItem=self.current.object[self.getIDProp()];gobackItem&&(goingBackFromID=gobackItem)}self.history.pop();var joespecs=self.history.pop();if(joespecs){if(obj&&$c.isArray(joespecs.data)){var objid=obj[self.getIDProp()];if(objid){var query={};query[self.getIDProp()]=objid;var found=joespecs.data.where(query);found.length&&$.extend(found[0],obj)}}joespecs.keyword&&(goingBackQuery=joespecs.keyword);var specs=$.extend({},joespecs.specs);specs.filters=joespecs.filters,self.show(joespecs.data,specs)}else self.closeButtonAction(!0)}},this.cleanUp=function(){self.current.fields=[],self.shiftSelecting=!1,self.allSelected=!1,self.current.userSpecs&&self.current.userSpecs.multiedit?self.overlay.addClass("multi-edit"):self.overlay.removeClass("multi-edit")},this.renderEditorSubmenu=function(specs){beginLogGroup("Submenu");var BM=new Benchmarker,sectionAnchors=renderSectionAnchors(),submenuButtons=renderSubmenuButtons();if(!(self.current.submenu||sectionAnchors.count||listMode||self.getCascadingProp("headerMenu")))return"";var subSpecs={search:!0,itemcount:!0,filters:$c.getProperty(self.current,"userSpecs.filters")||$c.getProperty(self.current,"schema.filters")||$c.getProperty(self.current,"schema.subsets")||!1,numCols:self.current.schema.columns||0},userSubmenu="object"!=$.type(self.current.submenu)?{}:self.current.submenu;if($.extend(subSpecs,userSubmenu),"list"==specs.mode)var filters_obj=self.Filter.getCached(),submenu='<div class="joe-panel-submenu">'+self.Aggregator.renderToggleButton()+self.renderViewModeButtons(subSpecs)+self.renderColumnCountSelector(subSpecs.numCols)+self.renderSorter()+(subSpecs.filters&&self.renderSubmenuFilters(subSpecs.filter)||"")+(subSpecs.search&&self.renderSubmenuSearch(subSpecs.search)||"")+(subSpecs.itemcount&&self.renderSubmenuItemcount(subSpecs.itemcount)||"")+submenuButtons.html+"</div><div class='joe-filters-holder'>"+function(){var act,sh='<div><joe-menu-label title="select one subset at a time"><b>Subsets</b></joe-menu-label>',starting=[];self.current.schema&&self.current.schema.hideAllSubset||starting.push({name:"All",filter:{}});var group=null;return starting.concat(_joe.current.subsets||[]).map(function(opt){if(opt.group_start)group=opt.group_start,sh+=renderOptionGroupStart(opt,"joe-subset-option");else if(opt.group_end)sh+="</joe-option-group>",group=null;else{var idval=opt.id||opt.name||"";if(!opt.condition||self.propAsFuncOrValue(opt.condition)){"active"==(act=self.current.subset&&self.current.subset.name==opt.name||!self.current.subset&&"All"==opt.name?"active":"")&&group&&(sh=sh.replace('<joe-option-group id="'+group+'-group" class="collapsed','<joe-option-group id="'+group+'-group" class="'));let optCount=self.current.list.where(opt.filter).length;sh+=`<joe-subset-option data-subset="${idval}" class="joe-subset-option ${act} " \n onclick="getJoe(${self.joe_index}).selectSubset('${(opt.id||opt.name||"").toString().replace(/\'/g,"\\'")}');">`+renderOptBorderColor(opt)+renderOptBGColor(opt)+renderOptStripeColor(opt)+'<span style="position:relative;">'+opt.name+"</span>"+`<option-count>${optCount}</option-count></joe-subset-option>`}}}),sh+="</div>",_bmResponse(BM,"subsets rendered"),sh}()+(filters_obj&&function(){_bmResponse(BM,"filters start");var fh='<div><joe-menu-label title="select multiple filters at once"><b>Filters</b></joe-menu-label>',filters=self.current.schema.filters;filters=self.propAsFuncOrValue(filters);var group=null;return(filters||[]).map(function(opt){if(opt.group_start)group=opt.group_start,fh+=renderOptionGroupStart(opt,"joe-filter-option");else if(opt.group_end)fh+="</joe-option-group>",group=null;else{var idval=opt.id||opt.name||"";if(!opt.condition||self.propAsFuncOrValue(opt.condition)){act="",self.current.filters&&self.current.filters[idval]?act="active":opt.hasOwnProperty("default")&&(act=self.propAsFuncOrValue(opt.default)?"active":"",self.toggleFilter(opt.name)),"active"==act&&group&&(fh=fh.replace('<joe-option-group id="'+group+'-group" class="collapsed">','<joe-option-group id="'+group+'-group" class="">'));let optCount=self.current.list.where(opt.filter).length;fh+='<joe-filter-option data-filter="'+idval+'" class="joe-filter-option '+act+'" onclick="getJoe('+self.joe_index+").toggleFilter('"+idval+"',this);\">"+renderOptBorderColor(opt)+renderOptBGColor(opt)+renderOptStripeColor(opt)+'<span class ="joe-option-checkbox"></span><span style="position:relative;">'+opt.name+"</span>"+`<option-count>${optCount}</option-count></joe-filter-option>`}}}),fh+='<joe-subset-option class="joe-subset-option clear-filters" onclick="'+getSelfStr+'.clearFilters()">clear filters</joe-subset-option>',fh+="</div>",_bmResponse(BM,"filters rendered"),fh}()||"")+"</div>"+self.Aggregator.renderAggregatorHolder(!1);else submenu='<div class="joe-panel-submenu">'+renderSidebarToggle("left")+renderSidebarToggle("right")+submenuButtons.html+(sectionAnchors.count&&sectionAnchors.code||"")+"</div>";function renderOptStripeColor(opt){var color=self.propAsFuncOrValue(opt.stripecolor||opt.stripeColor,null,null,opt),title="";return color&&$c.isObject(color.title)&&(title=' title="'+color.title+'" ',color=color.color),"<joe-stripe-color "+title+(color&&'style="background-color:'+color+';"'||"")+"></joe-stripe-color>"}function renderOptBGColor(opt){var color=self.propAsFuncOrValue(opt.bgcolor||opt.bgColor,null,null,opt);return color&&$c.isObject(color.title)&&(color=color.color),"<joe-bg-color "+(color&&'style="background-color:'+color+';"'||"")+"></joe-bg-color>"}function renderOptBorderColor(opt){var color=self.propAsFuncOrValue(opt.bordercolor||opt.borderColor,null,null,opt);return color&&$c.isObject(color.title)&&(color=color.color),"<joe-border-color "+(color&&'style="border:1px solid '+color+';"'||"")+"></joe-border-color>"}function renderOptionGroupStart(opt,childDom){var collapsed=self.propAsFuncOrValue(opt.collapsed)?"collapsed":"";if(opt.hasOwnProperty("filter")){var act,onclick,dataname,optdisplay=opt.display||opt.name||opt.group_start||"",optname=opt.id||opt.name||opt.group_start||"",cbox="";"joe-filter-option"==childDom?(dataname=' data-filter="'+optname+'" ',cbox='<span class ="joe-option-checkbox"></span>',act=self.current.filters&&self.current.filters[optname]?"active":"",onclick="getJoe("+self.joe_index+").toggleFilter('"+optname+"',this);_joe.Utils.stopPropagation();"):(dataname=' data-subset="'+optname+'" ',act=self.current.subset&&self.current.subset.name==optname||!self.current.subset&&"All"==opt.name?"active":"",onclick="getJoe("+self.joe_index+").selectSubset('"+optname.toString().replace(/\'/g,"\\'")+"');");var optiondiv="<"+childDom+" "+dataname+' class="'+childDom+" joe-group-option "+act+' " onclick='+onclick+">"+renderOptBorderColor(opt)+renderOptBGColor(opt)+renderOptStripeColor(opt)+cbox+'<span style="position:relative;">'+optdisplay+"</span></"+childDom+">";return'<joe-option-group id="'+opt.group_start+'-group" class="'+collapsed+' "><joe-menu-label onclick="$(this).parent().toggleClass(\'collapsed\');">'+optiondiv+"</joe-menu-label>"}return'<joe-option-group id="'+opt.group_start+'-group" class="'+collapsed+'"><joe-menu-label onclick="$(this).parent().toggleClass(\'collapsed\');">'+(opt.display||opt.name||opt.group_start)+"</joe-menu-label>"}return endLogGroup(),_bmResponse(BM,"[Submenu] rendered"),submenu},self.gotoSection=function(section,specs){specs=$.extend({},specs||{});if(section){var force_activation,i=specs.index||self.joe_index,sectionDom=$(".joe-overlay[data-joeindex="+i+"]").find(".joe-content-section[data-section='"+section+"']"),activated=sectionDom[0].hasClass("active");specs.hasOwnProperty("activate")&&(force_activation=specs.activate);var submenuDom=$(specs.dblclickdom)||self.overlay.find('joe-submenu-section[data-section="'+section+'"]');if(specs.focus){var tabbedmode,parent_dom=sectionDom.parents(".joe-content-sidebar,joe-panel-content");specs.hasOwnProperty("activate")?(submenuDom.toggleClass("active",force_activation),sectionDom.toggleClass("active",force_activation)):(submenuDom.toggleClass("active",!activated),sectionDom.toggleClass("active",!activated)),tabbedmode=submenuDom.parent().children(".active[data-panel="+submenuDom.data("panel")+"]").length>0,parent_dom.toggleClass("joe-tabbed-content",tabbedmode)}if(force_activation||!activated){sectionDom.removeClass("collapsed")[0].scrollIntoView();var sidebar=sectionDom.parents(".joe-content-sidebar");if(sidebar&&sidebar.length){var s=sidebar.data("side");self.toggleSidebar(s,!0),sectionDom.siblings(".joe-content-section").addClass("collapsed")}else"small-size"==self.sizeClass&&(self.toggleSidebar("left",!1),self.toggleSidebar("right",!1));$("joe-submenu-section-anchors.expanded").removeClass("expanded")}else $("joe-submenu-section-anchors.expanded").addClass("expanded")}},self.Sections={renderAchors:renderSectionAnchors,goto:self.gotoSection,gotoTop:function(index){var ajoe=getJoe(index);$(".joe-overlay[data-joeindex="+index+"]").find(".joe-panel-content").scrollTop(0),ajoe.panel.hasClass("small-size")&&(ajoe.toggleSidebar("right",!1),ajoe.toggleSidebar("left",!1)),$("joe-submenu-section-anchors.expanded").removeClass("expanded")}},self.Sections.toggleAll=function(expand){document.querySelectorAll(".joe-content-section").map(e=>{e.classList.toggle("collapsed",!expand)})},self.Sections.collapseAll=function(){document.querySelectorAll(".joe-content-section").map(e=>{e.classList.toggle("collapsed",!0)})},self.Sections.expandAll=function(){document.querySelectorAll(".joe-content-section").map(e=>{e.classList.toggle("collapsed",!1)})},self.Sections.toggleSome=function(sections,expand){sections.map(sect=>{document.querySelectorAll('.joe-content-section[data-section="'+sect+'"]').map(e=>{e.classList.toggle("collapsed",!expand)})})},self.Sections.unFocusAll=function(){self.overlay.find("joe-submenu-section").removeClass("active")},self.Sections.activate=function(sections){},self.Sections.setTabbedMode=function(show){self.overlay.find(".joe-content-sidebar,joe-panel-content").toggleClass("joe-tabbed-content",show)},self.Sections.toggle=function(dom){dom&&$(dom).parents("joe-submenu-section-anchors").toggleClass("expanded")},self.Sections.showAll=function(){self.Sections.toggleAll(!0)},this.Subset={getCached:function(list){list=list||self.current.list;var cache_query=self.current.schema.name+":"+self.current.subset.name,subcache=self.Cache.get(cache_query);return subcache||(subcache=list.where(self.current.subset.filter),self.Cache.set(subcache,{id:cache_query})),subcache}},this.Filter={refilter:function(){$c.isEmpty(self.current.filters)||self.filterListFromSubmenu(null,!0)},getCached:function(list){var BM=new Benchmarker;if(!self.current.schema||!self.current.schema.filters)return _bmResponse(BM,"filters gotten"),!1;list=list||self.current.list;var cache_query=self.current.schema.name+":filters",filtercache=self.Cache.get(cache_query);return filtercache||(filtercache=self.propAsFuncOrValue(self.current.schema.filters,self.current.list),self.Cache.set(filtercache,{id:cache_query})),_bmResponse(BM,"filters gotten"),filtercache}},this.renderSubmenuFilters=function(s){if(!(s||self.current.subsets||self.current.schema&&self.propAsFuncOrValue(self.current.schema.filters)))return"";var action=' onclick="getJoe('+self.joe_index+').toggleFiltersMenu();" ',active=self.current.subset?"active":"",count=$c.itemCount(self.current.filters);return"<div class='jif-panel-submenu-button joe-filters-toggle ' "+action+" title='show filters'>"+(active||count?'<joe-count-indicator class="'+active+(count?" count ":"")+'">'+(count||"")+"</joe-count-indicator>":"")+"</div>"};var leftMenuShowing=!1,rightMenuShowing=!1;this.toggleFiltersMenu=function(){leftMenuShowing=!leftMenuShowing,self.panel.toggleClass("show-filters",leftMenuShowing)},this.toggleAggregatorMenu=function(){rightMenuShowing=!rightMenuShowing,self.panel.toggleClass("show-aggregator",rightMenuShowing)},this.Filter.Options={datasetProperty:function(dataset,property,specs){var filters=[],groupname="string"==typeof(specs=specs||{}).group?specs.group:property;dataset=self.getDataset(self.propAsFuncOrValue(dataset)).sortBy(specs.sortby||"name");return specs.query&&(dataset=dataset.where(specs.query)),dataset.length?(specs.group&&filters.push({group_start:groupname,collapsed:specs.collapsed}),dataset.map(item=>{let props={name:item.name,filter:{}};props.filter[property]=item._id,filters.push(props)}),specs.group&&filters.push({group_end:groupname}),filters):[]},getDatasetPropertyValues:function(dataset,property,specs){var filters=[],groupname="string"==typeof(specs=specs||{}).group?specs.group:property;dataset=self.getDataset(self.propAsFuncOrValue(dataset)).sortBy(specs.sortby||"name");if(specs.query&&(dataset=dataset.where(specs.query)),!dataset.length)return[];specs.group&&filters.push({group_start:groupname,collapsed:specs.collapsed});var filterValues=specs.values||[];return dataset.map(item=>{item.hasOwnProperty(property)&&filterValues.push(item[property])}),(filterValues=Array.from(new Set(filterValues))).map(v=>{let filterObj={name:v,filter:{}};filterObj.filter[property]=v,filters.push(filterObj)}),specs.group&&filters.push({group_end:groupname}),filters},status:function(specs){specs=specs||{};"object"==$.type(schemaname)&&(specs=schemaname);var stat,schemaname=specs.schemaname||self.current.schema&&self.current.schema.name||"",stats=[],groupname="string"==typeof specs.group?specs.group:"tags";if(specs.group&&stats.push({group_start:groupname,collapsed:specs.collapsed}),self.Data.status.sortBy(specs.sortby||"index").where({datasets:{$in:[schemaname]}}).map(function(status){var sName=status.name;(stat={name:sName,id:status._id,filter:{status:status._id},title:self.propAsFuncOrValue(specs.title)||status.name})[specs.color||"bgcolor"]=status.color,stats.push(stat)}),specs.none){let noName="no status",noFil={$or:[{status:{$in:[null,""]}},{status:{$exists:!1}}]};stats.push({name:noName,filter:noFil})}return specs.group&&stats.push({group_end:groupname}),stats},tags:function(specs){var schemaname=(specs=specs||{}).schemaname||self.current.schema&&self.current.schema.name,filters=(schemaname=specs.schemaname||self.current.schema&&self.current.schema.name||"",[]),groupname="string"==typeof specs.group?specs.group:"tags";if(specs.group&&filters.push({group_start:groupname,collapsed:specs.collapsed}),_joe.Data.tag.sortBy(specs.sortby||"name").filter(function(tag){let fi={tags:{$in:[tag._id]}};if(-1!=tag.datasets.indexOf(schemaname)){let sName=tag.name;filters.push({name:sName,id:tag._id,filter:fi})}}),specs.untagged||specs.none){let noName="untagged",noFil={$or:[{tags:{$size:0}},{tags:{$exists:!1}}]};filters.push({name:noName,filter:noFil})}return specs.group&&filters.push({group_end:groupname}),filters}},this.Filter.generateQuery=this.generateFiltersQuery=function(){var filterinfo,filterobj,query={};for(var f in self.current.filters)if(!(filterinfo=(self.propAsFuncOrValue(self.current.schema.filters)||[]).where({name:f})[0]||self.current.filters[f]||{}).schema||!self.current.schema||!self.current.schema.__schemaname||filterinfo.schema==(self.current.schema.__Schemaname||self.current.schema.__schemaname))for(var ff in filterobj=filterinfo.filter)if(query[ff])switch($.type(filterobj[ff])){case"number":case"string":case"object":"string"==$.type(query[ff])||"number"==$.type(query[ff])?query[ff]={$in:[query[ff],filterobj[ff]]}:"object"==$.type(query[ff])&&query[ff].hasOwnProperty("$in")&&(query[ff].$in=query[ff].$in.concat(filterobj[ff].$in||[filterobj[ff]]))}else query[ff]=filterobj[ff];else delete self.current.filters[filterinfo.name];return logit(query),query},self.Search={schema:{title:"Search Results",name:"search",listTitle:function(item){return"<joe-full-right><joe-subtext>updated</joe-subtext><joe-subtitle>"+self.Utils.toDateString(item.joeUpdated)+"</joe-subtitle></joe-full-right>"+(_joe.schemas[item.itemtype].menuicon&&'<joe-icon class="icon-40 icon-grey fleft">'+_joe.schemas[item.itemtype].menuicon+"</joe-icon>"||"")+"<joe-subtext>${itemtype}</joe-subtext><joe-title>${name}</joe-title><joe-subtitle>${info}</joe-subtitle><joe-subtext>${_id}</joe-subtext>"},listmenu:[],sorter:["name",{name:"updated",value:"!joeUpdated"},"itemtype"],filters:function(){var f=[];return __appCollections.concat().sort().map(function(s){f.push({name:s,filter:{itemtype:s}})}),f},listAction:function(item){return"goJoeItem('"+item._id+"','"+item.itemtype+"')"}}},this.renderSubmenuSearch=function(s){return'<div class=\'joe-submenu-search \'><input class="joe-submenu-search-field" onkeyup="_joe.filterListFromSubmenu(this.value);" placeholder="search list" value="'+(self.current.keyword||$GET("keyword")||"")+'"/></div>'},this.searchTimeout;var searchTimeoutTime=$c.isMobile()?750:500,currentListItems,renderFieldTo;function renderSubmenuSelectors(specs){specs=$.extend({options:[],content:"",action:"nothing",buttonTemplate:"<div class='selection-label'>${label}</div>${name}",label:"label",cssclass:""},specs||{});var selectionTemplate="<div data-colcount='${name}' onclick='getJoe("+self.joe_index+")."+specs.action+"(${name});' class='jif-panel-button selector-button-${name} joe-selector-button '>"+specs.buttonTemplate+"</div>",onclick_action="onclick='$(this).parent().toggleClass(\"expanded\")'";return"<div class='joe-submenu-selector' >"+(specs.content||"<div class='joe-selector-button selector-label' "+onclick_action+">"+specs.label+"</div><div class='joe-selector-button selector-close joe-close-button' "+onclick_action+">&nbsp;</div><joe-submenu-selector-options>"+fillTemplate(selectionTemplate,specs.options)+"</joe-submenu-selector-options>")+"</div>"}function renderEditorStyles(){return(self.specs.style&&self.specs.style.inset?"joe-style-inset ":"")+(self.specs.style&&self.specs.style.cards?"joe-style-cards ":"")}function renderSidebarToggle(side){return self.current.sidebars[side].hidden?"":'<div class="jif-panel-submenu-button joe-sidebar-button joe-sidebar_'+side+'-button" title="toggle" onclick="getJoe('+self.joe_index+").toggleSidebar('"+side+"')\">"+self.SVG.icon["sidebar-"+side]+"</div>"}function cleanDeleted(list,schema){var query={};return query[self.getCascadingProp("deleted")||"_deleted"]={$in:[!1,"false",void 0]},list.where(query)}this.filterListFromSubmenu=function(keyword,now){function searchFilter(keyword,frominput){var searchBM=new Benchmarker;if(self.current.keyword!=keyword){keyword=keyword||$(".joe-submenu-search-field").val()||"",frominput||keyword||!self.current.keyword||(keyword=self.current.keyword,$(".joe-submenu-search-field").val(keyword));var testable,value=keyword.toLowerCase(),keywords=value.replace(/,/g," ").split(" "),filters=self.generateFiltersQuery();_joe.history[_joe.history.length-1].keyword=value,_joe.history[_joe.history.length-1].filters=self.current.filters;var id,idprop=self.getIDProp(),listables=self.current.list;self.current.subset&&(listables=self.Subset.getCached()),listables=cleanDeleted(listables);var searchables=self.current.schema&&self.current.schema.searchables;_bmResponse(searchBM,"search where"),self.current.filteredList=currentListItems=listables.where(filters).filter(function(i){if(!keyword)return!0;if(id=i[idprop],testable="",searchables){searchables.map(function(s){testable+=i[s]+" "}),testable=testable.toLowerCase()+id;for(var k=0,tot=keywords.length;k<tot;k++)if(-1==testable.indexOf(keywords[k]))return!1}else{tableMode?testable=self.renderTableItem(i,!0):gridMode||(testable=self.renderListItem(i,!0)),testable=testable.toLowerCase()+id;for(k=0,tot=keywords.length;k<tot;k++)if(-1==testable.indexOf(keywords[k]))return!1}return!0}),_bmResponse(searchBM,"search '"+keyword+"' filtered "+currentListItems.length+"/"+self.current.list.length+" items ["+listables.length+"]"),self.overlay.find(".joe-submenu-itemcount").html(currentListItems.length+" item"+(currentListItems.length>1?"s":"")),self.panel.find(".joe-panel-content").html(self.renderListItems(currentListItems,0,self.specs.dynamicDisplay))}self.current.keyword=keyword,self.current.search_schema;var titleObj=createTitleObject();titleObj.subTitle?self.panel.find(".joe-panel-title").addClass("subtitled").html(titleObj.docTitle+"<joe-subtext>"+titleObj.subTitle+"</joe-subtext>"):self.panel.find(".joe-panel-title").addClass("subtitled").html(titleObj.docTitle),self.panel.find(".joe-filters-toggle").replaceWith(self.renderSubmenuFilters()),self.Aggregator.update()}clearTimeout(self.searchTimeout),self.overlay.removeClass(".multi-edit"),now?searchFilter(keyword):self.searchTimeout=setTimeout(function(){searchFilter(keyword,!0)},searchTimeoutTime)},this.renderSubmenuItemcount=function(s){return"<div class='joe-submenu-itemcount'>items</div>"},this.nothing=function(nothing){alert(value)},this.renderViewModeButtons=function(subspecs){var gridspecs=self.current.schema&&(self.current.schema.grid||self.current.schema.gridView),tablespecs=tableSpecs;if(!gridspecs&&!tablespecs)return"";var modes=[{name:"list"}];gridspecs&&modes.push({name:"grid"}),tablespecs&&modes.push({name:"table"});var modeTemplate="<div data-view='${name}' onclick='getJoe("+self.joe_index+").setViewMode(\"${name}\");' class='jif-panel-button joe-viewmode-button ${name}-button joe-selector-button'>&nbsp;</div>",onclick_action="onclick='$(this).parent().toggleClass(\"expanded\")'";return"<div class='joe-submenu-selector joe-viewmode-selector opts-"+modes.length+"' ><div class='joe-selector-button selector-label' "+onclick_action+">view</div><div class='joe-selector-button selector-close joe-close-button' "+onclick_action+">&nbsp;</div><joe-submenu-selector-options>"+fillTemplate(modeTemplate,modes)+"</joe-submenu-selector-options></div>"},this.setViewMode=function(mode){self.reload(!0,{viewMode:mode})},this.renderColumnCountSelector=function(subspecs){if(!subspecs)return"";var modes=[{name:"1"},{name:"2"},{name:"3"},{name:"4"},{name:"5"}];"number"==typeof eval(subspecs)&&(modes=modes.slice(0,eval(subspecs)));var h=renderSubmenuSelectors({options:modes,label:"cols",value:colCount,action:"setColumnCount"});return h},this.setColumnCount=function(mode){self.overlay[0].className=self.overlay[0].className.replace(/cols-[0-9]/,"cols-"+mode),mode&&(colCount=mode);var multi=!!(mode&&mode>1);self.overlay.toggleClass("multi-col",multi)},this.Sorter={},this.Sorter.render=this.renderSorter=function(subspecs){var sorter=self.current.subset&&self.current.subset.sorter||self.current.schema&&self.current.schema.sorter||"name";if("string"==$.type(sorter)&&(sorter=sorter.split(",")),-1!=sorter.indexOf("name")||-1!=sorter.indexOf("!name")||sorter.where({field:"name"}).length||sorter.push("name"),1==sorter.length)return"";return'<label for="joe-'+self.joe_index+'-sorter" class="joe-list-sorter" ><svg onclick="getJoe('+self.joe_index+').Sorter.reverse();" class="joe-list-sorter-icon" title="reverse sort" xmlns="http://www.w3.org/2000/svg" viewBox="-20 6 40 40"><path d="M-4 16L-9.5 21.5 -8 23 -5 20 -5 28 -3 28 -3 20 0 23 1.5 21.5 -4 16zM3 16L3 18 5 18 5 16 3 16zM3 20L3 22 5 22 5 20 3 20zM3 24L3 32 0 29 -1.5 30.5 4 36 9.5 30.5 8 29 5 32 5 24 3 24zM-5 30L-5 32 -3 32 -3 30 -5 30zM-5 34L-5 36 -3 36 -3 34 -5 34z"/></svg><select title="sort" name="joe-'+self.joe_index+'-sorter" onchange="getJoe('+self.joe_index+').Sorter.resort(this.value);">'+sorter.map(function(so){var s=so,display=so;$c.isString(so)||(s=so.field||so.value,display=so.display||so.name||s),s=s.replace("!","");var valCheck=(self.current.sorter[0].field||self.current.sorter[0].value||self.current.sorter[0]).replace("!","");return"<option "+(s==valCheck?"selected":"")+' value="'+s+'">'+display+"</option>"}).join("")+"</select></label>"},this.Sorter.resort=function(sorter){self.reload(!0,{sorter:sorter})},this.Sorter.reverse=function(sorter){var curSorter=self.current.sorter;"array"==$.type(curSorter)&&(curSorter=[].concat(curSorter),"string"==$.type(curSorter[0])?0==curSorter[0].indexOf("!")?curSorter[0]=curSorter[0].substr(1):curSorter[0]="!"+curSorter[0]:"object"==$.type(curSorter[0])&&curSorter[0].value&&(0==curSorter[0].value.indexOf("!")?curSorter[0].value=curSorter[0].value.substr(1):curSorter[0].value="!"+curSorter[0].value),self.reload(!0,{sorter:curSorter}))},this.Submenu=this.Submenu||{},this.Aggregator={},this.Aggregator.renderToggleButton=function(){return s&&self.current.schema&&self.current.schema.hasOwnProperty("aggregator")?"<div class='jif-panel-submenu-button joe-aggregator-toggle ' "+(' onclick="getJoe('+self.joe_index+').toggleAggregatorMenu();" ')+" title='show aggregator'></div>":""},this.Aggregator.renderAggregatorHolder=function(contentOnly,content){if(!(s&&self.current.schema&&self.current.schema.hasOwnProperty("aggregator")))return"";var html=content=self.propAsFuncOrValue(self.current.schema.aggregator,self.current.filteredList||self.current.list);return contentOnly||(html="<div class='joe-aggregator-holder'>"+content+"</div>"),html},this.Aggregator.update=function(list){list=list||self.current.filteredList;var content=self.Aggregator.renderAggregatorHolder(!0),dom=document.querySelector('.joe-overlay[data-joeindex="0"]').getElementsByClassName("joe-aggregator-holder")[0];dom&&(dom.innerHTML=content)},this.renderEditorContent=function(specs){var content;self.current.sidebars={left:{collapsed:!1},right:{collapsed:!1}},specs||(specs={mode:"text",text:"No object or list selected"});var mode=specs.mode;switch(mode){case"text":content=self.renderTextContent(specs);break;case"rendering":content=self.renderHTMLContent(specs);break;case"list":content=self.renderListContent(specs);break;case"object":content=self.renderObjectContent(specs);break;default:content=content||""}var submenu="";specs.minimode||("list"==mode&&self.current.submenu||self.current.submenu||renderSectionAnchors().count||renderSubmenuButtons().content)&&(submenu=" with-submenu ");var scroll='onscroll="getJoe('+self.joe_index+').onListContentScroll(this);"',rightC=content.right||"",leftC=content.left||"",html='<joe-panel-content class="'+("joe-panel-content "+renderEditorStyles()+submenu)+'" '+(listMode&&scroll||"")+">"+(content.main||content)+"</joe-panel-content>"+self.renderSideBar("left",leftC,{css:submenu})+self.renderSideBar("right",rightC,{css:submenu});return self.current.sidebars.left.content=leftC,self.current.sidebars.right.content=rightC,html},this.renderSideBar=function(side,content,specs){side=side||"right";var addCss=(specs=specs||{}).css||"";return"<div class='joe-content-sidebar "+renderEditorStyles()+" joe-absolute "+side+"-side "+addCss+"' data-side='"+side+"'>"+(content||"")+__clearDiv__+"</div>"},this.toggleSidebar=function(side,hardset){if(-1==["right","left"].indexOf(side))return!1;self.panel.toggleClass(side+"-sidebar",hardset)},this.renderTextContent=function(specs){return'<div class="joe-text-content">'+((specs=specs||{}).text||specs.object||"")+"</div>"},this.renderHTMLContent=function(specs){return'<textarea class="joe-rendering-field">'+((specs=specs||{}).rendering||"")+"</textarea>"},this.Render.listContent=this.renderListContent=function(specs){var wBM=new Benchmarker;if(specs.minimode)return self.renderMiniListContent(specs);currentListItems=[],self.current.selectedListItems=[],self.current.anchorListItem=null;(specs=specs||{}).schema;var filteredList,numItemsToRender,list=specs.list||[],html="";list=cleanDeleted(list),currentListItems=list,self.current.subset&&(filteredList=currentListItems=self.Subset.getCached(list),_bmResponse(wBM,"list subsetted"));var primer=null;if(self.current.sorter&&("array"!=$.type(self.current.sorter)||self.current.sorter.length)){var sorterValues=self.current.sorter;if($c.isArray(self.current.sorter)&&self.current.sorter[0].field){sorterValues=[];for(var i=0,len=self.current.sorter.length;i<len;i++)sorterValues.push(self.current.sorter[i].field||self.current.sorter[i]),primer=self.current.sorter[i].primer||primer||null}else primer=self.current.sorter[0].primer||null;list=list.sortBy(sorterValues,null,primer)}return _bmResponse(wBM,"list sort complete"),$c.isEmpty(_joe.current.filters)||(filteredList=currentListItems.where(self.Filter.generateQuery()),currentListItems=filteredList,_bmResponse(wBM,"list filtered")),_bmResponse(wBM,"list prerender"),numItemsToRender=self.specs.dynamicDisplay||currentListItems.length,html+=self.renderListItems(currentListItems,0,numItemsToRender),_bmResponse(wBM,"list complete"),self.current.filteredList=filteredList,html},this.renderMiniListContent=function(specs){var wBM=new Benchmarker,schema=(specs=specs||{}).schema,list=specs.object||[],idprop=specs.idprop||"_id",html="",sorter=specs.sorter||"name";list=list.sortBy(sorter);for(var template,click="getJoe("+self.joe_index+").minis['"+specs.minimode+"'].callback('${"+idprop+"}')",li=0,tot=list.length;li<tot;li++){let item=list[li],schemaName=item.itemtype||item.schema||item.name;template=self.propAsFuncOrValue(specs.template,item)||"<joe-title>${name}</joe-title><joe-subtext>${"+idprop+"}</joe-subtext>",template='<joe-list-item schema="'+(schemaName||schema.name||schema)+'" class="joe-field-list-item clickable" onclick="'+click+'">'+template+"</joe-list-item>",html+=fillTemplate(template,item)}return _bmResponse(wBM,"minilist complete"),html},this.Render.listItems=this.renderListItems=function(items,start,stop){var listItem,html="",simple_sorter=(items=items||currentListItems,[]);self.current.sorter.map(function(s){simple_sorter.push(s.field||s.value||s)}),items=items.sortBy(simple_sorter);start=start||0,stop=stop||currentListItems.length-1;if(gridMode){for(var cell,colinfo,col_filter,subitems,gridspecs=self.current.schema&&(self.current.schema.grid||self.current.schema.gridView)||{},columns=self.propAsFuncOrValue(gridspecs.cols)||[],rows=self.propAsFuncOrValue(gridspecs.rows)||[],cells=[],c=0;c<columns.length;c++)col_filter=(colinfo=columns[c]).filter,subitems=items.where(col_filter),rows.length||(cell_filter=colinfo.filter,cell={name:colinfo.name,filter:col_filter,html:"",items:[]},subitems.map(function(i){cell.items.push(i),cell.html+=self.Render.gridItem(i)}),cells.push([cell]));html+='<table class="joe-grid-table"><thead>',columns.map(function(c){$c.isString(c)?html+="<th>"+c+"</th>":$c.isObject(c)&&(html+="<th>"+(c.header||c.display||c.name)+"</th>")}),html+="</thead><tbody>";for(var row_number=0,row_count=rows.length||1;row_number<row_count;)html+="<tr>",cells.map(function(cell_list){html+='<td class="joe-grid-cell">'+cell_list[row_number].html+"</td>"}),html+="</tr>",row_number++;return html+="</tbody></table>"}if(tableMode){html+='<table class="joe-item-table" cellspacing="0"><thead class="joe-table-head"><th>&nbsp;</th>',tableSpecs.cols.map(function(c){$c.isString(c)?html+="<th>"+c+"</th>":$c.isObject(c)&&(html+="<th>"+(c.header||c.display)+"</th>")}),html+="</thead><tbody>",stop=currentListItems.length;for(var i=start;i<stop;i++)(listItem=items[i])&&(html+=self.renderTableItem(listItem,!1,i+1));return html+="</tbody></table>"}for(i=start;i<stop;i++)(listItem=items[i])&&(html+=self.renderListItem(listItem,!1,i+1));return html},this.onListContentScroll=function(domObj){var listItem=self.panel.find(".joe-panel-content-option").last()[0],currentItemCount=self.panel.find(".joe-panel-content-option").length;if(currentItemCount!=currentListItems.length){var viewPortHeight=self.panel.find(".joe-panel-content").height(),html="";try{listItem.getBoundingClientRect().bottom-500<viewPortHeight&&(tableMode||(html+=self.renderListItems(null,currentItemCount,currentItemCount+self.specs.dynamicDisplay),self.panel.find(".joe-panel-content").append(html)))}catch(e){self.Error.add("error scrolling for more content: \n"+e,e,{caller:"self.onListContentScroll",domObj:domObj})}}},this.renderObjectContent=function(specs){renderFieldTo="main";var propObj,object=(specs=specs||{}).object,fields={main:"",left:"",right:""};specs.minimode||(self.current.fields=[],self.current.sections={}),specs.schema&&"string"==typeof specs.schema&&(specs.schema=self.schemas[specs.schema]);var fhtml,schemaFields=!!specs.schema&&self.propAsFuncOrValue(specs.schema.fields);if(specs.schema&&schemaFields)(schemaFields||[]).map(function(prop){fhtml=self.renderObjectPropFieldUI(prop,specs),fields[renderFieldTo]+=fhtml});else for(var prop in object)object.hasOwnProperty(prop)&&(propObj=$.extend({name:prop,type:"text",value:object[prop]},self.fields[prop],{value:object[prop]}),fields.main+=self.renderObjectField(propObj));fields.main;return fields};var rerenderingField=!1,preProp;function _getSection(secname){return self.current.sections[secname]}self.Fields.rerender=this.rerenderField=function(fieldname,valueObj){var ftype,field;fieldname&&(self.current.constructed=self.constructObjectFromFields(),self.current.constructed&&!$c.isEmpty(self.current.constructed)&&($.extend(self.current.constructed,valueObj||{}),rerenderingField=!0,$c.isArray(fieldname)&&(fieldname=fieldname.join(",")),fieldname.split(",").condense().map(function(f){var fields=self.renderObjectPropFieldUI(f);field=self.getField(f),ftype=self.propAsFuncOrValue(field.type,self.current.constructed).toLowerCase(),$(".joe-object-field[data-name="+f+"]").parent().replaceWith(fields),self.Fields[ftype]&&self.Fields[ftype].ready&&self.Fields[ftype].ready(self.current.constructed)}),rerenderingField=!1,self.current.constructed=null))},self.Set=self.Fields.set=function(field,value){if(!listMode){field=self.propAsFuncOrValue(field),value=self.propAsFuncOrValue(value);var vals={};return vals[field]=value,self.Fields.rerender(field,vals),value}logit("in list mode")},self.Get=self.Fields.get=function(field){if(!listMode)return self.constructObjectFromFields()[field];logit("in list mode")},self.renderObjectPropFieldUI=function(prop,specs){var fields="";if("string"==$.type(prop)&&prop.contains(":")){var ps=prop.split(":");prop={name:ps[0],type:ps[1]},ps[2]&&(ps[2].contains("%")&&parseInt(ps[2])?prop.width=ps[2]:prop.display=ps[2])}var schemaspec=specs&&specs.schema||self.current.schema,existingProp=(self.propAsFuncOrValue(schemaspec.fields)||[]).filter(function(s){return s.name==prop||s.extend==prop})[0];existingProp&&(prop=existingProp);var constructed=self.current.constructed||self.constructObjectFromFields();if("string"==$.type(prop)){var propObj=self.fields[prop]||self.current.fields.filter(function(f){return f.name==prop})[0]||{},fieldProp=$.extend({},propObj);propObj=extendField(prop);void 0!==constructed[prop]&&(fieldProp.value=constructed[prop]),fields+=self.renderObjectField(propObj)}else if("object"==$.type(prop)&&prop.name){fieldProp=$.extend({},prop||{}),propObj=extendField(prop.name);void 0!==constructed[prop.name]&&(fieldProp.value=constructed[prop.name]),fields+=self.renderObjectField(propObj)}else if(prop&&prop.extend){fieldProp=$.extend({},self.fields[prop.extend]||{},prop.specs||{}),propObj=extendField(prop.extend);void 0!==constructed[prop.extend]&&(fieldProp.value=constructed[prop.extend]),fields+=self.renderObjectField(propObj)}else"object"==$.type(prop)&&(prop.component?fields+=self.renderPropComponent(prop):prop.label?fields+=self.renderContentLabel(prop):prop.section_start?fields+=self.renderPropSectionStart(prop):prop.section_end?fields+=self.renderPropSectionEnd(prop):prop.sidebar_start?"main"!=(renderFieldTo=prop.sidebar_side||prop.sidebar_start||"main")&&(prop.hasOwnProperty("collapsed")&&(self.current.sidebars[renderFieldTo].collapsed=self.propAsFuncOrValue(prop.collapsed)),prop.hasOwnProperty("hidden")&&(self.current.sidebars[renderFieldTo].hidden=self.propAsFuncOrValue(prop.hidden),self.current.sidebars[renderFieldTo].hidden&&(self.current.sidebars[renderFieldTo].collapsed=!0))):prop.sidebar_end&&(renderFieldTo="main"));function extendField(propname){propname=propname||prop;var cobj=self.current.constructed||self.current.object,rerenderObj={};return rerenderingField&&(fieldProp.run||fieldProp.value)&&(fieldProp.run||(rerenderObj.value=fieldProp.value)),$.extend({name:propname,type:"text"},{onblur:schemaspec.onblur,onchange:schemaspec.onchange,onkeypress:schemaspec.onkeypress,onkeyup:schemaspec.onkeyup},fieldProp,rerenderObj,{value:cobj[propname]})}return fields},self.renderPropComponent=function(prop){var html,componentName=self.propAsFuncOrValue(prop.component),cobj=self.current.constructed||self.current.object;if(prop.specs){let specs=self.propAsFuncOrValue(prop.specs);var specHtml=Object.keys(specs).map(spec=>` ${specs}="${specs[spec]}"`);html=`<${componentName} item_id="${cobj._id}" ${specHtml} >${componentName}</${componentName}>`}else html=`<${componentName} item_id="${cobj._id}">${componentName}</${componentName}>`;return html},self.renderContentLabel=function(specs){return specs.hasOwnProperty("condition")&&!_joe.propAsFuncOrValue(specs.condition)||specs.hasOwnProperty("hidden")&&_joe.propAsFuncOrValue(specs.hidden)?"":"<div class='joe-content-label'>"+fillTemplate(specs.label,self.current.object)+"</div>"},self.renderPropSectionStart=function(prop){var show="",hidden=!1;prop.condition&&!prop.condition(self.current.object)&&(show=" no-section ",hidden=!0),self.current.sidebars[renderFieldTo]&&self.current.sidebars[renderFieldTo].hidden&&(show=" no-section ",hidden=!0);var secname=fillTemplate(self.propAsFuncOrValue(prop.display||prop.section_label||prop.section_start,self.current.object),self.current.object),secID=prop.section_start;if(!secname||!secID)return"";var section_html='<div class="joe-content-section '+show+" "+(self.propAsFuncOrValue(prop.collapsed)?"collapsed":"")+'" data-section="'+secID+'"><joe-content-section-label class="joe-content-section-label" onclick=\'$(this).parent().toggleClass("collapsed");\''+(" ondblclick=\"$('joe-submenu-section[data-section="+secID+"]').dblclick();\" ")+">"+secname+'</joe-content-section-label><div class="joe-content-section-content">';return self.current.sections[secID]={open:!0,name:secname,id:secID,hidden:hidden,renderTo:renderFieldTo,anchor:prop.anchor},section_html},self.renderPropSectionEnd=function(prop){var secID=prop.section_end,section=_getSection(secID);if(!secID||!section||!section.open)return"";var section_html=__clearDiv__+"</div></div>";return section.open=!1,section_html},this.renderEditorFooter=function(specs){var fBM=new Benchmarker,customMenu=!0,menu=(specs=specs||this.specs||{}).minimenu||listMode&&specs.schema&&specs.schema.listmenu||specs.listmenu||multiEdit&&(specs.multimenu||specs.schema&&specs.schema.multimenu||__defaultMultiButtons)||specs.menu||null;menu||(menu=__defaultObjectButtons,customMenu=!1),menu=self.propAsFuncOrValue(menu);var html='<div class="joe-panel-footer"><div class="joe-panel-menu">';return menu.map(function(m){html+=self.renderFooterMenuItem(m)},this),!specs.minimenu&&self.current.list&&"array"==$.type(self.current.data)&&(html+=self.renderFooterMenuItem(__selectAllBtn__),html+='<div class="joe-selection-indicator"></div>',customMenu||(html+=self.renderFooterMenuItem({label:"Multi-Edit",name:"multiEdit",css:"joe-multi-only",action:"getJoe("+self.joe_index+").editMultiple()"}))),html+=__clearDiv__+"</div></div>",_bmResponse(fBM,"[Footer] rendered"),html},this.renderFooterMenuItem=function(m){return self.renderMenuButtons(m,"joe-footer-button")},this.renderMenuButtons=function(button,menucss){if(!button)return"";menucss=menucss||"";for(var display,action,m,html="",b=0,tot=(button="array"==$.type(button)?button:[button]).length;b<tot;b++){m=button[b];let schema=self.propAsFuncOrValue(m.schema);m?m.condition&&!self.propAsFuncOrValue(m.condition)||(display=fillTemplate(self.propAsFuncOrValue(m.label||m.display||m.name),self.current.object),action=m.callback?"getJoe("+self.joe_index+").Cache.callback('"+m.callback+"');":fillTemplate(self.propAsFuncOrValue(m.action),self.current.object)||"alert('"+display+"')",html+=`<joe-button class="joe-button ${menucss} ${m.css||""}" action="${action}" \n data-btnid="${m.id||m.name}" \n ${schema&&`schema="${schema}"`||""} \n ${m.color&&`color="${m.color}"`||""} \n title="${m.title||display||""}">\n ${display}</joe-button>`):logit("error loading menu button")}return html};var prePropWidths=0;function _getPropPlaceholder(prop){var placeholder=self.propAsFuncOrValue(prop.placeholder||prop.display||prop.name)||"";return!1===prop.placeholder?"":placeholder&&' placeholder="'+placeholder+'"'||""}function _disableField(prop){return prop.hasOwnProperty("locked")&&self.propAsFuncOrValue(prop.locked)?" disabled ":""}function cleanString(value){return((value||"")+"").replace(/\"/g,"&quot;")}this.renderObjectField=function(prop,mini){if(prop.hasOwnProperty("condition")&&!self.propAsFuncOrValue(prop.condition))return"";var joeFieldBenchmarker=new Benchmarker;self.current.fields.push(prop),prop.value=prop.asFunction?prop.value:self.propAsFuncOrValue(prop.value),prop.format&&$.type("function"==prop.format)&&(prop.value=prop.format(prop.value,prop,self.current.item)),null==prop.value&&null!=prop.default&&(prop.value=prop.default),self.current.reset[prop.name]||(self.current.reset[prop.name]="object"==typeof prop.value?$.extend({},prop.value):prop.value),prop.reset=self.current.reset[prop.name];var hidden="",qHidden=self.propAsFuncOrValue(prop.hidden);qHidden&&(hidden=void 0===parseBoolean(qHidden)?"!"==qHidden[0]^!!$.extend({},self.current.object,self.constructObjectFromFields())[qHidden.replace("!","")]?"hidden":"":"hidden");prop.locked=self.propAsFuncOrValue(prop.locked);var cssClass=prop.cssClass?self.propAsFuncOrValue(prop.cssClass):"",required="";self.propAsFuncOrValue(prop.required)&&(required="joe-required");var html="",propdside=prop.sidebar_side||prop.side||renderFieldTo;preProp&&preProp.width&&!prop.width&&(html+='<div class="clear"></div>');var containercolor=self.propAsFuncOrValue(prop.containercolor,null,null,_jco(!0)[prop.name])||"";containercolor&&(containercolor=" background-color:"+containercolor+";");var sizestyles=" ";prop.height&&(sizestyles+="min-height:"+prop.height+"; "),prop.width?html+='<joe-field-container class="joe-field-container joe-fleft" style="width:'+prop.width+"; "+sizestyles+containercolor+'" data-side="'+propdside+'">':html+='<joe-field-container field="'+prop.name+'" class="joe-field-container" data-side="'+propdside+'" style="'+sizestyles+containercolor+'">';var proptype=self.propAsFuncOrValue(prop.type,self.current.constructed),fieldlabel=self.propAsFuncOrValue(prop.display||prop.label||prop.name),icon=self.propAsFuncOrValue(prop.icon);function renderFieldAttribute(attribute){var obj=rerenderingField?self.current.constructed:self.current.object,propval=prop[attribute];return propval&&'<joe-field-attribute class="jfa-'+attribute+'">'+fillTemplate(self.propAsFuncOrValue(propval),obj)+"</joe-field-attribute>"||""}return icon&&self.schemas[icon]&&self.schemas[icon].menuicon&&(icon=self.schemas[icon].menuicon),html+='<joe-field class="joe-object-field '+hidden+" "+required+" "+proptype+"-field "+(!1===prop.label?" hide-label ":"")+" "+cssClass+'" data-type="'+proptype+'" data-name="'+prop.name+'">'+renderFieldAttribute("before")+'<label class="joe-field-label '+(icon?"iconed":"")+' " title="'+prop.name+'">'+(icon||"")+fillTemplate(fieldlabel,self.current.object)+(required?"*":"")+self.renderFieldTooltip(prop)+self.renderFieldReloadIcon(prop)+"</label>",html+=self.renderFieldComment(prop),self.current.userSpecs&&self.current.userSpecs.multiedit&&(html+='<div class="joe-field-multiedit-toggle" onclick="$(this).parent().toggleClass(\'multi-selected\')"></div>'),html+=self.selectAndRenderFieldType(prop),html+=self.renderGotoLink(prop),html+=renderFieldAttribute("after"),html+="</joe-field>",html+="</joe-field-container>",preProp=prop,_bmResponse(joeFieldBenchmarker,"field "+prop.name+" "+prop.type),html},this.renderGotoLink=function(prop,style){var goto=self.propAsFuncOrValue(prop.goto);if(goto){var action="";"string"==$.type(goto)&&(action=goto,action="getJoe("+self.joe_index+").gotoFieldItem(this,'"+goto+"');");var btnHtml="";if("select"===(style||prop.type))btnHtml+='<div class="joe-button inline joe-view-button joe-iconed-button" onclick="'+action+'" title="view '+goto+'">view</div>';return btnHtml}return""},this.gotoFieldItem=function(dom,schema){var fieldname=$(dom).parents(".joe-object-field").data("name"),field=self.getField(fieldname),idprop=field.idprop||self.getIDProp(schema),values=self.getFieldValues(field.values,field),id=$(dom).siblings(".joe-field").val(),object=values.filter(function(v){return v[idprop]==id})[0]||!1;if(!object)return!1;self.show(object,{schema:schema})},this.renderFieldComment=function(prop){var comment=self.propAsFuncOrValue(prop.comment);return comment?'<div class="joe-field-comment">'+comment+"</div>":""},this.renderFieldTooltip=function(prop){return prop.tooltip?'<span class="joe-field-tooltip" title="'+__removeTags(prop.tooltip)+'">i</span>':""},this.renderFieldReloadIcon=function(prop){return self.propAsFuncOrValue(prop.reloadable)?` <joe-icon class="joe-reload-icon fright" title="Reload Field" onclick="_joe.Fields.rerender('${prop.name}')">⟳</joe-icon>`:""},this.selectAndRenderFieldType=function(prop){var html="",proptype=(self.propAsFuncOrValue(prop.type)||"").toLowerCase();switch(proptype||(console.error(prop),self.propAsFuncOrValue(prop.type)),proptype){case"select":html+=self.renderSelectField(prop);break;case"multisort":case"multisorter":html+=self.renderMultisorterField(prop);break;case"guid":html+=self.renderGuidField(prop);break;case"number":html+=self.renderNumberField(prop);break;case"int":html+=self.renderIntegerField(prop);break;case"date":html+=self.renderDateField(prop);break;case"boolean":html+=self.renderBooleanField(prop);break;case"geo":case"map":html+=self.renderGeoField(prop);break;case"image":case"img":html+=self.renderImageField(prop);break;case"buckets":html+=self.renderBucketsField(prop);break;case"content":html+=self.renderContentField(prop);break;case"url":html+=self.renderURLField(prop);break;case"tags":html+=self.renderTagsField(prop);break;case"color":html+=self.renderColorField(prop);break;case"button":html+=self.renderButtonField(prop);break;case"group":html+=self.renderCheckboxGroupField(prop);break;case"uploader":html+=self.renderUploaderField(prop);break;case"preview":html+=self.renderPreviewField(prop);break;case"passthrough":html+=self.renderPassthroughField(prop);break;case"userfavorite":html+=self.renderUserFavoriteField(prop);break;default:self.Fields[proptype]&&self.Fields[proptype].render?html+=self.Fields[proptype].render(prop):html+=self.renderTextField(prop)}if(prop.ai)try{var aiLabel=self.propAsFuncOrValue(prop.ai.label)||"AI";html+='<button type="button" class="joe-ai-autofill-button joe-iconed-button joe-button" onclick="if(window._joe && _joe.Ai && _joe.Ai.populateField){_joe.Ai.populateField(\''+(prop.name||"")+'\');}" title="Let AI suggest a value for this field">'+aiLabel+'</button><div class="clear"></div>'}catch(_e){}return html},this.getActionString=function(evt,prop){return(evt=prop[evt])?"string"==$.type(evt)?evt:prop[evt]?" "+self.functionName(prop[evt])+"(this); ":"":""},this.renderFieldAttributes=function(prop,evts){evts=evts||{};var bluraction="",changeaction="",keypressaction="",keyupaction="",rerender=prop.rerender?" getJoe("+self.joe_index+").rerenderField('"+prop.rerender+"'); ":"",disabled=-1==self.current.profile.lockedFields.indexOf(prop.name)?"":"disabled";return(evts.onblur||prop.onblur)&&(bluraction='onblur="'+(evts.onblur||"")+" "+self.getActionString("onblur",prop)+'"'),(evts.onchange||prop.onchange||rerender)&&(changeaction='onchange="'+rerender+(evts.onchange||"")+" "+self.getActionString("onchange",prop)+'"'),(evts.onkeypress||prop.onkeypress)&&(keypressaction='onkeypress="'+(evts.onkeypress||"")+" "+self.getActionString("onkeypress",prop)+'"'),(evts.onkeyup||prop.onkeyup)&&(keyupaction='onkeyup="'+(evts.onkeyup||"")+" "+self.getActionString("onkeyup",prop)+'"')," "+keyupaction+" "+keypressaction+" "+bluraction+" "+changeaction+" "+disabled+" "},this.renderTextField=function(prop){var autocomplete;prop.autocomplete&&prop.values&&("function"==typeof prop.values&&(prop.values=prop.values(self.current.object)),"string"==$.type(prop.values)&&self.getDataset(prop.values)&&(prop.values=self.getDataset(prop.values)),"array"!=$.type(prop.values)&&(prop.values=[prop.values]),autocomplete=prop.autocomplete);var disabled=_disableField(prop),fieldtype=prop.ftype&&"data-ftype='"+prop.ftype+"'"||"",placeholder=_getPropPlaceholder(prop),html=(prop.name,'<input class="joe-text-field joe-field '+(prop.skip?"skip-prop":"")+'" '+placeholder+'type="text" '+disabled+' name="'+prop.name+'" value="'+cleanString(prop.value||"")+'" maxlength="'+(prop.maxlength||prop.max||"")+'" '+self.renderFieldAttributes(prop)+(autocomplete?" onkeyup='this.nextSibling.search(this.value)'":"")+" "+fieldtype+"/>");return autocomplete&&(html+=`<joe-autocomplete class="joe-text-autocomplete" \n field="${prop.name}" \n itemId="${self.current.object._id}" \n schema="${self.current.object.itemType||self.current.schema&&self.current.schema.name||""}" \n joe-index=${self.joe_index}\n ">\n </joe-autocomplete>`),html};var textFieldAutocompleteHandler=function(e){e.target;$(".joe-text-autocomplete").removeClass("active"),$("body").unbind("click",textFieldAutocompleteHandler)};function getObjectlistSubProperty(prop){var subprop=prop;return"string"==$.type(prop)?(subprop={name:prop}).name=subprop.name||prop:subprop.extend&&self.fields[subprop.extend]&&((subprop=$.extend({},subprop,self.fields[subprop.extend],subprop.specs||{})).name=subprop.name||subprop.extend),subprop}function _objectlistTemplateClickHandler(templateDom,stopEditing){var templateContent,subobj,fieldname=$(templateDom).parents(".joe-object-field").data("name"),fieldObj=self.getField(fieldname),constructed=_jco(!0);if((stopEditing&&$(templateDom).parents(".joe-object-field").find(".editing")||$(templateDom).parent().siblings(".editing")).each(function(index,dom){subobj=constructed[fieldname][$(this).index()],templateContent=fillTemplate(self.propAsFuncOrValue(fieldObj.template,null,null,subobj),subobj),$(this).find(".row-template").html(templateContent),$(this).removeClass("editing")}),!stopEditing){var $row=$(templateDom).parents(".joe-objectlist-row");$row.addClass("editing"),$row.find(".joe-text-field,.joe-integer-field,.joe-number-field,select,textarea").eq(0)[0].focus()}}function _sortObjectListRows(property,sortBy){try{var overwrites={};overwrites[property]=_jco(!0)[property].sortBy(sortBy),_joe.Fields.rerender(property,overwrites)}catch(e){self.Error.add("error sorting objectlist",e,{property:property,sortBy:sortBy})}}function readyObjectListFields(){function olHelper(e,tr){var $originals=tr.children(),$helper=tr.clone();return $helper.hasClass("templated")?$helper.children().each(function(index){$(this).toggle($(this).hasClass("template-visible")).width($originals.eq(index).width())}):($helper.width(tr.width()),$helper.children().each(function(index){$(this).toggle(!$(this).hasClass("row-template")),$(this).width($originals.eq(index).width())})),$helper}self.overlay.find(".joe-objectlist-table.sortable").each(function(){$(this).find("tbody").sortable({axis:"y",handle:".joe-objectlist-object-row-handle",helper:olHelper})})}function _normalizeJsonField(fieldName,opts){opts=opts||{};var parent=getJoe(self.joe_index),$holder=parent.overlay.find('.joe-ace-holder[name="'+fieldName+'"]');if(!$holder.length)return{ok:!0};var editorId=$holder.data("ace_id"),editor=_joe.ace_editors[editorId];if(!editor)return{ok:!0};var text=editor.getValue();text&&text.trim()||(text="{}");try{var parsed=JSON.parse(text);try{var pretty=JSON.stringify(parsed,null,2);editor.setValue(pretty,-1)}catch(_e){}return $holder.removeClass("joe-field-error"),{ok:!0,parsed:parsed}}catch(e){var fixed=text;try{fixed=(fixed=(fixed=fixed.replace(/([{\[],\s*|[{]\s*|,\s*)([A-Za-z_][A-Za-z0-9_]*)\s*:/g,function(m,prefix,key){return prefix+'"'+key+'":'})).replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g,'"$1"')).replace(/,\s*([}\]])/g,"$1");var reparsed=JSON.parse(fixed);try{var prettyFixed=JSON.stringify(reparsed,null,2);editor.setValue(prettyFixed,-1)}catch(_e2){}return $holder.removeClass("joe-field-error"),{ok:!0,parsed:reparsed}}catch(_fixErr){return $holder.addClass("joe-field-error"),opts.showMessage&&parent.showMessage&&parent.showMessage("Field '"+fieldName+"' must be valid JSON (object)."),{ok:!1,error:e}}}}function _removeUploaderFile(id,filename){var joe_uploader=self.uploaders[id];file=joe_uploader.files.where({filename:filename})[0],file&&(joe_uploader.files.remove(file),joe_uploader.preview.html(_renderUploaderFilePreviews(joe_uploader.files,joe_uploader.cuid)))}function _renderUploaderFilePreviews(files,cuid){var jup_template,html="",alink="<a href='${url}${base64}' class='file-link' target='_blank'></a>",delete_btn='<joe-uploader-file-delete-btn class="svg-shadow" onclick="_joe.Fields.uploader.remove(\''+cuid+"','${filename}');\">"+self.SVG.icon.close+"</joe-uploader-delete-btn>",label="<joe-uploader-file-label>${filename}</joe-uploader-file-label>";return files.map(function(file){var filesize="<joe-uploader-file-label>${filename}</joe-uploader-file-label>";file.size?(file.size>1e6?filesize=`${(file.size/1e6).toFixed(2)} mb`:file.size>1e3&&(filesize=`${(file.size/1e3).toFixed(2)} kb`),filesize=`<joe-uploader-file-size>${filesize}</joe-uploader-file-size>`):filesize="",$c.isObject(file)||(file={url:file,filename:file.substr(file.lastIndexOf("/")>0&&file.lastIndexOf("/")||0)});jup_template=file.type&&file.type.contains("image")||!file.type&&(file.url||file.base64).split(".").contains(["jpg","jpeg","png","gif","svg"])?'<joe-uploader-file class="'+(file.uploaded?"uploaded":"")+'" style="background-image:url(${url}${base64})">'+alink+label+filesize+delete_btn+"</joe-uploader-file>":["doc","docx"].includes((file.url||file.base64).split(".").pop())?'<joe-uploader-file class="'+(file.uploaded?"uploaded":"")+'"><joe-uploader-file-extension >.'+(file.type.split("/")[1]||"docx")+"</joe-uploader-file-extension>"+alink+label+filesize+delete_btn+"</joe-uploader-file>":'<joe-uploader-file class="'+(file.uploaded?"uploaded":"")+'"><joe-uploader-file-extension >.'+(file.type.split("/")[1]||"???")+"</joe-uploader-file-extension>"+alink+label+filesize+delete_btn+"</joe-uploader-file>",html+=fillTemplate(jup_template,file)}),html+'<div class="clear"></div>'}this.showTextFieldAutoComplete=function(dom){$("body").unbind("click",textFieldAutocompleteHandler).bind("click",textFieldAutocompleteHandler);var content,show,autocomplete=dom.next(".joe-text-autocomplete");needles=dom.val().toLowerCase().replace(/,/," ").split(" "),autocomplete.find(".joe-text-autocomplete-option").each(function(i,obj){content=void 0===obj.textContent?obj.innerText:obj.textContent,show=self.checkAutocompleteValue(needles,content.replace(/,/," ").toLowerCase(),obj),$(obj).toggleClass("visible",show)}),autocomplete.addClass("active")},this.hideTextFieldAutoComplete=function(dom){dom.next(".joe-text-autocomplete").removeClass("active")},this.autocompleteTextFieldOptionClick=function(dom){var value=$(dom).data("value"),parent=$(dom).parents("joe-autocomplete");parent.prev(".joe-text-field").val(value),parent.removeClass("active"),parent.siblings(".joe-reference-add-button").click()},this.checkAutocompleteValue=function(needles,haystack,dom,additive){$(dom);if(!needles.length)return!0;for(var n=0,tot=needles.length;n<tot;n++)if(-1==haystack.indexOf(needles[n]))return!1;return!0},encapsulateFieldType("text",self.renderTextField),this.renderPasswordField=function(prop){return'<input class="joe-password-field joe-field" type="password" '+_disableField(prop)+' name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop)+" />"},encapsulateFieldType("password",self.renderPasswordField),this.renderNumberField=function(prop){var step=prop.step||"any";return'<input class="joe-number-field joe-field" type="number" '+_disableField(prop)+" "+_getPropPlaceholder(prop)+' step="'+step+'" name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop,{onblur:"getJoe("+self.joe_index+").returnNumber(this);"})+" />"},this.returnNumber=function(dom){$(dom).val()&&$(dom).val(parseFloat($(dom).val()))},encapsulateFieldType("number",self.renderNumberField),this.renderIntegerField=function(prop){return'<input class="joe-int-field joe-field" type="text" '+_getPropPlaceholder(prop)+' name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop,{onblur:"getJoe("+self.joe_index+").returnInt(this);"})+" />"},this.returnInt=function(dom){$(dom).val()&&$(dom).val(parseInt($(dom).val()))},encapsulateFieldType("integer",self.renderIntegerField),this.renderSelectField=function(prop,subObject){var disabled=_disableField(prop),values=(subObject=subObject||{},self.getFieldValues(prop.values,prop)),valObjs=[];if(prop.blank)switch($.type(prop.blank)){case"string":valObjs.push({name:prop.blank||""});break;case"object":valObjs.push({name:prop.blank.name||"",value:prop.blank.value||""});break;default:valObjs.push({name:""})}values.map(function(v){"object"!=$.type(v)?valObjs.push({name:v}):valObjs.push(v)});var selected,mul=prop.multiple||prop.allowMultiple,multiple=mul?" multiple ":"",selectSize=prop.size||.5*valObjs.length>10?10:valObjs.length/2;prop.size||mul||(selectSize=1);var style='style="';prop.minwidth&&(style+="min-width:"+self.propAsFuncOrValue(prop.minwidth)),style+='"';var template,val,optionVal,propertyValue,prop_idprop,html="<select "+disabled+' class="joe-select-field joe-field" name="'+prop.name+'" '+style+' value="'+(prop.value||"")+'" size="'+selectSize+'"'+self.renderFieldAttributes(prop)+multiple+" >";return valObjs.map(function(v){propertyValue=subObject[prop.name]||self.propAsFuncOrValue(prop.value,null,null,v),template=self.propAsFuncOrValue(prop.template,null,null,v)||"",optionVal=template?fillTemplate(template,v):v.display||v.label||v.name,prop_idprop=prop.idprop&&self.propAsFuncOrValue(prop.idprop,v,null,_jco())||null,val=prop_idprop&&v.hasOwnProperty(prop_idprop)?v[prop_idprop]:v._id||v.value||v.name||"","array"==$.type(propertyValue)?(selected="",selected=-1!=prop.value.indexOf(val)?"selected":""):selected=propertyValue==val?"selected":"",html+='<option value="'+val+'" '+selected+(self.propAsFuncOrValue(v.disabled)?'disabled="disabled"':"")+">"+optionVal+"</option>"}),html+="</select>"},encapsulateFieldType("select",self.renderSelectField),this.renderDateField=function(prop,subObject){if(prop.native){subObject=subObject||{};var placeholder=_getPropPlaceholder(prop),dateVal=_joe.Utils.toDateString(new Date(subObject[prop.name]||prop.value||""),"Y-m-d");return html='<input class="joe-date-field joe-field" type="date" '+placeholder+" "+_disableField(prop)+' name="'+prop.name+'" value="'+dateVal+'" '+self.renderFieldAttributes(prop)+' required pattern="d{2}/d{2}/d{4}" />'}subObject=subObject||{};var html='<input class="joe-date-field joe-field jquery" type="text" '+(placeholder=_getPropPlaceholder(prop))+" "+_disableField(prop)+' name="'+prop.name+'" value="'+(subObject[prop.name]||prop.value||"")+'" '+self.renderFieldAttributes(prop)+" />";return html+='<joe-datepicker-holder id="'+prop.name+'"></joe-datepicker-holder>'},this.readyDateField=function(prop){var field;self.overlay.find(".joe-date-field.jquery").each(function(i,dom){field=_joe.getField(dom.name),$(dom).parents(".joe-objectlist-row").length?$(dom).Zebra_DatePicker({format:"m/d/Y",first_day_of_week:0,readonly_element:!1,start_date:(new Date).format("m/d/y")}):$(dom).Zebra_DatePicker({always_visible:self.propAsFuncOrValue(field.always_visible)&&$("joe-datepicker-holder#"+$(dom).attr("name"))||!1,format:"m/d/Y",first_day_of_week:0,readonly_element:!1,container:$("joe-datepicker-holder#"+$(dom).attr("name"))})})},encapsulateFieldType("date",self.renderDateField,{ready:self.readyDateField}),this.renderTimeField=function(prop){return'<input class="joe-time-field joe-field" type="text" '+_disableField(prop)+' name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop)+" />"},this.readyTimeField=function(prop){var field;self.overlay.find(".joe-time-field").each(function(i,dom){field=_joe.getField(dom.name),$(dom).timepicker({timeFormat:"h:mm p",minTime:field.minTime,maxTime:field.maxTime,startTime:field.startTime,endTime:field.endTime,dropdown:!1})})},encapsulateFieldType("time",self.renderTimeField,{ready:self.readyTimeField}),this.renderGeoField=function(prop){var propLocation;try{propLocation=prop.value&&eval(prop.value)}catch(e){self.Error.add("error finding geo for "+(prop.name||""),e,prop.value)}var zoom=prop.zoom||4,mapDiv="joeGEO_"+prop.name,geoval=tryEval(prop.value),val=prop.value||"",geometrytype=prop.geometry||"point";if(geoval&&geoval[0]&&"array"==$.type(geoval[0])){var center=prop.center||[40.513,-96.02];geometrytype="polygon"}else var center=propLocation||prop.center||[40.513,-96.02];var geofield="polygon"==geometrytype?'<textarea placeholder="enter geometry here" onchange="_joe.addMapPolygon(\''+mapDiv+'\',this.value)" class="joe-geo-field joe-field" name="'+prop.name+'" '+_disableField(prop)+">"+val.replace(/\n/g,"")+"</textarea>":'<input class="joe-geo-field joe-field" type="text" value="'+val+'" name="'+prop.name+'" '+_disableField(prop)+"/>",html='<div class="joe-geo-map joe-field" name="'+prop.name+'" id="'+mapDiv+'" data-center="'+JSON.stringify(center)+'" data-zoom="'+zoom+'" data-value="'+val+'" data-geometrytype="'+geometrytype+'"data-hideattribution="'+(prop.hideAttribution||"")+'" onload="getJoe('+self.joe_index+').initGeoMap(this);"></div>'+geofield+'<script type="text/javascript">setTimeout(function(){getJoe('+self.joe_index+').initGeoMap("'+mapDiv+'");},100)<\/script>';return html},this.initGeoMap=function(id){var mapspecs=$("#"+id).data();$("#"+id).attr("name");self.current.cache.leaflet=self.current.cache.leaflet||{};var map=self.current.cache.leaflet[id]=L.map(id).setView(mapspecs.center,mapspecs.zoom);if(L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png",{}).addTo(map),"point"==mapspecs.geometrytype)(new L.esri.Controls.Geosearch).addTo(map).on("results",function(data){var latlng=data.latlng,map=self.current.cache.leaflet[$(data.target._input).parents(".joe-geo-map").attr("id")];map.marker?map.marker.setLatLng(latlng):self.addMapIcon(map,latlng),$("input[name="+map.prop+"]").val("["+latlng.lat+","+latlng.lng+"]")}),map.on("click",self.onMapClick),mapspecs.value&&self.addMapIcon(map,mapspecs.value);else if("polygon"==mapspecs.geometrytype){var geoval=tryEval(mapspecs.value);self.addMapPolygon(map,geoval)}mapspecs.hideattribution&&$(".leaflet-control-attribution").hide(),map.prop=$("#"+id).attr("name")},this.onMapClick=function(e,s,d){var map="click"==e.type?e.target:e.target.map||self.current.leaflet,ll=e&&e.latlng&&(e.latlng.latlng||e.latlng)||this.getLatLng();map.setView(ll),"dragend"==e.type||(map.marker?map.marker.setLatLng(ll):self.addMapIcon(map,ll)),$("input[name="+map.prop+"]").val("["+ll.lat+","+ll.lng+"]")},this.addMapIcon=function(map,latlng,specs){try{if(null===tryEval(latlng))throw"could not eval"+latlng;specs=specs||{};var myIcon=L.icon({iconUrl:specs.icon||"/JsonObjectEditor/img/mapstar.png",iconSize:[30,30]});map.marker=L.marker(latlng,{draggable:!0,icon:myIcon}).addTo(map),map.marker.map=map,map.marker.on("dragend",self.onMapClick)}catch(e){self.Error.add("error adding point to map",e,{latlng:latlng}),map.marker&&map.removeLayer(map.marker)}},this.addMapPolygon=function(map,geometry,specs){map=self.getMapFieldMap(map);try{geometry=tryEval(geometry),specs=specs||{};var myPoly=L.polygon(geometry);map.polygon=myPoly.addTo(map),map.polygon.map=map,map.fitBounds(myPoly.getBounds()),$("textarea[name="+map.prop+"]").val($("textarea[name="+map.prop+"]").val().replace(/\n/g,""))}catch(e){self.Error.add("error adding polygon to map",e,{geometry:geometry}),map.polygon&&map.removeLayer(map.polygon)}},this.getMapFieldMap=function(id){return"object"==typeof id?id:(-1==id.indexOf("joeGEO_")&&(id="joeGEO_"+id),self.current.cache.leaflet[id])},encapsulateFieldType("geo",self.renderGeoField,{ready:self.initGeoMap,addPoly:this.addMapPolygon}),this.renderBooleanField=function(prop){self.current.profile;return'<label class="joe-boolean-label" for="joe_checkbox-'+prop.name+'"><input class="joe-boolean-field joe-field" type="checkbox" name="'+prop.name+'" id="joe_checkbox-'+prop.name+'" '+([!0,"true"].contains(prop.value)?"checked":"")+self.renderFieldAttributes(prop)+" "+_disableField(prop)+"/> <small>"+(prop.label||"")+"</small></label>"},encapsulateFieldType("guid",self.renderGuidField),this.renderUserFavoriteField=function(prop){return"user favorite"},this.renderGuidField=function(prop){self.current.profile;return'<input class="joe-guid-field joe-field" type="text" '+_getPropPlaceholder(prop)+' name="'+prop.name+'" value="'+(prop.value||cuid())+'" disabled />'},encapsulateFieldType("guid",self.renderGuidField),this.renderCreateField=function(prop){var schema=self.schemas[prop.schema]||prop.schema,schemaTitle="";if(!schema||!schema.name)return"schema not found";schemaTitle=schema.name.toUpperCase();prop.name;return html=`<joe-button schema="${prop.schema}" icon="plus" color="orangegrey" action="_joe.Fields.create.go('${prop.name}')" style="float:none">\n new <b>${schemaTitle}</b>\n </joe-button>`,html},this.gotoCreatedItem=function(propname){var prop=self.getField(propname);if(!prop.schema)return"no schema selected";if(self.isNewItem()){if(!prop.autosave)return void alert("please save this item before creating another");self.updateObject()}var schema=self.schemas[prop.schema]||prop.schema,overwrites=self.propAsFuncOrValue(prop.new||prop.overwrites)||{},newitem=_joe.propAsFuncOrValue(schema.new),item=$.extend({},newitem,overwrites);goJoe(item,{schema:schema})},encapsulateFieldType("create",self.renderCreateField,{go:self.gotoCreatedItem}),this.renderImageField=function(prop){var html="";return self.propAsFuncOrValue(prop.hidefield)||(html+='<input class="joe-image-field joe-field" type="text" name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop)+' onkeyup="_joe.updateImageFieldImage(this);" '+_disableField(prop)+"/>"),html+='<img class="joe-image-field-image" src="'+(prop.value||"")+'" /><span class="joe-image-field-size"></span>'},this.updateImageFieldImage=function(dom,timeout){logit("img update");var src=$(dom).val(),img=$(dom).parent().find(".joe-image-field-image");self.updateImageSize(img),img.attr("src",src)},this.updateImageSize=function(img){var jqImg=$(img);jqImg.siblings(".joe-image-field-size").html(jqImg.width()+"w x "+jqImg.height()+"h")},encapsulateFieldType("image",self.renderImageField),this.renderMultisorterField=function(prop){var li,val_index,values=self.getFieldValues(prop.values,prop),optionsHtml="",idprop=prop.idprop||"id",template=prop.template||"${name} (${"+idprop+"})",value=prop.value||[],selectionsArray=Array(value.length);values||(values=[]),values.map(function(v){li=function(v){return'<li data-id="'+v[idprop]+'" ondblclick="_joe.toggleMultisorterBin(this);">'+fillTemplate(template,v)+"</li>"}(v),-1!=(val_index=value.indexOf(v[idprop]))?selectionsArray[val_index]=li:optionsHtml+=li});var selectionsHtml=selectionsArray.join(""),height=prop.height&&"style='max-height:"+prop.height+";'"||"";return'<div class="joe-multisorter-field joe-field" name="'+prop.name+'" data-ftype="multisorter" data-multiple="'+(prop.allowMultiple||"false")+'"><div class="joe-filter-field-holder"><input type="text"class="" onkeyup="_joe.filterSorterOptions(this);"/></div><p class="joe-tooltip"> double click or drag item to switch columns.</p><ul class="joe-multisorter-bin options-bin" '+height+">"+optionsHtml+'</ul><ul class="joe-multisorter-bin selections-bin" '+height+">"+selectionsHtml+"</ul>"+__clearDiv__+"</div>"},this.filterSorterOptions=function(dom){var sorterBM=new Benchmarker,query=$(dom).val().toLowerCase();$(dom).parents(".joe-field").find(".joe-multisorter-bin.options-bin").find("li").each(function(){$(this).toggle(-1!=$(this).html().toLowerCase().indexOf(query))}),_bmResponse(sorterBM,"found results for: "+query)},this.toggleMultisorterBin=function(dom){var id=$(dom).data("id"),parent=$(dom).parents(".joe-multisorter-bin"),target=(parent.parents(".joe-multisorter-field"),parent.siblings(".joe-multisorter-bin")),newDom=parent.find("li[data-id="+id+"]").detach();target.prepend(newDom)},encapsulateFieldType("multisorter",self.renderMultisorterField),this.renderBucketsField=function(prop){for(var values=self.getFieldValues(prop.values,prop),bucketNames=self.propAsFuncOrValue(prop.bucketNames)||[],bucketCount=self.propAsFuncOrValue(prop.bucketCount)||3,optionsHtml="",bucketsHtml=[],value=prop.value||[[],[],[]],i=0;i<bucketCount;i++)bucketsHtml.push(""),value[i]||value.push([]);var lihtml,foundItem,bucketItem,idprop=prop.idprop||"_id",template=prop.template||"${name} <br/><small>(${"+idprop+"})</small>",selectedIDs=[];for(i=0;i<bucketCount;i++)for(var li=0;li<value[i].length;li++)bucketItem=value[i][li],"string"==$.type(bucketItem)?((foundItem=values.filter(function(v){return v[idprop]==bucketItem})[0]||!1)||((foundItem={})[idprop]=li),selectedIDs.push(bucketItem),lihtml=self.renderBucketItem(foundItem,prop,!1)):"object"==$.type(bucketItem)&&(foundItem=bucketItem,lihtml=self.renderBucketItem(foundItem,prop,!0)),bucketsHtml[i]+=lihtml;var optionTemplate=prop.optionTemplate||template;values.map(function(v){var resolvedTemplate=self.propAsFuncOrValue(optionTemplate,self.current.object,null,v),optionContent=fillTemplate(resolvedTemplate||"",v);lihtml='<li data-value="'+v[idprop]+'" >'+optionContent+'<div class="joe-bucket-delete cui-block joe-icon" onclick="$(this).parent().remove()"></div></li>',(-1==selectedIDs.indexOf(v[idprop])||prop.allowMultiple)&&(optionsHtml+=lihtml)});var html='<div class="joe-buckets-field joe-field" name="'+prop.name+'" data-ftype="buckets"><div class="joe-filter-field-holder"><input type="text"class="" onkeyup="_joe.filterBucketOptions(this);"/></div><div class="joe-buckets-field-holder" style="width:25%;"><ul class="joe-buckets-bin options-bin '+(prop.allowMultiple?"allow-multiple":"")+'">'+optionsHtml+'</ul></div><div class="joe-buckets-field-holder" style="width:75%;">';return bucketsHtml.map(function(b,i){html+=function(id,name,width){return'<ul class="joe-buckets-bin selections-bin" '+(width?'style="width:'+width+'"':"")+">"+(name?'<div class="joe-bucket-label">'+name+"</div>":"")+bucketsHtml[id]+"</ul>"}(i,bucketNames[i]||"",prop.bucketWidth)}),html+=__clearDiv__+"</div>"+__clearDiv__+"</div>"},this.filterBucketOptions=function(dom){var query=$(dom).val().toLowerCase();$(dom).parents(".joe-buckets-field").find(".options-bin").find("li").each(function(){$(this).toggle(-1!=$(this).html().toLowerCase().indexOf(query))}),logit(query)},this.readyBinFields=function(){try{self.overlay.find(".joe-multisorter-bin").sortable({connectWith:".joe-multisorter-bin",placeholder:"joe-sortable-highlight",items:"li"}),self.overlay.find(".joe-buckets-bin").sortable({connectWith:".joe-buckets-bin",placeholder:"joe-sortable-highlight",items:"li",start:function(event,ui){sortable_index=ui.item.index(),ui.item.parents()},update:function(event,ui){ui.sender&&ui.sender.hasClass("options-bin")&&ui.sender.hasClass("allow-multiple")&&ui.sender.find("li").eq(sortable_index).before(ui.item.clone())}})}catch(e){self.Error.add("Error creating sortables:\n"+e,e,{caller:"self.readyBinFields"})}},this.renderBucketItem=function(item,fieldnameorobject,specs){var fieldObj="object"==$.type(fieldnameorobject)?fieldnameorobject:self.getField(fieldnameorobject)||{};!0!==specs&&!1!==specs||(specs={isobject:specs});var idprop=fieldObj.idprop||specs.idprop||"_id",template=fieldObj.template||specs.template||"${name} <br/><small>(${"+idprop+"})</small>",value=fieldObj.isobject||specs.isobject?'data-isobject=true data-value="'+encodeURI(JSON.stringify(item))+'"':'data-value="'+item[idprop]+'"',resolvedTemplate=self.propAsFuncOrValue(template,self.current.object,null,item);return"<li "+value+">"+fillTemplate(resolvedTemplate||"",item)+'<div class="joe-bucket-delete cui-block joe-icon" onclick="$(this).parent().remove()"></div></li>'},encapsulateFieldType("buckets",self.renderBucketsField,{create:self.renderBucketItem,ready:self.readyBinFields}),this.renderContentField=function(prop){var html="",itemObj=self.current.object,idProp=prop.idprop||self.getIDProp(),constructedItem=self.current.constructed||{};(!self.current.object[idProp]||constructedItem[idProp]&&constructedItem[idProp]==self.current.object[idProp])&&(itemObj=constructedItem,self.current.object[idProp]&&constructedItem[idProp]==self.current.object[idProp]&&(itemObj=rerenderingField?$.extend({},self.current.object,constructedItem):$.extend({},constructedItem,self.current.object)));try{prop.run?html+=prop.run(itemObj,prop)||"":prop.template?html+=fillTemplate(self.propAsFuncOrValue(prop.template),itemObj):prop.value&&(html+=self.propAsFuncOrValue(prop.value))}catch(e){return self.Error.add("error rendering field:"+e,e,{caller:"self.renderContentField"}),"error rendering field:"+e}return html},encapsulateFieldType("content",self.renderContentField),this.Render.fieldListItem=this.renderFieldListItem=function(item,contentTemplate,schema,specs){var schemaprop=(specs=$.extend({isObject:!1,deleteButton:!1,expander:null,gotoButton:!1,itemMenu:!1,schemaprop:!1,nonclickable:!1,action:!1,stripecolor:!1,bgcolor:!1,checkbox:!1,value:"",link:!1},specs)).schemaprop&&self.propAsFuncOrValue(specs.schemaprop,item),schemaobj=(schema=schemaprop&&item[schemaprop]||schema||item.itemtype||item.type,self.schemas[schema]),idprop=(contentTemplate=self.propAsFuncOrValue(contentTemplate,null,null,item)||self.propAsFuncOrValue(schemaobj&&(schemaobj.listTitle||schemaobj.listView&&schemaobj.listView.title),item)||"<joe-title>${name}</joe-title><joe-subtext>${itemtype}</joe-subtext>",specs.idprop||schemaobj&&schemaobj.idprop||"_id"),hasMenu=specs.itemMenu&&specs.itemMenu.length,action=self.propAsFuncOrValue(specs.action,item)||" onclick=\"goJoe(_joe.search('${"+idprop+"}')[0],{schema:'"+schema+"'})\" ",nonclickable=self.propAsFuncOrValue(specs.nonclickable,item),clickablelistitem=!specs.gotoButton&&!nonclickable,deleteButton='<div class="joe-delete-button joe-block-button right" onclick="__cancelPropagation();$(this).parent().remove();'+(specs.fieldname&&"_joe.Fields.objectreference.remove('"+specs.fieldname+"');"||"")+'">&nbsp;</div>',expanderContent=renderItemExpander(item,specs.expander),click=clickablelistitem?action:"",value=specs.isObject?'data-value="'+encodeURI(JSON.stringify(specs.value))+'" data-isObject=true':'data-value="'+specs.value+'"',link=specs.link&&self.propAsFuncOrValue(specs.link,item);return fillTemplate(`<joe-list-item schema="${schema}" \n itemId="${item[idprop]}"\n idprop="${idprop}"\n ${specs.icon&&`icon="${specs.icon}"`||""}\n class="`+(clickablelistitem?"joe-field-list-item clickable":"joe-field-item")+(specs.deleteButton?" deletable":"")+(specs.gotoButton?" gotobutton":"")+(specs.itemMenu?" itemmenu":"")+(specs.stripecolor?" striped":"")+(specs.checkbox?" checkboxed":"")+(specs.expander?" expander expander-collapsed":"")+'" '+(value||"")+">"+(hasMenu&&renderItemMenu(item,specs.itemMenu)||"")+self.Render.bgColor(item,specs.bgcolor)+self.Render.itemCheckbox(item,schemaobj)+(link&&'<a class="non-link" onclick="__cancelClick();" href="'+link+'">'||"")+'<div class="joe-field-item-content '+(nonclickable?"nonclickable":"")+'" '+click+" >"+self.propAsFuncOrValue(contentTemplate+__clearDiv__,item)+__clearDiv__+"</div>"+(link?"</a>":"")+self.Render.stripeColor(item,specs.stripecolor)+self._renderExpanderButton(expanderContent,item)+(specs.deleteButton&&deleteButton||"")+(specs.gotoButton?"${RUN[_renderGotoButton]}":"")+expanderContent+"</joe-list-item>",item)},this.renderURLField=function(prop){self.current.profile;var disabled=_disableField(prop),prefix=self.propAsFuncOrValue(prop.prefix);return(prefix=fillTemplate(prefix||"",self.current.object))+`<joe-button schema="${prop.schema||""}" action="view" class="joe-button" color="green" prefix="${prefix}" ></joe-button><input class="joe-url-field joe-field" type="text" `+self.renderFieldAttributes(prop)+'name="'+prop.name+'" value="'+(prop.value||"")+'" '+disabled+" />"+__clearDiv__},this.gotoFieldURL=function(dom,prefix){var url=$(dom).siblings(".joe-url-field").val();window.open((prefix||"")+url)},encapsulateFieldType("url",self.renderURLField),this.renderColorField=function(prop){return'<input class="joe-color-field joe-field" type="text" name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop)+" /><script>_joe._colorFieldListener($('input.joe-color-field[name="+prop.name+"]')[0]);$('input.joe-color-field[name="+prop.name+"]').keyup(_joe._colorFieldListener);<\/script>"},this._colorFieldListener=function(e){var field=e.delegateTarget||e,color=field.value;$(field).parents(".joe-object-field").css("background-color",color)},encapsulateFieldType("color",self.renderColorField),this.renderObjectListField=function(prop){var html="<table class='joe-objectlist-table "+(prop.hideHeadings?" hidden-heading ":"")+(!1===prop.sortable?"":" sortable ")+"' >"+self.renderObjectListHeaderProperties(prop)+self.renderObjectListObjects(prop)+"</table>",max=prop.max,pName=(prop.display||prop.name).split(" ");"s"==(pName=pName[pName.length-1])[pName.length-1]&&(pName=pName.substr(0,pName.length-1).toLowerCase());var label=prop.label||pName&&`add ${pName}`||"add item";if((!max||!prop.value||prop.value.length<max)&&!prop.locked){var addaction='onclick="getJoe('+self.joe_index+").addObjectListItem('"+prop.name+"')\"";html+='<div style="text-align:center;">';prop.hasOwnProperty("template")&&(html+='<joe-button style="" class=" joe-done-button joe-button joe-grey-button" onclick="_joe.Fields.objectlist.editHandler($(this).parents(\'.joe-object-field\').find(\'.row-template\').eq(0),true)"> - </joe-button>'),html+='<div class="joe-button joe-iconed-button joe-plus-button joe-orangegrey-button" '+addaction+"> "+label+"</div>"+__clearDiv__+"</div>"}return html},this.objectlistdefaultproperties=["name","_id"],this.renderObjectListHeaderProperties=function(prop){for(var property,subprop,width,onclick,properties=self.propAsFuncOrValue(prop.properties)||self.objectlistdefaultproperties,sortable=!1!==prop.sortable,html="<thead><tr>"+(sortable?'<th class="joe-objectlist-object-row-handle-header" ></th>':"")+'<th class="joe-objectlist-object-row-template-header"></th>',p=0,tot=properties.length;p<tot;p++)property={name:(subprop=getObjectlistSubProperty(properties[p])).display||subprop.name,type:subprop.type||"text"},onclick=sortable?'title="sort by '+property.name+" ("+subprop.name+')" onclick="_joe.Fields.objectlist.sortBy(\''+prop.name+"','"+subprop.name+"');\"":'title="('+subprop.name+')"',width=subprop.width?'width="'+subprop.width+'"':"",html+="<th "+onclick+" data-subprop='"+subprop.name+"' "+width+">"+(subprop.display||subprop.name)+"</th>";return html+="<th class='joe-objectlist-delete-header'></th>",html+="</tr></thead>"},this.renderObjectListObjects=function(prop){for(var obj,objects=prop.value||(self.current.constructed||self.current.object)[prop.name]||prop.default||[],properties=self.propAsFuncOrValue(prop.properties)||self.objectlistdefaultproperties,html="<tbody>",o=0,objecttot=objects.length;o<objecttot;o++)obj=objects[o],html+=self.renderObjectListRow(obj,properties,o,prop);return html+="</tbody>"},this.renderObjectListRow=function(object,objectListProperties,index,prop,editing){var property,properties=self.propAsFuncOrValue(objectListProperties)||self.objectlistdefaultproperties,sortable=!1!==prop.sortable,html="",templateContent=fillTemplate(self.propAsFuncOrValue(prop.template,null,null,object),object);html+="<tr class='joe-objectlist-row "+(templateContent||editing?"templated":"")+" "+(editing?"editing":"")+"' data-index='"+index+"'>"+(prop.locked?"<td class='template-visible'></td>":sortable?"<td class='sort-handle template-visible'><div class='joe-panel-button joe-objectlist-object-row-handle'>|||</div></td>":"");html+="<td class='row-template template-visible' onclick=\"_joe.Fields.objectlist.editHandler(this);\" colspan='"+(properties.length+1)+"'>"+templateContent+"</td>";for(var subprop,renderInput={text:self.renderTextField,select:self.renderSelectField,date:self.renderDateField,content:self.renderContentField,rendering:self.renderRenderingField,boolean:self.renderBooleanField,url:self.Fields.url.render},p=0,tot=properties.length;p<tot;p++)subprop=getObjectlistSubProperty(properties[p]),property=$.extend({name:subprop.name,type:subprop.type||"text",value:object[subprop.name]||""},subprop),self.Fields.objectlist.toReady.push(property.type),html+="<td>"+(renderInput[property.type]||self.Fields[property.type].render)(property,object)+"</td>";var delaction="onclick='getJoe("+self.joe_index+")._oldeleteaction(this);'";return html+=prop.locked?"<td class='template-visible'></td>":"<td class='template-visible'><div class='jif-panel-button joe-delete-button' "+delaction+">&nbsp;</div></td>",html+="</tr>"},this.addObjectListItem=function(fieldname,specs){self.Fields.objectlist.toReady=[];var fieldobj=self.getField(fieldname),index=$(".joe-object-field[data-name="+fieldname+"]").find(".joe-objectlist-row").length,content=self.renderObjectListRow(self.propAsFuncOrValue(fieldobj.new)||{},fieldobj.properties,index,fieldobj,fieldobj.hasOwnProperty("template"));$(".joe-object-field[data-name="+fieldname+"]").find("tbody").append(content),$(".joe-object-field[data-name="+fieldname+"] .joe-objectlist-row:last").find(".joe-text-field,.joe-integer-field,.joe-number-field,select,textarea").eq(0)[0].focus(),self.Fields.objectlist.toReady.map(function(fieldtype){self.Fields[fieldtype]&&self.Fields[fieldtype].ready&&self.Fields[fieldtype].ready(fieldobj)}),fieldobj.hasOwnProperty("template")&&_objectlistTemplateClickHandler($(".joe-object-field[data-name="+fieldname+"] .joe-objectlist-row:last .row-template"))},this._oldeleteaction=function(dom){$(dom).parents(".joe-objectlist-row").remove()},this.removeObjectListItem=function(fieldname,index){self.getField(fieldname);$(".joe-object-field[data-name=module_fields]").find("tbody").append(content)},encapsulateFieldType("objectlist",self.renderObjectListField,{add:self.addObjectListItem,ready:readyObjectListFields,toReady:[],editHandler:_objectlistTemplateClickHandler,sortBy:_sortObjectListRows}),this.renderCheckboxGroupField=function(prop){var checked,values=self.getFieldValues(prop.values,prop),locked=self.propAsFuncOrValue(prop.locked)?" disabled ":"",html="",propval=self.propAsFuncOrValue(prop.value);"array"!=$.type(propval)&&(propval=[propval]);var idprop=prop.idprop||"_id",cols=prop.cols||prop.numCols||2;return values.map(function(value){if("object"!=$.type(value)){var tempval={name:value};tempval[idprop]=value,value=tempval}"joe_checkbox-"+prop.name,checked=-1!=(propval||[]).indexOf(value[idprop])?" checked ":"",html+='<div class="joe-group-item '+locked+" cols-"+cols+'"><label ><div class="joe-group-item-checkbox"><input class="joe-field" '+locked+' type="checkbox" name="'+prop.name+'" '+checked+self.renderFieldAttributes(prop)+'value="'+value[idprop]+'" '+_disableField(prop)+` onchange="getJoe(${self.joe_index}).Fields.group.change('${prop.name}')" /></div>`+(prop.template&&fillTemplate(prop.template,value)||value.label||value.name||"")+"</label></div>"}),html+=__clearDiv__},this.onCheckboxGroupUpdate=function(fieldname){var fieldObj=self.Fields.get(fieldname),newTitle=_joe.propAsFuncOrValue(fieldObj.display||name);document.querySelector(`.joe-field-label[title="${fieldname}"]`).innerHTML=newTitle},encapsulateFieldType("group",self.renderCheckboxGroupField,{change:self.onCheckboxGroupUpdate}),this.renderCodeField=function(prop){self.current.profile;var height=prop.height?'style="height:'+prop.height+';"':"",code_language=(self.propAsFuncOrValue(prop.language)||"html").toLowerCase(),editor_id=cuid();return`<div>\n <joe-button class="tight" onclick="_joe.Fields.code.fullscreen('${editor_id}');"> &#x26F6; fullscreen</joe-button>\n </div><div class="clear joe-ace-holder joe-rendering-field joe-field" `+height+' data-ace_id="'+editor_id+'" data-ftype="ace" name="'+prop.name+'"><textarea class="" id="'+editor_id+'" >'+(prop.value||"")+'</textarea></div><script>var editor = ace.edit("'+editor_id+'");\t\t\teditor.setTheme("ace/theme/tomorrow");\t\t\teditor.getSession().setUseWrapMode(true);\t\t\teditor.getSession().setMode("ace/mode/'+code_language+'");\t\t\teditor.setOptions({\t\t\t\tenableBasicAutocompletion: true,\t\t\t\tenableLiveAutocompletion: false\t\t\t});\t\t\t_joe.ace_editors["'+editor_id+'"] = editor; <\/script>'},this.fullScreenCodeEditor=function(editor_id){var elem=document.querySelector(`div.joe-ace-holder[data-ace_id="${editor_id}"]`);elem.requestFullscreen?elem.requestFullscreen():elem.webkitRequestFullscreen?elem.webkitRequestFullscreen():elem.msRequestFullscreen&&elem.msRequestFullscreen()},encapsulateFieldType("code",self.renderCodeField,{fullscreen:this.fullScreenCodeEditor}),this.renderJsonField=function(prop){var displayValue,height=prop.height?'style="height:'+prop.height+';"':"",editor_id=cuid(),rawValue=void 0===prop.value?{}:prop.value;if("string"==typeof rawValue)try{rawValue=JSON.parse(rawValue)}catch(e){}if(null==rawValue&&(rawValue={}),"object"==typeof rawValue)try{displayValue=JSON.stringify(rawValue,null,2)}catch(e){displayValue="{}"}else try{displayValue=JSON.stringify(rawValue,null,2)}catch(e){displayValue="{}"}return'<div class="clear joe-ace-holder joe-rendering-field joe-field" '+height+' data-ace_id="'+editor_id+'" data-ftype="ace" name="'+prop.name+'"><textarea class="" id="'+editor_id+'" >'+(displayValue||"{}")+'</textarea></div><script>try{ var editor = ace.edit("'+editor_id+'"); editor.setTheme("ace/theme/tomorrow"); editor.getSession().setUseWrapMode(true); editor.getSession().setMode("ace/mode/json"); editor.setOptions({ enableBasicAutocompletion: true, enableLiveAutocompletion: false }); _joe.ace_editors["'+editor_id+'"] = editor; }catch(e){ console && console.warn && console.warn("ACE json init error",e);} <\/script>'},encapsulateFieldType("json",self.renderJsonField,{ready:function(){getJoe(self.joe_index).overlay.find(".joe-ace-holder[name]").each(function(){var name=$(this).attr("name"),field=self.getField(name);if(!field)return!0;if("json"!=(self.propAsFuncOrValue(field.type)||"").toLowerCase())return!0;var editorId=$(this).data("ace_id"),editor=_joe.ace_editors[editorId];if(!editor)return!0;editor.on("blur",function(){_normalizeJsonField(name,{showMessage:!1})})})},normalize:_normalizeJsonField}),this.renderQRCodeField=function(prop){prop.height&&prop.height;var size=prop.size||280,idprop=_joe.getIDProp(),template=self.propAsFuncOrValue(prop.template)||'{"${itemtype}":"${'+idprop+'}"}';fillTemplate;template=fillTemplate(template,self.current.object);var qrcode_url=prop.url||"http://www.qr-code-generator.com/phpqrcode/getCode.php?cht=qr&chl="+encodeURIComponent(template)+"&chs="+size+"x"+size+"&choe=UTF-8&chld=L|0",html='<a href="'+qrcode_url+'" target="_blank"><img class="joe-qrcode-image" src="'+qrcode_url+'" /></a>';return self.propAsFuncOrValue(prop.showContent)&&(html+="<joe-subtext>"+template+"</joe-subtext>"),html},encapsulateFieldType("qrcode",self.renderQRCodeField),this.renderRenderingField=function(prop){var locked=self.propAsFuncOrValue(prop.locked)?" disabled ":"",height=(self.current.profile,prop.height?'style="height:'+prop.height+';"':"");return'<textarea placeholder="'+(self.propAsFuncOrValue(prop.placeholder)||"")+'" class="joe-rendering-field joe-field" '+height+" "+locked+'name="'+prop.name+'" >'+(prop.value||"")+"</textarea>"},encapsulateFieldType("rendering",self.renderRenderingField),this.renderTagsField=function(prop){self.current.profile,prop.height&&prop.height;var specs=$.extend({},prop,{autocomplete:!0});return'<div class="joe-tags-container">'+self.renderTextField(specs)+'<div class="joe-text-input-button">add</div></div>'},this.uploaders={},this.renderUploaderField=function(prop){var uploader_id=cuid();"undefined"==typeof AWS&&$("body").append('<script>function none(){return; }<\/script><script type="text/javascript" src="https://sdk.amazonaws.com/js/aws-sdk-2.1.34.min.js"><\/script><script src="'+joe_web_dir+'js/libs/craydent-upload-2.0.0.js" type="text/javascript"><\/script>');var dz_message='<div style="line-height:100px;">drag files here to upload</div>',files=prop.value||[];if(files&&!$c.isArray(files)&&(files=[files]),prop.field&&self.current.object[prop.field]){var kfield=self.getField(prop.field),preview=self.current.object[prop.field];kfield.prefix&&(preview=fillTemplate(kfield.prefix,self.current.object)+preview),dz_message='<img src="'+preview+'"/>'}else files&&(files.length&&(dz_message=""),dz_message+=_renderUploaderFilePreviews(files,uploader_id));var html='<div class="joe-uploader joe-field" data-ftype="uploader" name="'+prop.name+'" data-uploader_id="'+uploader_id+'"><div class="joe-uploader-dropzone"><div class="joe-uploader-preview">'+dz_message+'</div></div><div class="joe-uploader-message">add a file</div><div class="joe-button joe-green-button joe-upload-cofirm-button hidden" onclick="_joe.uploaderConfirm(\''+uploader_id+"','"+prop.name+"');\">Upload File</div>"+__clearDiv__+"</div>",uploader_obj={cuid:uploader_id,prop:prop.name,files:files,max:prop.max||0};return self.uploaders[uploader_id]=uploader_obj,html},this.onUserUpload=function(file,base64){var dom=$(this.dropZone).parent(),joe_uploader=self.uploaders[dom.data("uploader_id")];if(_joe.getField(joe_uploader.prop).use_legacy)file?(joe_uploader.file=file,joe_uploader.base64=base64,$(joe_uploader.dropzone).find("img,div").replaceWith('<img src="'+base64+'">'),joe_uploader.message.html("<b>"+file.name+"</b> selected"),joe_uploader.confirmBtn.removeClass("hidden")):results.innerHTML="Nothing to upload.";else if(file){var fname=file.name.replace(/ /g,"_");if(joe_uploader.files.where({filename:fname}).length){var ext=fname.substr(fname.lastIndexOf("."));if((fname=fname.substr(0,fname.lastIndexOf("."))).lastIndexOf("_")>0){var fint=parseInt(fname.substr(fname.lastIndexOf("_")+1));fint+=1,fname=fname.substr(0,fname.lastIndexOf("_")+1)+fint}else fname+="_1";fname+=ext}var temp_file={uploaded:!1,filename:fname,extension:file.type||file.name.substr(file.name.lastIndexOf(".")),size:file.size,type:file.type,base64:base64,added:new Date};joe_uploader.files.push(temp_file),$(joe_uploader.preview).html(_renderUploaderFilePreviews(joe_uploader.files,joe_uploader.cuid)),joe_uploader.confirmBtn.removeClass("hidden")}else results.innerHTML="Nothing to upload."},this.uploaderConfirm=function(uploader_id){var joe_uploader=self.uploaders[uploader_id],field=_joe.getField(joe_uploader.prop);if(field.use_legacy){var file=joe_uploader.file,base64=joe_uploader.base64,extension=file.name.substr(file.name.lastIndexOf(".")),callback=function(err,url){if(err)joe_uploader.message.append("<div>"+(err.message||err)+"<br/>"+err+"</div>"),alert("error uploading");else{joe_uploader.message.html("<div>uploaded</div>"+url);var nprop={};field.field&&(nprop[field.field]=url),field.url_field&&(nprop[field.url_field]=url),self.rerenderField([field.field,field.url_field],nprop),self.updateObject(null,null,!0)}};if(field.onConfirm)file&&(joe_uploader.message.append("<div>pending</div>"),field.onConfirm({extension:extension,file:file,base64:base64,field:field},callback));else{var uploadFunction=field.upload||field.onupload||function(file,callback,base64_url){callback(null,base64_url)};file&&uploadFunction(file,callback,base64)}}else{var files=joe_uploader.files.where({uploaded:!1});callback=function(err,url,filename){if(self.upload_progress_counter--,err)joe_uploader.message.append("<div>"+(err.message||err)+"<br/>"+err+"</div>"),alert("error uploading");else{var fileobj=joe_uploader.files.where({filename:filename})[0];fileobj.uploaded=new Date,fileobj.url=url,delete fileobj.base64}0==self.upload_progress_counter&&(joe_uploader.message.html("<div>uploaded "+files.length+" files</div>"),joe_uploader.preview.html(_renderUploaderFilePreviews(joe_uploader.files,joe_uploader.cuid)),self.updateObject(null,null,!0))};if(field.onConfirm)files&&files.length&&(joe_uploader.message.append("<div>"+files.length+" pending</div>"),self.upload_progress_counter=files.length,files.map(function(file){field.onConfirm({file:file,field:field},callback)}));else{uploadFunction=field.upload||field.onupload||function(file,callback,base64_url){callback(null,base64_url)};file&&uploadFunction(file,callback,base64)}}},this.readyUploaders=function(){self.panel.find(".joe-uploader").each(function(){var id=$(this).data("uploader_id"),uploader=(self.Fields.get($(this).parents(".joe-object-field").data("name")),new Upload({useInputBox:!0,target:$(this).find(".joe-uploader-dropzone")[0],deferUpload:!0,onerror:function(data,status,response){var message=data.message||data||"Server responded with error code: "+status;message=-1!=message.indexOf("bytes")?"file is too small, needs to be larger than 1MB":message,alert(message),logit(data)},onfileselected:function(inputDom){console.log(inputDom.val),self.uploaders[id].uploader.upload()},onafterfileready:self.onUserUpload}));self.uploaders[id].ready=!0,self.uploaders[id].uploader=uploader,self.uploaders[id].message=$(this).find(".joe-uploader-message").html("awaiting file, previewing current"),self.uploaders[id].preview=$(this).find(".joe-uploader-preview"),self.uploaders[id].dropzone=$(this).find(".joe-uploader-dropzone"),self.uploaders[id].confirmBtn=$(this).find(".joe-upload-cofirm-button")})},encapsulateFieldType("uploader",self.renderUploaderField,{ready:self.readyUploaders,remove:_removeUploaderFile}),this.renderObjectReferenceField=function(prop){if(!prop.values||!prop.values.async){var values=self.getFieldValues(prop.values,prop);if(values)var value=(rerenderingField?self.current.constructed:self.current.object)[prop.name];prop.value||!self.current.object.hasOwnProperty(prop.name)&&prop.default,"array"!=$.type(value)&&(value=null!=value?[value]:[]);var disabled=_disableField(prop),idprop=prop.idprop||self.getIDProp(),template=prop.autocomplete_template||prop.template||"<joe-subtitle>${name} ${points}</joe-subtitle><joe-subtext>${${info} || ${"+idprop+"}}</joe-subtext>",html="Object Reference",specs=$.extend({},{autocomplete:{idprop:prop.idprop,template:template},values:values,skip:!0,name:prop.name,ftype:"objectReference",placeholder:prop.placeholder}),sortable=!0;prop.hasOwnProperty("sortable")&&(sortable=prop.sortable);html="";disabled||(html+='<div class="joe-references-container">'+self.renderTextField(specs)+'<div class="joe-text-input-button joe-reference-add-button" data-fieldname="'+prop.name+'"onclick="getJoe('+self.joe_index+').addObjectReferenceHandler(this);">add</div></div>'),html+=__clearDiv__+'<div class ="joe-object-references-holder '+disabled+(sortable&&!disabled?"sortable":"")+'" data-field="'+prop.name+'">';var refSpecs=$.extend({deleteButton:!disabled},prop.reference_specs||{});for(let i=0;i<value.length;i++){let v=value[i];$c.isObject(v)?html+=self.createObjectReferenceItem(v,null,prop.name,refSpecs):$c.isString(v)&&(html+=self.createObjectReferenceItem(null,v,prop.name,refSpecs))}return html+="</div>"}prop.values.search&&$.ajax("/API/search/",{data:prop.values.query||{},success:data=>{},error:err=>{}})},this.addObjectReferenceHandler=function(btn){var id=$(btn).siblings("input").val();if(!id)return!1;$(btn).siblings("input").val("");var fieldname=$(btn).data().fieldname,field=_getField(fieldname);$(".joe-object-references-holder[data-field="+fieldname+"]").append(self.createObjectReferenceItem(null,id,fieldname,field.reference_specs)),field.callback&&field.callback(_jco(!0)[fieldname])},this.removeObjectReferenceHandler=function(fieldname){var field=_getField(fieldname);field.callback&&field.callback(_jco(!0)[fieldname])},this.createObjectReferenceItem=function(item,id,fieldname,specs){var field=_getField(fieldname);specs=$.extend({expander:field.expander||field.itemExpander,gotoButton:field.gotoButton||field.goto,itemMenu:field.itemMenu,schemaprop:field.schemaprop||"itemtype",idprop:field.idprop,template:field.reference_template||field.template,deleteButton:!0,nonclickable:field.nonclickable,fieldname:fieldname,bgcolor:field.bgcolor,value:"${_id}"},specs||{});item&&"object"==typeof item&&(specs.isObject=!0,specs.value=item);var idprop=field.idprop||"_id";if(!item)for(var values=self.getFieldValues(field.values,field),i=0,tot=values.length;i<tot;i++)if(values[i][idprop]==id){item=values[i];break}if(!item)return'<div class="joe-field-item deletable" data-value="'+id+'">'+('<div class="joe-delete-button joe-block-button left" onclick="$(this).parent().remove();_joe.Fields.objectreference.remove(\''+fieldname+"');\">&nbsp;</div>")+"<div>REFERENCE NOT FOUND</div><span class='subtext'>"+id+"</span></div>";specs.link=location.href.replace(location.hash,`#/${item.itemtype}/${item._id}`);var icon=self.Render.schema_icon(item.itemtype),template=self.propAsFuncOrValue(specs.template,item,null,self.current.object)||`${icon}<joe-title>${item.name}</joe-title><joe-subtext>${item.info||item[idprop]}</joe-subtext>`,schema=item.itemtype&&_joe.schemas[item.itemtype]&&item.itemtype||"";return self.renderFieldListItem(item,template,schema,specs)},encapsulateFieldType("objectreference",self.renderObjectReferenceField,{create:self.createObjectReferenceItem,add:self.createObjectReferenceItem,remove:self.removeObjectReferenceHandler}),this.renderPreviewField=function(prop){var height=prop.height||"600px",url=self.propAsFuncOrValue(prop.url)||joe_web_dir+"pages/joe-preview.html",construct=_joe.constructObjectFromFields();obj=construct[self.getIDProp()]&&construct||self.current.object;var content=self.propAsFuncOrValue(prop.content,obj)||"",bodycontent=self.propAsFuncOrValue(prop.bodycontent,obj)||"",previewid=obj[self.getIDProp()]+"_"+prop.name;return window.__PreviewTest=function(){alert("test alert")},window.__previews=window.__previews||{},window.__previews[previewid]={content:content,bodycontent:bodycontent},url+="?pid="+previewid,'<div class="joe-button joe-reload-button joe-iconed-button" onclick="getJoe('+self.joe_index+").rerenderField('"+prop.name+'\');">Reload</div><div class="joe-preview-iframe-holder" style="height:'+height+'"><iframe class="joe-preview-field joe-field joe-preview-iframe" width="100%" height="100%" name="'+prop.name+'" src="'+url+'"></iframe></div><div class="joe-button joe-iconed-button joe-view-button multiline" onclick="window.open(\''+url+"','joe-preview-"+previewid+'\').joeparent = window;"> view fullscreen preview <p class="joe-subtext">'+url.length+" chars</p></div>"+__clearDiv__},encapsulateFieldType("preview",self.renderPreviewField);var tinyconfig={},goBackListIndex,sortable_index;function _readyCommentsField(fieldname){function updateCommentsField(payload){var html="";payload.error?html+="error:"+payload.error:html+=fillTemplate("<joe-comments-entry><joe-comments-user>${this.user.name}</joe-comments-user><joe-subtext>${RUN[_joe.Utils.prettyPrintDTS;${timestamp}]}</joe-subtext><joe-content>${comment}</joe-content></joe-comments-entry>",payload.comments.reverse()),$("joe-comments-view").html(html)}$("joe-comments-view").each(function(){$.ajax({url:"/API/comments/item/"+$(this).data().itemid,dataType:"jsonp",success:updateCommentsField})})}function _commentsAddHandler(dom,itemid){var comment=$(dom).siblings("textarea").val().trim();if($(dom).siblings("textarea").val(""),comment)try{var item=self.current.object,fieldName=$(dom).parents(".joe-object-field").data("name"),fieldObj=_joe.getField(fieldName),user=self.propAsFuncOrValue(fieldObj.user)||JOE.User||{},flag=self.propAsFuncOrValue(fieldObj.flag)||!1,payload={user:{_id:user._id,name:user.name},item:{_id:item._id,name:item.name,type:item.itemtype},comment:comment,flag:flag,timestamp:(new Date).toISOString()},action=fieldObj.action||function(payload){JOE.SERVER.socket.emit("save_comment",payload)};action(payload)}catch(e){self.Error.add("saving comment",e,{user:user,itemid:itemid,comment:comment,flag:flag})}}function encapsulateFieldType(name,render,additionalFunctions){render&&(self.Fields[name]={render:render},$.extend(self.Fields[name],additionalFunctions||{}))}function _getField(fieldname){for(var fieldobj,f=0,tot=self.current.fields.length;f<tot;f++)if((fieldobj=self.current.fields[f]).name==fieldname)return fieldobj;return!1}function renderItemMenu(item,buttons){if(!buttons)return"";if(!(buttons=self.propAsFuncOrValue(buttons,item)))return"";var oc,html='<item-menu class="joe-panel-content-option-menu"><table class=""><tbody><tr>';return buttons.map(function(b){b.hasOwnProperty("condition")&&!self.propAsFuncOrValue(b.condition,item)||(oc=b.url&&"window.open('"+fillTemplate(b.url,item)+"')"||b.action||"alert('"+b.name+"');",html+=fillTemplate('<td class="joe-option-menu-button '+(self.propAsFuncOrValue(b.css,item)||"")+'" onclick="'+oc+'">'+b.name+"</td>",item))}),html+="</tr></tbody></table></item-menu>"}function renderItemExpander(item,contentVal,specs){specs=specs||{};var content=fillTemplate(self.propAsFuncOrValue(contentVal,item,null,self.current.object),item);if(!content)return"";if(specs.onDemand)var html='<div class="joe-panel-content-option-expander on-demand" data-itemid="'+item[self.getIDProp(specs.schema)]+'" data-schema="'+(specs.schema||item.itemtype||self.current.schema)+'"></div>';else html='<div class="joe-panel-content-option-expander">'+content+"</div>";return html}function getDefaultSchema(schema){var menu=[];return(__jsu&&-1!=["super","admin","editor"].indexOf(__jsu.role)||$c.isEmpty(self.Data.user))&&(menu=[__exportBtn__,_joe.SERVER.History.button,__quicksaveBtn__,__deleteBtn__,__duplicateBtn__]),{subtitle:"${_subsetName}",callback:self.SERVER.save,onsave:function(item){let current=_jco(!0);current&&item[self.getIDProp(item.itemtype)]==current._id&&self.Fields.rerender("status,updated,timestamp")},new:function(){return{_id:cuid(),itemtype:schema,created:(new Date).toISOString()}},menu:menu}}this.renderTinyMCEField=function(prop){const locked=self.propAsFuncOrValue(prop.locked)?"disabled":"",heightStyle=prop.height?`style="height:${prop.height};"`:"",editor_id=cuid();return`<div class="joe-tinymce-holder joe-texteditor-field joe-field wysiwyg-field"\n data-texteditor_id="${editor_id}"\n data-ftype="tinymce"\n data-name="${prop.name}">\n <textarea id="${editor_id}" class="joe-tinymce" ${locked} ${heightStyle}>${prop.value||""}</textarea>\n </div>`},this.readyTinyMCEs=function(){tinymce.init({selector:".joe-tinymce",base_url:"/JsonObjectEditor/js/plugins/tinymce",suffix:".min",license_key:"gpl",browser_spellcheck:!0,contextmenu:!1,content_style:"\n body {\n font-size: 16px;\n line-height: 21px;\n }\n ",plugins:["table","wordcount","link","image","code","searchreplace","autoresize","fullscreen","lists"],toolbar:"fullscreen | undo redo | h1 h2 h3 h4 h5 |bold italic removeformat | bullist numlist outdent indent | code",skin_url:"/JsonObjectEditor/js/plugins/tinymce/skins/ui/oxide/",content_css:"/JsonObjectEditor/js/plugins/tinymce/skins/content/default/content.css",theme_url:"/JsonObjectEditor/js/plugins/tinymce/themes/silver/theme.min.js",icons_url:"/JsonObjectEditor/js/plugins/tinymce/icons/default/icons.min.js",init_instance_callback:function(editor){const fieldContainer=editor.targetElm.closest(".wysiwyg-field");if(fieldContainer){const fieldName=fieldContainer.getAttribute("data-name"),field=self.getField(fieldName);if(field&&field.height){const iframe=editor.getContainer().querySelector("iframe");iframe&&(iframe.style.height=`${field.height}px`)}}}})},this.cleanTinyMCEs=function(html){const temp=document.createElement("div");return temp.innerHTML=html,temp.querySelectorAll("*").forEach(el=>{[...el.attributes].forEach(attr=>{if(attr.name.startsWith("data-")&&el.removeAttribute(attr.name),"style"===attr.name){const styleVal=attr.value.toLowerCase();(styleVal.includes("font-weight: 400")||styleVal.includes("font-family")||styleVal.includes("white-space:pre")||styleVal.includes("line-height")||styleVal.includes("margin")||styleVal.includes("orphans")||styleVal.includes("widows"))&&el.removeAttribute("style")}}),"SPAN"===el.tagName&&0===el.attributes.length&&""===el.textContent.trim()&&el.remove()}),temp.innerHTML},self.texteditors=[],this.readyTextEditors=this.readyTinyMCEs,encapsulateFieldType("wysiwyg",self.renderTinyMCEField,{ready:self.readyTextEditors,clean:this.cleanTinyMCEs}),this.renderSubObjectField=function(prop){var action="getJoe("+self.joe_index+").Fields.subobject.openMini('"+prop.name+"');",html=prop.locked?"":'<div class="joe-button joe-view-button joe-iconed-button" onclick="'+action+'">Edit</div>';return html+="<joe-subobject-output><pre>"+JSON.stringify(prop.value,"","\t")+"</pre></joe-subobject-output>"},encapsulateFieldType("subobject",self.renderSubObjectField,{openMini:function(propname){var field=self.getField(propname),callback=self.Cache.add(function(data,id){self.getField(data.prop);self.current.object[data.prop]=self.Mini.construct(),self.Fields.rerender(data.prop)},{data:{prop:propname},type:"callback"}),specs={object:field.value,title:field.display||field.name,menu:[{name:"update",callback:callback.id}],schema:field.schema,name:self.joe_index+"-"+propname};_joe.showMiniJoe(specs)},construct:function(parentFind,outputObject){var propname;parentFind.find(".subobject-field").each(function(){propname=$(this).data("name"),outputObject[propname]=self.current.object[propname]})}}),this.renderPassthroughField=function(prop){return"passthrough"},this.renderButtonField=function(prop){var itemObj=self.current.object||{},display=self.propAsFuncOrValue(prop.display,itemObj),method=self.propAsFuncOrValue(prop.method,itemObj),onclick=self.propAsFuncOrValue(prop.onclick,itemObj),color=self.propAsFuncOrValue(prop.color,itemObj),schema=self.propAsFuncOrValue(prop.schema,itemObj),svgOverride=self.propAsFuncOrValue(prop.svg,itemObj),title=self.propAsFuncOrValue(prop.title,itemObj),bgcolor=self.propAsFuncOrValue(prop.bgcolor,itemObj),cssclass=self.propAsFuncOrValue(prop.cssclass,itemObj)||" joe-nofloat",svgMarkup="";schema&&_joe&&_joe.Schemas&&_joe.Schemas[schema]&&_joe.Schemas[schema].menuicon&&(svgMarkup=_joe.Schemas[schema].menuicon),svgOverride&&(svgMarkup='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">'+svgOverride+"</svg>");var styleAttr=bgcolor?'style="background-color: '+bgcolor+';"':"",html='<joe-button class="joe-button joe-field '+cssclass+(color?" joe-"+color+"-button":"")+'" name="'+(prop.name||"")+'" '+(schema?'schema="'+schema+'" ':"")+(method?'action="'+method+'" ':"")+(color?'color="'+color+'" ':"")+(title?'title="'+title+'" ':"")+(onclick?'onclick="'+onclick+'" ':"")+styleAttr+' data-btnid="'+(prop.name||"")+'">';return svgMarkup&&(html+=svgMarkup+" "),html+=(display||"Button")+"</joe-button>"},encapsulateFieldType("button",self.renderButtonField),this.renderCommentsField=function(prop){var item=self.propAsFuncOrValue(prop.item)||self.current.object,idprop=self.getIDProp(),user=self.propAsFuncOrValue(prop.user)||JOE.User||{},usertemplate=prop.usertemplate||"<joe-subtext><b>${name}</b> says: </joe-subtext>";return"<joe-comments-add>"+fillTemplate(usertemplate,user)+"<textarea></textarea>"+self.renderMenuButtons({css:"joe-iconed-button joe-comments-button fright",name:"comment",action:"_joe.Fields.comments.add(this);"})+__clearDiv__+"</joe-comments-add><joe-comments-view data-itemid='"+item[idprop]+"'>loading</joe-comments-view>"},encapsulateFieldType("comments",self.renderCommentsField,{add:_commentsAddHandler,ready:_readyCommentsField}),this.getField=this.Fields.get=_getField,this._renderExpanderButton=function(expanderContent,item){return expanderContent?'<div class="joe-panel-content-option-expander-button" onclick="_joe.toggleItemExpander(this);"></div>':""},this.toggleItemExpander=function(dom,itemid){if(dom){var expander=$(dom).siblings(".joe-panel-content-option-expander");if(expander.hasClass("on-demand")&&!expander.hasClass("demanded")){var id=expander.data("itemid"),schemaname=expander.data("schema"),item=_joe.getDataItem(id,schemaname),content=self.propAsFuncOrValue(self.schemas[schemaname].itemExpander,item);expander.addClass("demanded").html(content)}$(dom).closest(".expander").toggleClass("expander-collapsed").toggleClass("expander-expanded")}},this.renderItemExpander=renderItemExpander,this.renderTableItem=function(listItem,quick,index){var colprop,idprop=self.getIDProp(),id=listItem[idprop]||null;if(quick){var searchable="";return tableSpecs.cols.map(function(c){$c.isString(c)?searchable+=(listItem[c]||"")+" ":$c.isObject(c)&&(colprop=c.property||c.name,searchable+=(c.template&&self.propAsFuncOrValue(c.template,listItem[colprop],null,listItem)||listItem[colprop]||-1!=colprop.indexOf("${")&&colprop||"")+" "),searchable=fillTemplate(searchable,listItem)}),searchable}var schemaprop=self.current.schema&&self.current.schema.listView&&self.current.schema.listView.schemaprop,ghtml='<tr class="joe-panel-content-option trans-bgcol" '+(schemaprop?'onclick="getJoe('+self.joe_index+").listItemClickHandler({dom:this,id:'"+id+"',schema:'"+schemaprop+"'});\"":'onclick="getJoe('+self.joe_index+").listItemClickHandler({dom:this,id:'"+id+"'});\"")+">";return ghtml+='<td class="joe-table-checkbox"><label>'+index+(tableSpecs.multiselect?'<input type="checkbox" />':"")+"</label></td>",tableSpecs.cols.map(function(c){$c.isString(c)?ghtml+=fillTemplate("<td>"+(listItem[c]||"")+"</td>",listItem):$c.isObject(c)&&(colprop=c.property||c.name,ghtml+=fillTemplate("<td>"+(c.template&&self.propAsFuncOrValue(c.template,listItem[colprop],null,listItem)||listItem[colprop]||-1!=colprop.indexOf("${")&&colprop||"")+"</td>",listItem))}),ghtml+="</tr>"},this.Render.gridItem=this.renderGridItem=function(item,quick,index,specs){var schema=(specs=$.extend({template:"<joe-title>${name}</joe-title><joe-content>${info}</joe-content>",bgcolor:"#fff"},self.current.schema,self.current.schema.gridView,specs)).__schemaname,schemaobj=self.schemas[schema],contentTemplate=self.propAsFuncOrValue(specs.template,item)||"<joe-title>${name}</joe-title><joe-subtext>${itemtype}</joe-subtext>",idprop=specs.idprop||schemaobj&&schemaobj.idprop||"_id",hasMenu=specs.itemMenu&&specs.itemMenu.length,action=specs.action||" onclick=\"goJoe(_joe.search('${"+idprop+"}')[0],{schema:'"+schema+"'})\" ",nonclickable=self.propAsFuncOrValue(specs.nonclickable,item),clickablelistitem=!specs.gotoButton&&!nonclickable,expanderContent=renderItemExpander(item,specs.expander),click=clickablelistitem?action:"";return fillTemplate('<joe-option class="joe-content-option '+(specs.itemMenu?" itemmenu":"")+(specs.stripecolor?" striped":"")+(specs.expander?" expander expander-collapsed":"")+'" >'+(hasMenu&&renderItemMenu(item,specs.itemMenu)||"")+self.Render.bgColor(item,specs.bgcolor)+'<div class="joe-panel-content-option-content'+(nonclickable?"nonclickable":"")+'" '+click+" >"+self.propAsFuncOrValue(contentTemplate+__clearDiv__,item)+"</div>"+self.Render.stripeColor(item,specs.stripecolor)+self._renderExpanderButton(expanderContent,item)+expanderContent+"</joe-option>",item)},this.renderListItem=function(listItem,quick,index){var action,listSchema=$.extend({_listID:"id",stripeColor:null},self.current.schema,self.current.specs),idprop=self.getIDProp(),id=listItem[idprop]||null,customAction=self.current.schema&&(self.current.schema.listView&&self.current.schema.listView.action||self.current.schema.listAction);if(customAction)action='onclick="'+self.propAsFuncOrValue(customAction,listItem)+'"';else{var schemaprop=self.current.schema&&(self.current.schema.schemaprop||self.current.schema.listView&&self.current.schema.listView.schemaprop);action=schemaprop?'onclick="getJoe('+self.joe_index+").listItemClickHandler({dom:this,id:'"+id+"',schema:'"+listItem[schemaprop]+"',idprop:'_id'});\"":'onclick="getJoe('+self.joe_index+").listItemClickHandler({dom:this,id:'"+id+"'});\""}var stripeColor=self.propAsFuncOrValue(listSchema.stripeColor||listSchema.stripecolor,listItem),stripeHTML="",stripeTitle="";stripeColor&&("object"!=typeof stripeColor&&(stripeColor={color:stripeColor}),(stripeColor.title||stripeColor.name)&&(stripeTitle=' title="'+(stripeColor.title||stripeColor.name)+'" '),stripeHTML='style="background-color:'+stripeColor.color+';" '+stripeTitle);var bgColor=self.propAsFuncOrValue(listSchema.bgColor||listSchema.bgcolor,listItem),bgHTML="";bgColor&&(bgHTML=bgColor.color?'style="background-color:'+bgColor.color+';"':'style="background-color:'+bgColor+';"');var template=listSchema.listView&&listSchema.listView.template||listSchema._listTemplate,title=self.propAsFuncOrValue(listSchema.listView&&listSchema.listView.title||listSchema._listTitle||listSchema.listTitle,listItem);if(quick)return fillTemplate(template||title||"",listItem);var borderColor=fillTemplate(self.propAsFuncOrValue(listSchema.borderColor||listSchema.bordercolor,listItem)),borderHTML="";borderColor&&(borderHTML='style="border:1px solid '+borderColor+';"');var numberHTML="";if(index&&!listSchema.hideNumbers&&(numberHTML=index),template){var dup=$c.duplicate(listItem);dup.action=action,html=fillTemplate(template,dup)}else{title=title||listItem.name||id||"untitled";var listItemMenu=renderItemMenu(listItem,listSchema.listView&&listSchema.listView.itemMenu||listSchema.itemMenu),listItemExpander=renderItemExpander(listItem,listSchema.listView&&listSchema.listView.itemExpander||listSchema.itemExpander,{onDemand:listSchema.onDemandExpander,schema:listSchema.__schemaname}),listItemExpanderButton=self._renderExpanderButton(listItemExpander,listItem),icon=listSchema.listView&&listSchema.listView.icon||listSchema.icon||listSchema._icon||"",checkbox=self.Render.itemCheckbox(listItem,listSchema,{idprop:idprop}),user_icon=self.propAsFuncOrValue(icon,listItem),listItemIcon=user_icon&&function(icon,listItem){var url=icon.url||icon;if(-1==url.indexOf("<svg")){var width=icon.width?" width:"+icon.width+"; ":"",height=icon.height?" height:"+icon.height+"; ":"",iconURL=fillTemplate(url,listItem);return"<div style=\" background-image:url('"+iconURL+'\'); " class="joe-panel-content-option-icon trans-bgcol fleft" ><img style="'+width+height+'" src="'+iconURL+'"/></div>'}return'<div class="joe-panel-content-option-svg fleft" >'+icon+"</div>"}(user_icon,listItem)||"";title="<div class='joe-panel-content-option-content ' "+action+">"+checkbox+title+"<div class='clear'></div></div>";var html="<joe-option "+borderHTML+' class="'+(self.allSelected?"selected":"")+" joe-panel-content-option trans-bgcol "+(numberHTML?"numbered":"")+" joe-no-select "+(stripeColor?"striped":"")+" "+(listItemExpanderButton?"expander expander-collapsed":"")+(listItemMenu?" item-menu":"")+'" data-id="'+id+'" ><div class="joe-panel-content-option-bg" '+bgHTML+'></div><div class="joe-panel-content-option-stripe'+(stripeTitle?" titled":"")+'" '+stripeHTML+"></div>"+(numberHTML&&'<div class="joe-panel-content-option-number" >'+numberHTML+"</div>"||numberHTML)+(listItem._protected?'<svg xmlns="http://www.w3.org/2000/svg" class="protected-icon" viewBox="-6 -4 36 36"><path d="M12 1C8.7 1 6 3.7 6 7L6 8C4.9 8 4 8.9 4 10L4 20C4 21.1 4.9 22 6 22L18 22C19.1 22 20 21.1 20 20L20 10C20 8.9 19.1 8 18 8L18 7C18 3.7 15.3 1 12 1ZM12 3C14.3 3 16 4.7 16 7L16 8 8 8 8 7C8 4.7 9.7 3 12 3ZM12 13C13.1 13 14 13.9 14 15 14 16.1 13.1 17 12 17 10.9 17 10 16.1 10 15 10 13.9 10.9 13 12 13Z"></path></svg>':"")+listItemExpanderButton+listItemIcon+listItemMenu+fillTemplate(title,listItem)+listItemExpander+"</joe-option>"}return html},this.checkItem=function(itemID,prop,schema,dom){var checkboxAction,item=self.search(itemID)[0]||!1;if((schema=schema||self.current.schema||item&&self.schemas[item.itemtype])&&schema.checkbox&&schema.checkbox.action&&(checkboxAction=schema.checkbox.action),item){$(dom).toggleClass("checked");var overwrite={joeUpdated:new Date},isChecked=$(dom).hasClass("checked");checkboxAction?$.extend(overwrite,checkboxAction(item,isChecked,$(dom))||{}):overwrite[prop]=isChecked,$.extend(item,overwrite),schema.callback(item),window.event&&window.event.stopPropagation()}},this.shiftSelecting=!1,this.listItemClickHandler=function(specs){if(goBackListIndex=null,specs&&specs.dom&&(goBackListIndex=$(specs.dom).parents(".joe-panel-content-option").index()),self.current.selectedListItems=[],window.event)if(window.event.shiftKey||window.event.ctrlKey){if(window.event.ctrlKey)$(specs.dom).hasClass("joe-panel-content-option")?$(specs.dom).toggleClass("selected"):$(specs.dom).parents(".joe-panel-content-option").toggleClass("selected"),$(".joe-panel-content-option.selected").map(function(i,listitem){self.current.selectedListItems.push($(listitem).data("id"))});else if(window.event.shiftKey){var shiftIndex;if($(specs.dom).hasClass("joe-panel-content-option")?($(specs.dom).addClass("selected"),shiftIndex=$(specs.dom).index()):($(specs.dom).parents(".joe-panel-content-option").addClass("selected"),shiftIndex=$(specs.dom).parents(".joe-panel-content-option").index()),!1!==self.shiftSelecting){if(shiftIndex<self.shiftSelecting){var t=shiftIndex,p=self.shiftSelecting;self.shiftSelecting=t,shiftIndex=p}$(".joe-panel-content-option").slice(self.shiftSelecting,shiftIndex+1).addClass("selected"),$(".joe-panel-content-option").slice(shiftIndex+1).removeClass("selected"),$(".joe-panel-content-option").slice(0,self.shiftSelecting).removeClass("selected")}else self.shiftSelecting=shiftIndex;$(".joe-panel-content-option.selected").map(function(i,listitem){self.current.selectedListItems.push($(listitem).data("id"))})}}else self.editObjectFromList(specs);else self.editObjectFromList(specs);self.updateSelectionVisuals()},this.updateSelectionVisuals=function(){self.current.selectedListItems.length?(self.overlay.addClass("multi-edit"),self.overlay.find(".joe-selection-indicator").html(self.current.selectedListItems.length+" selected")):(self.overlay.removeClass("multi-edit"),self.overlay.find(".joe-selection-indicator").html(""))},this.editObjectFromList=function(specs){specs=specs||{},self.current.schema=specs.schema||self.current.schema||null;var list=specs.list||self.current.list,id=specs.id,idprop=specs.idprop||self.getIDProp(),object=list.filter(function(li){return li[idprop]==id})[0]||!1;if(object){var setts={schema:specs.schema||self.current.schema,callback:specs.callback};goJoe(object,setts)}else alert("error finding object")},this.showList=function(view,subset,filter){"string"==$.type(view)&&(view={collection:view,schema:view}),view.subset=subset||null;var showJoeListBenchmarker=new Benchmarker;self.current.clear();var dataList=self.Data[view.collection]||[];filter&&(dataList=dataList.where(filter)),goJoe(dataList,{schema:view.schema,subset:view.subset}),_bmResponse(showJoeListBenchmarker,'Joe View: "'+view.collection+'" shown')},this.editMultiple=function(){var haystack=self.current.list,idprop=self.getIDProp(),needles=self.current.selectedListItems,items=[],protoItem={};haystack.map(function(i){-1!=needles.indexOf(i[idprop])&&($.extend(protoItem,i),items.push(i))}),goJoe(protoItem,{title:"Multi-Edit "+(self.current.schema.__schemaname||"")+": "+items.length+" items",schema:self.current.schema||null,multiedit:!0})},this.filterList=function(list,props,specs){specs=specs||{};var found=(list||self.current.list).filter(function(arrobj){for(var p in props)if(arrobj[p]!=props[p])return!1;return!0});return!!found.length&&(specs.single?found[0]:found)},this.renderSubsetselector=function(specs){return listMode?'<div class="joe-subset-selector" >'+self.renderSubsetSelectorOptions(specs)+"</div>":""},this.renderSubsetSelectorOptions=function(specs){var subsets=self.current.subsets;function renderOption(opt){var html="";if(!opt.condition||self.propAsFuncOrValue(opt.condition))html='<div class="selector-option" onclick="getJoe('+self.joe_index+").selectSubset('"+(opt.id||opt.name||"")+"');\">"+opt.name+"</div>";return html}"function"==typeof subsets&&(subsets=subsets()),self.current.specs.subset&&(self.current.subset=subsets.filter(function(s){return s.id=s.id||s.name,s.id==self.current.specs.subset})[0]||!1);var html='<div class="selector-label selector-option" onclick="$(this).parent().toggleClass(\'active\')">'+(self.current.subset&&self.current.subset.name||"All")+'</div><div class="selector-options">'+renderOption({name:"All",filter:{}});return subsets.map(function(s){html+=renderOption(s)}),html+="</div>"},this.selectSubset=function(subset){self.hide();var schemaname=self.current.schema&&self.current.schema.name;goJoe(self.current.list,$.extend({},self.current.userSpecs,{subset:subset,schema:schemaname}))},this.toggleFilter=function(filtername,dom){parseFloat(filtername)==filtername&&(filtername=parseFloat(filtername));var filter=(self.current.schema&&self.propAsFuncOrValue(self.current.schema.filters)||[]).where({$or:[{name:filtername},{id:filtername}]})[0]||!1;filter?(self.current.schema&&self.current.schema.__schemaname&&(filter.schema=self.current.schema.__schemaname),self.current.filters[filtername]?delete self.current.filters[filtername]:self.current.filters[filtername]=filter,dom&&$(dom).toggleClass("active"),self.filterListFromSubmenu(null,!0)):logit("issue finding filter: "+filtername)},this.toggleFilterObject=function(filtername,filterObj,wait){parseFloat(filtername)==filtername&&(filtername=parseFloat(filtername));var filter=self.propAsFuncOrValue(filterObj);filter?(self.current.schema&&self.current.schema.__schemaname&&(filter.schema=self.current.schema.__schemaname),self.current.filters[filtername]&&delete self.current.filters[filtername],self.current.filters[filtername]={name:filtername,filter:filterObj},self.filterListFromSubmenu(null,!wait)):logit("issue finding filter: "+filtername)},this.clearFilters=function(){self.current.filters={},self.container.find(".joe-filter-option").removeClass("active"),self.filterListFromSubmenu(null,!0)},this.replaceRendering=function(dom,specs){var rendering=dom.toString();specs={datatype:"rendering",compact:!1,dom:dom};self.show(rendering,specs)},this.updateRendering=function(dom,callback){callback=self.current.callback||self.current.schema&&self.current.schema.callback||logit;if(!self.current.specs.dom)return!1;var newVal=$(".joe-rendering-field").val();$(self.current.specs.dom).replaceWith(newVal),logit("dom updated"),self.hide(),callback(newVal)},this.showPropertyEditor=function(prop){self.current.mutant=prop},this.addPropertyToEditor=function(prop){},this.minis={},this.showMiniJoe=function(specs,joespecs,data){var mini={},object=(specs=$.extend({mode:"text"},specs||{},joespecs||{})).props||specs.object||specs.list||specs.content;if(object){var title=specs.title||"Object Focus";mini.id=cuid();var mode=specs.mode||"object";switch(specs.object=object,specs.minimenu=specs.minimenu||specs.menu,$.type(object)){case"object":mode="object";break;case"array":mode="list"}specs.mode=mode;var minimode=mini.id;specs.minimode=minimode;var html=self.renderEditorHeader({title:title,minimode:minimode,close_action:'onclick="getJoe('+self.joe_index+").hideMini('"+minimode+"');\""});html+=self.renderMiniEditorContent(specs),html+=self.renderEditorFooter({minimenu:specs.menu,minimode:minimode});var height=specs.height||self.overlay.height()/2;mini.panel=self.overlay.find(self.Mini.selector),specs.name,mini.panel.attr("name",specs.name||mini.id),mini.panel.addClass("active").addClass("focus").html(html),$(".joe-mini-panel .joe-panel-footer").find(".joe-button:visible").length||$(".joe-mini-panel").addClass("no-footer-menu"),mini.panel.css("height",height),specs.width&&mini.panel.css("width",specs.width),mini.panel.draggable({handle:"joe-panel-header",snap:".joe-overlay"}).resizable({handles:"s"}),mini.callback=specs.callback||function(itemid){alert(itemid)},mini.data=data||{},self.minis[mini.id]=mini,self.Mini.id=mini.id,self.overlay.toggleClass("mini-active",!0)}},this.hideMini=function(miniid){try{miniid?(delete self.minis[miniid],$(self.Mini.selector+".ui-resizable").resizable("destroy").draggable("destroy"),$(self.Mini.selector).removeClass("active")):($(self.Mini.selector+".ui-resizable").resizable("destroy").draggable("destroy"),$(self.Mini.selector).removeClass("active"))}catch(e){self.Error.add("hidemini error: "+e,e,{warning:!0})}self.overlay.removeClass("mini-active")},this.constructObjectFromMiniFields=function(){var prop,object={};return $(".joe-mini-panel.active .joe-object-field").find(".joe-field").each(function(){if("checkbox"===$(this).attr("type"))prop=$(this).attr("name"),$(this).is(":checked")?object[prop]=!0:object[prop]=!1;else prop=$(this).attr("name"),object[prop]=$(this).val()}),object},this.renderMiniEditorContent=function(specs){var content;self.current.sidebars={left:{collapsed:!1},right:{collapsed:!1}},specs||(specs={mode:"text",text:"No object or list selected"});var mode=specs.mode;switch(mode){case"text":content=self.renderTextContent(specs);break;case"rendering":content=self.renderHTMLContent(specs);break;case"list":content=self.renderListContent(specs);break;case"object":content=self.renderObjectContent(specs);break;default:content=content||""}var submenu="";specs.minimode||("list"==mode&&self.current.submenu||self.current.submenu||renderSectionAnchors().count)&&(submenu=" with-submenu ");var scroll='onscroll="getJoe('+self.joe_index+').onListContentScroll(this);"',rightC=content.right||"",leftC=content.left||"",html='<joe-panel-content class="'+("joe-panel-content "+renderEditorStyles()+submenu)+'" '+(listMode&&scroll||"")+">"+(content.main||content)+"</joe-panel-content>"+self.renderSideBar("left",leftC,{css:submenu})+self.renderSideBar("right",rightC,{css:submenu});return self.current.sidebars.left.content=leftC,self.current.sidebars.right.content=rightC,html},this.Mini={selector:".joe-mini-panel",show:self.showMiniJoe,hide:self.hideMini,construct:self.constructObjectFromMiniFields,get:function(){return self.minis[self.Mini.id]||!1},clear:function(){self.hideMini(),self.minis={},delete self.Mini.id}},self.quickAdd=function(itemtype){if(!1!==(itemtype=itemtype)&&(itemtype=itemtype||self.current.schema&&self.current.schema.__schemaname),itemtype)self.createObject(itemtype);else{var sch,t=[];for(var d in self.Data)(sch=_joe.schemas[d])&&t.push({name:sch.name,info:sch.info,menuicon:sch.menuicon,default_schema:sch.default_schema||!1});t.sortBy("name"),_joe.showMiniJoe({title:"Create a new:",list:t,template:"<joe-schema-icon>${menuicon}</joe-schema-icon><joe-title>${name}</joe-title><joe-subtitle>${info}</joe-subtitle>",idprop:"name",sorter:"default_schema,name",menu:[],callback:function(item_id){self.createObject(item_id)}})}},self.schemas.search={title:"Search Results",name:"search",__schemaname:"search",listTitle:function(item){return"<joe-full-right><joe-subtext>updated</joe-subtext><joe-subtitle>"+self.Utils.toDateString(item.joeUpdated)+"</joe-subtitle></joe-full-right>"+(_joe.schemas[item.itemtype].menuicon&&'<joe-icon class="icon-40 icon-grey fleft">'+_joe.schemas[item.itemtype].menuicon+"</joe-icon>"||"")+"<joe-subtext>${itemtype}</joe-subtext><joe-title>${name}</joe-title><joe-subtitle>${info}</joe-subtitle><joe-subtext>${_id}</joe-subtext>"},listmenu:[],sorter:["name",{name:"updated",value:"!joeUpdated"},"itemtype"],dataset:function(){return _joe.search({name:/[a-z0-9 _\-\!\:]*/})},filters:function(){var f=[];return __appCollections.concat().sort().map(function(s){f.push({name:s,filter:{itemtype:s}})}),f},listAction:function(item){return"goJoeItem('"+item._id+"','"+item.itemtype+"')"}},self.quickFind=function(phrase){goJoe(_joe.search({name:/[a-z0-9 _\-\!\:]*/}),{schema:"search"},function(){self.panel.find(".joe-submenu-search-field").focus()})},self.search=function(id,specs){(specs=specs||{}).collections,specs.props||specs.properties;var results,haystack=[];for(var d in self.Data)haystack=haystack.concat(self.Data[d]);return"string"==$.type(id)?results=haystack.filter(function(r){return r._id==id}):"object"==$.type(id)&&(results=haystack.where(id)),results},self.addDataset=function(name,values,specs){values=self.propAsFuncOrValue(values,name);if(name&&values&&"array"==$.type(values)){self.Data[name]=values;var idprop=self.schemas[name]&&self.schemas[name].idprop||"_id";if(self.Data[name].map(dataitem=>{self.Indexes._add(idprop,dataitem)}),!self.schemas[name])return;if(self.schemas[name].onload)try{console.log(name+" onload"),self.schemas[name].onload(self.Data[name])}catch(e){self.Error.add("schema onload error: "+name,e)}}},self.deleteDataset=function(dataset){delete self.Data[dataset]},self.dit=0,self.getData=function(specs){(new Date).getTime();var objects=[];if((specs=specs||{}).schemas)specs.schemas.map(sc=>{objects=objects.concat(self.Data[sc])});else for(var d in self.Data)objects=objects.concat(self.Data[d]);var query=specs.query||specs.filters;query&&(objects=objects.where(self.propAsFuncOrValue(query)));var sortBy=specs.sort||specs.sortBy;return sortBy&&(objects=objects.sortBy(sortBy)),specs.limit&&(objects=objects.slice(0,specs.limit)),objects},self.getDataItem=function(id,datatype,idprop){var item,st=(new Date).getTime();function addtoDIT(){var el=(new Date).getTime()-st;self.dit+=el}idprop=idprop||self.schemas[datatype]&&self.schemas[datatype].idprop||"_id";if(self.Indexes[idprop]&&self.Indexes[idprop][id])return addtoDIT(),self.Indexes._usage++,self.Indexes[idprop][id];var dataset=self.Data[datatype];if(!self.Data[datatype])return addtoDIT(),!1;for(var i=0,tot=dataset.length;i<tot;i++)if((item=dataset[i])[idprop]==id)return addtoDIT(),item;return addtoDIT(),!1},self.getDataset=function(datatype,specs){var sortby=(specs=specs||{}).sortby||"name";if(self.Data[datatype])var data=self.Data[datatype].sortBy(sortby);else{if(specs.boolean=!0)return!1;data=[]}return specs.filter&&(data=data.where(specs.filter)),specs.reverse&&data.reverse(),specs.blank?[{name:"",val:""}].concat(data):data},self.getDataItemProp=function(id,dataset,prop,specs){specs=specs||{delimiter:","};if(prop=prop||"name",!id)return"";var vals="";return $c.isArray(id)||(id=[id]),id.map(function(item_id,i){var item=self.getDataItem(item_id,dataset);i>0&&(vals+=specs.delimiter||""),item&&(vals+=item[prop])}),vals},this.setSchema=function(schemaName){if(!schemaName)return!1;var schema="object"==$.type(schemaName)?schemaName:self.schemas[schemaName]||null;return schema&&self.current.schema&&self.current.schema.name&&self.current.schema.name!=schema.name&&(listMode&&self.current.schema&&"search"==self.current.schema.name||!listMode&&schema&&"search"==schema.name||(self.current.keyword="")),self.current.schema=schema,schema},this.resetSchema=function(schemaName){var newObj=self.constructObjectFromFields(self.joe_index);self.show($.extend(self.current.object,newObj),$c.merge(self.current.userSpecs,{noHistory:!0,schema:self.setSchema(schemaName)||self.current.schema}))},this.Schema={add:function(name,config,specs){self.schemas[name]=self.propAsFuncOrValue(config);var schemaObj=self.schemas[name];return schemaObj.__schemaname=schemaObj.name=name,schemaObj._id=cuid(),schemaObj},set:this.setSchema,reset:this.resetSchema},this.toggleOverlay=function(dom){$(dom).parents(".joe-overlay").toggleClass("active")},this.showItem=function(id,schemaname,specs,show_callback){if(schemaname){specs=specs||{};var item=self.getDataItem(id,schemaname);specs=$.extend(specs,{schema:schemaname}),self.show(item,specs,show_callback)}},this.show=function(data,specs,show_callback){data=data||"";((specs=specs||{}).force||self.checkChanges())&&(self.setEditingHashLink(!0),self.current.benchmarkers={},self.showBM=new Benchmarker,clearTimeout(self.hideTimeout),specs.container&&(self.container=$(specs.container)),self.panel.attr("class","joe-overlay-panel"),!0===specs.compact&&self.overlay.addClass("compact"),!1===specs.compact&&self.overlay.removeClass("compact"),self.populateFramework(data,specs),self.overlay.removeClass("hidden"),self.overlay.addClass("active"),self.current.show_callback=show_callback,setTimeout(self.onPanelShow,0),$(self.container).trigger({type:"showJoe",schema:self.current.specs.schema,subset:self.current.specs.subset}))},this.hide=function(timeout){timeout=timeout||0,self.overlay.addClass("hidden"),self.hideTimeout=setTimeout(function(){self.overlay.removeClass("active"),self.overlay.removeClass("hidden")},timeout)},this.reload=function(hideMessage,specs){logit("reloading joe "+self.joe_index),self._reloading=!0;specs=specs||{};var reloadBM=new Benchmarker,info=self.history.pop();if("object"==$.type(info.data))if(specs.overwrite||specs.overwrites)var obj=$.extend({},info.data,specs.overwrite||specs.overwrites);else obj=info.data;else obj=info.data;delete specs.overwrite,delete specs.overwrites;specs=$.extend({},info.specs,specs);self.show(obj,specs),hideMessage||self.showMessage("reloaded in "+reloadBM.stop()+" secs"),self._reloading=!1},this.compactMode=function(compact){!0===compact&&self.overlay.addClass("compact"),!1===compact&&self.overlay.removeClass("compact")},this.printObject=function(obj){goJoe("<pre>"+JSON.stringify(obj," "," ")+"</pre>")},0==self.joe_index&&(window.joeMini=this.showMiniJoe,window.goJoe=this.show,window.goJoeItem=this.showItem,window.listJoe=this.editObjectFromList),window.$J=window.$J||{_usages:{get:0,schema:0,search:0},get:function(itemID,callback,itemtype){"string"!=typeof callback||itemtype||(itemtype=callback,callback=null),$J._usages.get++;var item=self.getDataItem(itemID,itemtype)||$J.search({_id:itemID})[0];return!!item&&(callback&&callback(item),item)},schema:function(schemaname,callback){$J._usages.schema++;var schema=_joe.schemas[schemaname];if(schema)return callback&&callback(schema),schema},search:function(query,callback){$J._usages.search++;var results=_joe.search(query);return callback&&callback(results),results}},window.getJoe=function(index){return window._joes[index]||!1},$(document).keyup(function(e){var mode=self.getMode();27==e.keyCode?("list"==mode?self.deselectAllItems():"details"==mode&&$(".joe-text-autocomplete.active").length&&$(".joe-text-autocomplete.active").removeClass("active"),self.specs.useEscapeKey&&self.closeButtonAction()):e.ctrlKey&&13==e.keyCode&&self.specs.useControlEnter&&self.overlay.find(".joe-confirm-button").click()}),this.Autosave={possibleChanges:!0,unsavedChanges:!1,activate:function(){if(self.specs.autosave){var intercnt=1e3;"number"==typeof self.specs.autosave&&(intercnt=self.specs.autosave),self.Autosave.interval=setInterval(function(){if(self.Autosave.possibleChanges){var hasChanged=self.checkChanges(!0),showUnsaved=hasChanged&&"details"==self.getMode();document.title=(showUnsaved?"*":"")+document.title.replace("*",""),self.overlay.toggleClass("unsaved-changes",showUnsaved),self.Autosave.unsavedChanges=hasChanged}},intercnt)}},deactivate:function(){self.specs.autosave&&clearInterval(self.Autosave.interval)}},this.onPanelShow=function(){var BM=new Benchmarker;if(self.respond(),self.Autosave.activate(),self.Fields.date.ready(),self.Fields.time.ready(),currentListItems&&self.overlay.find(".joe-submenu-search-field").length&&((goingBackQuery||!$c.isEmpty(self.current.userSpecs.filters)&&listMode)&&(self.overlay.find(".joe-submenu-search-field").val(goingBackQuery),self.filterListFromSubmenu(self.overlay.find(".joe-submenu-search-field")[0].value,!0),goingBackQuery=""),self.overlay.find(".joe-submenu-itemcount").html(currentListItems.length+" item"+(1!=currentListItems.length?"s":""))),listMode||self.isNewItem()&&$(".joe-object-field.text-field").eq(0).find("input").focus(),self.readyBinFields(),$(".joe-preview-iframe-holder").resizable({handles:"s"}),self.overlay.find("input.joe-image-field").each(function(){_joe.updateImageFieldImage(this)}),self.overlay.find(".joe-object-references-holder.sortable").sortable({handle:".joe-field-item-content"}),self.Fields.objectlist.ready(),self.Fields.json&&self.Fields.json.ready&&self.Fields.json.ready(),self.current.sidebars){var lsb=self.current.sidebars.left,rsb=self.current.sidebars.right;self.panel.find(".joe-sidebar_left-button").toggleClass("active",""!=lsb.content),self.panel.find(".joe-sidebar_right-button").toggleClass("active",""!=rsb.content),"small-size"!=self.sizeClass&&self.panel.toggleClass("right-sidebar",rsb.content&&!rsb.collapsed||!1),self.panel.toggleClass("left-sidebar",lsb.content&&!lsb.collapsed||!1)}if(self.Fields.comments.ready(),self.readyUploaders(),self.readyTextEditors(),self.Mini.clear(),goingBackFromID){null!=goBackListIndex&&(goBackListIndex>self.specs.dynamicDisplay&&self.panel.find(".joe-panel-content").html(self.renderListItems(currentListItems,0,goBackListIndex+1)),goBackListIndex=null);try{self.overlay.find('.joe-panel-content-option[data-id="'+goingBackFromID+'"]').addClass("keyboard-selected")[0].scrollIntoView(!0)}catch(e){self.Error.add("go back to item not ready yet:"+goingBackFromID,e)}goingBackFromID=null}self._currentListItems=currentListItems,listMode&&(self.setColumnCount(colCount),self.panel.toggleClass("list-mode",listMode)),!self.panel.hasClass("small-size")&&(self.current.subsets||self.current.schema&&self.propAsFuncOrValue(self.current.schema.filters))||(leftMenuShowing=!1),self.panel.toggleClass("show-filters",leftMenuShowing&&listMode),self.panel.toggleClass("show-aggregator",rightMenuShowing&&listMode),self.specs.speechRecognition&&self.Speech.initMic(),self.setEditingHashLink(!1),self.current.changesConfirmed=!1;var panelShowFunction=self.getCascadingProp("onPanelShow");try{var exectime=(new Date-self.showBM._start)/1e3,state=self.getState(),timing={time:exectime,warnings:self.current.benchmarkers._warnings};panelShowFunction&&panelShowFunction(state,timing),panelShowFunction&&self.specs.onPanelShow&&panelShowFunction!=self.specs.onPanelShow&&self.specs.onPanelShow(state,timing),self.current.show_callback&&self.current.show_callback(self.getState(),{time:exectime})}catch(e){self.Error.add(e,e,{warning:!0})}_bmResponse(BM,"on panel show complete"),self.Fields.onPanelShow(),_bmResponse(BM,"fields onshow complete"),_bmResponse(self.showBM,"----Joe Shown")},this.checkChanges=function(nopopup){var mode=self.getMode();if(!mode||"list"==mode)return!0;var cc_construct=_jco(!0);if(self.current.schema&&!1===self.current.schema.checkChanges)return!0;if(!0===self.current.changesConfirmed)return!0;if(!_joe.current.object||!cc_construct)return!0;var f,test_info,changes=$c.changes(_joe.current.object,cc_construct),tocheck=[],check_msg="";if(changes&&changes.$length)for(var c in changes){if(f=self.getField(c),"$"!=c[0]&&"joeUpdated"!=c&&f&&"content"!=f.type&&!parseBoolean(f.passthrough)){if("json"==(self.propAsFuncOrValue(f.type)||"").toLowerCase()){var orig=_joe.current.object[c],rawNew=cc_construct[c],sameJson=!1;try{var parsedOrig="string"==typeof orig?JSON.parse(orig):orig,parsedNew="string"==typeof rawNew?JSON.parse(rawNew):rawNew;sameJson=JSON.stringify(parsedOrig)==JSON.stringify(parsedNew)}catch(_e){sameJson=!1}if(sameJson)continue}else if(JSON.stringify(_joe.current.object[c])==JSON.stringify(cc_construct[c]))continue;if(-1!=["qrcode"].indexOf(f.type));else if((""===cc_construct[c]||null===cc_construct[c]||$c.isArray(cc_construct[c])&&!cc_construct[c].length)&&(void 0===_joe.current.object[c]||null===_joe.current.object[c]||$c.isArray(_joe.current.object[c])&&!_joe.current.object[c].length))test_info="null to blank";else if("project"==self.current.object.itemtype&&"phases"==c)test_info="project phase";else if(!1!==cc_construct[c]||_joe.current.object[c])if("wysiwyg"==f.type&&__removeTags(cc_construct[c]).trim()==__removeTags(_joe.current.object[c]).trim())test_info="wysiwyg formatting";else if("objectReference"==f.type){test_info="is an objectReference";JSON.stringify(_joe.current.object[c]),JSON.stringify(cc_construct[c])}else tocheck.push(c),check_msg+=c+"\n";else test_info="boolean false"}test_info&&logit(test_info)}if(nopopup)return $(".joe-object-field.changed").removeClass("changed"),tocheck.map(field=>{}),tocheck.length>0&&tocheck;if(self.overlay.hasClass("active")&&!listMode&&!self.current.changesConfirmed&&tocheck.length){var confirmed=confirm("Are you sure you want to navigate away from this item?\nYou have unsaved changes:\n"+check_msg);return self.current.changesConfirmed=confirmed,confirmed}return tocheck},this.renderMessageContainer=function(){return'<joe-message-holder><div class="joe-message-container left"></div></joe-message-holder>'};var messageTimeouts=Array(4);function _defaultUpdateCallback(data){self.showMessage(data.name+" updated successfully")}this.showMessage=function(message,specs){var mspecs=$.extend({timeout:3,message_class:""},specs||{});message=message||"JOE Message";self.overlay.find(".joe-message-container").hasClass("active")?self.overlay.find(".joe-message-container").html('<div class="joe-message-content">'+message+"</div>").attr("class","joe-message-container active show-message"):(self.overlay.find(".joe-message-container").html('<div class="joe-message-content">'+message+"</div>").attr("class","joe-message-container active left"),self.overlay.find("joe-message-holder").addClass("active"));var target="getJoe("+self.joe_index+").overlay.find('.joe-message-container')",holder="getJoe("+self.joe_index+").overlay.find('joe-message-holder')";clearTimeout(messageTimeouts[0]),clearTimeout(messageTimeouts[1]),clearTimeout(messageTimeouts[2]),clearTimeout(messageTimeouts[3]),clearTimeout(messageTimeouts[4]),messageTimeouts[0]=setTimeout(target+".attr('class','joe-message-container active show-message')",400),mspecs.timeout&&(messageTimeouts[1]=setTimeout(target+".attr('class','joe-message-container active ')",1e3*mspecs.timeout+400-250),messageTimeouts[2]=setTimeout(target+".attr('class','joe-message-container active right')",1e3*mspecs.timeout+400),messageTimeouts[3]=setTimeout(target+".attr('class','joe-message-container'); ",1e3*mspecs.timeout+800+50),messageTimeouts[4]=setTimeout(holder+".removeClass('active');",1e3*mspecs.timeout+800+150))},this.Object={},this.Object.create=this.createObject=function(specs,item_defaults){specs=specs||{};var schema=self.current.schema;"string"==typeof specs&&(specs={schema:specs}),schema=self.schemas[specs.schema]||self.current.schema;item_defaults=item_defaults||self.propAsFuncOrValue(schema.new)||{},specs=$.extend({schema:schema},specs||{});var overwrites=self.propAsFuncOrValue(specs.overwrites)||{};goJoe($.extend({},item_defaults,overwrites),specs)},this.Object.validate=this.validateObject=function(obj){var req_fields=[];function olistVal(olistObj){var vals="";for(var i in olistObj)vals+=olistObj[i];return vals.replace(/ /g,""),vals}_joe.current.fields.filter(f=>f.validation&&"function"==typeof f.validation),req_fields=_joe.current.fields.filter(function(prop){return!!self.propAsFuncOrValue(prop.required)});var required_missed=[];if(req_fields.map(function(f){if(!obj[f.name]||$.type("array"==obj[f.name])&&"objectList"!=f.type&&0==obj[f.name].length||"objectList"==f.type&&0==obj[f.name].filter(olistVal).length)return required_missed.push(f),!1}),$(".joe-object-field").removeClass("joe-highlighted"),required_missed.length){var req_array=[];return required_missed.map(function(of){req_array.push(of.display||of.name),$(".joe-object-field[data-name="+of.name+"]").addClass("joe-highlighted")}),req_array=req_array.condense(!0),self.showMessage("There are <b>"+req_array.length+"</b> required fields currently missing. <br/>"+req_array.join()),!1}return!0},this.updateObjectAsync=function(ajaxURL,specs){specs=$.extend({oldObj:$.extend({},self.current.object),callback:function(data){self.showMessage(data.name+" updated successfully"),self.Cache.lookup[data._id]&&(self.Cache.lookup[data._id]=data)},ajaxObj:self.constructObjectFromFields(self.joe_index),overwrites:{},skipValidation:!1},specs||{});var newObj=$.extend(ajaxObj.newObj,specs.overwrites,{joeUpdated:new Date});if(!_joe.propAsFuncOrValue(self.skipValidation)&&!self.validateObject(obj))return!1;$.ajax({url:specs.ajaxObj,data:newObj,dataType:"jsonp",success:specs.callback})},this.Object.findAndModify=function(id,modifications,specs,callback){specs=specs||{},modifications=$.extend({joeUpdated:new Date},modifications||{});var schemaObj=specs.schema&&(_joe.schemas[specs.schema]||specs.schema),idprop=specs.idprop||schemaObj&&schemaObj.idprop||"_id",object=_joe.Indexes[idprop][id];!schemaObj&&object.itemtype&&_joe.schemas[object.itemtype]&&(schemaObj=_joe.schemas[object.itemtype]);var oldObj=$.extend({},object);$.extend(object,modifications);callback=specs.callback||schemaObj.schema&&schemaObj.callback||function(data){self.showMessage((data.name||data.itemtype)+" modified successfully")};var mode=_joe.getMode();if("details"==mode&&self.current.object==object?goJoe(self.current.object,{schema:self.current.object.itemtype,force:!0}):"list"==mode&&-1!=self.current.list.indexOf(object)&&_joe.reload(),logit((obj.name||"object")+" updated"),specs.goto)if(typeof specs.goto==string)goJoe(object,{schema:schemaObj});else{var gotoObject=_joe.search(specs.goto)[0]||!1;gotoObject&&goJoe(gotoObject,{schema:gotoObject.itemtype})}callback(obj,oldObj,oldObj.changes(obj))},this.Object.update=this.updateObject=function(dom,callback,stayOnItem,overwrites,skipValidation){self.Cache.clear();var oldObj=$.extend({},self.current.object);callback=callback||self.current.callback||self.current.schema&&self.current.schema.callback||function(data){self.showMessage(data.name+" updated successfully")};var newObj=self.constructObjectFromFields(self.joe_index);if(_joe&&_joe.current&&_joe.current.fields)for(var jsonField,normResult,i=0,tot=_joe.current.fields.length;i<tot;i++)if(jsonField=_joe.current.fields[i],"json"==(self.propAsFuncOrValue(jsonField.type)||"").toLowerCase()){if(!(normResult=self.Fields.json&&self.Fields.json.normalize?self.Fields.json.normalize(jsonField.name,{showMessage:!0}):{ok:!0}).ok)return!1;var parsed=normResult.parsed||(newObj[jsonField.name]&&"object"==typeof newObj[jsonField.name]?newObj[jsonField.name]:{});newObj[jsonField.name]=parsed}newObj.joeUpdated=new Date,overwrites=overwrites||{};var obj=$.extend(newObj,overwrites);if(!_joe.propAsFuncOrValue(skipValidation)&&!self.validateObject(obj))return!1;obj=$.extend(self.current.object,newObj);var itemtype=self.current.object.itemtype&&self.Data[self.current.object.itemtype]?self.current.object.itemtype:null,index=self.current.list&&self.current.list.indexOf(obj);!self.current.list||-1!=index&&null!=index||itemtype&&self.current.list[0]&&self.current.list[0].itemtype==itemtype||itemtype||self.current.list.push(obj);var dsname=itemtype||self.current.schema.__schemaname,idprop=self.getIDProp();self.Data[dsname]&&(self.getDataItem(obj[idprop],dsname)||self.Data[dsname].push(obj),logit("item matches current schema, updating...")),logit((obj.name||"object")+" updated"),callback(obj,oldObj,oldObj.changes(obj)),stayOnItem||self.goBack(obj)},this.deleteObject=function(callback){var obj=self.current.object;if(!confirm("Are you sure you want to DELETE\n"+obj.name+"\n"+obj[self.getIDProp()]))return!1;callback=self.current.callback||self.current.schema&&self.current.schema.callback||logit;if(obj[self.getCascadingProp("deleted")||"_deleted"]=(new Date).toISOString(),!self.current.list||!obj||-1==self.current.list.indexOf(obj))return logit("object or list not found"),callback(obj),self.current.changesConfirmed=!0,void self.goBack();var index=self.current.list.indexOf(obj);self.current.list.removeAt(index),logit("object deleted"),callback(obj),self.current.changesConfirmed=!0,self.goBack()},this.Object.duplicate=this.duplicateObject=function(specs){var deletes=(specs=specs||{}).deletes||[],itemobj=$.extend({},self.current.object);delete itemobj[self.getIDProp()],delete itemobj.joeUpdated,delete itemobj.created,itemobj.name=itemobj.name+" copy",deletes.map(function(d){delete itemobj[d]}),goJoe(itemobj,self.current.userSpecs)},this.Object.construct=this.constructObjectFromFields=function(index){var constructBM=new Benchmarker,object={};self.current.object&&(object.joeUpdated=self.current.object.joeUpdated);var prop,groups={},parentFind=$(".joe-overlay.active");if(index&&(parentFind=self.overlay.find(".joe-object-field")),!parentFind.find(".joe-field").length&&self.current.object)return self.current.object;return parentFind.find(".joe-field").each(function(){if("joe-button"===this.nodeName.toLowerCase())return!0;if($(this).parents(".objectList-field,.objectlist-field").length)return!0;if($(this).parents(_joe.Mini.selector).length)return!0;if(!self.current.userSpecs||!self.current.userSpecs.multiedit||$(this).parents(".joe-object-field").hasClass("multi-selected"))switch($(this).attr("type")){case"checkbox":prop=$(this).attr("name"),groups[prop]||this.parentElement.classList.contains("joe-group-item-checkbox")?(groups[prop]=groups[prop]||[],$(this).is(":checked")&&groups[prop].push($(this).val()),object[prop]=groups[prop]):$(this).is(":checked")?object[prop]=!0:object[prop]=!1;break;default:if((prop=this.getAttribute("data-name")||this.getAttribute("name"))&&"undefined"!=prop){switch($(this).data("ftype")){case"passthrough":object[prop]=self.propAsFuncOrValue(object[prop]);break;case"ace":var editor=_joe.ace_editors[$(this).data("ace_id")];object[prop]=editor?editor.getValue():self.current.object[prop];break;case"ckeditor":editor=CKEDITOR.instances[$(this).data("ckeditor_id")];object[prop]=editor?editor.getData():self.current.object[prop];break;case"tinymce":var editorId=this.getAttribute("data-texteditor_id");editor=window.tinymce?.get(editorId);object[prop]=editor?editor.getContent():self.current.object[prop],object[prop]=self.cleanTinyMCEs(object[prop]);break;case"multisorter":var vals=[];$(this).find(".selections-bin").find("li").each(function(){vals.push($(this).data("id"))}),object[prop]=vals;break;case"uploader":var joe_uploader=self.uploaders[$(this).data("uploader_id")];object[prop]=joe_uploader.files;break;case"buckets":vals=[];$(this).find(".selections-bin").each(function(){vals.push([]),$(this).find("li").each(function(){var dom;vals[vals.length-1].push((dom=this,$(dom).data().isobject?obj=JSON.parse(decodeURI($(dom).data().value)):$(dom).data().value))})}),object[prop]=vals;break;case"objectReference":var obj;vals=[];object[prop]="objectReference",$('.objectReference-field[data-name="'+prop+'"]').find(".joe-field-list-item,.joe-field-item").each(function(){$(this).data().isobject?(obj=JSON.parse(decodeURI($(this).data().value)),vals.push(obj)):vals.push($(this).data().value)}),object[prop]=vals.condense();break;default:object[prop]=$(this).val()}break}}}),["subobject"].map(function(fieldtype){self.Fields[fieldtype].construct(parentFind,object)}),parentFind.find(".joe-object-field.content-field").each(function(){prop=$(this).data("name");var cfield=self.getField(prop);cfield.passthrough&&(!0===cfield.passthrough?object[prop]=self.current.object[prop]:object[prop]=self.propAsFuncOrValue(cfield.passthrough,self.current.object))}),parentFind.find(".objectList-field").each(function(){var subVal,subInput,ol_property=$(this).data("name"),ol_array=[],subprops=[];$(this).find("thead").find("th").each(function(i){subprops.push($(this).data("subprop"))}),$(this).find("tbody").find("tr").each(function(){var ol_array_obj={};$(this).find("td").each(function(i){var $cell=$(this),$groupCheckboxes=$cell.find('.joe-group-item-checkbox input[type="checkbox"]'),$radios=$cell.find('input[type="radio"]'),$checkboxes=$cell.find('input[type="checkbox"]');if($groupCheckboxes.length)subVal=$groupCheckboxes.filter(":checked").map(function(){return $(this).val()}).get();else if($radios.length){var r=$radios.filter(":checked").val();subVal=void 0===r?null:r}else 1===$checkboxes.length?subVal=$checkboxes.is(":checked"):$checkboxes.length>1?subVal=$checkboxes.filter(":checked").map(function(){return $(this).val()}).get():(subInput=$cell.find("input,select,textarea"),subVal=subInput.val());ol_array_obj[subprops[i]]=subVal}),delete ol_array_obj.undefined,ol_array.push(ol_array_obj)}),object[ol_property]=ol_array}),_bmResponse(constructBM,"----constructed",null,.01),!$c.isEmpty(object)&&object||!1},this.Object.getFromServer=function(id,specs,callback){var schemaName=(specs=specs||{}).schema||_joe.current.schemaName||_joe.current.schema&&_joe.current.schema.__schemaname,goto=!1!==specs.goto;if(!schemaName||!id)return console.warn("Cannot fetch object: missing schema or ID."),void(callback&&callback(!1));var url="/API/object/"+schemaName+"/_id/"+id;$.get(url,function(data){if(!data||!data._id)return console.warn("No object returned from server."),void(callback&&callback(!1));var toUpdate=_joe.search(id)[0]||!1;if(toUpdate&&$.extend(!0,toUpdate,data),goto){_joe.current.object&&_joe.current.object._id==data._id&&(_joe.current.object=data);var specs=$.extend({},_joe.current.specs||{},{schema:schemaName,force:!0});_joe.show(data,specs)}callback&&callback(!0,data)}).fail(function(err){console.error("Error fetching object from server:",err),callback&&callback(!1)})},this.Object.flatten=function(id,options={}){const{recursive:recursive=!0,depth:depth=1,visited:visited=new Set}=options;let object=null;if(id?object=$J.get(id):_joe?.current?.object&&(object=_joe.current.object),!object)return null;const flattened={},currentId=object._id||object.id;currentId&&visited.add(currentId);for(const[field,val]of Object.entries(object))if(null!=val)if("_id"!=field)if("string"==typeof val&&$c.isCuid(val)&&recursive&&depth>0)if(visited.has(val))flattened[field]=val;else{const expanded=_joe.Object.flatten(val,{recursive:recursive,depth:depth-1,visited:new Set(visited)});flattened[field]=expanded||val}else Array.isArray(val)&&val.every(v=>"string"==typeof v&&$c.isCuid(v))&&recursive&&depth>0?flattened[field]=val.map(refId=>{if(!visited.has(refId)){return _joe.Object.flatten(refId,{recursive:recursive,depth:depth-1,visited:new Set(visited)})||refId}return refId}):flattened[field]=val;else flattened[field]=val;return flattened},this.Export={},this.Export.JSON=this.exportJSON=function(object,specs){var minify=(specs=specs||{}).minify||null,objvar=specs.objvar||"",obobj=minify?JSON.stringify(object):JSON.stringify(object,""," ");goJoe("<b>"+(specs.title||objvar&&"var "+objvar+" = "||"JSON Object")+"</b><br/><pre>"+obobj+"</pre>",{schema:specs.schema}),logit(obobj)},this.Export.csv=function(schemaname,specs){for(;!schemaname;)if(null===(schemaname=prompt("schema name (itemtype)?")))return;var schema=_joe.schemas[schemaname];if(schema){var idprop=(specs=$.extend({labels:!0},specs||{})).idprop||schema.idprop||"_id",arrData=_joe.Data[schemaname].sortBy("name");specs.filter&&(arrData=arrData.where(specs.filter));var CSV="";if(CSV+=schemaname+"\r\n\n",specs.labels){var row="";for(var index in arrData[0])row+=index+",";CSV+=(row=row.slice(0,-1))+"\r\n"}for(var i=0;i<arrData.length;i++){var colval;row="";for(var index in arrData[i])colval=arrData[i][index],index!=idprop&&$c.isCuid(colval)&&(colval=_joe.Cache.get(colval).name),row+='"'+colval+'",';row.slice(0,row.length-1),CSV+=row+"\r\n"}if(""!=CSV){var fileName="JOE-"+$c.pluralize(schemaname)+"-"+$c.format(new Date,"m-d-Y")+".csv",uri="data:text/csv;charset=utf-8,"+escape(CSV),downloadLink=document.createElement("a");downloadLink.href=uri,downloadLink.download=fileName,document.body.appendChild(downloadLink),downloadLink.click(),document.body.removeChild(downloadLink)}else alert("Invalid data")}else alert('no schema "'+schemaname+'" found ')},this.updateMultipleObjects=function(dom,multipleCallback,callback){callback=callback||self.current.onUpdate||self.current.callback||self.current.schema&&(self.current.schema.onUpdate||self.current.schema.callback)||logit,multipleCallback=multipleCallback||self.current.onMultipleUpdate||self.current.multipleCallback||self.current.schema&&(self.current.schema.onMultipleUpdate||self.current.schema.multipleCallback)||logit;var idprop=self.getIDProp(),newObj=self.constructObjectFromFields(self.joe_index);if(Object&&Object.keys&&1==Object.keys(newObj).length&&"joeUpdated"==Object.keys(newObj)[0])self.showMessage("please select at least one property to update.");else{delete newObj[idprop],delete newObj.id,delete newObj._id;var haystack=self.current.list,needles=self.current.selectedListItems,updatedItems=[];haystack.map(function(i){-1!=needles.indexOf(i[idprop])&&($.extend(i,newObj),callback(i),updatedItems.push(i))}),logit(updatedItems.length+" item(s) updated"),multipleCallback(updatedItems),self.goBack(),self.showMessage(updatedItems.length+" item(s) updated")}},this.deleteMultipleObjects=function(callback){callback=self.current.callback||self.current.schema&&self.current.schema.callback||logit;var obj=self.current.object;if(!self.current.list||!obj||-1==self.current.list.indexOf(obj))return alert("object or list not found"),self.hide(),void callback(obj);var index=self.current.list.indexOf(obj);self.current.list.removeAt(index),logit("object deleted"),self.hide(),callback(obj)},this.selectAllItems=function(){self.current.selectedListItems=[];var currentItemIDs=currentListItems.map(function(item){return item[self.getIDProp()]});self.overlay.addClass("multi-edit"),self.current.selectedListItems=currentItemIDs,self.overlay.find(".joe-panel-content-option").addClass("selected"),self.allSelected=!0,self.updateSelectionVisuals()},this.deselectAllItems=function(){self.current.selectedListItems=[],self.overlay[0].classList.remove("multi-edit"),self.overlay.find(".joe-panel-content-option").removeClass("selected"),self.allSelected=!1,self.updateSelectionVisuals()},this.analyzeImportMerge=function(newArr,oldArr,idprop,specs){if(self.showMessage("Beginning Merge Analysis of "+(newArr.length+oldArr.length),{timeout:0}),_webworkers){(_joeworker=new Worker(joe_web_dir+"js/joe-worker.js")).onmessage=function(e){e.data.worker_update?(e.data.worker_update.message?self.showMessage(e.data.worker_update.message,{timeout:0}):self.showMessage("Merged "+e.data.worker_update.current+"/"+e.data.worker_update.total+" in "+e.data.worker_update.time+" secs",{timeout:0}),logit("Merged "+e.data.worker_update.current+"/"+e.data.worker_update.total+" in "+e.data.worker_update.time+" secs")):(self.showMessage("Analysis Completed in "+e.data.time+" secs",{timeout:0}),confirm("Run Merge? \n"+JSON.stringify(e.data.results,null,"\n"))?specs.callback(e.data):self.showMessage("next step cancelled"))};var safespecs=$.extend({},specs);return delete safespecs.icallback,delete safespecs.callback,void _joeworker.postMessage({action:"analyzeMerge",data:{newArr:newArr,oldArr:oldArr,idprop:idprop,specs:safespecs}})}var aimBM=new Benchmarker,defs=(idprop=idprop||"_id",{callback:function(data){self.showMiniJoe({title:"Merge results",props:JSON.stringify(data.results,null,"\n"),mode:"text",menu:[]})},deleteOld:!1,dateProp:null,icallback:null});specs=$.extend(defs,specs);var newObj,oldObj,data={add:[],update:[],same:[],delete:[]},i=(oldArr=oldArr.sortBy(idprop),newArr=newArr.sortBy(idprop),0),query={},oldIDs=[],newIDs=[];oldArr.map(function(s){oldIDs.push(s[idprop])}),newArr.map(function(s){newIDs.push(s[idprop])}),(query={})[idprop]={$nin:oldIDs},data.add=newArr.where(query),query[idprop]={$in:newIDs};var existing=oldArr.where(query);query[idprop]={$in:oldIDs};for(var onetoone=newArr.where(query),len=(i=0,existing.length);i<len;i++)newObj=onetoone[i],oldObj=existing[i],newObj?specs.dateProp&&newObj[specs.dateProp]&&oldObj[specs.dateProp]&&newObj[specs.dateProp]==oldObj[specs.dateProp]?data.same.push(newObj):data.update.push(newObj):data.same.push(oldObj);data.results={add:data.add.length,update:data.update.length,same:data.same.length},self._mergeAnalyzeResults=data,logit("Joe Analyzed in "+aimBM.stop()+" seconds"),confirm("Run Merge? \n"+JSON.stringify(data.results,null,"\n"))&&specs.callback(data)},this.analyzeClassObject=function(object,ref,maxDepth,classString){var classString=classString,maxDepth=maxDepth||10,data={methods:[],properties:[]},pReg=/function[\s*]\(([_a-z,A-Z0-9]*)\)/,curProp,params;function parseFunction(object,p,parent,depth){var parent=parent||"",curProp=object[p];params=pReg.exec(object[p]),params=params&&params[1]||"";try{var comments=/\/\*\|([\s\S]*)?\|\*\//;evalString=curProp.toString().match(comments),evalString&&evalString[1]&&(evalString=eval("("+evalString[1].replace(/\*/g,"")+")"))}catch(e){evalString={error:'Could not evalutate "'+p+'": \n'+e},self.Error.add('Could not evalutate "'+p+'": \n'+e,e,{caller:"self.analyzeClassObject"})}var funcName=parent+p,methodObj={code:object[p],name:funcName,global_function:!1,propname:p,ref:ref,class:ref,args:params,parameters:comments&&(comments.params||comments.parameters)||null,_id:ref+"_"+funcName,comments:evalString||{},itemtype:"method",parent:parent||null};if(classString)try{methodObj.count=(classString.toString().match(new RegExp((parent||".")+p,"g"))||[]).length}catch(e){self.Error.add("issue with static class: "+ref,e,{caller:"self.analyzeClassObject"})}return methodObj.comments&&(methodObj.comments.info||methodObj.comments.description)&&(methodObj.description=methodObj.comments.info||methodObj.comments.description),methodObj.comments&&methodObj.comments.tags&&(methodObj.tags=methodObj.comments.tags.split(",")),data.methods.push(methodObj),{_id:ref+"_"+funcName}}function parseProperty(object,p,parent,depth){if(!(depth>maxDepth)){depth=depth||0;depth++;parent=parent||"";var curProp=object[p],propName=parent+p,propObj={name:propName,ref:ref,class:ref,_id:ref+"_"+propName,itemtype:"property",parent:parent||null,depth:depth,propname:p};if("object"==$.type(curProp)){var subproperties=[];for(var sub in curProp)try{curProp.hasOwnProperty(sub)&&object!=window.document&&object!=window&&("function"==$.type(curProp[sub])?subproperties.push(parseFunction(curProp,sub,propName+".",depth)._id):subproperties.push(parseProperty(curProp,sub,propName+".",depth)._id))}catch(e){self.Error.add(sub+": "+e+":"+curProp[sub],e,{caller:"parseProperty"})}subproperties.length&&(propObj.subproperties=subproperties),propObj.value=object[p]}else propObj.value=object[p];return data.properties.push(propObj),{_id:ref+"_"+propName}}}for(var p in object){curProp=object[p];try{"function"==$.type(curProp)?parseFunction(object,p):parseProperty(object,p)}catch(e){self.Error.add(e,e)}}return data},this.functionName=function(func){var name=func.toString();return/function ([^\(]*)/.exec(name)[1]},this.getState=function(){return{object:_jco(),list:self.current.filteredList,schema:self.current.schema&&self.current.schema.name||null,title:self.current.title}},this.getCascadingProp=function(propname,schema){schema=schema&&(self.schemas[schema]||schema)||self.current.schema;return self.current[propname]||self.current.userSpecs&&self.current.userSpecs[propname]||schema&&(listMode&&schema.listView&&schema.listView[propname]||schema[propname])||self.specs[propname]},this.getIDProp=function(schema){return schema&&self.schemas[schema]&&self.schemas[schema].idprop||self.current.schema&&(self.current.schema.idprop||self.current.schema._listID)||"_id"},this.propAsFuncOrValue=function(prop,toPass,defaultTo,secondToPass){try{toPass=toPass||!$c.isEmpty(self.current.constructed)&&self.current.constructed||self.current.object;return prop&&"function"==typeof prop?prop(toPass,secondToPass):prop}catch(e){return self.Error.add("JOE: error parsing propAsFunction: "+e,e,{caller:"self.propAsFuncOrValue"}),""}},this.getFieldValues=function(values,prop){var vals=self.propAsFuncOrValue(values)||[];if(vals.isString()&&(vals=self.getDataset(vals)||[]),prop){var sortby=prop.sortby||prop.sortBy;sortby&&(vals=vals.sortBy(sortby))}return vals},this.Hash={},this.setEditingHashLink=function(bool){window._joeEditingHash=bool||!1};var hash_delimiter="/";function navigateItems(goto){var gotoIndex,gotoObject,dataset,objIndex=self.getObjectIndex();if(!(dataset=objIndex.dataset))return alert("no dataset set");(gotoIndex=objIndex.index+goto)>dataset.length-1?gotoIndex=0:gotoIndex<0&&(gotoIndex=dataset.length-1),gotoObject=dataset[gotoIndex],self.show(gotoObject,{schema:self.current.schema.__schemaname})}location.href&&-1!=location.href.indexOf(":::")&&(hash_delimiter=":::"),this.Hash.delimiter=hash_delimiter,this.updateHashLink=function(){if(self.specs.useHashlink){var hashInfo={};hashInfo.schema_name=self.current.schema&&self.current.schema.__schemaname,listMode?(hashInfo.object_id="",hashInfo.subset=self.current.subset&&self.current.subset.name||""):(hashInfo.subset="",hashInfo.object_id=self.current.object&&self.current.object[self.getIDProp()]||"");var hashtemplate="string"==$.type(specs.useHashlink)?specs.useHashlink:hash_delimiter+"${schema_name}"+((hashInfo.object_id||hashInfo.subset)&&hash_delimiter||"")+"${object_id}${subset}";return location.hash=fillTemplate(hashtemplate,hashInfo),location.hash}},this.Hash.update=this.updateHashLink,this.readHashLink=function(hash){if(!self.specs.useHashlink)return!1;try{if(!(useHash=hash||$GET("!")||location.hash)||0!=self.joe_index)return!1;var useHash,hashBreakdown=(useHash=useHash.replace("#","")).split(hash_delimiter).condense();if(!(hashBreakdown=hashBreakdown.filter(function(v){return""!==v})).length)return self.closeButtonAction(),!1;var dataset,hashInfo={},hashSchema=self.schemas[hashBreakdown[0]],hashItemID=hashBreakdown[1]||"";if(!hashSchema||!(hashSchema.dataset||!$.isEmptyObject(self.Data)&&self.Data[hashSchema.__schemaname]))throw error,'dataset for "'+hashSchema+'" not found';if(dataset=hashSchema.dataset?"function"==typeof hashSchema.dataset?hashSchema.dataset():hashSchema.dataset:self.Data[hashSchema.__schemaname]||[],hashInfo.schema=hashSchema,!$.isEmptyObject(self.Data)){var curkey=self.current.keyword;if(self.current.keyword=hashInfo.keyword=$GET("keyword"),self.current.keyword=self.current.keyword||curkey,hashItemID){var collectionName=hashSchema.__collection||hashSchema.__schemaname;if(-1!=hashItemID.indexOf("@")){hashItemID=hashItemID.substr(0,hashItemID.indexOf("@"))}if(-1!=hashItemID.indexOf(":")){var key=hashItemID.split(":")[0],value=hashItemID.split(":")[1];if(collectionName)(collectionItem=self.getDataItem(value,collectionName,key))&&goJoe(collectionItem,hashInfo);else hashInfo.subset=hashItemID,goJoe(dataset,hashInfo)}else{var collectionItem;if(collectionName)(collectionItem=self.getDataItem(hashItemID,collectionName))?goJoe(collectionItem,hashInfo):(hashInfo.subset=hashItemID,goJoe(dataset,hashInfo))}}else goJoe(dataset,hashInfo);var section=$GET("section")||hashBreakdown[2]||!1;section&&self.gotoSection(section)}}catch(e){return self.Error.add("error reading hashlink:"+e,e,{useHash:useHash||""}),!1}return __gotoJoeSection=self.gotoSection,!0},this.Hash.read=this.readHashLink,this.isNewItem=function(){if(listMode)return!1;var idprop=self.getIDProp();return!(self.current.object&&self.current.object[idprop]&&self.search(self.current.object[idprop]).length)},this.respond=function(e){var w=self.overlay.width(),curPanel=(self.overlay.height(),self.panel[0]),sizeClass="";-1==curPanel.className.indexOf("-size")&&(curPanel.className+=" large-size "),sizeClass=w<600?"small-size":"large-size",curPanel.className=curPanel.className.replace(/[a-z]*-size/,sizeClass),htmlRef.className=htmlRef.className.replace(/[a-z]*-size/,"joe"+sizeClass),self.sizeClass=sizeClass},this._renderGotoButton=function(id,dataset,schema){var item={};item._id=id||this._id,item.dataset=dataset||this.itemtype,item.schema=schema||item.dataset;var idprop=self.getIDProp(schema);return fillTemplate('<div class="joe-block-button goto-icon" onclick="goJoe(_joe.getDataItem(\'${'+idprop+"}','${dataset}'),{schema:'${schema}'})\"></div>",item)},window._renderGotoButton=this._renderGotoButton,this.smartSave=function(item,newItem,schema){},this.parseAPI=function(jsObj,libraryname){goJoe(self.analyzeClassObject(jsObj,libraryname).methods,{schema:"method",title:libraryname+" Methods"})},window.joeAPI=this.parseAPI,this.jsonp=function(url,dataset,callback,data){callback=callback||logit,$.ajax({url:url,data:data,dataType:"jsonp",callback:function(data){callback(data,dataset)}})},this.next=function(){navigateItems(1)},this.previous=function(){navigateItems(-1)},this.getObjectIndex=function(object){var dataset;object=object||self.current.item,self.getIDProp();if(self.current.filteredList)dataset=self.current.filteredList;else{if(!self.current.schema)return alert("no schema set");dataset=self.getDataset(self.current.schema.__schemaname).sortBy(self.current.schema.sorter||["name"])}return dataset?{index:dataset.indexOf(self.current.object),dataset:dataset}:{index:-1,dataset:null}};var getSelfStr="getJoe("+self.joe_index+")";this.IO={Export:{}},this.IO.Export.button=__exportBtn__,this.IO.Export.schema={fields:[{name:"code",type:"code"}]},this.IO.Export.json=self.exportJSON,this.IO.Export.csv=self.Export.csv,this.IO.export=function(item,json,specs){specs=$.extend({minify:!1,schema:self.IO.Export.schema,objvar:self.current.schema.__schemaname},specs),item=item||_jco();if(json)self.exportJSON(item,specs);else{var item_spec={code:JSON.stringify(item).replace(/,"/i,',\n"')};self.show(item_spec,{schema:self.IO.Export.schema})}},this.Components={loaded:{},styleTag:"joeWebComponentStyles"},this.Components.load=function(coName){if(!document.getElementById(self.Components.styleTag)){var c=document.createElement("style");c.id=self.Components.styleTag,document.body.appendChild(c)}if(!self.Components.loaded[coName]){var script=document.createElement("script");script.type="text/javascript";var wd=window.web_dir||"/JsonObjectEditor/";script.src=`${wd}web-components/${coName}.js`,document.body.appendChild(script),self.Components.loaded[coName]=!0}},this.Components.appendStyles=function(styles){var styleTag=document.getElementById(_joe.Components.styleTag);styleTag&&(styleTag.innerHTML+=styles)},this.Components.getAttributes=function(comp){for(var d={},a=0;a<comp.attributes.length;a++)d[comp.attributes[a].name]=comp.attributes[a].value;return d},this.Components.init=function(){self.Components.load("joe-button"),self.Components.load("joe-field"),self.Components.load("joe-list-item"),self.Components.load("joe-autocomplete"),self.Components.load("joe-user-cube"),self.Components.load("joe-card"),self.Components.load("capp-components")},this.buttons={create:__createBtn__,quickSave:__quicksaveBtn__,save:__saveBtn__,delete:__deleteBtn__,multiSave:__multisaveBtn__,selectAll:__selectAllBtn__,duplicate:__duplicateBtn__,export:self.IO.Export.Button},this.buttons.next={name:"next",display:"next >",css:"joe-fright",action:getSelfStr+".next()"},this.buttons.previous={name:"previous",display:"< prev",css:"joe-fleft",action:getSelfStr+".previous()"},this.Speech={init:function(force){(force||self.specs.speechRecognition)&&(self.addStylesheet(joe_web_dir+"js/plugins/microphone/microphone.min.css",{name:"microphone-css"}),self.addScript(joe_web_dir+"js/plugins/microphone/microphone.min.js",{name:"microphone-js"}))},confirm:function(){self.Mini.show({object:"hello",title:"Audio",menu:[{name:"confirm"},{name:"cancel"}]})},initMic:function(){var mic=self.Speech.mic=new Wit.Microphone(document.getElementById("speech-button-"+self.joe_index)),info=function(msg){logit(msg)},error=function(msg){logit(msg)};mic.onready=function(){info("Microphone is ready to record")},mic.onaudiostart=function(){info("Recording started"),error("")},mic.onaudioend=function(){info("Recording stopped, processing started")},mic.onresult=function(intent,entities){logit(intent)},mic.onerror=function(err){error("Error: "+err)},mic.onconnecting=function(){info("Microphone is connecting")},mic.ondisconnected=function(){info("Microphone is not connected")},mic.connect("3J7E3INLVHRRZYVTX6VBXWUXXGMRDEPS")}},this.TITLE={dom:function(){return self.panel&&self.panel.find(".joe-panel-title")||null},get:function(){return self.TITLE.dom.html()},set:function(value,specs){specs=$.extend({before:"",after:""},specs||{});if(value=self.propAsFuncOrValue(value))return self.TITLE.dom().html(specs.before+value+specs.after),value;var tempObj=self.constructObjectFromFields(),titleObj=$.extend({},tempObj,{_listCount:(currentListItems||[]).length||"0"}),cTitle=self.propAsFuncOrValue(self.current.title,tempObj),titleStr=fillTemplate(cTitle,titleObj);return self.TITLE.dom().html(specs.before+titleStr+specs.after),document.title=titleStr,titleStr}};var iceServers=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:webrtcweb.com:7788",username:"muazkh",credential:"muazkh"},{urls:"turn:webrtcweb.com:7788",username:"muazkh",credential:"muazkh"},{urls:"turn:webrtcweb.com:8877",username:"muazkh",credential:"muazkh"},{urls:"turns:webrtcweb.com:7788",username:"muazkh",credential:"muazkh"},{urls:"turns:webrtcweb.com:8877",username:"muazkh",credential:"muazkh"},{urls:"stun:webrtcweb.com:4455",username:"muazkh",credential:"muazkh"},{urls:"turns:webrtcweb.com:4455",username:"muazkh",credential:"muazkh"},{urls:"turn:webrtcweb.com:5544?transport=tcp",username:"muazkh",credential:"muazkh"}],rtcConfig={iceServers:iceServers,sdpSemantics:"plan-b"},useRTC=!1;this.CONNECT={gotStream:function(stream){logit("Received local stream"),self.CONNECT.videos.local&&(self.CONNECT.videos.local.srcObject=stream),self.CONNECT.streams.local=stream,self.CONNECT.RTC.addStream(self.CONNECT.streams.local)},RTC:useRTC&&window.RTCPeerConnection&&new RTCPeerConnection(rtcConfig)||null,newConnection:function(){self.CONNECT.RTC=new RTCPeerConnection(rtcConfig),self.CONNECT.init()},init:function(){self.CONNECT.RTC.oniceconnectionstatechange=function(){"completed"==self.CONNECT.RTC.iceConnectionState&&(logit("ICE state: "+self.CONNECT.RTC.iceConnectionState),self.CONNECT.offerinprogress||confirm("connect request received")||self.CONNECT.end(self.CONNECT.userid,!0),logit("stopping CONNECT interval -init"),clearInterval(self.CONNECT.offerinterval),self.CONNECT.offerinprogress=!1)},self.CONNECT.RTC.onaddstream=function(evt){logit("stream"),self.CONNECT.streams.remote=evt.stream,self.CONNECT.videos.remote.srcObject=self.CONNECT.streams.remote,self.CONNECT.videos.remote.play()},self.CONNECT.RTC.onremovestream=function(evt){logit("stream ended:",evt)},self.CONNECT.RTC.onicecandidate=function(evt){}},videos:{},streams:{},start:function(userid,makeoffer){if("closed"==self.CONNECT.RTC.signalingState&&(self.CONNECT.RTC=new RTCPeerConnection(iceServers)),userid){self.CONNECT.end(userid);var userobj=self.getDataItem(userid,"user"),popup=self.CONNECT.createPopup(userobj);if(self.CONNECT.videos.local=$("#"+popup.domid).find(".joe-connect-myvideo")[0],self.CONNECT.videos.remote=$("#"+popup.domid).find(".joe-connect-video")[0],navigator.mediaDevices.getUserMedia({audio:!0,video:!0}).then(self.CONNECT.gotStream).catch(function(e){alert("getUserMedia() error: "+e.name),console.log(e)}),makeoffer){var RTC=self.CONNECT.RTC;RTC.createOffer().then(function(offer){return RTC.setLocalDescription(offer)},function(data){alert("error in RTC"+data),logit(data)}).then(function(){self.SERVER.socket.emit("connect_offer",{user:_joe.User._id,target:userid,sdp:RTC.localDescription})}).catch(function(reason){console.log(reason)})}}else _joe.showMiniJoe({title:"CONNECT w/",list:self.Data.user.where({_id:{$ne:self.User._id}}),template:function(user){var template="<joe-title>${name}</joe-title><joe-subtitle>${fullname}</joe-subtitle><joe-subtext>${info}</joe-subtext>";return user.image_url&&(template='<joe-listitem-icon style="background-image:url(${image_url});"></joe-listitem-icon>'+template),template},idprop:"_id",menu:[],callback:function(item_id){self.CONNECT.start(item_id)}})},sendOfferToServer:function(offer){},end:function(userid,clear){capp.Popup.delete("connect_"+userid),clear&&(logit("stopping CONNECT interval - end"),clearInterval(self.CONNECT.offerinterval),self.CONNECT.offerinprogress=!1,self.CONNECT.userid=null,self.CONNECT.RTC.close(),self.CONNECT.streams.remote&&self.CONNECT.streams.remote.getTracks().forEach(function(track){track.stop()}),self.CONNECT.streams.local&&self.CONNECT.streams.local.getTracks().forEach(function(track){track.stop()}))},template:function(userobj){return'<joe-video-holder><video autoplay class="joe-connect-video"></video><video autoplay class="joe-connect-myvideo"></video></joe-video-holder>'+userobj.name},createPopup:function(userobj,specs){return capp.Popup.add("connect w/ <b>"+(userobj.fullname||userobj.name)+"</b>",self.propAsFuncOrValue(self.CONNECT.template,userobj),{id:"connect_"+userobj._id,active:!0,close_action:"_joe.CONNECT.end('"+userobj._id+"',true);"})}},useRTC&&window.RTCPeerConnection&&this.CONNECT.init(),this.SERVER={Plugins:{awsFileUpload:function(data,callback){var file=data.file,field=data.field;if(field.bucketname||(_joe.Data.setting.where({name:"AWS_BUCKETNAME"})[0]||{value:""}).value){var filename=file.filename,directory=_joe.current.object._id,url=field&&self.propAsFuncOrValue(field.server_url)||location.port&&"//"+__jsc.hostname+":"+__jsc.port+"/API/plugin/awsConnect/"||"//"+__jsc.hostname+"/API/plugin/awsConnect/",Key=directory+"/"+filename;$.ajax({url:url,type:"POST",data:{Key:Key,base64:file.base64,extension:file.extension,contentType:file.type,ACL:field.hasOwnProperty("ACL")?field.ACL:"public-read"},success:function(response){if(!response.error){var url;if(logit(response),!(url=response.url)){var bucket=response.bucket||(_joe.Data.setting.where({name:"AWS_BUCKETNAME"})[0]||{value:""}).value,region=(_joe.Utils.Settings("AWS_S3CONFIG")||{}).region;url=((_joe.Data.setting.where({name:"AWS_S3PREFIX"})[0]||{value:""}).value||"https://"+bucket+".s3."+(region||"")+".amazonaws.com/")+response.Key}var filename=response.Key.replace(self.current.object._id+"/","");if(field.url_field){var nprop={};_joe.current.object[field.url_field]=url,nprop[field.url_field]=url,_joe.Fields.rerender(field.url_field,nprop)}}callback(response.error,url,filename)},error:function(xhr,status,err){var message=xhr&&(xhr.responseJSON&&(xhr.responseJSON.error||xhr.responseJSON.code)||xhr.responseText)||err||status||"Upload failed";callback&&callback(message)}})}else{callback&&callback("AWS bucket not configured")}},awsConnect:function(data,callback){return _joe.SERVER.Plugins.awsFileUpload({file:{base64:data.base64,extension:data.extension,type:data.contentType,filename:_joe.current.object._id+data.extension,name:_joe.current.object._id+data.extension},field:data.field},callback)}},ready:{schemas:!1,datasets:!1,localstorage:!1,user:!1,app:!1},Cache:{reload:function(collections){$.ajax({url:"/API/cache/update/"+(collections||""),datatype:"jsonp",success:function(data){data.error?alert(data.error):location.reload()}})}},History:{get:function(id,callback){if(id=id||self.current.item&&self.current.item[self.getIDProp()]){callback=callback||logit;$.ajax({url:"/API/history/itemid/"+id,dataType:"jsonp",success:function(data){if(data.error)return alert(error);callback(data)}})}},show:function(history_response,specs){var results=history_response.results,item=self.search(history_response.query.itemid)[0]||{name:"not found"};goJoe(results,{schema:self.SERVER.History.schema,title:"History of ["+item.itemtype+"] "+item.name})},schema:{title:"[${collection} history] ${this.historical.name}",sorter:["!timestamp"],listTitle:function(item){return"<joe-title>"+(item.changes&&item.changes.__length||0)+" changes by ${this.user.name}</joe-title><joe-subtitle>${RUN[_joe.Utils.prettyPrintDTS;${timestamp}]}</joe-subtitle>"},checkChanges:!1,fields:["itemid:cuid","collection","timestamp",{name:"user",type:"subObject",locked:!0},{name:"historical",type:"subObject",locked:!0},{name:"changes",type:"subObject",locked:!0}]},button:{name:"history",label:"&nbsp;",title:"Item History",action:"_joe.SERVER.History.get('${_id}',_joe.SERVER.History.show)",css:"joe-history-button joe-left-button"}},User:{get:function(){$.ajax({url:"/API/user/current",dataType:"jsonp",success:function(data){data.error?alert("error getting user:\n"+data.error):data.user&&(_joe.User=data.user,self.SERVER.User.store(),self.SERVER.User.signin(),logit("logged in as "+_joe.User.name)),self.SERVER.ready.user=!0,self.SERVER.onLoadComplete()}})},store:function(){var now=new Date,expireTime=now.getTime()+36e7;now.setTime(expireTime),$("#cappUser").html(_joe.User.name),document.cookie="_j_user="+_joe.User.name+";expires="+now.toGMTString()+";path=/",document.cookie="_j_token="+_joe.User.token+";expires="+now.toGMTString()+";path=/"},signin:function(obj,oldObj,changes){self.SERVER.socket.emit("signin",{user:_joe.User}),self.SERVER.socket.on("user_info",function(data){if(data.error||!data.connected_users||!$c.itemCount(data.connected_users))return self.Error.add("improper user data returned",null,data),void logit("user info",data);logit("user info",data);var userObj=data.connected_users[_joe.User._id];if(userObj&&userObj.sockets){var imageHtml="";_joe.User&&_joe.User.image&&(imageHtml='<img class="capp-user-icon" src="'+_joe.User.image+'" />',$("#cappUser").addClass("with-image")),$("#cappUser").html(imageHtml+"<capp-user-name><b>"+_joe.User.name+"</b>"+(userObj.sockets.length>1&&"<small> x"+userObj.sockets.length+"</small>"||"")+"</capp-user-name>"),$("#cappUserMenu").find(".user-info").remove();var user,user_html="";for(var u in data.connected_users)u!=_joe.User._id&&(user_html+='<capp-menu-content class="user-info"><b onclick="_joe.CONNECT.start(\''+(user=data.connected_users[u]).user._id+"',true);\">"+user.user.name+"</b>"+fillTemplate("<span onclick=\"window.open('${url}')\"> ${app}</span>",user.sockets)+"</capp-menu-content>");$("#cappUserMenu capp-menu-panel").append(user_html)}})},Render:{cubes:function(ids,cssclass,user_dataset){"string"==typeof ids&&(ids=ids.split(","));var users=_joe.Data[user_dataset||"user"].where({_id:{$in:ids}}),html="";return users.map(function(user){html+=self.SERVER.User.Render.cube(user,cssclass)}),html},cube:function(userobj,cssclass){var css=cssclass||"fright",u=userobj,html="",name=u.fullname||u.name;return initials=name[0]+(name.indexOf(" ")>0&&name[name.indexOf(" ")+1]||""),html+='<joe-user-cube title="'+name+'" style="background-color:'+userobj.color+'" class="joe-initials '+css+'">'+initials+" <span>"+name+"</span></joe-user-cube>"},userBar:function(userid,cssclass,dataset,nameprop){var user=_joe.Data[dataset||"user"].where({_id:userid})[0]||!1;if(!user)return"";var name=user[nameprop||"name"]||user.fullname||user.name;return'<joe-user-bar title="'+name+'" style="background-color:'+user.color+'" class="joe-initials '+css+'">'+name+"</joe-user-bar>"}}},handleUpdate:function(payload){try{for(var new_item,old_item,r=0,tot=payload.results.length;r<tot;r++){var schemaname=(new_item=payload.results[r]).itemtype;schemaname&&self.schemas[schemaname]&&self.schemas[schemaname].onload&&self.schemas[schemaname].onload([new_item]),_joe.Data[new_item.itemtype]||(_joe.Data[new_item.itemtype]=[]),(old_item=_joe.Data[new_item.itemtype].where({_id:new_item._id})[0]||!1)?($.extend(old_item,new_item),_joe.current.list&&-1!=_joe.current.list.indexOf(old_item)&&listMode&&_joe.reload(!0)):(_joe.Data[new_item.itemtype].push(new_item),_joe.current.list&&-1!=_joe.current.list.indexOf(new_item)&&listMode&&_joe.reload(!0))}for(var sc in self.Data)capp&&capp.Button.update(sc+"SchemaBtn",{counter:self.Data[sc].length});specs.onServerUpdate&&specs.onServerUpdate()}catch(e){self.Error.add("error handling update",e)}},save:function(obj,oldObj,changes){self.SERVER.socket.emit("save",{item:obj})},delete:function(obj,oldObj,changes){self.SERVER.socket.emit("delete",{item:obj})},save_ajax:function(obj,oldObj,changes){ajax({url:"/API/save/",dataType:"jsonp",onsuccess:function(data){if(data.error)alert("Error Saving:\n"+data.error);else if("object"==$.type(data.results)){var result=data.results,itemtype=result.itemtype||self.current.schema.name;self.showMessage(itemtype+", "+result.name+"<br/><b>saved successfully</b>")}},data:obj})},updateObject:function(ajaxURL,specs){specs=$.extend({oldObj:$.extend({},self.current.object),callback:function(data){self.showMessage(data.name+" updated successfully")},ajaxObj:self.constructObjectFromFields(self.joe_index),overwrites:{},skipValidation:!1},specs||{});var newObj=$.extend(ajaxObj.newObj,specs.overwrites,{joeUpdated:(new Date).toISOString()});if(!_joe.propAsFuncOrValue(self.skipValidation)&&!self.validateObject(obj))return!1;$.ajax({url:specs.ajaxObj,data:newObj,dataType:"jsonp",success:specs.callback})},loadSchema:function(schemaName,schemaObj){let sobj;return sobj=$.extend({},getDefaultSchema(schemaName),schemaObj),unstringifyFunctions(sobj),sobj.error?self.Error.add(sobj.error,null):self.Schema.add(schemaName,sobj),sobj},loadSchemas:function(collectionsSTR,callback){"Array"==$.type(collectionsSTR)&&(collectionsSTR=collectionsSTR.join(",")),ajax({url:"/API/schema/"+collectionsSTR,dataType:"jsonp",onsuccess:function(data){if(data.error)alert(data.error);else{var sobj,default_schemas=[];for(var schema in data.schemas)(sobj=self.SERVER.loadSchema(schema,data.schemas[schema])).error?self.Error.add(sobj.error,null):sobj.default_schema?default_schemas.push(sobj):capp.Button.addFromSchema(self.Schema.add(schema,sobj));capp.Menu.add("<capp-button-icon >"+_joe.SVG.icon.menu+" </capp-button-icon><capp-menu-icon-label>default Schemas</capp-menu-icon-label> ",default_schemas,"capp-panel",{labelcss:"no-padding",cssclass:"default-schemas-menu",template:function(sc_btn){var so=self.schemas[sc_btn.name];return capp.Button.addFromSchema(so,{container:!1})}}),data.fields&&(unstringifyFunctions(data.fields),self.specs.fields=self.fields=data.fields)}self.SERVER.ready.schemas=!0,self.SERVER.onLoadComplete(),callback&&callback()}})},loadDatasets:function(collectionsSTR){if(self.specs.localStorage&&"undefined"!=typeof Storage){self.SERVER.LocalStorage.loadData();var toget=[];APPINFO.collections.map(function(coll){_joe.Data[coll]||toget.push(coll)}),self.SERVER.LocalStorage.getUpdates(),toget.length?(logit("retrieving "+toget.length+" datasets "),self.SERVER.getDatasets(toget)):(self.SERVER.ready.datasets=!0,self.SERVER.onLoadComplete())}else self.SERVER.ready.localstorage=!0,self.SERVER.getDatasets(collectionsSTR)},loadAdditionalItems:function(items){if(!items||!items.length)return self.SERVER.ready.additionalItems=!0,void self.SERVER.onLoadComplete();ajax({url:"/API/search/",data:{query:{_id:{$in:items}}},dataType:"jsonp",onsuccess:function(data){var items=data.results||[],schemas=[],datasets={};items.map(i=>{-1==__jsu.schemas.indexOf(i.itemtype)&&(datasets[i.itemtype]=datasets[i.itemtype]||[],datasets[i.itemtype].push(i),schemas.push(i.itemtype))}),schemas=Array.from(new Set(schemas)),ajax({url:"/API/schema/"+schemas.join(","),dataType:"jsonp",data:{mode:"additionalItems"},onsuccess:function(data){if(data.error)alert(data.error);else for(var schema in data.schemas)self.SERVER.loadSchema(schema,data.schemas[schema]),self.Data[schema]&&self.Data[schema].length||self.addDataset(schema,datasets[schema]);self.SERVER.ready.additionalItems=!0,self.SERVER.onLoadComplete()}})}})},loadApp:function(){},getDatasets:function(collectionsSTR){"Array"==$.type(collectionsSTR)&&(collectionsSTR=collectionsSTR.join(",")),ajax({url:"/API/datasets/"+collectionsSTR,dataType:"jsonp",onsuccess:function(data){if(data.error)alert(data.error);else for(var dataset in data.datasets)self.addDataset(dataset,data.datasets[dataset]),capp&&capp.Button.update(dataset+"SchemaBtn",{counter:data.datasets[dataset].length});self.SERVER.ready.datasets=!0,self.SERVER.onLoadComplete()}})},LocalStorage:{saveData:function(){localStorage.joeData=JSON.stringify(_joe.Data),localStorage.timestamp=(new Date).toISOString()},loadData:function(){if(localStorage.joeData){var allData=JSON.parse(localStorage.joeData);APPINFO.collections.map(function(coll){("user"==coll||__jsu.schemas&&-1!=__jsu.schemas.indexOf(coll))&&self.addDataset(coll,allData[coll])})}},getUpdates:function(dateISO){dateISO=dateISO||"undefined"!=typeof Storage&&localStorage.timestamp||null;var query={itemtype:{$in:APPINFO.collections}};dateISO&&(query.joeUpdated={$gte:dateISO}),$.ajax({url:"/API/search/",dataType:"jsonp",data:{query:query},success:self.SERVER.LocalStorage.handleUpdates})},handleUpdates:function(data){data.error&&alert(data.error),logit(data.results.length+" updates in "+data.benchmark),self.SERVER.handleUpdate(data),self.SERVER.ready.localstorage=!0,self.SERVER.onLoadComplete()}},onLoadComplete:function(){if(self.SERVER.ready.datasets&&self.SERVER.ready.schemas&&self.SERVER.ready.user&&self.SERVER.ready.localstorage){if(!self.SERVER.ready.additionalItems)return void self.SERVER.loadAdditionalItems(__jsu.items);for(let name in self.schemas){const schema=self.schemas[name];if(schema.onload&&self.Data[name])try{console.log(`Rerunning onload for schema: ${name}`),schema.onload(self.Data[name])}catch(e){self.Error.add("schema onload re-run error: "+name,e)}}for(var sc in self.Data)capp&&capp.Button.update(sc+"SchemaBtn",{counter:self.Data[sc].length});self.SERVER.socket.on("message",function(message){message.sender?alert(message.sender+" -\n"+message.message):alert(message)}),self.SERVER.socket.on("comments_updated",function(info){self.current.object&&info.itemid==self.current.object[self.getIDProp()]&&JOE.Fields.comments.ready()}),self.SERVER.socket.on("log_data",function(data,name){name=name||"";console.log(name,data)}),self.SERVER.socket.on("item_updated",_joe.SERVER.handleUpdate),self.SERVER.socket.on("save_successful",function(data){var result=data.results;"array"==$.type(result)&&1==result.length?(result=result[0],self.showMessage(result.itemtype+", "+result.name+"<br/><b>saved successfully</b>")):self.showMessage(result.itemtype+", "+result.name+"<br/><b>saved successfully</b>"),self.schemas[result.itemtype]&&self.schemas[result.itemtype].onsave&&self.schemas[result.itemtype].onsave(result)}),self.SERVER.socket.on("connect_answer",function(data){logit("answer received");var userid=data.user;self.CONNECT.offerinprogress||(logit("REREQUESTING: "+userid),self.CONNECT.offerinprogress=!0,self.CONNECT.offerinterval=setInterval(function(){logit("ICE state: "+self.CONNECT.RTC.iceConnectionState),"completed"!=_joe.CONNECT.RTC.iceConnectionState?_joe.CONNECT.start(userid,!0):(logit("stopping CONNECT interval - interval"),clearInterval(self.CONNECT.offerinterval),self.CONNECT.offerinprogress=!1)},3e3)),self.CONNECT.RTC.setRemoteDescription(new RTCSessionDescription(data.sdp))}),self.SERVER.socket.on("connect_offer",function(data){var RTC=self.CONNECT.RTC;self.CONNECT.userid=data.user,_joe.CONNECT.start(data.user,!1),logit(data),RTC.setRemoteDescription(new RTCSessionDescription(data.sdp)).then(function(){RTC.createAnswer().then(function(answer){RTC.setLocalDescription(new RTCSessionDescription(answer)),self.SERVER.socket.emit("connect_answer",{user:_joe.User._id,target:data.user,sdp:answer,socketid:data.socketid})},function(e){console.log(e),alert(e)})})}),_joe.Hash.read(),specs.onServerLoadComplete&&specs.onServerLoadComplete(),self.specs.localStorage&&"undefined"!=typeof Storage&&self.SERVER.LocalStorage.saveData()}},socket:self.specs.socket&&io(self.specs.socket,{rejectUnauthorized:!1})||null},this.addStylesheet=function(href,specs,cancelAppend){var s=document.createElement("link");specs=$.extend({rel:"stylesheet"},specs||{});return $.extend(s,specs),s.href=href,cancelAppend||document.head.appendChild(s),s},this.addScript=function(src,specs,cancelAppend){var s=document.createElement("script");specs=$.extend({type:"text/javascript"},specs||{});return $.extend(s,specs),s.src=src,cancelAppend||document.body.appendChild(s),s},this.nowISO=(new Date).toISOString();var nd=new Date;function parseDateTimeForGoogle(){}return this.times={},nd.setHours(0,0,0,0),this.times.SOD=nd.toISOString(),nd.setHours(24,0,0,0),this.times.EOD=nd.toISOString(),this.Utils={cleanString:function(str){return str.replace(/[^A-Z0-9]+/gi,"_")},stopPropagation:function(e){return(e=e||window.event).stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),!1},getPossibleValues:function(propertyName,schema,specs){if((specs=$.extend({format:"object"},specs||{})).static&&_joe.Cache.static[specs.static])return _joe.Cache.static[specs.static];for(var propval,types={},i=0;i<_joe.Data[schema].length;i++){propval=_joe.Data[schema][i][propertyName],(specs.allowNulls||null!=propval)&&(types[propval]=types[propval]||0,types[propval]++)}return specs.static&&(_joe.Cache.static[specs.static]=types),types},Settings:function(settingName,specs){specs=specs||{};var s=(self.Data.setting||[]).where({name:settingName})[0],setting=s||{};if(specs.object)return setting;if("code"==setting.setting_type&&!specs.raw){if(0==setting.value.trim().indexOf("function")&&specs.params){var p=tryEval(s.value);return p?p(specs.params):specs.params}return tryEval(s.value)}return setting.value},toDollars:function(amount){return parseFloat(amount).toFixed(2)},joeState:self.getState,nextDay:function(x){var now=new Date;return now.setDate(now.getDate()+(x+(7-now.getDay()))%7),now},toDateInput:function(date){var dt=date||new Date;"string"==typeof dt&&(dt=new Date(dt)),console.log(dt,date);var monthstr=dt.getUTCMonth()+1;monthstr=monthstr<10?"0"+monthstr:monthstr;var dayStr=("0"+dt.getUTCDate()).slice(-2);return`${dt.getUTCFullYear().toString()}-${monthstr}-${dayStr}`},toDateString:function(dt,specs){if("Y-m-d"==specs)return self.Utils.toDateInput(dt);specs=specs||{};"string"==typeof(dt=dt||new Date)&&(dt=new Date(dt));var dts_str="",monthstr=dt.getUTCMonth()+1,dayStr=("0"+dt.getUTCDate()).slice(-2),yearStr=dt.getUTCFullYear().toString();return dts_str+=(monthstr<10?"0"+monthstr:monthstr)+"/"+dayStr+"/"+(specs.fullyear&&yearStr||yearStr.substr(2,4))},prettyPrintDTS:function(dts,specs){specs=$.extend({showtime:!0,showdate:!0},specs||{});"string"==typeof(dts=dts||new Date)&&(dts=new Date(dts));var dts_str="";if(specs.showtime){var ampm="a",dmins=dts.getMinutes().toString(),dhours=dts.getHours();dhours>12&&(ampm="p",dhours-=12),dhours||(dhours=12),dts_str+=dhours+":"+(2==dmins.length?dmins:"0"+dmins)+ampm}return specs.showdate&&specs.showtime&&(dts_str+=" "),specs.showdate&&(dts_str+=dts.getMonth()+1+"/"+dts.getDate()+"/"+dts.getUTCFullYear().toString().substr(2,4)),dts_str},getRandomColor:function(){for(var color="#",i=0;i<6;i++)color+="0123456789ABCDEF"[Math.floor(16*Math.random())];return color},benchmarkit:function(torun,name){var bm=new Benchmarker,t=torun();return _bmResponse(bm,"benchmarker",name||""),t}},this.SVG={icon:{assistant:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">\n <path d="M294.49 618.18v64.49c0 22.42.95 35.46 2.84 39.12 2.4 4.94 6.93 8.52 12.29 9.71 9.18 2.13 18.6 3.01 28.02 2.64h17.31c18.81 0 28.22 6.04 28.22 18.11 0 13.96-9.93 22.51-29.8 25.64-24.41 2.74-48.98 3.87-73.55 3.37-29.87 0-51.01-5.79-63.44-17.38-12.42-11.59-18.66-31.41-18.7-59.47v-81.08c.85-11.33-1.15-22.68-5.81-33.04-5.69-7.66-14.07-12.88-23.46-14.6-11.09-2.78-18.54-13.19-17.58-24.58-1.07-11.43 6.42-21.9 17.58-24.58 9.41-1.95 17.77-7.32 23.46-15.07 4.7-10.35 6.7-21.71 5.81-33.04v-80.88c0-27.62 6.21-47.22 18.63-58.81 12.42-11.59 33.57-17.36 63.44-17.31 26.13-.73 52.27.66 78.17 4.16 6.92 1.05 13.37 4.16 18.5 8.92 4.27 4.08 6.66 9.75 6.61 15.66 0 12.07-9.41 18.11-28.22 18.11h-17.84c-16.04 0-27.05 1.72-33.04 5.15-5.92 3.96-9.36 10.72-9.05 17.84v92.71c-.35 31.23-8.72 52.03-25.11 62.38-1.29.88-2.06 2.34-2.05 3.9 0 2.42 2.93 6.06 8.79 10.9 6.54 5.96 11.3 13.63 13.74 22.14 3.19 11.34 4.62 23.11 4.23 34.89Zm435.01-134.4v-64.23c0-22.42-.95-35.46-2.84-39.12-2.4-4.94-6.93-8.52-12.29-9.71-9.18-2.13-18.6-3.01-28.02-2.64h-17.18c-18.81 0-28.22-6.04-28.22-18.11 0-13.96 9.93-22.42 29.8-25.37 24.42-2.73 48.98-3.86 73.55-3.37 29.87 0 51.01 5.79 63.44 17.38 12.42 11.59 18.63 31.19 18.63 58.81v81.28c-.88 11.33 1.12 22.69 5.81 33.04 5.75 7.62 14.1 12.87 23.46 14.74 11.16 2.71 18.62 13.22 17.51 24.65.74 9.18-4.03 17.93-12.16 22.27-4.09 1.86-8.33 3.34-12.69 4.43-8.51 2.69-15.35 9.08-18.63 17.38-2.71 9.15-3.85 18.69-3.37 28.22v81.01c0 27.8-6.21 47.47-18.63 59.01-12.42 11.54-33.57 17.33-63.44 17.38-26.13.74-52.27-.65-78.17-4.16-6.92-1.05-13.37-4.16-18.5-8.92-4.31-4.17-6.7-9.93-6.61-15.93 0-12.07 9.41-18.11 28.22-18.11 2.25 0 8.19.18 17.84.53 11.25.56 22.5-1.19 33.04-5.15 4.1-2.12 7.02-5.98 7.93-10.51 1.33-11.91 1.82-23.9 1.45-35.88v-64.49c-.51-12.88 1.38-25.74 5.55-37.93 4.19-9.77 11.07-18.15 19.82-24.18 1.29-.88 2.06-2.34 2.05-3.9 0-2.42-2.93-6.06-8.79-10.9-6.55-5.96-11.31-13.63-13.74-22.14-3.43-11.46-5.05-23.39-4.82-35.35Z"/>\n <rect width="74.5" height="189" x="409.75" y="456.75" rx="33.94" ry="33.94"/>\n <rect width="74.5" height="189" x="539.75" y="456.75" rx="33.94" ry="33.94"/>\n </svg>',favorite:'<?xml version="1.0" encoding="UTF-8"?><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M4 2h16a1 1 0 0 1 1 1v19.276a.5.5 0 0 1-.704.457L12 19.03l-8.296 3.702A.5.5 0 0 1 3 22.276V3a1 1 0 0 1 1-1zm8 11.5l2.939 1.545-.561-3.272 2.377-2.318-3.286-.478L12 6l-1.47 2.977-3.285.478 2.377 2.318-.56 3.272L12 13.5z"/></svg>',left:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-5 -5 36 36"><path d="M11.3 21C7.1 18.2 3.3 13.8 3.2 13.6 3.1 13.5 3 13.2 3 13 3 12.8 3.1 12.5 3.2 12.3 3.3 12.1 7.2 7.7 11.3 4.9 11.6 4.7 12 4.7 12.4 4.8 12.8 5.1 13 5.4 13 5.8L13 9.5C13 9.5 21.7 10 22.1 10.3 22.7 10.7 23 12 23 13 23 14.1 22.6 15.2 22.1 15.6 21.7 15.9 13 16.5 13 16.5L13 20.2C13 20.6 12.8 20.9 12.4 21.1 12.1 21.3 11.7 21.2 11.3 21Z"/></svg>',cancel:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-5 -5 36 36"><path d="M13 0.2C5.9 0.2 0.2 5.9 0.2 13 0.2 20.1 5.9 25.8 13 25.8 20.1 25.8 25.8 20.1 25.8 13 25.8 5.9 20.1 0.2 13 0.2ZM18.8 17.4L17.4 18.8C17.1 19 16.7 19 16.5 18.8L13 15.3 9.5 18.8C9.3 19 8.9 19 8.6 18.8L7.2 17.4C7 17.1 7 16.7 7.2 16.5L10.7 13 7.2 9.5C7 9.3 7 8.9 7.2 8.6L8.6 7.2C8.9 7 9.3 7 9.5 7.2L13 10.7 16.5 7.2C16.7 7 17.1 7 17.4 7.2L18.8 8.6C19 8.9 19 9.3 18.8 9.5L15.3 13 18.8 16.5C19 16.7 19 17.1 18.8 17.4Z"/></svg>',close:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-6 -6 44 44"><path d="M26 22.3L22.3 26c0 0-5.9-6.3-6.3-6.3C15.6 19.7 9.7 26 9.7 26L6 22.3c0 0 6.3-5.8 6.3-6.3C12.3 15.5 6 9.7 6 9.7l3.7-3.7c0 0 5.9 6.3 6.3 6.3 0.4 0 6.3-6.3 6.3-6.3L26 9.7c0 0-6.3 5.9-6.3 6.3C19.7 16.4 26 22.3 26 22.3z"/></svg>',unsaved:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-8 -8 48 48"><g data-name="Layer 2"><path d="M24.4 3.4h-21V28.6H28.6V7.5Zm-5 2.8v4.5H16.6V6.1Zm6.5 19.7H6.1V6.1h3.5v7.2H22.2V6.1h1.1l2.6 2.5Z"/><polygon points="20.9 22.5 18 19.6 20.9 16.7 18.9 14.7 16 17.6 13.1 14.7 11.1 16.7 14.1 19.6 11.1 22.5 13.1 24.5 16 21.5 18.9 24.5 20.9 22.5"/></g></svg>',"sidebar-right":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 48 48"><g><path d="M38,36H2V4H38ZM26,6H4V34H26Z"/></g></svg>',"sidebar-left":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 48 48"><path d="M2 4H38V36H2ZM14 34H36V6H14Z"/></svg>',menu:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-5 -5 42 42"><path d="M16 6C14.9 6 14 6.9 14 8 14 9.1 14.9 10 16 10 17.1 10 18 9.1 18 8 18 6.9 17.1 6 16 6zM16 14C14.9 14 14 14.9 14 16 14 17.1 14.9 18 16 18 17.1 18 18 17.1 18 16 18 14.9 17.1 14 16 14zM16 22C14.9 22 14 22.9 14 24 14 25.1 14.9 26 16 26 17.1 26 18 25.1 18 24 18 22.9 17.1 22 16 22z"/></svg>',sections:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-10 -10 120 120"><polygon points="50 90 35 75 65 75 50 90"/><polygon points="50 10 65 25 35 25 50 10"/><circle cx="50" cy="50" r="10"/></svg>',help:'<svg viewBox="-384 -384 1792 1792" style=""><g><path d="M448 768h128v-128h-128v128zM512 256c-96 0-192 96-192 192h128c0-32 32-64 64-64s64 32 64 64c0 64-128 64-128 128h128c64-22 128-64 128-160s-96-160-192-160zM512 0c-283 0-512 229-512 512s229 512 512 512 512-229 512-512-229-512-512-512zM512 896c-212 0-384-172-384-384s172-384 384-384 384 172 384 384-172 384-384 384z"></path></g></svg>'}},self.getCurrentObject=function(construct,force){if(construct){if(self.current.constructed)return self.current.constructed;var obj=self.constructObjectFromFields();return obj[self.getIDProp()]||force?obj:self.current.object}return self.current.object},window._jco=self.getCurrentObject,this.Colors={ai:"#0D9488"},this.Colors.priority={1:"#cc4500",2:"#FFee33",3:"#acf"},this.Snippets={},this.Snippets.priorityStripeColor=function(item){if(item.priority&&item.priority<100)return{title:`P${item.priority}`,color:_joe.Colors.priority[item.priority]}},this.Google={Calendar:{list:function(){if(!self.Google.Calendar.calendars)return self.Google.loadCalendarApi(),void self.Google.Calendar.list();goJoe(_joe.Google.Calendar.calendars,{schema:{idprop:"id",listWindowTitle:"Google Calendars",title:"gcal: ${summary}",listTitle:"<joe-title>${summary}</joe-title><joe-subtitle>${id}</joe-subtitle>",itemMenu:function(item){return[{name:"view",action:"window.open('https://calendar.google.com/calendar/embed?mode=WEEK&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;src=${id}&amp;color=%236B3304&amp;ctz=America%2FChicago');"}]},sorter:["summary"],checkChanges:!1,stripeColor:function(cal){return cal.backgroundColor},bgColor:function(cal){return _joe.Google.Calendar&&_joe.Google.Calendar.active&&_joe.Google.Calendar.active.id==cal.id?"goldenrod":""}}})}},client_id:null,init:function(){console.log("google authed",self.Google.access_token),self.Google.listCalendars()},scopes:["https://www.googleapis.com/auth/calendar"],loadCalendarApi:function(access_token,callback){access_token&&(self.Google.access_token=access_token);callback=callback||self.Google.init;gapi.client.load("calendar","v3",callback)},listCalendars:function(){gapi.client.calendar.calendarList.list().execute(function(resp){self.Google.Calendar.calendars=resp.items,self.Google.Calendar.active=self.Utils.Settings("GOOGLE_CALENDARID")&&resp.items.where({id:self.Utils.Settings("GOOGLE_CALENDARID")})[0]||resp.items.where({primary:!0})[0]||!1,capp&&capp.Reload.all()})}},this.Google.authorize=function(immediate,callback,hidePopup){var client_id=self.Google.client_id=self.Utils.Settings("GOOGLE_CLIENTID");self.Google.access_token?self.Google.loadCalendarApi():client_id&&gapi&&gapi.auth?gapi.auth.authorize({client_id:self.Google.client_id,scope:self.Google.scopes.join(" "),immediate:!0},function(authResult){if(authResult&&!authResult.error)self.Google.loadCalendarApi(authResult.access_token);else{if(JACmode)if(!confirm("jac mode enabled, login to google?"))return;gapi.auth.authorize({client_id:self.Google.client_id,scope:self.Google.scopes.join(" "),immediate:!1},function(authResult){authResult&&!authResult.error?self.Google.loadCalendarApi(authResult.access_token):self.Error.add("google client:"+authResult.error+","+authResult.error_subtype,authResult.error+","+authResult.error_subtype,{c:client_id,g:gapi,auth:gapi.auth,authResult:authResult})})}}):self.Error.add("error in google client api",null,{c:client_id,g:gapi,auth:gapi.auth})},this.Google.Calendar.Event={buildResource:function(event){var template=self.Utils.Settings("GOOGLE_EVENT_TEMPLATE",{params:event})||"${info} \r\n ${description}",descriptionString=fillTemplate(template,$.extend({URL:"//"+__jsc.hostname+":"+__jsc.port+location.pathname+location.hash},event)),res={sendNotifications:event.sendNotifications||!1,summary:event.name||event.address+" "+(event.event_type||""),description:descriptionString,location:event.location||fillTemplate("${street_address} ${city} ${state} ${zip}",event),start:{dateTime:$c.format(new Date(event.date+" "+event.start_time),"Y-m-d")+"T"+$c.format(new Date(event.date+" "+event.start_time),"H:i:00.000")+event.timezone_offset},end:{dateTime:$c.format(new Date(event.date+" "+event.end_time),"Y-m-d")+"T"+$c.format(new Date(event.date+" "+event.end_time),"H:i:00.000")+event.timezone_offset},id:event._id.replace(/-/g,""),attendees:[]},lead_person=event.leader||event.lead;if(lead_person){var leader=self.Cache.get(lead_person);res.attendees.push({name:leader.fullname||leader.first&&leader.first+" "+leader.last||leader.name,id:leader._id,email:leader.email})}return(event.attendees||event.team_members||[]).map(function(att){var attendee=self.Cache.get(att);res.attendees.push({name:attendee.fullname||attendee.first&&attendee.first+" "+attendee.last||attendee.name,id:attendee._id,email:attendee.email})}),res},getObject:function(eventid){return self.current.object&&self.current.object._id==eventid?_jco(!0):self.getDataItem(eventid,"event")},add:function(eventid,force,saveFirst){if(!self.Google.access_token||!self.Google.Calendar.calendars)return alert("please login to your google account and then try again."),void self.Google.authorize(!0);try{var event=self.Google.Calendar.Event.getObject(eventid);if(!event)return void alert("event not found: "+eventid);if(!event.published&&!force)return void alert("event not published: "+event.name);var resource=self.Google.Calendar.Event.buildResource(event),request=gapi.client.calendar.events.insert({calendarId:self.Google.Calendar.active.id,resource:resource,sendNotifications:resource.sendNotifications});request.sendNotifications=resource.sendNotifications,request.execute(function(resp){if(resp.error&&409==resp.error.code){logit("updating");var ovr={status:"confirmed"};event.published||(ovr.status="cancelled"),ovr.save=saveFirst,self.Google.Calendar.Event.update(eventid,ovr)}else saveFirst&&(_joe.current.object.published_ts=new Date,self.updateObject(null,null,!0),_joe.rerenderField("published_ts"));logit(resp)})}catch(e){self.Error.add("error adding event",e,eventid),alert("error adding event \n"+e)}},update:function(eventid,specs){try{var saveFirst=specs.save,event=self.Google.Calendar.Event.getObject(eventid),resource=$.extend(self.Google.Calendar.Event.buildResource(event),specs||{status:"confirmed"}),request=gapi.client.calendar.events.patch({calendarId:self.Google.Calendar.active.id,resource:resource,eventId:eventid.replace(/-/g,""),sendNotifications:resource.sendNotifications});request.sendNotifications=resource.sendNotifications,request.execute(function(resp){resp.error?alert(resp.error.message||resp.error):saveFirst&&(_joe.current.object.published_ts=new Date,self.updateObject(null,null,!0),_joe.rerenderField("published_ts")),logit(resp)})}catch(e){self.Error.add("error updating event",e,eventid)}},publish:function(query){if(self.Google.Calendar.calendars&&self.Google.access_token){query=query||{published:!0};if(self.Data.event){var topublish=self.Data.event.where(query),notpublish=self.Data.event.where(function(){return!this.published});confirm("publish "+topublish.length+" events?\n you have "+notpublish.length+"/"+self.Data.event.length+" unpublished events")&&topublish.map(function(ev){self.Google.Calendar.Event.add(ev._id)})}}else gapi.auth.authorize({client_id:self.Google.client_id,scope:self.Google.scopes.join(" "),immediate:!1},function(authResult){authResult&&!authResult.error?(self.Google.loadCalendarApi(),self.Google.Calendar.Event.publish()):(alert("error authorizing calendars"),self.Error.add("google client:"+authResult.error+","+authResult.error_subtype,authResult.error+","+authResult.error_subtype,{c:client_id,g:gapi,auth:gapi.auth,authResult:authResult}))})}},self.specs.autoInit&&self.init(),this}function _classic_unstringifyFunctions(propObject){for(var p in propObject)"string"==typeof propObject[p]&&0==propObject[p].indexOf("(function")?propObject[p]=tryEval("("+propObject[p].replace(/;r\n/g,";\n").replace(/<br \/>/g,"")+")"):"object"==typeof propObject[p]&&unstringifyFunctions(propObject[p]);return propObject}function unstringifyFunctions(propObject){for(var p in propObject)if("string"==typeof propObject[p]){var trimmed=propObject[p].trim();(trimmed.startsWith("(function")||trimmed.startsWith("(async function"))&&(propObject[p]=tryEval(trimmed.replace(/;r\n/g,";\n").replace(/<br \/>/g,"")))}else"object"==typeof propObject[p]&&null!==propObject[p]&&unstringifyFunctions(propObject[p]);return propObject}location&&"file://"==location.origin&&(joe_web_dir=location.href.slice(0,location.href.lastIndexOf("/")+1)),__docWriter=function(src,type,cancelWrite){var html="";switch((type=type||"js").toLowerCase()){case"js":case"javascript":html+='<script type="text/javascript" src="'+src+'"><\/script>';break;case"css":case"stylesheet":html+='<link href="'+src+'" rel="stylesheet" type="text/css">'}return cancelWrite||document.write(html),html},__loadAdditionalFiles=function(){var bonuses="";"undefined"==typeof jQuery&&(__docWriter(joe_web_dir+"js/libs/jquery-1.11.3.min.js","js"),__docWriter(joe_web_dir+"js/libs/jquery-ui.min.js")),bonuses+=__docWriter(joe_web_dir+"js/libs/jquery.ui.touch-punch.min.js"),("undefined"==typeof Craydent||!Craydent.VERSION||Craydent.VERSION<"1.7.37")&&(bonuses+=__docWriter(joe_web_dir+"js/libs/craydent-1.8.1.js","js",!0)),document.write(bonuses)};var __clearDiv__='<div class="clear"></div>',__createBtn__={name:"create",icon:"plus",action:"create",color:"orange",schema:function(){return _joe.current.schema&&_joe.current.schema.name},css:" joe-add-button joe-iconed-button"},__quicksaveBtn__={name:"quicksave",label:"Save",action:"_joe.updateObject(this,null,true);",css:"joe-quicksave-button joe-confirm-button joe-iconed-button"},__saveBtn__={name:"save",label:"Save",action:"_joe.updateObject(this);",css:"joe-save-button joe-confirm-button joe-iconed-button"},__deleteBtn__={name:"delete",label:"Delete",action:"_joe.deleteObject(this);",css:"joe-delete-button joe-iconed-button joe-red-button",condition:function(){return _joe.isNewItem&&!_joe.isNewItem()}},__multisaveBtn__={name:"save_multi",label:"Multi Save",action:"_joe.updateMultipleObjects(this);",css:"joe-save-button joe-confirm-button joe-multi-only"},__multideleteBtn__={name:"delete_multi",label:"Multi Delete",action:"_joe.deleteMultipleObjects(this);",css:"joe-delete-button joe-multi-only"},__selectAllBtn__={name:"select_all",label:"select all",action:"_joe.selectAllItems();",css:"joe-left-button joe-multi-always"},__replaceBtn__={name:"replace",label:"Replace",action:"_joe.updateRendering(this);",css:"joe-replace-button joe-confirm-button"},__duplicateBtn__={name:"duplicate",label:"Duplicate",action:"_joe.duplicateObject();",css:"joe-left-button joe-iconed-button joe-duplicate-button"},__exportBtn__={name:"export",display:"<b>{&#8593;}</b>",condition:function(){return _joe.User&&"super"==_joe.User.role},css:"joe-export-button joe-left-button joe-grey-button joe-orangegrey-button",action:"_joe.IO.export(null,true)"},__systemFieldsSection=[{section_start:"system",collapsed:!0},"_id","created","itemtype",{section_end:"system"}],__defaultButtons=[__createBtn__],__defaultObjectButtons=[__deleteBtn__,__saveBtn__],__defaultMultiButtons=[__multisaveBtn__,__multideleteBtn__];function __removeTags(str){return str?str.replace(/<(?:.|\n)*?>/gm,""):""}function _COUNT(array){return array?array.isArray()||array.isString()?array.length:array.isFunction?array.toString().length:0:0}function showJOEWarnings(){goJoe(_joe.current.benchmarkers._warnings,{schema:{title:"benchmarker warnings",listTitle:"<joe-title>${name}</joe-title><joe-subtitle>${info}</joe-subtitle>",checkChanges:!1}})}function _bmResponse(benchmarker,message,bmname,threshhold){var t=benchmarker.stop(),m=message+" in "+t+" secs";_joe.current.benchmarkers=_joe.current.benchmarkers||{};var name=bmname||message,payload={info:t,name:name,_id:cuid()};_joe.current.benchmarkers._warnings=_joe.current.benchmarkers._warnings||[],_joe.current.benchmarkers[name]=payload,$c.DEBUG_MODE&&window.console&&window.console.warn?t>.4?(window.console.warn(m),_joe.current.benchmarkers[name].warn=!0,_joe.current.benchmarkers._warnings.push(payload)):(!threshhold||t>threshhold)&&logit(m):logit(m)}function beginLogGroup(name,expanded){$c.DEBUG_MODE&&(expanded?window.console&&window.console.group&&console.group(name):window.console&&window.console.groupCollapsed&&console.groupCollapsed(name))}function endLogGroup(){$c.DEBUG_MODE&&window.console&&window.console.groupEnd&&console.groupEnd()}function _renderUserCubes(user,cssclass,user_dataset){var title,initials,css=cssclass||"fleft",u=user,html="",color=user.color||"#cbcbcb";if(u.first&&u.last)title=u.first+" "+u.last,initials=u.first[0]+u.last[0];else{var name=u.fullname||u.name;title=name,initials=name[0]+(name.indexOf(" ")>0&&name[name.indexOf(" ")+1]||"")}return html+='<joe-user-cube title="'+title+'" class="'+css+'" style="background-color:'+color+'">'+initials+" <span>"+title+"</span></joe-user-cube>"}function warn(message){console&&console.warn&&console.warn(message)}function formatMoney(number,places,symbol,thousand,decimal){number=number||0,places=isNaN(places=Math.abs(places))?2:places,symbol=void 0!==symbol?symbol:"$",thousand=thousand||",",decimal=decimal||".";var negative=number<0?"-":"",i=parseInt(number=Math.abs(+number||0).toFixed(places),10)+"",j=(j=i.length)>3?j%3:0;return symbol+negative+(j?i.substr(0,j)+thousand:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+thousand)+(places?decimal+Math.abs(number-i).toFixed(places).slice(2):"")}!function(t,e,i){var n=t.L,o={version:"0.7.2"};"object"==typeof module&&"object"==typeof module.exports?module.exports=o:"function"==typeof define&&define.amd&&define(o),o.noConflict=function(){return t.L=n,this},t.L=o,o.Util={extend:function(t){var e,i,n,o,s=Array.prototype.slice.call(arguments,1);for(i=0,n=s.length;n>i;i++)for(e in o=s[i]||{})o.hasOwnProperty(e)&&(t[e]=o[e]);return t},bind:function(t,e){var i=arguments.length>2?Array.prototype.slice.call(arguments,2):null;return function(){return t.apply(e,i||arguments)}},stamp:function(){var t=0,e="_leaflet_id";return function(i){return i[e]=i[e]||++t,i[e]}}(),invokeEach:function(t,e,i){var n,o;if("object"==typeof t){for(n in o=Array.prototype.slice.call(arguments,3),t)e.apply(i,[n,t[n]].concat(o));return!0}return!1},limitExecByInterval:function(t,e,i){var n,o;return function s(){var a=arguments;return n?void(o=!0):(n=!0,setTimeout(function(){n=!1,o&&(s.apply(i,a),o=!1)},e),void t.apply(i,a))}},falseFn:function(){return!1},formatNum:function(t,e){var i=Math.pow(10,e||5);return Math.round(t*i)/i},trim:function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")},splitWords:function(t){return o.Util.trim(t).split(/\s+/)},setOptions:function(t,e){return t.options=o.extend({},t.options,e),t.options},getParamString:function(t,e,i){var n=[];for(var o in t)n.push(encodeURIComponent(i?o.toUpperCase():o)+"="+encodeURIComponent(t[o]));return(e&&-1!==e.indexOf("?")?"&":"?")+n.join("&")},template:function(t,e){return t.replace(/\{ *([\w_]+) *\}/g,function(t,n){var o=e[n];if(o===i)throw new Error("No value provided for variable "+t);return"function"==typeof o&&(o=o(e)),o})},isArray:Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},emptyImageUrl:"data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="},function(){function e(e){var i,n,o=["webkit","moz","o","ms"];for(i=0;i<o.length&&!n;i++)n=t[o[i]+e];return n}function i(e){var i=+new Date,o=Math.max(0,16-(i-n));return n=i+o,t.setTimeout(e,o)}var n=0,s=t.requestAnimationFrame||e("RequestAnimationFrame")||i,a=t.cancelAnimationFrame||e("CancelAnimationFrame")||e("CancelRequestAnimationFrame")||function(e){t.clearTimeout(e)};o.Util.requestAnimFrame=function(e,n,a,r){return e=o.bind(e,n),a&&s===i?void e():s.call(t,e,r)},o.Util.cancelAnimFrame=function(e){e&&a.call(t,e)}}(),o.extend=o.Util.extend,o.bind=o.Util.bind,o.stamp=o.Util.stamp,o.setOptions=o.Util.setOptions,o.Class=function(){},o.Class.extend=function(t){var e=function(){this.initialize&&this.initialize.apply(this,arguments),this._initHooks&&this.callInitHooks()},i=function(){};i.prototype=this.prototype;var n=new i;for(var s in n.constructor=e,e.prototype=n,this)this.hasOwnProperty(s)&&"prototype"!==s&&(e[s]=this[s]);t.statics&&(o.extend(e,t.statics),delete t.statics),t.includes&&(o.Util.extend.apply(null,[n].concat(t.includes)),delete t.includes),t.options&&n.options&&(t.options=o.extend({},n.options,t.options)),o.extend(n,t),n._initHooks=[];var a=this;return e.__super__=a.prototype,n.callInitHooks=function(){if(!this._initHooksCalled){a.prototype.callInitHooks&&a.prototype.callInitHooks.call(this),this._initHooksCalled=!0;for(var t=0,e=n._initHooks.length;e>t;t++)n._initHooks[t].call(this)}},e},o.Class.include=function(t){o.extend(this.prototype,t)},o.Class.mergeOptions=function(t){o.extend(this.prototype.options,t)},o.Class.addInitHook=function(t){var e=Array.prototype.slice.call(arguments,1),i="function"==typeof t?t:function(){this[t].apply(this,e)};this.prototype._initHooks=this.prototype._initHooks||[],this.prototype._initHooks.push(i)};var s="_leaflet_events";o.Mixin={},o.Mixin.Events={addEventListener:function(t,e,i){if(o.Util.invokeEach(t,this.addEventListener,this,e,i))return this;var n,a,r,h,l,u,c,d=this[s]=this[s]||{},p=i&&i!==this&&o.stamp(i);for(n=0,a=(t=o.Util.splitWords(t)).length;a>n;n++)r={action:e,context:i||this},h=t[n],p?(u=(l=h+"_idx")+"_len",(c=d[l]=d[l]||{})[p]||(c[p]=[],d[u]=(d[u]||0)+1),c[p].push(r)):(d[h]=d[h]||[],d[h].push(r));return this},hasEventListeners:function(t){var e=this[s];return!!e&&(t in e&&e[t].length>0||t+"_idx"in e&&e[t+"_idx_len"]>0)},removeEventListener:function(t,e,i){if(!this[s])return this;if(!t)return this.clearAllEventListeners();if(o.Util.invokeEach(t,this.removeEventListener,this,e,i))return this;var n,a,r,h,l,u,c,d,_=this[s],m=i&&i!==this&&o.stamp(i);for(n=0,a=(t=o.Util.splitWords(t)).length;a>n;n++)if(c=(u=(r=t[n])+"_idx")+"_len",d=_[u],e){if(h=m&&d?d[m]:_[r]){for(l=h.length-1;l>=0;l--)h[l].action!==e||i&&h[l].context!==i||(h.splice(l,1)[0].action=o.Util.falseFn);i&&d&&0===h.length&&(delete d[m],_[c]--)}}else delete _[r],delete _[u],delete _[c];return this},clearAllEventListeners:function(){return delete this[s],this},fireEvent:function(t,e){if(!this.hasEventListeners(t))return this;var i,n,a,r,h,l=o.Util.extend({},e,{type:t,target:this}),u=this[s];if(u[t])for(n=0,a=(i=u[t].slice()).length;a>n;n++)i[n].action.call(i[n].context,l);for(h in r=u[t+"_idx"])if(i=r[h].slice())for(n=0,a=i.length;a>n;n++)i[n].action.call(i[n].context,l);return this},addOneTimeEventListener:function(t,e,i){if(o.Util.invokeEach(t,this.addOneTimeEventListener,this,e,i))return this;var n=o.bind(function(){this.removeEventListener(t,e,i).removeEventListener(t,n,i)},this);return this.addEventListener(t,e,i).addEventListener(t,n,i)}},o.Mixin.Events.on=o.Mixin.Events.addEventListener,o.Mixin.Events.off=o.Mixin.Events.removeEventListener,o.Mixin.Events.once=o.Mixin.Events.addOneTimeEventListener,o.Mixin.Events.fire=o.Mixin.Events.fireEvent,function(){var n="ActiveXObject"in t,s=n&&!e.addEventListener,a=navigator.userAgent.toLowerCase(),r=-1!==a.indexOf("webkit"),h=-1!==a.indexOf("chrome"),l=-1!==a.indexOf("phantom"),u=-1!==a.indexOf("android"),c=-1!==a.search("android [23]"),d=-1!==a.indexOf("gecko"),p=typeof orientation!=i+"",_=t.navigator&&t.navigator.msPointerEnabled&&t.navigator.msMaxTouchPoints&&!t.PointerEvent,m=t.PointerEvent&&t.navigator.pointerEnabled&&t.navigator.maxTouchPoints||_,f="devicePixelRatio"in t&&t.devicePixelRatio>1||"matchMedia"in t&&t.matchMedia("(min-resolution:144dpi)")&&t.matchMedia("(min-resolution:144dpi)").matches,g=e.documentElement,v=n&&"transition"in g.style,y="WebKitCSSMatrix"in t&&"m11"in new t.WebKitCSSMatrix&&!c,P="MozPerspective"in g.style,L="OTransition"in g.style,x=!t.L_DISABLE_3D&&(v||y||P||L)&&!l,w=!t.L_NO_TOUCH&&!l&&function(){var t="ontouchstart";if(m||t in g)return!0;var i=e.createElement("div"),n=!1;return!!i.setAttribute&&(i.setAttribute(t,"return;"),"function"==typeof i[t]&&(n=!0),i.removeAttribute(t),i=null,n)}();o.Browser={ie:n,ielt9:s,webkit:r,gecko:d&&!r&&!t.opera&&!n,android:u,android23:c,chrome:h,ie3d:v,webkit3d:y,gecko3d:P,opera3d:L,any3d:x,mobile:p,mobileWebkit:p&&r,mobileWebkit3d:p&&y,mobileOpera:p&&t.opera,touch:w,msPointer:_,pointer:m,retina:f}}(),o.Point=function(t,e,i){this.x=i?Math.round(t):t,this.y=i?Math.round(e):e},o.Point.prototype={clone:function(){return new o.Point(this.x,this.y)},add:function(t){return this.clone()._add(o.point(t))},_add:function(t){return this.x+=t.x,this.y+=t.y,this},subtract:function(t){return this.clone()._subtract(o.point(t))},_subtract:function(t){return this.x-=t.x,this.y-=t.y,this},divideBy:function(t){return this.clone()._divideBy(t)},_divideBy:function(t){return this.x/=t,this.y/=t,this},multiplyBy:function(t){return this.clone()._multiplyBy(t)},_multiplyBy:function(t){return this.x*=t,this.y*=t,this},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},distanceTo:function(t){var e=(t=o.point(t)).x-this.x,i=t.y-this.y;return Math.sqrt(e*e+i*i)},equals:function(t){return(t=o.point(t)).x===this.x&&t.y===this.y},contains:function(t){return t=o.point(t),Math.abs(t.x)<=Math.abs(this.x)&&Math.abs(t.y)<=Math.abs(this.y)},toString:function(){return"Point("+o.Util.formatNum(this.x)+", "+o.Util.formatNum(this.y)+")"}},o.point=function(t,e,n){return t instanceof o.Point?t:o.Util.isArray(t)?new o.Point(t[0],t[1]):t===i||null===t?t:new o.Point(t,e,n)},o.Bounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},o.Bounds.prototype={extend:function(t){return t=o.point(t),this.min||this.max?(this.min.x=Math.min(t.x,this.min.x),this.max.x=Math.max(t.x,this.max.x),this.min.y=Math.min(t.y,this.min.y),this.max.y=Math.max(t.y,this.max.y)):(this.min=t.clone(),this.max=t.clone()),this},getCenter:function(t){return new o.Point((this.min.x+this.max.x)/2,(this.min.y+this.max.y)/2,t)},getBottomLeft:function(){return new o.Point(this.min.x,this.max.y)},getTopRight:function(){return new o.Point(this.max.x,this.min.y)},getSize:function(){return this.max.subtract(this.min)},contains:function(t){var e,i;return(t="number"==typeof t[0]||t instanceof o.Point?o.point(t):o.bounds(t))instanceof o.Bounds?(e=t.min,i=t.max):e=i=t,e.x>=this.min.x&&i.x<=this.max.x&&e.y>=this.min.y&&i.y<=this.max.y},intersects:function(t){t=o.bounds(t);var e=this.min,i=this.max,n=t.min,s=t.max,a=s.x>=e.x&&n.x<=i.x,r=s.y>=e.y&&n.y<=i.y;return a&&r},isValid:function(){return!(!this.min||!this.max)}},o.bounds=function(t,e){return!t||t instanceof o.Bounds?t:new o.Bounds(t,e)},o.Transformation=function(t,e,i,n){this._a=t,this._b=e,this._c=i,this._d=n},o.Transformation.prototype={transform:function(t,e){return this._transform(t.clone(),e)},_transform:function(t,e){return e=e||1,t.x=e*(this._a*t.x+this._b),t.y=e*(this._c*t.y+this._d),t},untransform:function(t,e){return e=e||1,new o.Point((t.x/e-this._b)/this._a,(t.y/e-this._d)/this._c)}},o.DomUtil={get:function(t){return"string"==typeof t?e.getElementById(t):t},getStyle:function(t,i){var n=t.style[i];if(!n&&t.currentStyle&&(n=t.currentStyle[i]),(!n||"auto"===n)&&e.defaultView){var o=e.defaultView.getComputedStyle(t,null);n=o?o[i]:null}return"auto"===n?null:n},getViewportOffset:function(t){var i,n=0,s=0,a=t,r=e.body,h=e.documentElement;do{if(n+=a.offsetTop||0,s+=a.offsetLeft||0,n+=parseInt(o.DomUtil.getStyle(a,"borderTopWidth"),10)||0,s+=parseInt(o.DomUtil.getStyle(a,"borderLeftWidth"),10)||0,i=o.DomUtil.getStyle(a,"position"),a.offsetParent===r&&"absolute"===i)break;if("fixed"===i){n+=r.scrollTop||h.scrollTop||0,s+=r.scrollLeft||h.scrollLeft||0;break}if("relative"===i&&!a.offsetLeft){var l=o.DomUtil.getStyle(a,"width"),u=o.DomUtil.getStyle(a,"max-width"),c=a.getBoundingClientRect();("none"!==l||"none"!==u)&&(s+=c.left+a.clientLeft),n+=c.top+(r.scrollTop||h.scrollTop||0);break}a=a.offsetParent}while(a);a=t;do{if(a===r)break;n-=a.scrollTop||0,s-=a.scrollLeft||0,a=a.parentNode}while(a);return new o.Point(s,n)},documentIsLtr:function(){return o.DomUtil._docIsLtrCached||(o.DomUtil._docIsLtrCached=!0,o.DomUtil._docIsLtr="ltr"===o.DomUtil.getStyle(e.body,"direction")),o.DomUtil._docIsLtr},create:function(t,i,n){var o=e.createElement(t);return o.className=i,n&&n.appendChild(o),o},hasClass:function(t,e){if(t.classList!==i)return t.classList.contains(e);var n=o.DomUtil._getClass(t);return n.length>0&&new RegExp("(^|\\s)"+e+"(\\s|$)").test(n)},addClass:function(t,e){if(t.classList!==i)for(var n=o.Util.splitWords(e),s=0,a=n.length;a>s;s++)t.classList.add(n[s]);else if(!o.DomUtil.hasClass(t,e)){var r=o.DomUtil._getClass(t);o.DomUtil._setClass(t,(r?r+" ":"")+e)}},removeClass:function(t,e){t.classList!==i?t.classList.remove(e):o.DomUtil._setClass(t,o.Util.trim((" "+o.DomUtil._getClass(t)+" ").replace(" "+e+" "," ")))},_setClass:function(t,e){t.className.baseVal===i?t.className=e:t.className.baseVal=e},_getClass:function(t){return t.className.baseVal===i?t.className:t.className.baseVal},setOpacity:function(t,e){if("opacity"in t.style)t.style.opacity=e;else if("filter"in t.style){var i=!1,n="DXImageTransform.Microsoft.Alpha";try{i=t.filters.item(n)}catch(o){if(1===e)return}e=Math.round(100*e),i?(i.Enabled=100!==e,i.Opacity=e):t.style.filter+=" progid:"+n+"(opacity="+e+")"}},testProp:function(t){for(var i=e.documentElement.style,n=0;n<t.length;n++)if(t[n]in i)return t[n];return!1},getTranslateString:function(t){var e=o.Browser.webkit3d,n=(e?",0":"")+")";return"translate"+(e?"3d":"")+"("+t.x+"px,"+t.y+"px"+n},getScaleString:function(t,e){return o.DomUtil.getTranslateString(e.add(e.multiplyBy(-1*t)))+(" scale("+t+") ")},setPosition:function(t,e,i){t._leaflet_pos=e,!i&&o.Browser.any3d?t.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(e):(t.style.left=e.x+"px",t.style.top=e.y+"px")},getPosition:function(t){return t._leaflet_pos}},o.DomUtil.TRANSFORM=o.DomUtil.testProp(["transform","WebkitTransform","OTransform","MozTransform","msTransform"]),o.DomUtil.TRANSITION=o.DomUtil.testProp(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),o.DomUtil.TRANSITION_END="webkitTransition"===o.DomUtil.TRANSITION||"OTransition"===o.DomUtil.TRANSITION?o.DomUtil.TRANSITION+"End":"transitionend",function(){if("onselectstart"in e)o.extend(o.DomUtil,{disableTextSelection:function(){o.DomEvent.on(t,"selectstart",o.DomEvent.preventDefault)},enableTextSelection:function(){o.DomEvent.off(t,"selectstart",o.DomEvent.preventDefault)}});else{var i=o.DomUtil.testProp(["userSelect","WebkitUserSelect","OUserSelect","MozUserSelect","msUserSelect"]);o.extend(o.DomUtil,{disableTextSelection:function(){if(i){var t=e.documentElement.style;this._userSelect=t[i],t[i]="none"}},enableTextSelection:function(){i&&(e.documentElement.style[i]=this._userSelect,delete this._userSelect)}})}o.extend(o.DomUtil,{disableImageDrag:function(){o.DomEvent.on(t,"dragstart",o.DomEvent.preventDefault)},enableImageDrag:function(){o.DomEvent.off(t,"dragstart",o.DomEvent.preventDefault)}})}(),o.LatLng=function(t,e,n){if(t=parseFloat(t),e=parseFloat(e),isNaN(t)||isNaN(e))throw new Error("Invalid LatLng object: ("+t+", "+e+")");this.lat=t,this.lng=e,n!==i&&(this.alt=parseFloat(n))},o.extend(o.LatLng,{DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,MAX_MARGIN:1e-9}),o.LatLng.prototype={equals:function(t){return!!t&&(t=o.latLng(t),Math.max(Math.abs(this.lat-t.lat),Math.abs(this.lng-t.lng))<=o.LatLng.MAX_MARGIN)},toString:function(t){return"LatLng("+o.Util.formatNum(this.lat,t)+", "+o.Util.formatNum(this.lng,t)+")"},distanceTo:function(t){t=o.latLng(t);var i=o.LatLng.DEG_TO_RAD,n=(t.lat-this.lat)*i,s=(t.lng-this.lng)*i,a=this.lat*i,r=t.lat*i,h=Math.sin(n/2),l=Math.sin(s/2),u=h*h+l*l*Math.cos(a)*Math.cos(r);return 12756274*Math.atan2(Math.sqrt(u),Math.sqrt(1-u))},wrap:function(t,e){var i=this.lng;return i=(i+(e=e||180))%(e-(t=t||-180))+(t>i||i===e?e:t),new o.LatLng(this.lat,i)}},o.latLng=function(t,e){return t instanceof o.LatLng?t:o.Util.isArray(t)?"number"==typeof t[0]||"string"==typeof t[0]?new o.LatLng(t[0],t[1],t[2]):null:t===i||null===t?t:"object"==typeof t&&"lat"in t?new o.LatLng(t.lat,"lng"in t?t.lng:t.lon):e===i?null:new o.LatLng(t,e)},o.LatLngBounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},o.LatLngBounds.prototype={extend:function(t){if(!t)return this;var e=o.latLng(t);return(t=null!==e?e:o.latLngBounds(t))instanceof o.LatLng?this._southWest||this._northEast?(this._southWest.lat=Math.min(t.lat,this._southWest.lat),this._southWest.lng=Math.min(t.lng,this._southWest.lng),this._northEast.lat=Math.max(t.lat,this._northEast.lat),this._northEast.lng=Math.max(t.lng,this._northEast.lng)):(this._southWest=new o.LatLng(t.lat,t.lng),this._northEast=new o.LatLng(t.lat,t.lng)):t instanceof o.LatLngBounds&&(this.extend(t._southWest),this.extend(t._northEast)),this},pad:function(t){var e=this._southWest,i=this._northEast,n=Math.abs(e.lat-i.lat)*t,s=Math.abs(e.lng-i.lng)*t;return new o.LatLngBounds(new o.LatLng(e.lat-n,e.lng-s),new o.LatLng(i.lat+n,i.lng+s))},getCenter:function(){return new o.LatLng((this._southWest.lat+this._northEast.lat)/2,(this._southWest.lng+this._northEast.lng)/2)},getSouthWest:function(){return this._southWest},getNorthEast:function(){return this._northEast},getNorthWest:function(){return new o.LatLng(this.getNorth(),this.getWest())},getSouthEast:function(){return new o.LatLng(this.getSouth(),this.getEast())},getWest:function(){return this._southWest.lng},getSouth:function(){return this._southWest.lat},getEast:function(){return this._northEast.lng},getNorth:function(){return this._northEast.lat},contains:function(t){t="number"==typeof t[0]||t instanceof o.LatLng?o.latLng(t):o.latLngBounds(t);var e,i,n=this._southWest,s=this._northEast;return t instanceof o.LatLngBounds?(e=t.getSouthWest(),i=t.getNorthEast()):e=i=t,e.lat>=n.lat&&i.lat<=s.lat&&e.lng>=n.lng&&i.lng<=s.lng},intersects:function(t){t=o.latLngBounds(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),s=t.getNorthEast(),a=s.lat>=e.lat&&n.lat<=i.lat,r=s.lng>=e.lng&&n.lng<=i.lng;return a&&r},toBBoxString:function(){return[this.getWest(),this.getSouth(),this.getEast(),this.getNorth()].join(",")},equals:function(t){return!!t&&(t=o.latLngBounds(t),this._southWest.equals(t.getSouthWest())&&this._northEast.equals(t.getNorthEast()))},isValid:function(){return!(!this._southWest||!this._northEast)}},o.latLngBounds=function(t,e){return!t||t instanceof o.LatLngBounds?t:new o.LatLngBounds(t,e)},o.Projection={},o.Projection.SphericalMercator={MAX_LATITUDE:85.0511287798,project:function(t){var e=o.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),s=t.lng*e,a=n*e;return a=Math.log(Math.tan(Math.PI/4+a/2)),new o.Point(s,a)},unproject:function(t){var e=o.LatLng.RAD_TO_DEG,i=t.x*e,n=(2*Math.atan(Math.exp(t.y))-Math.PI/2)*e;return new o.LatLng(n,i)}},o.Projection.LonLat={project:function(t){return new o.Point(t.lng,t.lat)},unproject:function(t){return new o.LatLng(t.y,t.x)}},o.CRS={latLngToPoint:function(t,e){var i=this.projection.project(t),n=this.scale(e);return this.transformation._transform(i,n)},pointToLatLng:function(t,e){var i=this.scale(e),n=this.transformation.untransform(t,i);return this.projection.unproject(n)},project:function(t){return this.projection.project(t)},scale:function(t){return 256*Math.pow(2,t)},getSize:function(t){var e=this.scale(t);return o.point(e,e)}},o.CRS.Simple=o.extend({},o.CRS,{projection:o.Projection.LonLat,transformation:new o.Transformation(1,0,-1,0),scale:function(t){return Math.pow(2,t)}}),o.CRS.EPSG3857=o.extend({},o.CRS,{code:"EPSG:3857",projection:o.Projection.SphericalMercator,transformation:new o.Transformation(.5/Math.PI,.5,-.5/Math.PI,.5),project:function(t){return this.projection.project(t).multiplyBy(6378137)}}),o.CRS.EPSG900913=o.extend({},o.CRS.EPSG3857,{code:"EPSG:900913"}),o.CRS.EPSG4326=o.extend({},o.CRS,{code:"EPSG:4326",projection:o.Projection.LonLat,transformation:new o.Transformation(1/360,.5,-1/360,.5)}),o.Map=o.Class.extend({includes:o.Mixin.Events,options:{crs:o.CRS.EPSG3857,fadeAnimation:o.DomUtil.TRANSITION&&!o.Browser.android23,trackResize:!0,markerZoomAnimation:o.DomUtil.TRANSITION&&o.Browser.any3d},initialize:function(t,e){e=o.setOptions(this,e),this._initContainer(t),this._initLayout(),this._onResize=o.bind(this._onResize,this),this._initEvents(),e.maxBounds&&this.setMaxBounds(e.maxBounds),e.center&&e.zoom!==i&&this.setView(o.latLng(e.center),e.zoom,{reset:!0}),this._handlers=[],this._layers={},this._zoomBoundLayers={},this._tileLayersNum=0,this.callInitHooks(),this._addLayers(e.layers)},setView:function(t,e){return e=e===i?this.getZoom():e,this._resetView(o.latLng(t),this._limitZoom(e)),this},setZoom:function(t,e){return this._loaded?this.setView(this.getCenter(),t,{zoom:e}):(this._zoom=this._limitZoom(t),this)},zoomIn:function(t,e){return this.setZoom(this._zoom+(t||1),e)},zoomOut:function(t,e){return this.setZoom(this._zoom-(t||1),e)},setZoomAround:function(t,e,i){var n=this.getZoomScale(e),s=this.getSize().divideBy(2),r=(t instanceof o.Point?t:this.latLngToContainerPoint(t)).subtract(s).multiplyBy(1-1/n),h=this.containerPointToLatLng(s.add(r));return this.setView(h,e,{zoom:i})},fitBounds:function(t,e){e=e||{},t=t.getBounds?t.getBounds():o.latLngBounds(t);var i=o.point(e.paddingTopLeft||e.padding||[0,0]),n=o.point(e.paddingBottomRight||e.padding||[0,0]),s=this.getBoundsZoom(t,!1,i.add(n)),a=n.subtract(i).divideBy(2),r=this.project(t.getSouthWest(),s),h=this.project(t.getNorthEast(),s),l=this.unproject(r.add(h).divideBy(2).add(a),s);return s=e&&e.maxZoom?Math.min(e.maxZoom,s):s,this.setView(l,s,e)},fitWorld:function(t){return this.fitBounds([[-90,-180],[90,180]],t)},panTo:function(t,e){return this.setView(t,this._zoom,{pan:e})},panBy:function(t){return this.fire("movestart"),this._rawPanBy(o.point(t)),this.fire("move"),this.fire("moveend")},setMaxBounds:function(t){return t=o.latLngBounds(t),this.options.maxBounds=t,t?(this._loaded&&this._panInsideMaxBounds(),this.on("moveend",this._panInsideMaxBounds,this)):this.off("moveend",this._panInsideMaxBounds,this)},panInsideBounds:function(t,e){var i=this.getCenter(),n=this._limitCenter(i,this._zoom,t);return i.equals(n)?this:this.panTo(n,e)},addLayer:function(t){var e=o.stamp(t);return this._layers[e]||(this._layers[e]=t,!t.options||isNaN(t.options.maxZoom)&&isNaN(t.options.minZoom)||(this._zoomBoundLayers[e]=t,this._updateZoomLevels()),this.options.zoomAnimation&&o.TileLayer&&t instanceof o.TileLayer&&(this._tileLayersNum++,this._tileLayersToLoad++,t.on("load",this._onTileLayerLoad,this)),this._loaded&&this._layerAdd(t)),this},removeLayer:function(t){var e=o.stamp(t);return this._layers[e]?(this._loaded&&t.onRemove(this),delete this._layers[e],this._loaded&&this.fire("layerremove",{layer:t}),this._zoomBoundLayers[e]&&(delete this._zoomBoundLayers[e],this._updateZoomLevels()),this.options.zoomAnimation&&o.TileLayer&&t instanceof o.TileLayer&&(this._tileLayersNum--,this._tileLayersToLoad--,t.off("load",this._onTileLayerLoad,this)),this):this},hasLayer:function(t){return!!t&&o.stamp(t)in this._layers},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},invalidateSize:function(t){if(!this._loaded)return this;t=o.extend({animate:!1,pan:!0},!0===t?{animate:!0}:t);var e=this.getSize();this._sizeChanged=!0,this._initialCenter=null;var i=this.getSize(),n=e.divideBy(2).round(),s=i.divideBy(2).round(),a=n.subtract(s);return a.x||a.y?(t.animate&&t.pan?this.panBy(a):(t.pan&&this._rawPanBy(a),this.fire("move"),t.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(o.bind(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:e,newSize:i})):this},addHandler:function(t,e){if(!e)return this;var i=this[t]=new e(this);return this._handlers.push(i),this.options[t]&&i.enable(),this},remove:function(){this._loaded&&this.fire("unload"),this._initEvents("off");try{delete this._container._leaflet}catch(t){this._container._leaflet=i}return this._clearPanes(),this._clearControlPos&&this._clearControlPos(),this._clearHandlers(),this},getCenter:function(){return this._checkIfLoaded(),this._initialCenter&&!this._moved()?this._initialCenter:this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var t=this.getPixelBounds(),e=this.unproject(t.getBottomLeft()),i=this.unproject(t.getTopRight());return new o.LatLngBounds(e,i)},getMinZoom:function(){return this.options.minZoom===i?this._layersMinZoom===i?0:this._layersMinZoom:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===i?this._layersMaxZoom===i?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(t,e,i){t=o.latLngBounds(t);var n,s=this.getMinZoom()-(e?1:0),a=this.getMaxZoom(),r=this.getSize(),h=t.getNorthWest(),l=t.getSouthEast(),u=!0;i=o.point(i||[0,0]);do{s++,n=this.project(l,s).subtract(this.project(h,s)).add(i),u=e?n.x<r.x||n.y<r.y:r.contains(n)}while(u&&a>=s);return u&&e?null:e?s:s-1},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new o.Point(this._container.clientWidth,this._container.clientHeight),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(){var t=this._getTopLeftPoint();return new o.Bounds(t,t.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._initialTopLeftPoint},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(t){var e=this.options.crs;return e.scale(t)/e.scale(this._zoom)},getScaleZoom:function(t){return this._zoom+Math.log(t)/Math.LN2},project:function(t,e){return e=e===i?this._zoom:e,this.options.crs.latLngToPoint(o.latLng(t),e)},unproject:function(t,e){return e=e===i?this._zoom:e,this.options.crs.pointToLatLng(o.point(t),e)},layerPointToLatLng:function(t){var e=o.point(t).add(this.getPixelOrigin());return this.unproject(e)},latLngToLayerPoint:function(t){return this.project(o.latLng(t))._round()._subtract(this.getPixelOrigin())},containerPointToLayerPoint:function(t){return o.point(t).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(t){return o.point(t).add(this._getMapPanePos())},containerPointToLatLng:function(t){var e=this.containerPointToLayerPoint(o.point(t));return this.layerPointToLatLng(e)},latLngToContainerPoint:function(t){return this.layerPointToContainerPoint(this.latLngToLayerPoint(o.latLng(t)))},mouseEventToContainerPoint:function(t){return o.DomEvent.getMousePosition(t,this._container)},mouseEventToLayerPoint:function(t){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))},mouseEventToLatLng:function(t){return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))},_initContainer:function(t){var e=this._container=o.DomUtil.get(t);if(!e)throw new Error("Map container not found.");if(e._leaflet)throw new Error("Map container is already initialized.");e._leaflet=!0},_initLayout:function(){var t=this._container;o.DomUtil.addClass(t,"leaflet-container"+(o.Browser.touch?" leaflet-touch":"")+(o.Browser.retina?" leaflet-retina":"")+(o.Browser.ielt9?" leaflet-oldie":"")+(this.options.fadeAnimation?" leaflet-fade-anim":""));var e=o.DomUtil.getStyle(t,"position");"absolute"!==e&&"relative"!==e&&"fixed"!==e&&(t.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var t=this._panes={};this._mapPane=t.mapPane=this._createPane("leaflet-map-pane",this._container),this._tilePane=t.tilePane=this._createPane("leaflet-tile-pane",this._mapPane),t.objectsPane=this._createPane("leaflet-objects-pane",this._mapPane),t.shadowPane=this._createPane("leaflet-shadow-pane"),t.overlayPane=this._createPane("leaflet-overlay-pane"),t.markerPane=this._createPane("leaflet-marker-pane"),t.popupPane=this._createPane("leaflet-popup-pane");var e=" leaflet-zoom-hide";this.options.markerZoomAnimation||(o.DomUtil.addClass(t.markerPane,e),o.DomUtil.addClass(t.shadowPane,e),o.DomUtil.addClass(t.popupPane,e))},_createPane:function(t,e){return o.DomUtil.create("div",t,e||this._panes.objectsPane)},_clearPanes:function(){this._container.removeChild(this._mapPane)},_addLayers:function(t){for(var e=0,i=(t=t?o.Util.isArray(t)?t:[t]:[]).length;i>e;e++)this.addLayer(t[e])},_resetView:function(t,e,i,n){var s=this._zoom!==e;n||(this.fire("movestart"),s&&this.fire("zoomstart")),this._zoom=e,this._initialCenter=t,this._initialTopLeftPoint=this._getNewTopLeftPoint(t),i?this._initialTopLeftPoint._add(this._getMapPanePos()):o.DomUtil.setPosition(this._mapPane,new o.Point(0,0)),this._tileLayersToLoad=this._tileLayersNum;var a=!this._loaded;this._loaded=!0,a&&(this.fire("load"),this.eachLayer(this._layerAdd,this)),this.fire("viewreset",{hard:!i}),this.fire("move"),(s||n)&&this.fire("zoomend"),this.fire("moveend",{hard:!i})},_rawPanBy:function(t){o.DomUtil.setPosition(this._mapPane,this._getMapPanePos().subtract(t))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_updateZoomLevels:function(){var t,e=1/0,n=-1/0,o=this._getZoomSpan();for(t in this._zoomBoundLayers){var s=this._zoomBoundLayers[t];isNaN(s.options.minZoom)||(e=Math.min(e,s.options.minZoom)),isNaN(s.options.maxZoom)||(n=Math.max(n,s.options.maxZoom))}t===i?this._layersMaxZoom=this._layersMinZoom=i:(this._layersMaxZoom=n,this._layersMinZoom=e),o!==this._getZoomSpan()&&this.fire("zoomlevelschange")},_panInsideMaxBounds:function(){this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(e){if(o.DomEvent){e=e||"on",o.DomEvent[e](this._container,"click",this._onMouseClick,this);var i,n,s=["dblclick","mousedown","mouseup","mouseenter","mouseleave","mousemove","contextmenu"];for(i=0,n=s.length;n>i;i++)o.DomEvent[e](this._container,s[i],this._fireMouseEvent,this);this.options.trackResize&&o.DomEvent[e](t,"resize",this._onResize,this)}},_onResize:function(){o.Util.cancelAnimFrame(this._resizeRequest),this._resizeRequest=o.Util.requestAnimFrame(function(){this.invalidateSize({debounceMoveend:!0})},this,!1,this._container)},_onMouseClick:function(t){!this._loaded||!t._simulated&&(this.dragging&&this.dragging.moved()||this.boxZoom&&this.boxZoom.moved())||o.DomEvent._skipped(t)||(this.fire("preclick"),this._fireMouseEvent(t))},_fireMouseEvent:function(t){if(this._loaded&&!o.DomEvent._skipped(t)){var e=t.type;if(e="mouseenter"===e?"mouseover":"mouseleave"===e?"mouseout":e,this.hasEventListeners(e)){"contextmenu"===e&&o.DomEvent.preventDefault(t);var i=this.mouseEventToContainerPoint(t),n=this.containerPointToLayerPoint(i),s=this.layerPointToLatLng(n);this.fire(e,{latlng:s,layerPoint:n,containerPoint:i,originalEvent:t})}}},_onTileLayerLoad:function(){this._tileLayersToLoad--,this._tileLayersNum&&!this._tileLayersToLoad&&this.fire("tilelayersload")},_clearHandlers:function(){for(var t=0,e=this._handlers.length;e>t;t++)this._handlers[t].disable()},whenReady:function(t,e){return this._loaded?t.call(e||this,this):this.on("load",t,e),this},_layerAdd:function(t){t.onAdd(this),this.fire("layeradd",{layer:t})},_getMapPanePos:function(){return o.DomUtil.getPosition(this._mapPane)},_moved:function(){var t=this._getMapPanePos();return t&&!t.equals([0,0])},_getTopLeftPoint:function(){return this.getPixelOrigin().subtract(this._getMapPanePos())},_getNewTopLeftPoint:function(t,e){var i=this.getSize()._divideBy(2);return this.project(t,e)._subtract(i)._round()},_latLngToNewLayerPoint:function(t,e,i){var n=this._getNewTopLeftPoint(i,e).add(this._getMapPanePos());return this.project(t,e)._subtract(n)},_getCenterLayerPoint:function(){return this.containerPointToLayerPoint(this.getSize()._divideBy(2))},_getCenterOffset:function(t){return this.latLngToLayerPoint(t).subtract(this._getCenterLayerPoint())},_limitCenter:function(t,e,i){if(!i)return t;var n=this.project(t,e),s=this.getSize().divideBy(2),a=new o.Bounds(n.subtract(s),n.add(s)),r=this._getBoundsOffset(a,i,e);return this.unproject(n.add(r),e)},_limitOffset:function(t,e){if(!e)return t;var i=this.getPixelBounds(),n=new o.Bounds(i.min.add(t),i.max.add(t));return t.add(this._getBoundsOffset(n,e))},_getBoundsOffset:function(t,e,i){var n=this.project(e.getNorthWest(),i).subtract(t.min),s=this.project(e.getSouthEast(),i).subtract(t.max),a=this._rebound(n.x,-s.x),r=this._rebound(n.y,-s.y);return new o.Point(a,r)},_rebound:function(t,e){return t+e>0?Math.round(t-e)/2:Math.max(0,Math.ceil(t))-Math.max(0,Math.floor(e))},_limitZoom:function(t){var e=this.getMinZoom(),i=this.getMaxZoom();return Math.max(e,Math.min(i,t))}}),o.map=function(t,e){return new o.Map(t,e)},o.Projection.Mercator={MAX_LATITUDE:85.0840591556,R_MINOR:6356752.314245179,R_MAJOR:6378137,project:function(t){var e=o.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),s=this.R_MAJOR,a=this.R_MINOR,r=t.lng*e*s,h=n*e,l=a/s,u=Math.sqrt(1-l*l),c=u*Math.sin(h);c=Math.pow((1-c)/(1+c),.5*u);var d=Math.tan(.5*(.5*Math.PI-h))/c;return h=-s*Math.log(d),new o.Point(r,h)},unproject:function(t){for(var e,i=o.LatLng.RAD_TO_DEG,n=this.R_MAJOR,s=this.R_MINOR,a=t.x*i/n,r=s/n,h=Math.sqrt(1-r*r),l=Math.exp(-t.y/n),u=Math.PI/2-2*Math.atan(l),p=15,_=.1;Math.abs(_)>1e-7&&--p>0;)e=h*Math.sin(u),u+=_=Math.PI/2-2*Math.atan(l*Math.pow((1-e)/(1+e),.5*h))-u;return new o.LatLng(u*i,a)}},o.CRS.EPSG3395=o.extend({},o.CRS,{code:"EPSG:3395",projection:o.Projection.Mercator,transformation:function(){var e=o.Projection.Mercator.R_MAJOR,i=.5/(Math.PI*e);return new o.Transformation(i,.5,-i,.5)}()}),o.TileLayer=o.Class.extend({includes:o.Mixin.Events,options:{minZoom:0,maxZoom:18,tileSize:256,subdomains:"abc",errorTileUrl:"",attribution:"",zoomOffset:0,opacity:1,unloadInvisibleTiles:o.Browser.mobile,updateWhenIdle:o.Browser.mobile},initialize:function(t,e){(e=o.setOptions(this,e)).detectRetina&&o.Browser.retina&&e.maxZoom>0&&(e.tileSize=Math.floor(e.tileSize/2),e.zoomOffset++,e.minZoom>0&&e.minZoom--,this.options.maxZoom--),e.bounds&&(e.bounds=o.latLngBounds(e.bounds)),this._url=t;var i=this.options.subdomains;"string"==typeof i&&(this.options.subdomains=i.split(""))},onAdd:function(t){this._map=t,this._animated=t._zoomAnimated,this._initContainer(),t.on({viewreset:this._reset,moveend:this._update},this),this._animated&&t.on({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||(this._limitedUpdate=o.Util.limitExecByInterval(this._update,150,this),t.on("move",this._limitedUpdate,this)),this._reset(),this._update()},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this._container.parentNode.removeChild(this._container),t.off({viewreset:this._reset,moveend:this._update},this),this._animated&&t.off({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||t.off("move",this._limitedUpdate,this),this._container=null,this._map=null},bringToFront:function(){var t=this._map._panes.tilePane;return this._container&&(t.appendChild(this._container),this._setAutoZIndex(t,Math.max)),this},bringToBack:function(){var t=this._map._panes.tilePane;return this._container&&(t.insertBefore(this._container,t.firstChild),this._setAutoZIndex(t,Math.min)),this},getAttribution:function(){return this.options.attribution},getContainer:function(){return this._container},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},setZIndex:function(t){return this.options.zIndex=t,this._updateZIndex(),this},setUrl:function(t,e){return this._url=t,e||this.redraw(),this},redraw:function(){return this._map&&(this._reset({hard:!0}),this._update()),this},_updateZIndex:function(){this._container&&this.options.zIndex!==i&&(this._container.style.zIndex=this.options.zIndex)},_setAutoZIndex:function(t,e){var i,n,o,s=t.children,a=-e(1/0,-1/0);for(n=0,o=s.length;o>n;n++)s[n]!==this._container&&(i=parseInt(s[n].style.zIndex,10),isNaN(i)||(a=e(a,i)));this.options.zIndex=this._container.style.zIndex=(isFinite(a)?a:0)+e(1,-1)},_updateOpacity:function(){var t,e=this._tiles;if(o.Browser.ielt9)for(t in e)o.DomUtil.setOpacity(e[t],this.options.opacity);else o.DomUtil.setOpacity(this._container,this.options.opacity)},_initContainer:function(){var t=this._map._panes.tilePane;if(!this._container){if(this._container=o.DomUtil.create("div","leaflet-layer"),this._updateZIndex(),this._animated){var e="leaflet-tile-container";this._bgBuffer=o.DomUtil.create("div",e,this._container),this._tileContainer=o.DomUtil.create("div",e,this._container)}else this._tileContainer=this._container;t.appendChild(this._container),this.options.opacity<1&&this._updateOpacity()}},_reset:function(t){for(var e in this._tiles)this.fire("tileunload",{tile:this._tiles[e]});this._tiles={},this._tilesToLoad=0,this.options.reuseTiles&&(this._unusedTiles=[]),this._tileContainer.innerHTML="",this._animated&&t&&t.hard&&this._clearBgBuffer(),this._initContainer()},_getTileSize:function(){var t=this._map,e=t.getZoom()+this.options.zoomOffset,i=this.options.maxNativeZoom,n=this.options.tileSize;return i&&e>i&&(n=Math.round(t.getZoomScale(e)/t.getZoomScale(i)*n)),n},_update:function(){if(this._map){var t=this._map,e=t.getPixelBounds(),i=t.getZoom(),n=this._getTileSize();if(!(i>this.options.maxZoom||i<this.options.minZoom)){var s=o.bounds(e.min.divideBy(n)._floor(),e.max.divideBy(n)._floor());this._addTilesFromCenterOut(s),(this.options.unloadInvisibleTiles||this.options.reuseTiles)&&this._removeOtherTiles(s)}}},_addTilesFromCenterOut:function(t){var i,n,s,a=[],r=t.getCenter();for(i=t.min.y;i<=t.max.y;i++)for(n=t.min.x;n<=t.max.x;n++)s=new o.Point(n,i),this._tileShouldBeLoaded(s)&&a.push(s);var h=a.length;if(0!==h){a.sort(function(t,e){return t.distanceTo(r)-e.distanceTo(r)});var l=e.createDocumentFragment();for(this._tilesToLoad||this.fire("loading"),this._tilesToLoad+=h,n=0;h>n;n++)this._addTile(a[n],l);this._tileContainer.appendChild(l)}},_tileShouldBeLoaded:function(t){if(t.x+":"+t.y in this._tiles)return!1;var e=this.options;if(!e.continuousWorld){var i=this._getWrapTileNum();if(e.noWrap&&(t.x<0||t.x>=i.x)||t.y<0||t.y>=i.y)return!1}if(e.bounds){var n=e.tileSize,o=t.multiplyBy(n),s=o.add([n,n]),a=this._map.unproject(o),r=this._map.unproject(s);if(e.continuousWorld||e.noWrap||(a=a.wrap(),r=r.wrap()),!e.bounds.intersects([a,r]))return!1}return!0},_removeOtherTiles:function(t){var e,i,n,o;for(o in this._tiles)e=o.split(":"),i=parseInt(e[0],10),n=parseInt(e[1],10),(i<t.min.x||i>t.max.x||n<t.min.y||n>t.max.y)&&this._removeTile(o)},_removeTile:function(t){var e=this._tiles[t];this.fire("tileunload",{tile:e,url:e.src}),this.options.reuseTiles?(o.DomUtil.removeClass(e,"leaflet-tile-loaded"),this._unusedTiles.push(e)):e.parentNode===this._tileContainer&&this._tileContainer.removeChild(e),o.Browser.android||(e.onload=null,e.src=o.Util.emptyImageUrl),delete this._tiles[t]},_addTile:function(t,e){var i=this._getTilePos(t),n=this._getTile();o.DomUtil.setPosition(n,i,o.Browser.chrome),this._tiles[t.x+":"+t.y]=n,this._loadTile(n,t),n.parentNode!==this._tileContainer&&e.appendChild(n)},_getZoomForUrl:function(){var t=this.options,e=this._map.getZoom();return t.zoomReverse&&(e=t.maxZoom-e),e+=t.zoomOffset,t.maxNativeZoom?Math.min(e,t.maxNativeZoom):e},_getTilePos:function(t){var e=this._map.getPixelOrigin(),i=this._getTileSize();return t.multiplyBy(i).subtract(e)},getTileUrl:function(t){return o.Util.template(this._url,o.extend({s:this._getSubdomain(t),z:t.z,x:t.x,y:t.y},this.options))},_getWrapTileNum:function(){return this._map.options.crs.getSize(this._map.getZoom()).divideBy(this._getTileSize())._floor()},_adjustTilePoint:function(t){var e=this._getWrapTileNum();this.options.continuousWorld||this.options.noWrap||(t.x=(t.x%e.x+e.x)%e.x),this.options.tms&&(t.y=e.y-t.y-1),t.z=this._getZoomForUrl()},_getSubdomain:function(t){var e=Math.abs(t.x+t.y)%this.options.subdomains.length;return this.options.subdomains[e]},_getTile:function(){if(this.options.reuseTiles&&this._unusedTiles.length>0){var t=this._unusedTiles.pop();return this._resetTile(t),t}return this._createTile()},_resetTile:function(){},_createTile:function(){var t=o.DomUtil.create("img","leaflet-tile");return t.style.width=t.style.height=this._getTileSize()+"px",t.galleryimg="no",t.onselectstart=t.onmousemove=o.Util.falseFn,o.Browser.ielt9&&this.options.opacity!==i&&o.DomUtil.setOpacity(t,this.options.opacity),o.Browser.mobileWebkit3d&&(t.style.WebkitBackfaceVisibility="hidden"),t},_loadTile:function(t,e){t._layer=this,t.onload=this._tileOnLoad,t.onerror=this._tileOnError,this._adjustTilePoint(e),t.src=this.getTileUrl(e),this.fire("tileloadstart",{tile:t,url:t.src})},_tileLoaded:function(){this._tilesToLoad--,this._animated&&o.DomUtil.addClass(this._tileContainer,"leaflet-zoom-animated"),this._tilesToLoad||(this.fire("load"),this._animated&&(clearTimeout(this._clearBgBufferTimer),this._clearBgBufferTimer=setTimeout(o.bind(this._clearBgBuffer,this),500)))},_tileOnLoad:function(){var t=this._layer;this.src!==o.Util.emptyImageUrl&&(o.DomUtil.addClass(this,"leaflet-tile-loaded"),t.fire("tileload",{tile:this,url:this.src})),t._tileLoaded()},_tileOnError:function(){var t=this._layer;t.fire("tileerror",{tile:this,url:this.src});var e=t.options.errorTileUrl;e&&(this.src=e),t._tileLoaded()}}),o.tileLayer=function(t,e){return new o.TileLayer(t,e)},o.TileLayer.WMS=o.TileLayer.extend({defaultWmsParams:{service:"WMS",request:"GetMap",version:"1.1.1",layers:"",styles:"",format:"image/jpeg",transparent:!1},initialize:function(t,e){this._url=t;var i=o.extend({},this.defaultWmsParams),n=e.tileSize||this.options.tileSize;for(var s in i.width=i.height=e.detectRetina&&o.Browser.retina?2*n:n,e)this.options.hasOwnProperty(s)||"crs"===s||(i[s]=e[s]);this.wmsParams=i,o.setOptions(this,e)},onAdd:function(t){this._crs=this.options.crs||t.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var e=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[e]=this._crs.code,o.TileLayer.prototype.onAdd.call(this,t)},getTileUrl:function(t){var e=this._map,i=this.options.tileSize,n=t.multiplyBy(i),s=n.add([i,i]),a=this._crs.project(e.unproject(n,t.z)),r=this._crs.project(e.unproject(s,t.z)),h=this._wmsVersion>=1.3&&this._crs===o.CRS.EPSG4326?[r.y,a.x,a.y,r.x].join(","):[a.x,r.y,r.x,a.y].join(","),l=o.Util.template(this._url,{s:this._getSubdomain(t)});return l+o.Util.getParamString(this.wmsParams,l,!0)+"&BBOX="+h},setParams:function(t,e){return o.extend(this.wmsParams,t),e||this.redraw(),this}}),o.tileLayer.wms=function(t,e){return new o.TileLayer.WMS(t,e)},o.TileLayer.Canvas=o.TileLayer.extend({options:{async:!1},initialize:function(t){o.setOptions(this,t)},redraw:function(){for(var t in this._map&&(this._reset({hard:!0}),this._update()),this._tiles)this._redrawTile(this._tiles[t]);return this},_redrawTile:function(t){this.drawTile(t,t._tilePoint,this._map._zoom)},_createTile:function(){var t=o.DomUtil.create("canvas","leaflet-tile");return t.width=t.height=this.options.tileSize,t.onselectstart=t.onmousemove=o.Util.falseFn,t},_loadTile:function(t,e){t._layer=this,t._tilePoint=e,this._redrawTile(t),this.options.async||this.tileDrawn(t)},drawTile:function(){},tileDrawn:function(t){this._tileOnLoad.call(t)}}),o.tileLayer.canvas=function(t){return new o.TileLayer.Canvas(t)},o.ImageOverlay=o.Class.extend({includes:o.Mixin.Events,options:{opacity:1},initialize:function(t,e,i){this._url=t,this._bounds=o.latLngBounds(e),o.setOptions(this,i)},onAdd:function(t){this._map=t,this._image||this._initImage(),t._panes.overlayPane.appendChild(this._image),t.on("viewreset",this._reset,this),t.options.zoomAnimation&&o.Browser.any3d&&t.on("zoomanim",this._animateZoom,this),this._reset()},onRemove:function(t){t.getPanes().overlayPane.removeChild(this._image),t.off("viewreset",this._reset,this),t.options.zoomAnimation&&t.off("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},setOpacity:function(t){return this.options.opacity=t,this._updateOpacity(),this},bringToFront:function(){return this._image&&this._map._panes.overlayPane.appendChild(this._image),this},bringToBack:function(){var t=this._map._panes.overlayPane;return this._image&&t.insertBefore(this._image,t.firstChild),this},setUrl:function(t){this._url=t,this._image.src=this._url},getAttribution:function(){return this.options.attribution},_initImage:function(){this._image=o.DomUtil.create("img","leaflet-image-layer"),this._map.options.zoomAnimation&&o.Browser.any3d?o.DomUtil.addClass(this._image,"leaflet-zoom-animated"):o.DomUtil.addClass(this._image,"leaflet-zoom-hide"),this._updateOpacity(),o.extend(this._image,{galleryimg:"no",onselectstart:o.Util.falseFn,onmousemove:o.Util.falseFn,onload:o.bind(this._onImageLoad,this),src:this._url})},_animateZoom:function(t){var e=this._map,i=this._image,n=e.getZoomScale(t.zoom),s=this._bounds.getNorthWest(),a=this._bounds.getSouthEast(),r=e._latLngToNewLayerPoint(s,t.zoom,t.center),h=e._latLngToNewLayerPoint(a,t.zoom,t.center)._subtract(r),l=r._add(h._multiplyBy(.5*(1-1/n)));i.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(l)+" scale("+n+") "},_reset:function(){var t=this._image,e=this._map.latLngToLayerPoint(this._bounds.getNorthWest()),i=this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(e);o.DomUtil.setPosition(t,e),t.style.width=i.x+"px",t.style.height=i.y+"px"},_onImageLoad:function(){this.fire("load")},_updateOpacity:function(){o.DomUtil.setOpacity(this._image,this.options.opacity)}}),o.imageOverlay=function(t,e,i){return new o.ImageOverlay(t,e,i)},o.Icon=o.Class.extend({options:{className:""},initialize:function(t){o.setOptions(this,t)},createIcon:function(t){return this._createIcon("icon",t)},createShadow:function(t){return this._createIcon("shadow",t)},_createIcon:function(t,e){var n,i=this._getIconUrl(t);if(!i){if("icon"===t)throw new Error("iconUrl not set in Icon options (see the docs).");return null}return n=e&&"IMG"===e.tagName?this._createImg(i,e):this._createImg(i),this._setIconStyles(n,t),n},_setIconStyles:function(t,e){var i,n=this.options,s=o.point(n[e+"Size"]);!(i=o.point("shadow"===e&&n.shadowAnchor||n.iconAnchor))&&s&&(i=s.divideBy(2,!0)),t.className="leaflet-marker-"+e+" "+n.className,i&&(t.style.marginLeft=-i.x+"px",t.style.marginTop=-i.y+"px"),s&&(t.style.width=s.x+"px",t.style.height=s.y+"px")},_createImg:function(t,i){return(i=i||e.createElement("img")).src=t,i},_getIconUrl:function(t){return o.Browser.retina&&this.options[t+"RetinaUrl"]?this.options[t+"RetinaUrl"]:this.options[t+"Url"]}}),o.icon=function(t){return new o.Icon(t)},o.Icon.Default=o.Icon.extend({options:{iconSize:[25,41],iconAnchor:[12,41],popupAnchor:[1,-34],shadowSize:[41,41]},_getIconUrl:function(t){var e=t+"Url";if(this.options[e])return this.options[e];o.Browser.retina&&"icon"===t&&(t+="-2x");var i=o.Icon.Default.imagePath;if(!i)throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");return i+"/marker-"+t+".png"}}),o.Icon.Default.imagePath=function(){var t,i,n,s,a=e.getElementsByTagName("script"),r=/[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;for(t=0,i=a.length;i>t;t++)if((n=a[t].src).match(r))return((s=n.split(r)[0])?s+"/":"")+"images"}(),o.Marker=o.Class.extend({includes:o.Mixin.Events,options:{icon:new o.Icon.Default,title:"",alt:"",clickable:!0,draggable:!1,keyboard:!0,zIndexOffset:0,opacity:1,riseOnHover:!1,riseOffset:250},initialize:function(t,e){o.setOptions(this,e),this._latlng=o.latLng(t)},onAdd:function(t){this._map=t,t.on("viewreset",this.update,this),this._initIcon(),this.update(),this.fire("add"),t.options.zoomAnimation&&t.options.markerZoomAnimation&&t.on("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this.dragging&&this.dragging.disable(),this._removeIcon(),this._removeShadow(),this.fire("remove"),t.off({viewreset:this.update,zoomanim:this._animateZoom},this),this._map=null},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=o.latLng(t),this.update(),this.fire("move",{latlng:this._latlng})},setZIndexOffset:function(t){return this.options.zIndexOffset=t,this.update(),this},setIcon:function(t){return this.options.icon=t,this._map&&(this._initIcon(),this.update()),this._popup&&this.bindPopup(this._popup),this},update:function(){if(this._icon){var t=this._map.latLngToLayerPoint(this._latlng).round();this._setPos(t)}return this},_initIcon:function(){var t=this.options,e=this._map,n=e.options.zoomAnimation&&e.options.markerZoomAnimation?"leaflet-zoom-animated":"leaflet-zoom-hide",s=t.icon.createIcon(this._icon),a=!1;s!==this._icon&&(this._icon&&this._removeIcon(),a=!0,t.title&&(s.title=t.title),t.alt&&(s.alt=t.alt)),o.DomUtil.addClass(s,n),t.keyboard&&(s.tabIndex="0"),this._icon=s,this._initInteraction(),t.riseOnHover&&o.DomEvent.on(s,"mouseover",this._bringToFront,this).on(s,"mouseout",this._resetZIndex,this);var r=t.icon.createShadow(this._shadow),h=!1;r!==this._shadow&&(this._removeShadow(),h=!0),r&&o.DomUtil.addClass(r,n),this._shadow=r,t.opacity<1&&this._updateOpacity();var l=this._map._panes;a&&l.markerPane.appendChild(this._icon),r&&h&&l.shadowPane.appendChild(this._shadow)},_removeIcon:function(){this.options.riseOnHover&&o.DomEvent.off(this._icon,"mouseover",this._bringToFront).off(this._icon,"mouseout",this._resetZIndex),this._map._panes.markerPane.removeChild(this._icon),this._icon=null},_removeShadow:function(){this._shadow&&this._map._panes.shadowPane.removeChild(this._shadow),this._shadow=null},_setPos:function(t){o.DomUtil.setPosition(this._icon,t),this._shadow&&o.DomUtil.setPosition(this._shadow,t),this._zIndex=t.y+this.options.zIndexOffset,this._resetZIndex()},_updateZIndex:function(t){this._icon.style.zIndex=this._zIndex+t},_animateZoom:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center).round();this._setPos(e)},_initInteraction:function(){if(this.options.clickable){var t=this._icon,e=["dblclick","mousedown","mouseover","mouseout","contextmenu"];o.DomUtil.addClass(t,"leaflet-clickable"),o.DomEvent.on(t,"click",this._onMouseClick,this),o.DomEvent.on(t,"keypress",this._onKeyPress,this);for(var i=0;i<e.length;i++)o.DomEvent.on(t,e[i],this._fireMouseEvent,this);o.Handler.MarkerDrag&&(this.dragging=new o.Handler.MarkerDrag(this),this.options.draggable&&this.dragging.enable())}},_onMouseClick:function(t){var e=this.dragging&&this.dragging.moved();(this.hasEventListeners(t.type)||e)&&o.DomEvent.stopPropagation(t),e||(this.dragging&&this.dragging._enabled||!this._map.dragging||!this._map.dragging.moved())&&this.fire(t.type,{originalEvent:t,latlng:this._latlng})},_onKeyPress:function(t){13===t.keyCode&&this.fire("click",{originalEvent:t,latlng:this._latlng})},_fireMouseEvent:function(t){this.fire(t.type,{originalEvent:t,latlng:this._latlng}),"contextmenu"===t.type&&this.hasEventListeners(t.type)&&o.DomEvent.preventDefault(t),"mousedown"!==t.type?o.DomEvent.stopPropagation(t):o.DomEvent.preventDefault(t)},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},_updateOpacity:function(){o.DomUtil.setOpacity(this._icon,this.options.opacity),this._shadow&&o.DomUtil.setOpacity(this._shadow,this.options.opacity)},_bringToFront:function(){this._updateZIndex(this.options.riseOffset)},_resetZIndex:function(){this._updateZIndex(0)}}),o.marker=function(t,e){return new o.Marker(t,e)},o.DivIcon=o.Icon.extend({options:{iconSize:[12,12],className:"leaflet-div-icon",html:!1},createIcon:function(t){var i=t&&"DIV"===t.tagName?t:e.createElement("div"),n=this.options;return i.innerHTML=!1!==n.html?n.html:"",n.bgPos&&(i.style.backgroundPosition=-n.bgPos.x+"px "+-n.bgPos.y+"px"),this._setIconStyles(i,"icon"),i},createShadow:function(){return null}}),o.divIcon=function(t){return new o.DivIcon(t)},o.Map.mergeOptions({closePopupOnClick:!0}),o.Popup=o.Class.extend({includes:o.Mixin.Events,options:{minWidth:50,maxWidth:300,autoPan:!0,closeButton:!0,offset:[0,7],autoPanPadding:[5,5],keepInView:!1,className:"",zoomAnimation:!0},initialize:function(t,e){o.setOptions(this,t),this._source=e,this._animated=o.Browser.any3d&&this.options.zoomAnimation,this._isOpen=!1},onAdd:function(t){this._map=t,this._container||this._initLayout();var e=t.options.fadeAnimation;e&&o.DomUtil.setOpacity(this._container,0),t._panes.popupPane.appendChild(this._container),t.on(this._getEvents(),this),this.update(),e&&o.DomUtil.setOpacity(this._container,1),this.fire("open"),t.fire("popupopen",{popup:this}),this._source&&this._source.fire("popupopen",{popup:this})},addTo:function(t){return t.addLayer(this),this},openOn:function(t){return t.openPopup(this),this},onRemove:function(t){t._panes.popupPane.removeChild(this._container),o.Util.falseFn(this._container.offsetWidth),t.off(this._getEvents(),this),t.options.fadeAnimation&&o.DomUtil.setOpacity(this._container,0),this._map=null,this.fire("close"),t.fire("popupclose",{popup:this}),this._source&&this._source.fire("popupclose",{popup:this})},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=o.latLng(t),this._map&&(this._updatePosition(),this._adjustPan()),this},getContent:function(){return this._content},setContent:function(t){return this._content=t,this.update(),this},update:function(){this._map&&(this._container.style.visibility="hidden",this._updateContent(),this._updateLayout(),this._updatePosition(),this._container.style.visibility="",this._adjustPan())},_getEvents:function(){var t={viewreset:this._updatePosition};return this._animated&&(t.zoomanim=this._zoomAnimation),("closeOnClick"in this.options?this.options.closeOnClick:this._map.options.closePopupOnClick)&&(t.preclick=this._close),this.options.keepInView&&(t.moveend=this._adjustPan),t},_close:function(){this._map&&this._map.closePopup(this)},_initLayout:function(){var t,e="leaflet-popup",i=e+" "+this.options.className+" leaflet-zoom-"+(this._animated?"animated":"hide"),n=this._container=o.DomUtil.create("div",i);this.options.closeButton&&((t=this._closeButton=o.DomUtil.create("a",e+"-close-button",n)).href="#close",t.innerHTML="&#215;",o.DomEvent.disableClickPropagation(t),o.DomEvent.on(t,"click",this._onCloseButtonClick,this));var s=this._wrapper=o.DomUtil.create("div",e+"-content-wrapper",n);o.DomEvent.disableClickPropagation(s),this._contentNode=o.DomUtil.create("div",e+"-content",s),o.DomEvent.disableScrollPropagation(this._contentNode),o.DomEvent.on(s,"contextmenu",o.DomEvent.stopPropagation),this._tipContainer=o.DomUtil.create("div",e+"-tip-container",n),this._tip=o.DomUtil.create("div",e+"-tip",this._tipContainer)},_updateContent:function(){if(this._content){if("string"==typeof this._content)this._contentNode.innerHTML=this._content;else{for(;this._contentNode.hasChildNodes();)this._contentNode.removeChild(this._contentNode.firstChild);this._contentNode.appendChild(this._content)}this.fire("contentupdate")}},_updateLayout:function(){var t=this._contentNode,e=t.style;e.width="",e.whiteSpace="nowrap";var i=t.offsetWidth;i=Math.min(i,this.options.maxWidth),i=Math.max(i,this.options.minWidth),e.width=i+1+"px",e.whiteSpace="",e.height="";var n=t.offsetHeight,s=this.options.maxHeight,a="leaflet-popup-scrolled";s&&n>s?(e.height=s+"px",o.DomUtil.addClass(t,a)):o.DomUtil.removeClass(t,a),this._containerWidth=this._container.offsetWidth},_updatePosition:function(){if(this._map){var t=this._map.latLngToLayerPoint(this._latlng),e=this._animated,i=o.point(this.options.offset);e&&o.DomUtil.setPosition(this._container,t),this._containerBottom=-i.y-(e?0:t.y),this._containerLeft=-Math.round(this._containerWidth/2)+i.x+(e?0:t.x),this._container.style.bottom=this._containerBottom+"px",this._container.style.left=this._containerLeft+"px"}},_zoomAnimation:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center);o.DomUtil.setPosition(this._container,e)},_adjustPan:function(){if(this.options.autoPan){var t=this._map,e=this._container.offsetHeight,i=this._containerWidth,n=new o.Point(this._containerLeft,-e-this._containerBottom);this._animated&&n._add(o.DomUtil.getPosition(this._container));var s=t.layerPointToContainerPoint(n),a=o.point(this.options.autoPanPadding),r=o.point(this.options.autoPanPaddingTopLeft||a),h=o.point(this.options.autoPanPaddingBottomRight||a),l=t.getSize(),u=0,c=0;s.x+i+h.x>l.x&&(u=s.x+i-l.x+h.x),s.x-u-r.x<0&&(u=s.x-r.x),s.y+e+h.y>l.y&&(c=s.y+e-l.y+h.y),s.y-c-r.y<0&&(c=s.y-r.y),(u||c)&&t.fire("autopanstart").panBy([u,c])}},_onCloseButtonClick:function(t){this._close(),o.DomEvent.stop(t)}}),o.popup=function(t,e){return new o.Popup(t,e)},o.Map.include({openPopup:function(t,e,i){if(this.closePopup(),!(t instanceof o.Popup)){var n=t;t=new o.Popup(i).setLatLng(e).setContent(n)}return t._isOpen=!0,this._popup=t,this.addLayer(t)},closePopup:function(t){return t&&t!==this._popup||(t=this._popup,this._popup=null),t&&(this.removeLayer(t),t._isOpen=!1),this}}),o.Marker.include({openPopup:function(){return this._popup&&this._map&&!this._map.hasLayer(this._popup)&&(this._popup.setLatLng(this._latlng),this._map.openPopup(this._popup)),this},closePopup:function(){return this._popup&&this._popup._close(),this},togglePopup:function(){return this._popup&&(this._popup._isOpen?this.closePopup():this.openPopup()),this},bindPopup:function(t,e){var i=o.point(this.options.icon.options.popupAnchor||[0,0]);return i=i.add(o.Popup.prototype.options.offset),e&&e.offset&&(i=i.add(e.offset)),e=o.extend({offset:i},e),this._popupHandlersAdded||(this.on("click",this.togglePopup,this).on("remove",this.closePopup,this).on("move",this._movePopup,this),this._popupHandlersAdded=!0),t instanceof o.Popup?(o.setOptions(t,e),this._popup=t):this._popup=new o.Popup(e,this).setContent(t),this},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this.togglePopup,this).off("remove",this.closePopup,this).off("move",this._movePopup,this),this._popupHandlersAdded=!1),this},getPopup:function(){return this._popup},_movePopup:function(t){this._popup.setLatLng(t.latlng)}}),o.LayerGroup=o.Class.extend({initialize:function(t){var e,i;if(this._layers={},t)for(e=0,i=t.length;i>e;e++)this.addLayer(t[e])},addLayer:function(t){var e=this.getLayerId(t);return this._layers[e]=t,this._map&&this._map.addLayer(t),this},removeLayer:function(t){var e=t in this._layers?t:this.getLayerId(t);return this._map&&this._layers[e]&&this._map.removeLayer(this._layers[e]),delete this._layers[e],this},hasLayer:function(t){return!!t&&(t in this._layers||this.getLayerId(t)in this._layers)},clearLayers:function(){return this.eachLayer(this.removeLayer,this),this},invoke:function(t){var e,i,n=Array.prototype.slice.call(arguments,1);for(e in this._layers)(i=this._layers[e])[t]&&i[t].apply(i,n);return this},onAdd:function(t){this._map=t,this.eachLayer(t.addLayer,t)},onRemove:function(t){this.eachLayer(t.removeLayer,t),this._map=null},addTo:function(t){return t.addLayer(this),this},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},getLayer:function(t){return this._layers[t]},getLayers:function(){var t=[];for(var e in this._layers)t.push(this._layers[e]);return t},setZIndex:function(t){return this.invoke("setZIndex",t)},getLayerId:function(t){return o.stamp(t)}}),o.layerGroup=function(t){return new o.LayerGroup(t)},o.FeatureGroup=o.LayerGroup.extend({includes:o.Mixin.Events,statics:{EVENTS:"click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose"},addLayer:function(t){return this.hasLayer(t)?this:("on"in t&&t.on(o.FeatureGroup.EVENTS,this._propagateEvent,this),o.LayerGroup.prototype.addLayer.call(this,t),this._popupContent&&t.bindPopup&&t.bindPopup(this._popupContent,this._popupOptions),this.fire("layeradd",{layer:t}))},removeLayer:function(t){return this.hasLayer(t)?(t in this._layers&&(t=this._layers[t]),t.off(o.FeatureGroup.EVENTS,this._propagateEvent,this),o.LayerGroup.prototype.removeLayer.call(this,t),this._popupContent&&this.invoke("unbindPopup"),this.fire("layerremove",{layer:t})):this},bindPopup:function(t,e){return this._popupContent=t,this._popupOptions=e,this.invoke("bindPopup",t,e)},openPopup:function(t){for(var e in this._layers){this._layers[e].openPopup(t);break}return this},setStyle:function(t){return this.invoke("setStyle",t)},bringToFront:function(){return this.invoke("bringToFront")},bringToBack:function(){return this.invoke("bringToBack")},getBounds:function(){var t=new o.LatLngBounds;return this.eachLayer(function(e){t.extend(e instanceof o.Marker?e.getLatLng():e.getBounds())}),t},_propagateEvent:function(t){t=o.extend({layer:t.target,target:this},t),this.fire(t.type,t)}}),o.featureGroup=function(t){return new o.FeatureGroup(t)},o.Path=o.Class.extend({includes:[o.Mixin.Events],statics:{CLIP_PADDING:function(){var i=((o.Browser.mobile?1280:2e3)/Math.max(t.outerWidth,t.outerHeight)-1)/2;return Math.max(0,Math.min(.5,i))}()},options:{stroke:!0,color:"#0033ff",dashArray:null,lineCap:null,lineJoin:null,weight:5,opacity:.5,fill:!1,fillColor:null,fillOpacity:.2,clickable:!0},initialize:function(t){o.setOptions(this,t)},onAdd:function(t){this._map=t,this._container||(this._initElements(),this._initEvents()),this.projectLatlngs(),this._updatePath(),this._container&&this._map._pathRoot.appendChild(this._container),this.fire("add"),t.on({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){t._pathRoot.removeChild(this._container),this.fire("remove"),this._map=null,o.Browser.vml&&(this._container=null,this._stroke=null,this._fill=null),t.off({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},projectLatlngs:function(){},setStyle:function(t){return o.setOptions(this,t),this._container&&this._updateStyle(),this},redraw:function(){return this._map&&(this.projectLatlngs(),this._updatePath()),this}}),o.Map.include({_updatePathViewport:function(){var t=o.Path.CLIP_PADDING,e=this.getSize(),n=o.DomUtil.getPosition(this._mapPane).multiplyBy(-1)._subtract(e.multiplyBy(t)._round()),s=n.add(e.multiplyBy(1+2*t)._round());this._pathViewport=new o.Bounds(n,s)}}),o.Path.SVG_NS="http://www.w3.org/2000/svg",o.Browser.svg=!(!e.createElementNS||!e.createElementNS(o.Path.SVG_NS,"svg").createSVGRect),o.Path=o.Path.extend({statics:{SVG:o.Browser.svg},bringToFront:function(){var t=this._map._pathRoot,e=this._container;return e&&t.lastChild!==e&&t.appendChild(e),this},bringToBack:function(){var t=this._map._pathRoot,e=this._container,i=t.firstChild;return e&&i!==e&&t.insertBefore(e,i),this},getPathString:function(){},_createElement:function(t){return e.createElementNS(o.Path.SVG_NS,t)},_initElements:function(){this._map._initPathRoot(),this._initPath(),this._initStyle()},_initPath:function(){this._container=this._createElement("g"),this._path=this._createElement("path"),this.options.className&&o.DomUtil.addClass(this._path,this.options.className),this._container.appendChild(this._path)},_initStyle:function(){this.options.stroke&&(this._path.setAttribute("stroke-linejoin","round"),this._path.setAttribute("stroke-linecap","round")),this.options.fill&&this._path.setAttribute("fill-rule","evenodd"),this.options.pointerEvents&&this._path.setAttribute("pointer-events",this.options.pointerEvents),this.options.clickable||this.options.pointerEvents||this._path.setAttribute("pointer-events","none"),this._updateStyle()},_updateStyle:function(){this.options.stroke?(this._path.setAttribute("stroke",this.options.color),this._path.setAttribute("stroke-opacity",this.options.opacity),this._path.setAttribute("stroke-width",this.options.weight),this.options.dashArray?this._path.setAttribute("stroke-dasharray",this.options.dashArray):this._path.removeAttribute("stroke-dasharray"),this.options.lineCap&&this._path.setAttribute("stroke-linecap",this.options.lineCap),this.options.lineJoin&&this._path.setAttribute("stroke-linejoin",this.options.lineJoin)):this._path.setAttribute("stroke","none"),this.options.fill?(this._path.setAttribute("fill",this.options.fillColor||this.options.color),this._path.setAttribute("fill-opacity",this.options.fillOpacity)):this._path.setAttribute("fill","none")},_updatePath:function(){var t=this.getPathString();t||(t="M0 0"),this._path.setAttribute("d",t)},_initEvents:function(){if(this.options.clickable){(o.Browser.svg||!o.Browser.vml)&&o.DomUtil.addClass(this._path,"leaflet-clickable"),o.DomEvent.on(this._container,"click",this._onMouseClick,this);for(var t=["dblclick","mousedown","mouseover","mouseout","mousemove","contextmenu"],e=0;e<t.length;e++)o.DomEvent.on(this._container,t[e],this._fireMouseEvent,this)}},_onMouseClick:function(t){this._map.dragging&&this._map.dragging.moved()||this._fireMouseEvent(t)},_fireMouseEvent:function(t){if(this.hasEventListeners(t.type)){var e=this._map,i=e.mouseEventToContainerPoint(t),n=e.containerPointToLayerPoint(i),s=e.layerPointToLatLng(n);this.fire(t.type,{latlng:s,layerPoint:n,containerPoint:i,originalEvent:t}),"contextmenu"===t.type&&o.DomEvent.preventDefault(t),"mousemove"!==t.type&&o.DomEvent.stopPropagation(t)}}}),o.Map.include({_initPathRoot:function(){this._pathRoot||(this._pathRoot=o.Path.prototype._createElement("svg"),this._panes.overlayPane.appendChild(this._pathRoot),this.options.zoomAnimation&&o.Browser.any3d?(o.DomUtil.addClass(this._pathRoot,"leaflet-zoom-animated"),this.on({zoomanim:this._animatePathZoom,zoomend:this._endPathZoom})):o.DomUtil.addClass(this._pathRoot,"leaflet-zoom-hide"),this.on("moveend",this._updateSvgViewport),this._updateSvgViewport())},_animatePathZoom:function(t){var e=this.getZoomScale(t.zoom),i=this._getCenterOffset(t.center)._multiplyBy(-e)._add(this._pathViewport.min);this._pathRoot.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(i)+" scale("+e+") ",this._pathZooming=!0},_endPathZoom:function(){this._pathZooming=!1},_updateSvgViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max,n=i.x-e.x,s=i.y-e.y,a=this._pathRoot,r=this._panes.overlayPane;o.Browser.mobileWebkit&&r.removeChild(a),o.DomUtil.setPosition(a,e),a.setAttribute("width",n),a.setAttribute("height",s),a.setAttribute("viewBox",[e.x,e.y,n,s].join(" ")),o.Browser.mobileWebkit&&r.appendChild(a)}}}),o.Path.include({bindPopup:function(t,e){return t instanceof o.Popup?this._popup=t:((!this._popup||e)&&(this._popup=new o.Popup(e,this)),this._popup.setContent(t)),this._popupHandlersAdded||(this.on("click",this._openPopup,this).on("remove",this.closePopup,this),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this._openPopup).off("remove",this.closePopup),this._popupHandlersAdded=!1),this},openPopup:function(t){return this._popup&&(t=t||this._latlng||this._latlngs[Math.floor(this._latlngs.length/2)],this._openPopup({latlng:t})),this},closePopup:function(){return this._popup&&this._popup._close(),this},_openPopup:function(t){this._popup.setLatLng(t.latlng),this._map.openPopup(this._popup)}}),o.Browser.vml=!o.Browser.svg&&function(){try{var t=e.createElement("div");t.innerHTML='<v:shape adj="1"/>';var i=t.firstChild;return i.style.behavior="url(#default#VML)",i&&"object"==typeof i.adj}catch(n){return!1}}(),o.Path=o.Browser.svg||!o.Browser.vml?o.Path:o.Path.extend({statics:{VML:!0,CLIP_PADDING:.02},_createElement:function(){try{return e.namespaces.add("lvml","urn:schemas-microsoft-com:vml"),function(t){return e.createElement("<lvml:"+t+' class="lvml">')}}catch(t){return function(t){return e.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}}(),_initPath:function(){var t=this._container=this._createElement("shape");o.DomUtil.addClass(t,"leaflet-vml-shape"+(this.options.className?" "+this.options.className:"")),this.options.clickable&&o.DomUtil.addClass(t,"leaflet-clickable"),t.coordsize="1 1",this._path=this._createElement("path"),t.appendChild(this._path),this._map._pathRoot.appendChild(t)},_initStyle:function(){this._updateStyle()},_updateStyle:function(){var t=this._stroke,e=this._fill,i=this.options,n=this._container;n.stroked=i.stroke,n.filled=i.fill,i.stroke?(t||((t=this._stroke=this._createElement("stroke")).endcap="round",n.appendChild(t)),t.weight=i.weight+"px",t.color=i.color,t.opacity=i.opacity,t.dashStyle=i.dashArray?o.Util.isArray(i.dashArray)?i.dashArray.join(" "):i.dashArray.replace(/( *, *)/g," "):"",i.lineCap&&(t.endcap=i.lineCap.replace("butt","flat")),i.lineJoin&&(t.joinstyle=i.lineJoin)):t&&(n.removeChild(t),this._stroke=null),i.fill?(e||(e=this._fill=this._createElement("fill"),n.appendChild(e)),e.color=i.fillColor||i.color,e.opacity=i.fillOpacity):e&&(n.removeChild(e),this._fill=null)},_updatePath:function(){var t=this._container.style;t.display="none",this._path.v=this.getPathString()+" ",t.display=""}}),o.Map.include(o.Browser.svg||!o.Browser.vml?{}:{_initPathRoot:function(){if(!this._pathRoot){var t=this._pathRoot=e.createElement("div");t.className="leaflet-vml-container",this._panes.overlayPane.appendChild(t),this.on("moveend",this._updatePathViewport),this._updatePathViewport()}}}),o.Browser.canvas=!!e.createElement("canvas").getContext,o.Path=o.Path.SVG&&!t.L_PREFER_CANVAS||!o.Browser.canvas?o.Path:o.Path.extend({statics:{CANVAS:!0,SVG:!1},redraw:function(){return this._map&&(this.projectLatlngs(),this._requestUpdate()),this},setStyle:function(t){return o.setOptions(this,t),this._map&&(this._updateStyle(),this._requestUpdate()),this},onRemove:function(t){t.off("viewreset",this.projectLatlngs,this).off("moveend",this._updatePath,this),this.options.clickable&&(this._map.off("click",this._onClick,this),this._map.off("mousemove",this._onMouseMove,this)),this._requestUpdate(),this._map=null},_requestUpdate:function(){this._map&&!o.Path._updateRequest&&(o.Path._updateRequest=o.Util.requestAnimFrame(this._fireMapMoveEnd,this._map))},_fireMapMoveEnd:function(){o.Path._updateRequest=null,this.fire("moveend")},_initElements:function(){this._map._initPathRoot(),this._ctx=this._map._canvasCtx},_updateStyle:function(){var t=this.options;t.stroke&&(this._ctx.lineWidth=t.weight,this._ctx.strokeStyle=t.color),t.fill&&(this._ctx.fillStyle=t.fillColor||t.color)},_drawPath:function(){var t,e,i,n,s,a;for(this._ctx.beginPath(),t=0,i=this._parts.length;i>t;t++){for(e=0,n=this._parts[t].length;n>e;e++)s=this._parts[t][e],a=(0===e?"move":"line")+"To",this._ctx[a](s.x,s.y);this instanceof o.Polygon&&this._ctx.closePath()}},_checkIfEmpty:function(){return!this._parts.length},_updatePath:function(){if(!this._checkIfEmpty()){var t=this._ctx,e=this.options;this._drawPath(),t.save(),this._updateStyle(),e.fill&&(t.globalAlpha=e.fillOpacity,t.fill()),e.stroke&&(t.globalAlpha=e.opacity,t.stroke()),t.restore()}},_initEvents:function(){this.options.clickable&&(this._map.on("mousemove",this._onMouseMove,this),this._map.on("click",this._onClick,this))},_onClick:function(t){this._containsPoint(t.layerPoint)&&this.fire("click",t)},_onMouseMove:function(t){this._map&&!this._map._animatingZoom&&(this._containsPoint(t.layerPoint)?(this._ctx.canvas.style.cursor="pointer",this._mouseInside=!0,this.fire("mouseover",t)):this._mouseInside&&(this._ctx.canvas.style.cursor="",this._mouseInside=!1,this.fire("mouseout",t)))}}),o.Map.include(o.Path.SVG&&!t.L_PREFER_CANVAS||!o.Browser.canvas?{}:{_initPathRoot:function(){var t,i=this._pathRoot;i||((i=this._pathRoot=e.createElement("canvas")).style.position="absolute",(t=this._canvasCtx=i.getContext("2d")).lineCap="round",t.lineJoin="round",this._panes.overlayPane.appendChild(i),this.options.zoomAnimation&&(this._pathRoot.className="leaflet-zoom-animated",this.on("zoomanim",this._animatePathZoom),this.on("zoomend",this._endPathZoom)),this.on("moveend",this._updateCanvasViewport),this._updateCanvasViewport())},_updateCanvasViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max.subtract(e),n=this._pathRoot;o.DomUtil.setPosition(n,e),n.width=i.x,n.height=i.y,n.getContext("2d").translate(-e.x,-e.y)}}}),o.LineUtil={simplify:function(t,e){if(!e||!t.length)return t.slice();var i=e*e;return t=this._reducePoints(t,i),this._simplifyDP(t,i)},pointToSegmentDistance:function(t,e,i){return Math.sqrt(this._sqClosestPointOnSegment(t,e,i,!0))},closestPointOnSegment:function(t,e,i){return this._sqClosestPointOnSegment(t,e,i)},_simplifyDP:function(t,e){var n=t.length,s=new(typeof Uint8Array!=i+""?Uint8Array:Array)(n);s[0]=s[n-1]=1,this._simplifyDPStep(t,s,e,0,n-1);var a,r=[];for(a=0;n>a;a++)s[a]&&r.push(t[a]);return r},_simplifyDPStep:function(t,e,i,n,o){var s,a,r,h=0;for(a=n+1;o-1>=a;a++)(r=this._sqClosestPointOnSegment(t[a],t[n],t[o],!0))>h&&(s=a,h=r);h>i&&(e[s]=1,this._simplifyDPStep(t,e,i,n,s),this._simplifyDPStep(t,e,i,s,o))},_reducePoints:function(t,e){for(var i=[t[0]],n=1,o=0,s=t.length;s>n;n++)this._sqDist(t[n],t[o])>e&&(i.push(t[n]),o=n);return s-1>o&&i.push(t[s-1]),i},clipSegment:function(t,e,i,n){var o,s,a,r=n?this._lastCode:this._getBitCode(t,i),h=this._getBitCode(e,i);for(this._lastCode=h;;){if(!(r|h))return[t,e];if(r&h)return!1;o=r||h,s=this._getEdgeIntersection(t,e,o,i),a=this._getBitCode(s,i),o===r?(t=s,r=a):(e=s,h=a)}},_getEdgeIntersection:function(t,e,i,n){var s=e.x-t.x,a=e.y-t.y,r=n.min,h=n.max;return 8&i?new o.Point(t.x+s*(h.y-t.y)/a,h.y):4&i?new o.Point(t.x+s*(r.y-t.y)/a,r.y):2&i?new o.Point(h.x,t.y+a*(h.x-t.x)/s):1&i?new o.Point(r.x,t.y+a*(r.x-t.x)/s):void 0},_getBitCode:function(t,e){var i=0;return t.x<e.min.x?i|=1:t.x>e.max.x&&(i|=2),t.y<e.min.y?i|=4:t.y>e.max.y&&(i|=8),i},_sqDist:function(t,e){var i=e.x-t.x,n=e.y-t.y;return i*i+n*n},_sqClosestPointOnSegment:function(t,e,i,n){var s,a=e.x,r=e.y,h=i.x-a,l=i.y-r,u=h*h+l*l;return u>0&&((s=((t.x-a)*h+(t.y-r)*l)/u)>1?(a=i.x,r=i.y):s>0&&(a+=h*s,r+=l*s)),h=t.x-a,l=t.y-r,n?h*h+l*l:new o.Point(a,r)}},o.Polyline=o.Path.extend({initialize:function(t,e){o.Path.prototype.initialize.call(this,e),this._latlngs=this._convertLatLngs(t)},options:{smoothFactor:1,noClip:!1},projectLatlngs:function(){this._originalPoints=[];for(var t=0,e=this._latlngs.length;e>t;t++)this._originalPoints[t]=this._map.latLngToLayerPoint(this._latlngs[t])},getPathString:function(){for(var t=0,e=this._parts.length,i="";e>t;t++)i+=this._getPathPartStr(this._parts[t]);return i},getLatLngs:function(){return this._latlngs},setLatLngs:function(t){return this._latlngs=this._convertLatLngs(t),this.redraw()},addLatLng:function(t){return this._latlngs.push(o.latLng(t)),this.redraw()},spliceLatLngs:function(){var t=[].splice.apply(this._latlngs,arguments);return this._convertLatLngs(this._latlngs,!0),this.redraw(),t},closestLayerPoint:function(t){for(var e,i,n=1/0,s=this._parts,a=null,r=0,h=s.length;h>r;r++)for(var l=s[r],u=1,c=l.length;c>u;u++){e=l[u-1],i=l[u];var d=o.LineUtil._sqClosestPointOnSegment(t,e,i,!0);n>d&&(n=d,a=o.LineUtil._sqClosestPointOnSegment(t,e,i))}return a&&(a.distance=Math.sqrt(n)),a},getBounds:function(){return new o.LatLngBounds(this.getLatLngs())},_convertLatLngs:function(t,e){var i,n,s=e?t:[];for(i=0,n=t.length;n>i;i++){if(o.Util.isArray(t[i])&&"number"!=typeof t[i][0])return;s[i]=o.latLng(t[i])}return s},_initEvents:function(){o.Path.prototype._initEvents.call(this)},_getPathPartStr:function(t){for(var e,i=o.Path.VML,n=0,s=t.length,a="";s>n;n++)e=t[n],i&&e._round(),a+=(n?"L":"M")+e.x+" "+e.y;return a},_clipPoints:function(){var t,e,i,n=this._originalPoints,s=n.length;if(this.options.noClip)this._parts=[n];else{this._parts=[];var a=this._parts,r=this._map._pathViewport,h=o.LineUtil;for(t=0,e=0;s-1>t;t++)(i=h.clipSegment(n[t],n[t+1],r,t))&&(a[e]=a[e]||[],a[e].push(i[0]),(i[1]!==n[t+1]||t===s-2)&&(a[e].push(i[1]),e++))}},_simplifyPoints:function(){for(var t=this._parts,e=o.LineUtil,i=0,n=t.length;n>i;i++)t[i]=e.simplify(t[i],this.options.smoothFactor)},_updatePath:function(){this._map&&(this._clipPoints(),this._simplifyPoints(),o.Path.prototype._updatePath.call(this))}}),o.polyline=function(t,e){return new o.Polyline(t,e)},o.PolyUtil={},o.PolyUtil.clipPolygon=function(t,e){var i,n,s,a,r,h,l,u,c,d=[1,4,2,8],p=o.LineUtil;for(n=0,l=t.length;l>n;n++)t[n]._code=p._getBitCode(t[n],e);for(a=0;4>a;a++){for(u=d[a],i=[],n=0,s=(l=t.length)-1;l>n;s=n++)r=t[n],h=t[s],r._code&u?h._code&u||((c=p._getEdgeIntersection(h,r,u,e))._code=p._getBitCode(c,e),i.push(c)):(h._code&u&&((c=p._getEdgeIntersection(h,r,u,e))._code=p._getBitCode(c,e),i.push(c)),i.push(r));t=i}return t},o.Polygon=o.Polyline.extend({options:{fill:!0},initialize:function(t,e){o.Polyline.prototype.initialize.call(this,t,e),this._initWithHoles(t)},_initWithHoles:function(t){var e,i,n;if(t&&o.Util.isArray(t[0])&&"number"!=typeof t[0][0])for(this._latlngs=this._convertLatLngs(t[0]),this._holes=t.slice(1),e=0,i=this._holes.length;i>e;e++)(n=this._holes[e]=this._convertLatLngs(this._holes[e]))[0].equals(n[n.length-1])&&n.pop();(t=this._latlngs).length>=2&&t[0].equals(t[t.length-1])&&t.pop()},projectLatlngs:function(){var t,e,i,n;if(o.Polyline.prototype.projectLatlngs.call(this),this._holePoints=[],this._holes)for(t=0,i=this._holes.length;i>t;t++)for(this._holePoints[t]=[],e=0,n=this._holes[t].length;n>e;e++)this._holePoints[t][e]=this._map.latLngToLayerPoint(this._holes[t][e])},setLatLngs:function(t){return t&&o.Util.isArray(t[0])&&"number"!=typeof t[0][0]?(this._initWithHoles(t),this.redraw()):o.Polyline.prototype.setLatLngs.call(this,t)},_clipPoints:function(){var t=this._originalPoints,e=[];if(this._parts=[t].concat(this._holePoints),!this.options.noClip){for(var i=0,n=this._parts.length;n>i;i++){var s=o.PolyUtil.clipPolygon(this._parts[i],this._map._pathViewport);s.length&&e.push(s)}this._parts=e}},_getPathPartStr:function(t){return o.Polyline.prototype._getPathPartStr.call(this,t)+(o.Browser.svg?"z":"x")}}),o.polygon=function(t,e){return new o.Polygon(t,e)},function(){function t(t){return o.FeatureGroup.extend({initialize:function(t,e){this._layers={},this._options=e,this.setLatLngs(t)},setLatLngs:function(e){var i=0,n=e.length;for(this.eachLayer(function(t){n>i?t.setLatLngs(e[i++]):this.removeLayer(t)},this);n>i;)this.addLayer(new t(e[i++],this._options));return this},getLatLngs:function(){var t=[];return this.eachLayer(function(e){t.push(e.getLatLngs())}),t}})}o.MultiPolyline=t(o.Polyline),o.MultiPolygon=t(o.Polygon),o.multiPolyline=function(t,e){return new o.MultiPolyline(t,e)},o.multiPolygon=function(t,e){return new o.MultiPolygon(t,e)}}(),o.Rectangle=o.Polygon.extend({initialize:function(t,e){o.Polygon.prototype.initialize.call(this,this._boundsToLatLngs(t),e)},setBounds:function(t){this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return[(t=o.latLngBounds(t)).getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}}),o.rectangle=function(t,e){return new o.Rectangle(t,e)},o.Circle=o.Path.extend({initialize:function(t,e,i){o.Path.prototype.initialize.call(this,i),this._latlng=o.latLng(t),this._mRadius=e},options:{fill:!0},setLatLng:function(t){return this._latlng=o.latLng(t),this.redraw()},setRadius:function(t){return this._mRadius=t,this.redraw()},projectLatlngs:function(){var t=this._getLngRadius(),e=this._latlng,i=this._map.latLngToLayerPoint([e.lat,e.lng-t]);this._point=this._map.latLngToLayerPoint(e),this._radius=Math.max(this._point.x-i.x,1)},getBounds:function(){var t=this._getLngRadius(),e=this._mRadius/40075017*360,i=this._latlng;return new o.LatLngBounds([i.lat-e,i.lng-t],[i.lat+e,i.lng+t])},getLatLng:function(){return this._latlng},getPathString:function(){var t=this._point,e=this._radius;return this._checkIfEmpty()?"":o.Browser.svg?"M"+t.x+","+(t.y-e)+"A"+e+","+e+",0,1,1,"+(t.x-.1)+","+(t.y-e)+" z":(t._round(),e=Math.round(e),"AL "+t.x+","+t.y+" "+e+","+e+" 0,23592600")},getRadius:function(){return this._mRadius},_getLatRadius:function(){return this._mRadius/40075017*360},_getLngRadius:function(){return this._getLatRadius()/Math.cos(o.LatLng.DEG_TO_RAD*this._latlng.lat)},_checkIfEmpty:function(){if(!this._map)return!1;var t=this._map._pathViewport,e=this._radius,i=this._point;return i.x-e>t.max.x||i.y-e>t.max.y||i.x+e<t.min.x||i.y+e<t.min.y}}),o.circle=function(t,e,i){return new o.Circle(t,e,i)},o.CircleMarker=o.Circle.extend({options:{radius:10,weight:2},initialize:function(t,e){o.Circle.prototype.initialize.call(this,t,null,e),this._radius=this.options.radius},projectLatlngs:function(){this._point=this._map.latLngToLayerPoint(this._latlng)},_updateStyle:function(){o.Circle.prototype._updateStyle.call(this),this.setRadius(this.options.radius)},setLatLng:function(t){return o.Circle.prototype.setLatLng.call(this,t),this._popup&&this._popup._isOpen&&this._popup.setLatLng(t),this},setRadius:function(t){return this.options.radius=this._radius=t,this.redraw()},getRadius:function(){return this._radius}}),o.circleMarker=function(t,e){return new o.CircleMarker(t,e)},o.Polyline.include(o.Path.CANVAS?{_containsPoint:function(t,e){var i,n,s,a,r,l,u=this.options.weight/2;for(o.Browser.touch&&(u+=10),i=0,a=this._parts.length;a>i;i++)for(n=0,s=(r=(l=this._parts[i]).length)-1;r>n;s=n++)if((e||0!==n)&&u>=o.LineUtil.pointToSegmentDistance(t,l[s],l[n]))return!0;return!1}}:{}),o.Polygon.include(o.Path.CANVAS?{_containsPoint:function(t){var e,i,n,s,a,r,h,l,u=!1;if(o.Polyline.prototype._containsPoint.call(this,t,!0))return!0;for(s=0,h=this._parts.length;h>s;s++)for(a=0,r=(l=(e=this._parts[s]).length)-1;l>a;r=a++)i=e[a],n=e[r],i.y>t.y!=n.y>t.y&&t.x<(n.x-i.x)*(t.y-i.y)/(n.y-i.y)+i.x&&(u=!u);return u}}:{}),o.Circle.include(o.Path.CANVAS?{_drawPath:function(){var t=this._point;this._ctx.beginPath(),this._ctx.arc(t.x,t.y,this._radius,0,2*Math.PI,!1)},_containsPoint:function(t){var e=this._point,i=this.options.stroke?this.options.weight/2:0;return t.distanceTo(e)<=this._radius+i}}:{}),o.CircleMarker.include(o.Path.CANVAS?{_updateStyle:function(){o.Path.prototype._updateStyle.call(this)}}:{}),o.GeoJSON=o.FeatureGroup.extend({initialize:function(t,e){o.setOptions(this,e),this._layers={},t&&this.addData(t)},addData:function(t){var e,i,n,s=o.Util.isArray(t)?t:t.features;if(s){for(e=0,i=s.length;i>e;e++)((n=s[e]).geometries||n.geometry||n.features||n.coordinates)&&this.addData(s[e]);return this}var a=this.options;if(!a.filter||a.filter(t)){var r=o.GeoJSON.geometryToLayer(t,a.pointToLayer,a.coordsToLatLng,a);return r.feature=o.GeoJSON.asFeature(t),r.defaultOptions=r.options,this.resetStyle(r),a.onEachFeature&&a.onEachFeature(t,r),this.addLayer(r)}},resetStyle:function(t){var e=this.options.style;e&&(o.Util.extend(t.options,t.defaultOptions),this._setLayerStyle(t,e))},setStyle:function(t){this.eachLayer(function(e){this._setLayerStyle(e,t)},this)},_setLayerStyle:function(t,e){"function"==typeof e&&(e=e(t.feature)),t.setStyle&&t.setStyle(e)}}),o.extend(o.GeoJSON,{geometryToLayer:function(t,e,i,n){var s,a,r,h,l="Feature"===t.type?t.geometry:t,u=l.coordinates,c=[];switch(i=i||this.coordsToLatLng,l.type){case"Point":return s=i(u),e?e(t,s):new o.Marker(s);case"MultiPoint":for(r=0,h=u.length;h>r;r++)s=i(u[r]),c.push(e?e(t,s):new o.Marker(s));return new o.FeatureGroup(c);case"LineString":return a=this.coordsToLatLngs(u,0,i),new o.Polyline(a,n);case"Polygon":if(2===u.length&&!u[1].length)throw new Error("Invalid GeoJSON object.");return a=this.coordsToLatLngs(u,1,i),new o.Polygon(a,n);case"MultiLineString":return a=this.coordsToLatLngs(u,1,i),new o.MultiPolyline(a,n);case"MultiPolygon":return a=this.coordsToLatLngs(u,2,i),new o.MultiPolygon(a,n);case"GeometryCollection":for(r=0,h=l.geometries.length;h>r;r++)c.push(this.geometryToLayer({geometry:l.geometries[r],type:"Feature",properties:t.properties},e,i,n));return new o.FeatureGroup(c);default:throw new Error("Invalid GeoJSON object.")}},coordsToLatLng:function(t){return new o.LatLng(t[1],t[0],t[2])},coordsToLatLngs:function(t,e,i){var n,o,s,a=[];for(o=0,s=t.length;s>o;o++)n=e?this.coordsToLatLngs(t[o],e-1,i):(i||this.coordsToLatLng)(t[o]),a.push(n);return a},latLngToCoords:function(t){var e=[t.lng,t.lat];return t.alt!==i&&e.push(t.alt),e},latLngsToCoords:function(t){for(var e=[],i=0,n=t.length;n>i;i++)e.push(o.GeoJSON.latLngToCoords(t[i]));return e},getFeature:function(t,e){return t.feature?o.extend({},t.feature,{geometry:e}):o.GeoJSON.asFeature(e)},asFeature:function(t){return"Feature"===t.type?t:{type:"Feature",properties:{},geometry:t}}});var a={toGeoJSON:function(){return o.GeoJSON.getFeature(this,{type:"Point",coordinates:o.GeoJSON.latLngToCoords(this.getLatLng())})}};o.Marker.include(a),o.Circle.include(a),o.CircleMarker.include(a),o.Polyline.include({toGeoJSON:function(){return o.GeoJSON.getFeature(this,{type:"LineString",coordinates:o.GeoJSON.latLngsToCoords(this.getLatLngs())})}}),o.Polygon.include({toGeoJSON:function(){var t,e,i,n=[o.GeoJSON.latLngsToCoords(this.getLatLngs())];if(n[0].push(n[0][0]),this._holes)for(t=0,e=this._holes.length;e>t;t++)(i=o.GeoJSON.latLngsToCoords(this._holes[t])).push(i[0]),n.push(i);return o.GeoJSON.getFeature(this,{type:"Polygon",coordinates:n})}}),function(){function t(t){return function(){var e=[];return this.eachLayer(function(t){e.push(t.toGeoJSON().geometry.coordinates)}),o.GeoJSON.getFeature(this,{type:t,coordinates:e})}}o.MultiPolyline.include({toGeoJSON:t("MultiLineString")}),o.MultiPolygon.include({toGeoJSON:t("MultiPolygon")}),o.LayerGroup.include({toGeoJSON:function(){var e,i=this.feature&&this.feature.geometry,n=[];if(i&&"MultiPoint"===i.type)return t("MultiPoint").call(this);var s=i&&"GeometryCollection"===i.type;return this.eachLayer(function(t){t.toGeoJSON&&(e=t.toGeoJSON(),n.push(s?e.geometry:o.GeoJSON.asFeature(e)))}),s?o.GeoJSON.getFeature(this,{geometries:n,type:"GeometryCollection"}):{type:"FeatureCollection",features:n}}})}(),o.geoJson=function(t,e){return new o.GeoJSON(t,e)},o.DomEvent={addListener:function(t,e,i,n){var s,a,r,h=o.stamp(i),l="_leaflet_"+e+h;return t[l]?this:(s=function(e){return i.call(n||t,e||o.DomEvent._getEvent())},o.Browser.pointer&&0===e.indexOf("touch")?this.addPointerListener(t,e,s,h):(o.Browser.touch&&"dblclick"===e&&this.addDoubleTapListener&&this.addDoubleTapListener(t,s,h),"addEventListener"in t?"mousewheel"===e?(t.addEventListener("DOMMouseScroll",s,!1),t.addEventListener(e,s,!1)):"mouseenter"===e||"mouseleave"===e?(a=s,r="mouseenter"===e?"mouseover":"mouseout",s=function(e){return o.DomEvent._checkMouse(t,e)?a(e):void 0},t.addEventListener(r,s,!1)):"click"===e&&o.Browser.android?(a=s,s=function(t){return o.DomEvent._filterClick(t,a)},t.addEventListener(e,s,!1)):t.addEventListener(e,s,!1):"attachEvent"in t&&t.attachEvent("on"+e,s),t[l]=s,this))},removeListener:function(t,e,i){var n=o.stamp(i),s="_leaflet_"+e+n,a=t[s];return a?(o.Browser.pointer&&0===e.indexOf("touch")?this.removePointerListener(t,e,n):o.Browser.touch&&"dblclick"===e&&this.removeDoubleTapListener?this.removeDoubleTapListener(t,n):"removeEventListener"in t?"mousewheel"===e?(t.removeEventListener("DOMMouseScroll",a,!1),t.removeEventListener(e,a,!1)):"mouseenter"===e||"mouseleave"===e?t.removeEventListener("mouseenter"===e?"mouseover":"mouseout",a,!1):t.removeEventListener(e,a,!1):"detachEvent"in t&&t.detachEvent("on"+e,a),t[s]=null,this):this},stopPropagation:function(t){return t.stopPropagation?t.stopPropagation():t.cancelBubble=!0,o.DomEvent._skipped(t),this},disableScrollPropagation:function(t){var e=o.DomEvent.stopPropagation;return o.DomEvent.on(t,"mousewheel",e).on(t,"MozMousePixelScroll",e)},disableClickPropagation:function(t){for(var e=o.DomEvent.stopPropagation,i=o.Draggable.START.length-1;i>=0;i--)o.DomEvent.on(t,o.Draggable.START[i],e);return o.DomEvent.on(t,"click",o.DomEvent._fakeStop).on(t,"dblclick",e)},preventDefault:function(t){return t.preventDefault?t.preventDefault():t.returnValue=!1,this},stop:function(t){return o.DomEvent.preventDefault(t).stopPropagation(t)},getMousePosition:function(t,e){if(!e)return new o.Point(t.clientX,t.clientY);var i=e.getBoundingClientRect();return new o.Point(t.clientX-i.left-e.clientLeft,t.clientY-i.top-e.clientTop)},getWheelDelta:function(t){var e=0;return t.wheelDelta&&(e=t.wheelDelta/120),t.detail&&(e=-t.detail/3),e},_skipEvents:{},_fakeStop:function(t){o.DomEvent._skipEvents[t.type]=!0},_skipped:function(t){var e=this._skipEvents[t.type];return this._skipEvents[t.type]=!1,e},_checkMouse:function(t,e){var i=e.relatedTarget;if(!i)return!0;try{for(;i&&i!==t;)i=i.parentNode}catch(n){return!1}return i!==t},_getEvent:function(){var e=t.event;if(!e)for(var i=arguments.callee.caller;i&&(!(e=i.arguments[0])||t.Event!==e.constructor);)i=i.caller;return e},_filterClick:function(t,e){var i=t.timeStamp||t.originalEvent.timeStamp,n=o.DomEvent._lastClick&&i-o.DomEvent._lastClick;return n&&n>100&&1e3>n||t.target._simulatedClick&&!t._simulated?void o.DomEvent.stop(t):(o.DomEvent._lastClick=i,e(t))}},o.DomEvent.on=o.DomEvent.addListener,o.DomEvent.off=o.DomEvent.removeListener,o.Draggable=o.Class.extend({includes:o.Mixin.Events,statics:{START:o.Browser.touch?["touchstart","mousedown"]:["mousedown"],END:{mousedown:"mouseup",touchstart:"touchend",pointerdown:"touchend",MSPointerDown:"touchend"},MOVE:{mousedown:"mousemove",touchstart:"touchmove",pointerdown:"touchmove",MSPointerDown:"touchmove"}},initialize:function(t,e){this._element=t,this._dragStartTarget=e||t},enable:function(){if(!this._enabled){for(var t=o.Draggable.START.length-1;t>=0;t--)o.DomEvent.on(this._dragStartTarget,o.Draggable.START[t],this._onDown,this);this._enabled=!0}},disable:function(){if(this._enabled){for(var t=o.Draggable.START.length-1;t>=0;t--)o.DomEvent.off(this._dragStartTarget,o.Draggable.START[t],this._onDown,this);this._enabled=!1,this._moved=!1}},_onDown:function(t){if(this._moved=!1,!(t.shiftKey||1!==t.which&&1!==t.button&&!t.touches||(o.DomEvent.stopPropagation(t),o.Draggable._disabled||(o.DomUtil.disableImageDrag(),o.DomUtil.disableTextSelection(),this._moving)))){var i=t.touches?t.touches[0]:t;this._startPoint=new o.Point(i.clientX,i.clientY),this._startPos=this._newPos=o.DomUtil.getPosition(this._element),o.DomEvent.on(e,o.Draggable.MOVE[t.type],this._onMove,this).on(e,o.Draggable.END[t.type],this._onUp,this)}},_onMove:function(t){if(t.touches&&t.touches.length>1)this._moved=!0;else{var i=t.touches&&1===t.touches.length?t.touches[0]:t,s=new o.Point(i.clientX,i.clientY).subtract(this._startPoint);(s.x||s.y)&&(o.DomEvent.preventDefault(t),this._moved||(this.fire("dragstart"),this._moved=!0,this._startPos=o.DomUtil.getPosition(this._element).subtract(s),o.DomUtil.addClass(e.body,"leaflet-dragging"),o.DomUtil.addClass(t.target||t.srcElement,"leaflet-drag-target")),this._newPos=this._startPos.add(s),this._moving=!0,o.Util.cancelAnimFrame(this._animRequest),this._animRequest=o.Util.requestAnimFrame(this._updatePosition,this,!0,this._dragStartTarget))}},_updatePosition:function(){this.fire("predrag"),o.DomUtil.setPosition(this._element,this._newPos),this.fire("drag")},_onUp:function(t){for(var i in o.DomUtil.removeClass(e.body,"leaflet-dragging"),o.DomUtil.removeClass(t.target||t.srcElement,"leaflet-drag-target"),o.Draggable.MOVE)o.DomEvent.off(e,o.Draggable.MOVE[i],this._onMove).off(e,o.Draggable.END[i],this._onUp);o.DomUtil.enableImageDrag(),o.DomUtil.enableTextSelection(),this._moved&&this._moving&&(o.Util.cancelAnimFrame(this._animRequest),this.fire("dragend",{distance:this._newPos.distanceTo(this._startPos)})),this._moving=!1}}),o.Handler=o.Class.extend({initialize:function(t){this._map=t},enable:function(){this._enabled||(this._enabled=!0,this.addHooks())},disable:function(){this._enabled&&(this._enabled=!1,this.removeHooks())},enabled:function(){return!!this._enabled}}),o.Map.mergeOptions({dragging:!0,inertia:!o.Browser.android23,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,inertiaThreshold:o.Browser.touch?32:18,easeLinearity:.25,worldCopyJump:!1}),o.Map.Drag=o.Handler.extend({addHooks:function(){if(!this._draggable){var t=this._map;this._draggable=new o.Draggable(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDrag,this),t.on("viewreset",this._onViewReset,this),t.whenReady(this._onViewReset,this))}this._draggable.enable()},removeHooks:function(){this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){var t=this._map;t._panAnim&&t._panAnim.stop(),t.fire("movestart").fire("dragstart"),t.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(){if(this._map.options.inertia){var t=this._lastTime=+new Date,e=this._lastPos=this._draggable._newPos;this._positions.push(e),this._times.push(t),t-this._times[0]>200&&(this._positions.shift(),this._times.shift())}this._map.fire("move").fire("drag")},_onViewReset:function(){var t=this._map.getSize()._divideBy(2),e=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=e.subtract(t).x,this._worldWidth=this._map.project([0,180]).x},_onPreDrag:function(){var t=this._worldWidth,e=Math.round(t/2),i=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-e+i)%t+e-i,s=(n+e+i)%t-e-i,a=Math.abs(o+i)<Math.abs(s+i)?o:s;this._draggable._newPos.x=a},_onDragEnd:function(t){var e=this._map,i=e.options,n=+new Date-this._lastTime,s=!i.inertia||n>i.inertiaThreshold||!this._positions[0];if(e.fire("dragend",t),s)e.fire("moveend");else{var a=this._lastPos.subtract(this._positions[0]),r=(this._lastTime+n-this._times[0])/1e3,h=i.easeLinearity,l=a.multiplyBy(h/r),u=l.distanceTo([0,0]),c=Math.min(i.inertiaMaxSpeed,u),d=l.multiplyBy(c/u),p=c/(i.inertiaDeceleration*h),_=d.multiplyBy(-p/2).round();_.x&&_.y?(_=e._limitOffset(_,e.options.maxBounds),o.Util.requestAnimFrame(function(){e.panBy(_,{duration:p,easeLinearity:h,noMoveStart:!0})})):e.fire("moveend")}}}),o.Map.addInitHook("addHandler","dragging",o.Map.Drag),o.Map.mergeOptions({doubleClickZoom:!0}),o.Map.DoubleClickZoom=o.Handler.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var e=this._map,i=e.getZoom()+(t.originalEvent.shiftKey?-1:1);"center"===e.options.doubleClickZoom?e.setZoom(i):e.setZoomAround(t.containerPoint,i)}}),o.Map.addInitHook("addHandler","doubleClickZoom",o.Map.DoubleClickZoom),o.Map.mergeOptions({scrollWheelZoom:!0}),o.Map.ScrollWheelZoom=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"mousewheel",this._onWheelScroll,this),o.DomEvent.on(this._map._container,"MozMousePixelScroll",o.DomEvent.preventDefault),this._delta=0},removeHooks:function(){o.DomEvent.off(this._map._container,"mousewheel",this._onWheelScroll),o.DomEvent.off(this._map._container,"MozMousePixelScroll",o.DomEvent.preventDefault)},_onWheelScroll:function(t){var e=o.DomEvent.getWheelDelta(t);this._delta+=e,this._lastMousePos=this._map.mouseEventToContainerPoint(t),this._startTime||(this._startTime=+new Date);var i=Math.max(40-(+new Date-this._startTime),0);clearTimeout(this._timer),this._timer=setTimeout(o.bind(this._performZoom,this),i),o.DomEvent.preventDefault(t),o.DomEvent.stopPropagation(t)},_performZoom:function(){var t=this._map,e=this._delta,i=t.getZoom();e=e>0?Math.ceil(e):Math.floor(e),e=Math.max(Math.min(e,4),-4),e=t._limitZoom(i+e)-i,this._delta=0,this._startTime=null,e&&("center"===t.options.scrollWheelZoom?t.setZoom(i+e):t.setZoomAround(this._lastMousePos,i+e))}}),o.Map.addInitHook("addHandler","scrollWheelZoom",o.Map.ScrollWheelZoom),o.extend(o.DomEvent,{_touchstart:o.Browser.msPointer?"MSPointerDown":o.Browser.pointer?"pointerdown":"touchstart",_touchend:o.Browser.msPointer?"MSPointerUp":o.Browser.pointer?"pointerup":"touchend",addDoubleTapListener:function(t,i,n){function s(t){var e;if(o.Browser.pointer?(_.push(t.pointerId),e=_.length):e=t.touches.length,!(e>1)){var i=Date.now(),n=i-(r||i);h=t.touches?t.touches[0]:t,l=n>0&&u>=n,r=i}}function a(t){if(o.Browser.pointer){var e=_.indexOf(t.pointerId);if(-1===e)return;_.splice(e,1)}if(l){if(o.Browser.pointer){var n,s={};for(var a in h)n=h[a],s[a]="function"==typeof n?n.bind(h):n;h=s}h.type="dblclick",i(h),r=null}}var r,h,l=!1,u=250,c="_leaflet_",d=this._touchstart,p=this._touchend,_=[];t[c+d+n]=s,t[c+p+n]=a;var m=o.Browser.pointer?e.documentElement:t;return t.addEventListener(d,s,!1),m.addEventListener(p,a,!1),o.Browser.pointer&&m.addEventListener(o.DomEvent.POINTER_CANCEL,a,!1),this},removeDoubleTapListener:function(t,i){var n="_leaflet_";return t.removeEventListener(this._touchstart,t[n+this._touchstart+i],!1),(o.Browser.pointer?e.documentElement:t).removeEventListener(this._touchend,t[n+this._touchend+i],!1),o.Browser.pointer&&e.documentElement.removeEventListener(o.DomEvent.POINTER_CANCEL,t[n+this._touchend+i],!1),this}}),o.extend(o.DomEvent,{POINTER_DOWN:o.Browser.msPointer?"MSPointerDown":"pointerdown",POINTER_MOVE:o.Browser.msPointer?"MSPointerMove":"pointermove",POINTER_UP:o.Browser.msPointer?"MSPointerUp":"pointerup",POINTER_CANCEL:o.Browser.msPointer?"MSPointerCancel":"pointercancel",_pointers:[],_pointerDocumentListener:!1,addPointerListener:function(t,e,i,n){switch(e){case"touchstart":return this.addPointerListenerStart(t,e,i,n);case"touchend":return this.addPointerListenerEnd(t,e,i,n);case"touchmove":return this.addPointerListenerMove(t,e,i,n);default:throw"Unknown touch event type"}},addPointerListenerStart:function(t,i,n,s){var r=this._pointers,h=function(t){o.DomEvent.preventDefault(t);for(var e=!1,i=0;i<r.length;i++)if(r[i].pointerId===t.pointerId){e=!0;break}e||r.push(t),t.touches=r.slice(),t.changedTouches=[t],n(t)};if(t["_leaflet_touchstart"+s]=h,t.addEventListener(this.POINTER_DOWN,h,!1),!this._pointerDocumentListener){var l=function(t){for(var e=0;e<r.length;e++)if(r[e].pointerId===t.pointerId){r.splice(e,1);break}};e.documentElement.addEventListener(this.POINTER_UP,l,!1),e.documentElement.addEventListener(this.POINTER_CANCEL,l,!1),this._pointerDocumentListener=!0}return this},addPointerListenerMove:function(t,e,i,n){function o(t){if(t.pointerType!==t.MSPOINTER_TYPE_MOUSE&&"mouse"!==t.pointerType||0!==t.buttons){for(var e=0;e<a.length;e++)if(a[e].pointerId===t.pointerId){a[e]=t;break}t.touches=a.slice(),t.changedTouches=[t],i(t)}}var a=this._pointers;return t["_leaflet_touchmove"+n]=o,t.addEventListener(this.POINTER_MOVE,o,!1),this},addPointerListenerEnd:function(t,e,i,n){var s=this._pointers,a=function(t){for(var e=0;e<s.length;e++)if(s[e].pointerId===t.pointerId){s.splice(e,1);break}t.touches=s.slice(),t.changedTouches=[t],i(t)};return t["_leaflet_touchend"+n]=a,t.addEventListener(this.POINTER_UP,a,!1),t.addEventListener(this.POINTER_CANCEL,a,!1),this},removePointerListener:function(t,e,i){var o=t["_leaflet_"+e+i];switch(e){case"touchstart":t.removeEventListener(this.POINTER_DOWN,o,!1);break;case"touchmove":t.removeEventListener(this.POINTER_MOVE,o,!1);break;case"touchend":t.removeEventListener(this.POINTER_UP,o,!1),t.removeEventListener(this.POINTER_CANCEL,o,!1)}return this}}),o.Map.mergeOptions({touchZoom:o.Browser.touch&&!o.Browser.android23,bounceAtZoomLimits:!0}),o.Map.TouchZoom=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){o.DomEvent.off(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(t){var i=this._map;if(t.touches&&2===t.touches.length&&!i._animatingZoom&&!this._zooming){var n=i.mouseEventToLayerPoint(t.touches[0]),s=i.mouseEventToLayerPoint(t.touches[1]),a=i._getCenterLayerPoint();this._startCenter=n.add(s)._divideBy(2),this._startDist=n.distanceTo(s),this._moved=!1,this._zooming=!0,this._centerOffset=a.subtract(this._startCenter),i._panAnim&&i._panAnim.stop(),o.DomEvent.on(e,"touchmove",this._onTouchMove,this).on(e,"touchend",this._onTouchEnd,this),o.DomEvent.preventDefault(t)}},_onTouchMove:function(t){var e=this._map;if(t.touches&&2===t.touches.length&&this._zooming){var i=e.mouseEventToLayerPoint(t.touches[0]),n=e.mouseEventToLayerPoint(t.touches[1]);this._scale=i.distanceTo(n)/this._startDist,this._delta=i._add(n)._divideBy(2)._subtract(this._startCenter),1!==this._scale&&(e.options.bounceAtZoomLimits||!(e.getZoom()===e.getMinZoom()&&this._scale<1||e.getZoom()===e.getMaxZoom()&&this._scale>1))&&(this._moved||(o.DomUtil.addClass(e._mapPane,"leaflet-touching"),e.fire("movestart").fire("zoomstart"),this._moved=!0),o.Util.cancelAnimFrame(this._animRequest),this._animRequest=o.Util.requestAnimFrame(this._updateOnMove,this,!0,this._map._container),o.DomEvent.preventDefault(t))}},_updateOnMove:function(){var t=this._map,e=this._getScaleOrigin(),i=t.layerPointToLatLng(e),n=t.getScaleZoom(this._scale);t._animateZoom(i,n,this._startCenter,this._scale,this._delta)},_onTouchEnd:function(){if(this._moved&&this._zooming){var t=this._map;this._zooming=!1,o.DomUtil.removeClass(t._mapPane,"leaflet-touching"),o.Util.cancelAnimFrame(this._animRequest),o.DomEvent.off(e,"touchmove",this._onTouchMove).off(e,"touchend",this._onTouchEnd);var i=this._getScaleOrigin(),n=t.layerPointToLatLng(i),s=t.getZoom(),a=t.getScaleZoom(this._scale)-s,r=a>0?Math.ceil(a):Math.floor(a),h=t._limitZoom(s+r),l=t.getZoomScale(h)/this._scale;t._animateZoom(n,h,i,l)}else this._zooming=!1},_getScaleOrigin:function(){var t=this._centerOffset.subtract(this._delta).divideBy(this._scale);return this._startCenter.add(t)}}),o.Map.addInitHook("addHandler","touchZoom",o.Map.TouchZoom),o.Map.mergeOptions({tap:!0,tapTolerance:15}),o.Map.Tap=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){o.DomEvent.off(this._map._container,"touchstart",this._onDown,this)},_onDown:function(t){if(t.touches){if(o.DomEvent.preventDefault(t),this._fireClick=!0,t.touches.length>1)return this._fireClick=!1,void clearTimeout(this._holdTimeout);var i=t.touches[0],n=i.target;this._startPos=this._newPos=new o.Point(i.clientX,i.clientY),n.tagName&&"a"===n.tagName.toLowerCase()&&o.DomUtil.addClass(n,"leaflet-active"),this._holdTimeout=setTimeout(o.bind(function(){this._isTapValid()&&(this._fireClick=!1,this._onUp(),this._simulateEvent("contextmenu",i))},this),1e3),o.DomEvent.on(e,"touchmove",this._onMove,this).on(e,"touchend",this._onUp,this)}},_onUp:function(t){if(clearTimeout(this._holdTimeout),o.DomEvent.off(e,"touchmove",this._onMove,this).off(e,"touchend",this._onUp,this),this._fireClick&&t&&t.changedTouches){var i=t.changedTouches[0],n=i.target;n&&n.tagName&&"a"===n.tagName.toLowerCase()&&o.DomUtil.removeClass(n,"leaflet-active"),this._isTapValid()&&this._simulateEvent("click",i)}},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_onMove:function(t){var e=t.touches[0];this._newPos=new o.Point(e.clientX,e.clientY)},_simulateEvent:function(i,n){var o=e.createEvent("MouseEvents");o._simulated=!0,n.target._simulatedClick=!0,o.initMouseEvent(i,!0,!0,t,1,n.screenX,n.screenY,n.clientX,n.clientY,!1,!1,!1,!1,0,null),n.target.dispatchEvent(o)}}),o.Browser.touch&&!o.Browser.pointer&&o.Map.addInitHook("addHandler","tap",o.Map.Tap),o.Map.mergeOptions({boxZoom:!0}),o.Map.BoxZoom=o.Handler.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._moved=!1},addHooks:function(){o.DomEvent.on(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){o.DomEvent.off(this._container,"mousedown",this._onMouseDown),this._moved=!1},moved:function(){return this._moved},_onMouseDown:function(t){return this._moved=!1,!(!t.shiftKey||1!==t.which&&1!==t.button)&&(o.DomUtil.disableTextSelection(),o.DomUtil.disableImageDrag(),this._startLayerPoint=this._map.mouseEventToLayerPoint(t),void o.DomEvent.on(e,"mousemove",this._onMouseMove,this).on(e,"mouseup",this._onMouseUp,this).on(e,"keydown",this._onKeyDown,this))},_onMouseMove:function(t){this._moved||(this._box=o.DomUtil.create("div","leaflet-zoom-box",this._pane),o.DomUtil.setPosition(this._box,this._startLayerPoint),this._container.style.cursor="crosshair",this._map.fire("boxzoomstart"));var e=this._startLayerPoint,i=this._box,n=this._map.mouseEventToLayerPoint(t),s=n.subtract(e),a=new o.Point(Math.min(n.x,e.x),Math.min(n.y,e.y));o.DomUtil.setPosition(i,a),this._moved=!0,i.style.width=Math.max(0,Math.abs(s.x)-4)+"px",i.style.height=Math.max(0,Math.abs(s.y)-4)+"px"},_finish:function(){this._moved&&(this._pane.removeChild(this._box),this._container.style.cursor=""),o.DomUtil.enableTextSelection(),o.DomUtil.enableImageDrag(),o.DomEvent.off(e,"mousemove",this._onMouseMove).off(e,"mouseup",this._onMouseUp).off(e,"keydown",this._onKeyDown)},_onMouseUp:function(t){this._finish();var e=this._map,i=e.mouseEventToLayerPoint(t);if(!this._startLayerPoint.equals(i)){var n=new o.LatLngBounds(e.layerPointToLatLng(this._startLayerPoint),e.layerPointToLatLng(i));e.fitBounds(n),e.fire("boxzoomend",{boxZoomBounds:n})}},_onKeyDown:function(t){27===t.keyCode&&this._finish()}}),o.Map.addInitHook("addHandler","boxZoom",o.Map.BoxZoom),o.Map.mergeOptions({keyboard:!0,keyboardPanOffset:80,keyboardZoomOffset:1}),o.Map.Keyboard=o.Handler.extend({keyCodes:{left:[37],right:[39],down:[40],up:[38],zoomIn:[187,107,61,171],zoomOut:[189,109,173]},initialize:function(t){this._map=t,this._setPanOffset(t.options.keyboardPanOffset),this._setZoomOffset(t.options.keyboardZoomOffset)},addHooks:function(){var t=this._map._container;-1===t.tabIndex&&(t.tabIndex="0"),o.DomEvent.on(t,"focus",this._onFocus,this).on(t,"blur",this._onBlur,this).on(t,"mousedown",this._onMouseDown,this),this._map.on("focus",this._addHooks,this).on("blur",this._removeHooks,this)},removeHooks:function(){this._removeHooks();var t=this._map._container;o.DomEvent.off(t,"focus",this._onFocus,this).off(t,"blur",this._onBlur,this).off(t,"mousedown",this._onMouseDown,this),this._map.off("focus",this._addHooks,this).off("blur",this._removeHooks,this)},_onMouseDown:function(){if(!this._focused){var i=e.body,n=e.documentElement,o=i.scrollTop||n.scrollTop,s=i.scrollLeft||n.scrollLeft;this._map._container.focus(),t.scrollTo(s,o)}},_onFocus:function(){this._focused=!0,this._map.fire("focus")},_onBlur:function(){this._focused=!1,this._map.fire("blur")},_setPanOffset:function(t){var e,i,n=this._panKeys={},o=this.keyCodes;for(e=0,i=o.left.length;i>e;e++)n[o.left[e]]=[-1*t,0];for(e=0,i=o.right.length;i>e;e++)n[o.right[e]]=[t,0];for(e=0,i=o.down.length;i>e;e++)n[o.down[e]]=[0,t];for(e=0,i=o.up.length;i>e;e++)n[o.up[e]]=[0,-1*t]},_setZoomOffset:function(t){var e,i,n=this._zoomKeys={},o=this.keyCodes;for(e=0,i=o.zoomIn.length;i>e;e++)n[o.zoomIn[e]]=t;for(e=0,i=o.zoomOut.length;i>e;e++)n[o.zoomOut[e]]=-t},_addHooks:function(){o.DomEvent.on(e,"keydown",this._onKeyDown,this)},_removeHooks:function(){o.DomEvent.off(e,"keydown",this._onKeyDown,this)},_onKeyDown:function(t){var e=t.keyCode,i=this._map;if(e in this._panKeys){if(i._panAnim&&i._panAnim._inProgress)return;i.panBy(this._panKeys[e]),i.options.maxBounds&&i.panInsideBounds(i.options.maxBounds)}else{if(!(e in this._zoomKeys))return;i.setZoom(i.getZoom()+this._zoomKeys[e])}o.DomEvent.stop(t)}}),o.Map.addInitHook("addHandler","keyboard",o.Map.Keyboard),o.Handler.MarkerDrag=o.Handler.extend({initialize:function(t){this._marker=t},addHooks:function(){var t=this._marker._icon;this._draggable||(this._draggable=new o.Draggable(t,t)),this._draggable.on("dragstart",this._onDragStart,this).on("drag",this._onDrag,this).on("dragend",this._onDragEnd,this),this._draggable.enable(),o.DomUtil.addClass(this._marker._icon,"leaflet-marker-draggable")},removeHooks:function(){this._draggable.off("dragstart",this._onDragStart,this).off("drag",this._onDrag,this).off("dragend",this._onDragEnd,this),this._draggable.disable(),o.DomUtil.removeClass(this._marker._icon,"leaflet-marker-draggable")},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){this._marker.closePopup().fire("movestart").fire("dragstart")},_onDrag:function(){var t=this._marker,e=t._shadow,i=o.DomUtil.getPosition(t._icon),n=t._map.layerPointToLatLng(i);e&&o.DomUtil.setPosition(e,i),t._latlng=n,t.fire("move",{latlng:n}).fire("drag")},_onDragEnd:function(t){this._marker.fire("moveend").fire("dragend",t)}}),o.Control=o.Class.extend({options:{position:"topright"},initialize:function(t){o.setOptions(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var e=this._map;return e&&e.removeControl(this),this.options.position=t,e&&e.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this._map=t;var e=this._container=this.onAdd(t),i=this.getPosition(),n=t._controlCorners[i];return o.DomUtil.addClass(e,"leaflet-control"),-1!==i.indexOf("bottom")?n.insertBefore(e,n.firstChild):n.appendChild(e),this},removeFrom:function(t){var e=this.getPosition();return t._controlCorners[e].removeChild(this._container),this._map=null,this.onRemove&&this.onRemove(t),this},_refocusOnMap:function(){this._map&&this._map.getContainer().focus()}}),o.control=function(t){return new o.Control(t)},o.Map.include({addControl:function(t){return t.addTo(this),this},removeControl:function(t){return t.removeFrom(this),this},_initControlPos:function(){function t(t,s){var a=i+t+" "+i+s;e[t+s]=o.DomUtil.create("div",a,n)}var e=this._controlCorners={},i="leaflet-",n=this._controlContainer=o.DomUtil.create("div",i+"control-container",this._container);t("top","left"),t("top","right"),t("bottom","left"),t("bottom","right")},_clearControlPos:function(){this._container.removeChild(this._controlContainer)}}),o.Control.Zoom=o.Control.extend({options:{position:"topleft",zoomInText:"+",zoomInTitle:"Zoom in",zoomOutText:"-",zoomOutTitle:"Zoom out"},onAdd:function(t){var e="leaflet-control-zoom",i=o.DomUtil.create("div",e+" leaflet-bar");return this._map=t,this._zoomInButton=this._createButton(this.options.zoomInText,this.options.zoomInTitle,e+"-in",i,this._zoomIn,this),this._zoomOutButton=this._createButton(this.options.zoomOutText,this.options.zoomOutTitle,e+"-out",i,this._zoomOut,this),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),i},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},_zoomIn:function(t){this._map.zoomIn(t.shiftKey?3:1)},_zoomOut:function(t){this._map.zoomOut(t.shiftKey?3:1)},_createButton:function(t,e,i,n,s,a){var r=o.DomUtil.create("a",i,n);r.innerHTML=t,r.href="#",r.title=e;var h=o.DomEvent.stopPropagation;return o.DomEvent.on(r,"click",h).on(r,"mousedown",h).on(r,"dblclick",h).on(r,"click",o.DomEvent.preventDefault).on(r,"click",s,a).on(r,"click",this._refocusOnMap,a),r},_updateDisabled:function(){var t=this._map,e="leaflet-disabled";o.DomUtil.removeClass(this._zoomInButton,e),o.DomUtil.removeClass(this._zoomOutButton,e),t._zoom===t.getMinZoom()&&o.DomUtil.addClass(this._zoomOutButton,e),t._zoom===t.getMaxZoom()&&o.DomUtil.addClass(this._zoomInButton,e)}}),o.Map.mergeOptions({zoomControl:!0}),o.Map.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new o.Control.Zoom,this.addControl(this.zoomControl))}),o.control.zoom=function(t){return new o.Control.Zoom(t)},o.Control.Attribution=o.Control.extend({options:{position:"bottomright",prefix:'<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'},initialize:function(t){o.setOptions(this,t),this._attributions={}},onAdd:function(t){for(var e in this._container=o.DomUtil.create("div","leaflet-control-attribution"),o.DomEvent.disableClickPropagation(this._container),t._layers)t._layers[e].getAttribution&&this.addAttribution(t._layers[e].getAttribution());return t.on("layeradd",this._onLayerAdd,this).on("layerremove",this._onLayerRemove,this),this._update(),this._container},onRemove:function(t){t.off("layeradd",this._onLayerAdd).off("layerremove",this._onLayerRemove)},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t?(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update(),this):void 0},removeAttribution:function(t){return t?(this._attributions[t]&&(this._attributions[t]--,this._update()),this):void 0},_update:function(){if(this._map){var t=[];for(var e in this._attributions)this._attributions[e]&&t.push(e);var i=[];this.options.prefix&&i.push(this.options.prefix),t.length&&i.push(t.join(", ")),this._container.innerHTML=i.join(" | ")}},_onLayerAdd:function(t){t.layer.getAttribution&&this.addAttribution(t.layer.getAttribution())},_onLayerRemove:function(t){t.layer.getAttribution&&this.removeAttribution(t.layer.getAttribution())}}),o.Map.mergeOptions({attributionControl:!0}),o.Map.addInitHook(function(){this.options.attributionControl&&(this.attributionControl=(new o.Control.Attribution).addTo(this))}),o.control.attribution=function(t){return new o.Control.Attribution(t)},o.Control.Scale=o.Control.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0,updateWhenIdle:!1},onAdd:function(t){this._map=t;var e="leaflet-control-scale",i=o.DomUtil.create("div",e),n=this.options;return this._addScales(n,e,i),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),i},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,e,i){t.metric&&(this._mScale=o.DomUtil.create("div",e+"-line",i)),t.imperial&&(this._iScale=o.DomUtil.create("div",e+"-line",i))},_update:function(){var t=this._map.getBounds(),e=t.getCenter().lat,n=6378137*Math.PI*Math.cos(e*Math.PI/180)*(t.getNorthEast().lng-t.getSouthWest().lng)/180,o=this._map.getSize(),s=this.options,a=0;o.x>0&&(a=n*(s.maxWidth/o.x)),this._updateScales(s,a)},_updateScales:function(t,e){t.metric&&e&&this._updateMetric(e),t.imperial&&e&&this._updateImperial(e)},_updateMetric:function(t){var e=this._getRoundNum(t);this._mScale.style.width=this._getScaleWidth(e/t)+"px",this._mScale.innerHTML=1e3>e?e+" m":e/1e3+" km"},_updateImperial:function(t){var e,i,n,o=3.2808399*t,s=this._iScale;o>5280?(e=o/5280,i=this._getRoundNum(e),s.style.width=this._getScaleWidth(i/e)+"px",s.innerHTML=i+" mi"):(n=this._getRoundNum(o),s.style.width=this._getScaleWidth(n/o)+"px",s.innerHTML=n+" ft")},_getScaleWidth:function(t){return Math.round(this.options.maxWidth*t)-10},_getRoundNum:function(t){var e=Math.pow(10,(Math.floor(t)+"").length-1),i=t/e;return e*(i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:1)}}),o.control.scale=function(t){return new o.Control.Scale(t)},o.Control.Layers=o.Control.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0},initialize:function(t,e,i){for(var n in o.setOptions(this,i),this._layers={},this._lastZIndex=0,this._handlingClick=!1,t)this._addLayer(t[n],n);for(n in e)this._addLayer(e[n],n,!0)},onAdd:function(t){return this._initLayout(),this._update(),t.on("layeradd",this._onLayerChange,this).on("layerremove",this._onLayerChange,this),this._container},onRemove:function(t){t.off("layeradd",this._onLayerChange).off("layerremove",this._onLayerChange)},addBaseLayer:function(t,e){return this._addLayer(t,e),this._update(),this},addOverlay:function(t,e){return this._addLayer(t,e,!0),this._update(),this},removeLayer:function(t){var e=o.stamp(t);return delete this._layers[e],this._update(),this},_initLayout:function(){var t="leaflet-control-layers",e=this._container=o.DomUtil.create("div",t);e.setAttribute("aria-haspopup",!0),o.Browser.touch?o.DomEvent.on(e,"click",o.DomEvent.stopPropagation):o.DomEvent.disableClickPropagation(e).disableScrollPropagation(e);var i=this._form=o.DomUtil.create("form",t+"-list");if(this.options.collapsed){o.Browser.android||o.DomEvent.on(e,"mouseover",this._expand,this).on(e,"mouseout",this._collapse,this);var n=this._layersLink=o.DomUtil.create("a",t+"-toggle",e);n.href="#",n.title="Layers",o.Browser.touch?o.DomEvent.on(n,"click",o.DomEvent.stop).on(n,"click",this._expand,this):o.DomEvent.on(n,"focus",this._expand,this),o.DomEvent.on(i,"click",function(){setTimeout(o.bind(this._onInputClick,this),0)},this),this._map.on("click",this._collapse,this)}else this._expand();this._baseLayersList=o.DomUtil.create("div",t+"-base",i),this._separator=o.DomUtil.create("div",t+"-separator",i),this._overlaysList=o.DomUtil.create("div",t+"-overlays",i),e.appendChild(i)},_addLayer:function(t,e,i){var n=o.stamp(t);this._layers[n]={layer:t,name:e,overlay:i},this.options.autoZIndex&&t.setZIndex&&(this._lastZIndex++,t.setZIndex(this._lastZIndex))},_update:function(){if(this._container){this._baseLayersList.innerHTML="",this._overlaysList.innerHTML="";var t,e,i=!1,n=!1;for(t in this._layers)e=this._layers[t],this._addItem(e),n=n||e.overlay,i=i||!e.overlay;this._separator.style.display=n&&i?"":"none"}},_onLayerChange:function(t){var e=this._layers[o.stamp(t.layer)];if(e){this._handlingClick||this._update();var i=e.overlay?"layeradd"===t.type?"overlayadd":"overlayremove":"layeradd"===t.type?"baselayerchange":null;i&&this._map.fire(i,e)}},_createRadioElement:function(t,i){var n='<input type="radio" class="leaflet-control-layers-selector" name="'+t+'"';i&&(n+=' checked="checked"'),n+="/>";var o=e.createElement("div");return o.innerHTML=n,o.firstChild},_addItem:function(t){var i,n=e.createElement("label"),s=this._map.hasLayer(t.layer);t.overlay?((i=e.createElement("input")).type="checkbox",i.className="leaflet-control-layers-selector",i.defaultChecked=s):i=this._createRadioElement("leaflet-base-layers",s),i.layerId=o.stamp(t.layer),o.DomEvent.on(i,"click",this._onInputClick,this);var a=e.createElement("span");return a.innerHTML=" "+t.name,n.appendChild(i),n.appendChild(a),(t.overlay?this._overlaysList:this._baseLayersList).appendChild(n),n},_onInputClick:function(){var t,e,i,n=this._form.getElementsByTagName("input"),o=n.length;for(this._handlingClick=!0,t=0;o>t;t++)e=n[t],i=this._layers[e.layerId],e.checked&&!this._map.hasLayer(i.layer)?this._map.addLayer(i.layer):!e.checked&&this._map.hasLayer(i.layer)&&this._map.removeLayer(i.layer);this._handlingClick=!1,this._refocusOnMap()},_expand:function(){o.DomUtil.addClass(this._container,"leaflet-control-layers-expanded")},_collapse:function(){this._container.className=this._container.className.replace(" leaflet-control-layers-expanded","")}}),o.control.layers=function(t,e,i){return new o.Control.Layers(t,e,i)},o.PosAnimation=o.Class.extend({includes:o.Mixin.Events,run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._newPos=e,this.fire("start"),t.style[o.DomUtil.TRANSITION]="all "+(i||.25)+"s cubic-bezier(0,0,"+(n||.5)+",1)",o.DomEvent.on(t,o.DomUtil.TRANSITION_END,this._onTransitionEnd,this),o.DomUtil.setPosition(t,e),o.Util.falseFn(t.offsetWidth),this._stepTimer=setInterval(o.bind(this._onStep,this),50)},stop:function(){this._inProgress&&(o.DomUtil.setPosition(this._el,this._getPos()),this._onTransitionEnd(),o.Util.falseFn(this._el.offsetWidth))},_onStep:function(){var t=this._getPos();return t?(this._el._leaflet_pos=t,void this.fire("step")):void this._onTransitionEnd()},_transformRe:/([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,_getPos:function(){var e,i,n,s=this._el,a=t.getComputedStyle(s);if(o.Browser.any3d){if(!(n=a[o.DomUtil.TRANSFORM].match(this._transformRe)))return;e=parseFloat(n[1]),i=parseFloat(n[2])}else e=parseFloat(a.left),i=parseFloat(a.top);return new o.Point(e,i,!0)},_onTransitionEnd:function(){o.DomEvent.off(this._el,o.DomUtil.TRANSITION_END,this._onTransitionEnd,this),this._inProgress&&(this._inProgress=!1,this._el.style[o.DomUtil.TRANSITION]="",this._el._leaflet_pos=this._newPos,clearInterval(this._stepTimer),this.fire("step").fire("end"))}}),o.Map.include({setView:function(t,e,n){if((e=e===i?this._zoom:this._limitZoom(e),t=this._limitCenter(o.latLng(t),e,this.options.maxBounds),n=n||{},this._panAnim&&this._panAnim.stop(),this._loaded&&!n.reset&&!0!==n)&&(n.animate!==i&&(n.zoom=o.extend({animate:n.animate},n.zoom),n.pan=o.extend({animate:n.animate},n.pan)),this._zoom!==e?this._tryAnimatedZoom&&this._tryAnimatedZoom(t,e,n.zoom):this._tryAnimatedPan(t,n.pan)))return clearTimeout(this._sizeTimer),this;return this._resetView(t,e),this},panBy:function(t,e){if(e=e||{},!(t=o.point(t).round()).x&&!t.y)return this;if(this._panAnim||(this._panAnim=new o.PosAnimation,this._panAnim.on({step:this._onPanTransitionStep,end:this._onPanTransitionEnd},this)),e.noMoveStart||this.fire("movestart"),!1!==e.animate){o.DomUtil.addClass(this._mapPane,"leaflet-pan-anim");var i=this._getMapPanePos().subtract(t);this._panAnim.run(this._mapPane,i,e.duration||.25,e.easeLinearity)}else this._rawPanBy(t),this.fire("move").fire("moveend");return this},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){o.DomUtil.removeClass(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(t,e){var i=this._getCenterOffset(t)._floor();return!(!0!==(e&&e.animate)&&!this.getSize().contains(i))&&(this.panBy(i,e),!0)}}),o.PosAnimation=o.DomUtil.TRANSITION?o.PosAnimation:o.PosAnimation.extend({run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._duration=i||.25,this._easeOutPower=1/Math.max(n||.5,.2),this._startPos=o.DomUtil.getPosition(t),this._offset=e.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){this._inProgress&&(this._step(),this._complete())},_animate:function(){this._animId=o.Util.requestAnimFrame(this._animate,this),this._step()},_step:function(){var t=+new Date-this._startTime,e=1e3*this._duration;e>t?this._runFrame(this._easeOut(t/e)):(this._runFrame(1),this._complete())},_runFrame:function(t){var e=this._startPos.add(this._offset.multiplyBy(t));o.DomUtil.setPosition(this._el,e),this.fire("step")},_complete:function(){o.Util.cancelAnimFrame(this._animId),this._inProgress=!1,this.fire("end")},_easeOut:function(t){return 1-Math.pow(1-t,this._easeOutPower)}}),o.Map.mergeOptions({zoomAnimation:!0,zoomAnimationThreshold:4}),o.DomUtil.TRANSITION&&o.Map.addInitHook(function(){this._zoomAnimated=this.options.zoomAnimation&&o.DomUtil.TRANSITION&&o.Browser.any3d&&!o.Browser.android23&&!o.Browser.mobileOpera,this._zoomAnimated&&o.DomEvent.on(this._mapPane,o.DomUtil.TRANSITION_END,this._catchTransitionEnd,this)}),o.Map.include(o.DomUtil.TRANSITION?{_catchTransitionEnd:function(t){this._animatingZoom&&t.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(t,e,i){if(this._animatingZoom)return!0;if(i=i||{},!this._zoomAnimated||!1===i.animate||this._nothingToAnimate()||Math.abs(e-this._zoom)>this.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(e),o=this._getCenterOffset(t)._divideBy(1-1/n),s=this._getCenterLayerPoint()._add(o);return!(!0!==i.animate&&!this.getSize().contains(o))&&(this.fire("movestart").fire("zoomstart"),this._animateZoom(t,e,s,n,null,!0),!0)},_animateZoom:function(t,e,i,n,s,a){this._animatingZoom=!0,o.DomUtil.addClass(this._mapPane,"leaflet-zoom-anim"),this._animateToCenter=t,this._animateToZoom=e,o.Draggable&&(o.Draggable._disabled=!0),this.fire("zoomanim",{center:t,zoom:e,origin:i,scale:n,delta:s,backwards:a})},_onZoomTransitionEnd:function(){this._animatingZoom=!1,o.DomUtil.removeClass(this._mapPane,"leaflet-zoom-anim"),this._resetView(this._animateToCenter,this._animateToZoom,!0,!0),o.Draggable&&(o.Draggable._disabled=!1)}}:{}),o.TileLayer.include({_animateZoom:function(t){this._animating||(this._animating=!0,this._prepareBgBuffer());var e=this._bgBuffer,i=o.DomUtil.TRANSFORM,n=t.delta?o.DomUtil.getTranslateString(t.delta):e.style[i],s=o.DomUtil.getScaleString(t.scale,t.origin);e.style[i]=t.backwards?s+" "+n:n+" "+s},_endZoomAnim:function(){var t=this._tileContainer,e=this._bgBuffer;t.style.visibility="",t.parentNode.appendChild(t),o.Util.falseFn(e.offsetWidth),this._animating=!1},_clearBgBuffer:function(){var t=this._map;!t||t._animatingZoom||t.touchZoom._zooming||(this._bgBuffer.innerHTML="",this._bgBuffer.style[o.DomUtil.TRANSFORM]="")},_prepareBgBuffer:function(){var t=this._tileContainer,e=this._bgBuffer,i=this._getLoadedTilesPercentage(e),n=this._getLoadedTilesPercentage(t);return e&&i>.5&&.5>n?(t.style.visibility="hidden",void this._stopLoadingImages(t)):(e.style.visibility="hidden",e.style[o.DomUtil.TRANSFORM]="",this._tileContainer=e,e=this._bgBuffer=t,this._stopLoadingImages(e),void clearTimeout(this._clearBgBufferTimer))},_getLoadedTilesPercentage:function(t){var e,i,n=t.getElementsByTagName("img"),o=0;for(e=0,i=n.length;i>e;e++)n[e].complete&&o++;return o/i},_stopLoadingImages:function(t){var e,i,n,s=Array.prototype.slice.call(t.getElementsByTagName("img"));for(e=0,i=s.length;i>e;e++)(n=s[e]).complete||(n.onload=o.Util.falseFn,n.onerror=o.Util.falseFn,n.src=o.Util.emptyImageUrl,n.parentNode.removeChild(n))}}),o.Map.include({_defaultLocateOptions:{watch:!1,setView:!1,maxZoom:1/0,timeout:1e4,maximumAge:0,enableHighAccuracy:!1},locate:function(t){if(t=this._locateOptions=o.extend(this._defaultLocateOptions,t),!navigator.geolocation)return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var e=o.bind(this._handleGeolocationResponse,this),i=o.bind(this._handleGeolocationError,this);return t.watch?this._locationWatchId=navigator.geolocation.watchPosition(e,i,t):navigator.geolocation.getCurrentPosition(e,i,t),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(t){var e=t.code,i=t.message||(1===e?"permission denied":2===e?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:e,message:"Geolocation error: "+i+"."})},_handleGeolocationResponse:function(t){var e=t.coords.latitude,i=t.coords.longitude,n=new o.LatLng(e,i),s=180*t.coords.accuracy/40075017,a=s/Math.cos(o.LatLng.DEG_TO_RAD*e),r=o.latLngBounds([e-s,i-a],[e+s,i+a]),h=this._locateOptions;if(h.setView){var l=Math.min(this.getBoundsZoom(r),h.maxZoom);this.setView(n,l)}var u={latlng:n,bounds:r,timestamp:t.timestamp};for(var c in t.coords)"number"==typeof t.coords[c]&&(u[c]=t.coords[c]);this.fire("locationfound",u)}})}(window,document),function(a){function b(a,b){for(var c,d=b=b||window,e=a.split(".");c=e.shift();)d[c]||(d[c]={}),d=d[c];return d}b("L.esri.Services.Geocoding"),b("L.esri.Controls.Geosearch"),a.esri.Services.Geocoding=a.Class.extend({includes:a.Mixin.Events,options:{url:"https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/",outFields:"Subregion, Region, PlaceName, Match_addr, Country, Addr_type, City, Place_addr"},initialize:function(b){a.Util.setOptions(this,b)},request:function(b,d,e){var f="c"+(1e9*Math.random()).toString(36).replace(".","_");d.f="json",d.callback="L.esri.Services.Geocoding._callback."+f;var g=document.createElement("script");g.type="text/javascript",g.src=b+function(a){var b="?";for(var c in a)if(a.hasOwnProperty(c)){var d=c,e=a[c];b+=encodeURIComponent(d),b+="=",b+=encodeURIComponent(e),b+="&"}return b.substring(0,b.length-1)}(d),g.id=f,this.fire("loading"),a.esri.Services.Geocoding._callback[f]=a.Util.bind(function(b){this.fire("load"),e(b),document.body.removeChild(g),delete a.esri.Services.Geocoding._callback[f]},this),document.body.appendChild(g)},geocode:function(b,c,d){var e={outFields:this.options.outFields},f=a.extend(e,c);f.text=b,this.request(this.options.url+"find",f,d)},suggest:function(a,b,c){var d=b||{};d.text=a,this.request(this.options.url+"suggest",d,c)}}),a.esri.Services.geocoding=function(b){return new a.esri.Services.Geocoding(b)},a.esri.Services.Geocoding._callback={},a.esri.Controls.Geosearch=a.Control.extend({includes:a.Mixin.Events,options:{position:"topleft",zoomToResult:!0,useMapBounds:11,collapseAfterResult:!0,expanded:!1,maxResults:25},initialize:function(b){a.Util.setOptions(this,b),this._service=new a.esri.Services.Geocoding},_processMatch:function(b,c){var e=c.feature.attributes,f=function(b){var c=new a.LatLng(b.ymin,b.xmin),d=new a.LatLng(b.ymax,b.xmax);return new a.LatLngBounds(c,d)}(c.extent);return{text:b,bounds:f,latlng:new a.LatLng(c.feature.geometry.y,c.feature.geometry.x),name:e.PlaceName,match:e.Addr_type,country:e.Country,region:e.Region,subregion:e.Subregion,city:e.City,address:e.Place_addr?e.Place_addr:e.Match_addr}},_geocode:function(b,c){var d={};if(c)d.magicKey=c;else{var e=this._map.getBounds(),f=e.getCenter(),g=e.getNorthWest();d.bbox=e.toBBoxString(),d.maxLocations=this.options.maxResults,d.location=f.lng+","+f.lat,d.distance=Math.min(Math.max(f.distanceTo(g),2e3),5e4)}a.DomUtil.addClass(this._input,"geocoder-control-loading"),this.fire("loading"),this._service.geocode(b,d,a.Util.bind(function(c){if(c.error)this.fire("error",{code:c.error.code,message:c.error.messsage});else if(c.locations.length){var d,e=[],f=new a.LatLngBounds;for(d=c.locations.length-1;d>=0;d--)e.push(this._processMatch(b,c.locations[d]));for(d=e.length-1;d>=0;d--)f.extend(e[d].bounds);this.fire("results",{results:e,bounds:f,latlng:f.getCenter()}),this.options.zoomToResult&&this._map.fitBounds(f)}else this.fire("results",{results:[],bounds:null,latlng:null,text:b});a.DomUtil.removeClass(this._input,"geocoder-control-loading"),this.fire("load"),this.clear(),this._input.blur()},this))},_suggest:function(b){a.DomUtil.addClass(this._input,"geocoder-control-loading");var c={};if(!0===this.options.useMapBounds||this._map.getZoom()>=this.options.useMapBounds){var d=this._map.getBounds(),e=d.getCenter(),f=d.getNorthWest();c.location=e.lng+","+e.lat,c.distance=Math.min(Math.max(e.distanceTo(f),2e3),5e4)}this._service.suggest(b,c,a.Util.bind(function(b){if(this._input.value){if(this._suggestions.innerHTML="",this._suggestions.style.display="none",b.suggestions){this._suggestions.style.display="block";for(var c=0;c<b.suggestions.length;c++){var d=a.DomUtil.create("li","geocoder-control-suggestion",this._suggestions);d.innerHTML=b.suggestions[c].text,d["data-magic-key"]=b.suggestions[c].magicKey}}a.DomUtil.removeClass(this._input,"geocoder-control-loading")}},this))},clear:function(){this._suggestions.innerHTML="",this._suggestions.style.display="none",this._input.value="",this.options.collapseAfterResult&&a.DomUtil.removeClass(this._container,"geocoder-control-expanded")},onAdd:function(b){return this._map=b,b.attributionControl?b.attributionControl.addAttribution("Geocoding by Esri"):a.control.attribution().addAttribution("Geocoding by Esri").addTo(b),this._container=a.DomUtil.create("div","geocoder-control"+(this.options.expanded?" geocoder-control-expanded":"")),this._input=a.DomUtil.create("input","geocoder-control-input leaflet-bar",this._container),this._suggestions=a.DomUtil.create("ul","geocoder-control-suggestions leaflet-bar",this._container),a.DomEvent.addListener(this._input,"focus",function(){a.DomUtil.addClass(this._container,"geocoder-control-expanded")},this),a.DomEvent.addListener(this._container,"click",function(){a.DomUtil.addClass(this._container,"geocoder-control-expanded"),this._input.focus()},this),a.DomEvent.addListener(this._suggestions,"mousedown",function(a){var b=a.target||a.srcElement;this._geocode(b.innerHTML,b["data-magic-key"]),this.clear()},this),a.DomEvent.addListener(this._input,"blur",function(){this.clear()},this),a.DomEvent.addListener(this._input,"keydown",function(b){var c=this._suggestions.querySelectorAll(".geocoder-control-selected")[0];switch(b.keyCode){case 13:c?(this._geocode(c.innerHTML,c["data-magic-key"]),this.clear()):this.options.allowMultipleResults?this._geocode(this._input.value):a.DomUtil.addClass(this._suggestions.childNodes[0],"geocoder-control-selected"),this.clear(),a.DomEvent.preventDefault(b);break;case 38:c&&a.DomUtil.removeClass(c,"geocoder-control-selected"),c&&c.previousSibling?a.DomUtil.addClass(c.previousSibling,"geocoder-control-selected"):a.DomUtil.addClass(this._suggestions.childNodes[this._suggestions.childNodes.length-1],"geocoder-control-selected"),a.DomEvent.preventDefault(b);break;case 40:c&&a.DomUtil.removeClass(c,"geocoder-control-selected"),c&&c.nextSibling?a.DomUtil.addClass(c.nextSibling,"geocoder-control-selected"):a.DomUtil.addClass(this._suggestions.childNodes[0],"geocoder-control-selected"),a.DomEvent.preventDefault(b)}},this),a.DomEvent.addListener(this._input,"keyup",function(a){var b=a.which||a.keyCode,c=(a.target||a.srcElement).value;return c.length<2?void 0:27===b?(this._suggestions.innerHTML="",void(this._suggestions.style.display="none")):void(13!==b&&38!==b&&40!==b&&this._suggest(c))},this),a.DomEvent.disableClickPropagation(this._container),this._container},onRemove:function(a){a.attributionControl.removeAttribution("Geocoding by Esri")}}),a.esri.Controls.geosearch=function(b){return new a.esri.Controls.Geosearch(b)}}(L),function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(t){"use strict";t.Zebra_DatePicker=function(e,s){var i,n,a,r,o,d,c,l,h,_,g,u,f,p,b,y,v,m,w,k,D,A,M,F,C,Y,P,S,Z,x,z,I,N,O,W,j,T,J,L,H={always_visible:!1,container:t("body"),custom_classes:!1,days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],days_abbr:!1,default_position:"above",direction:0,disabled_dates:!1,enabled_dates:!1,first_day_of_week:1,format:"Y-m-d",header_captions:{days:"F, Y",months:"Y",years:"Y1 - Y2"},header_navigation:["&#171;","&#187;"],icon_position:"right",inside:!0,lang_clear_date:"Clear date",months:["January","February","March","April","May","June","July","August","September","October","November","December"],months_abbr:!1,offset:[5,-5],open_icon_only:!1,pair:!1,readonly_element:!0,select_other_months:!1,show_clear_date:0,show_icon:!0,show_other_months:!0,show_select_today:"Today",show_week_number:!1,start_date:!1,strict:!1,view:"days",weekend_days:[0,6],zero_pad:!1,onChange:null,onClear:null,onOpen:null,onClose:null,onSelect:null},V={},$=this;$.settings={};var q=t(e),E=function(e){var A,S,Z,x,E={days:["d","j","D"],months:["F","m","M","n","t"],years:["o","Y","y"]},Q=!1,U=!1,X=!1,G=null;if(T=Math.floor(65536*(1+Math.random())).toString(16),!e)for(A in $.settings=t.extend({},H,s),V.readonly=q.attr("readonly"),V.style=q.attr("style"),q.data())0===A.indexOf("zdp_")&&(A=A.replace(/^zdp\_/,""),void 0!==H[A]&&($.settings[A]="pair"===A?t(q.data("zdp_"+A)):q.data("zdp_"+A)));for(G in $.settings.readonly_element&&q.attr("readonly","readonly"),E)t.each(E[G],function(t,e){$.settings.format.indexOf(e)>-1&&("days"===G?Q=!0:"months"===G?U=!0:"years"===G&&(X=!0))});for(Z in z=Q&&U&&X?["years","months","days"]:!Q&&U&&X?["years","months"]:Q&&U&&!X?["months","days"]:Q||U||!X?Q||!U||X?["years","months","days"]:["months"]:["years"],-1===t.inArray($.settings.view,z)&&($.settings.view=z[z.length-1]),D=[],k=[],J={},L=[],$.settings.custom_classes)$.settings.custom_classes.hasOwnProperty(Z)&&L.push(Z);for(x=0;x<2+L.length;x++)S=0===x?$.settings.disabled_dates:1===x?$.settings.enabled_dates:$.settings.custom_classes[L[x-2]],t.isArray(S)&&S.length>0&&t.each(S,function(){var e,s,i,n,a=this.split(" ");for(e=0;e<4;e++){for(a[e]||(a[e]="*"),a[e]=a[e].indexOf(",")>-1?a[e].split(","):new Array(a[e]),s=0;s<a[e].length;s++)if(a[e][s].indexOf("-")>-1&&null!==(n=a[e][s].match(/^([0-9]+)\-([0-9]+)/))){for(i=ct(n[1]);i<=ct(n[2]);i++)-1===t.inArray(i,a[e])&&a[e].push(i+"");a[e].splice(s,1)}for(s=0;s<a[e].length;s++)a[e][s]=isNaN(ct(a[e][s]))?a[e][s]:ct(a[e][s])}0===x?D.push(a):1===x?k.push(a):(void 0===J[L[x-2]]&&(J[L[x-2]]=[]),J[L[x-2]].push(a))});var K,tt,et=new Date,nt=$.settings.reference_date?$.settings.reference_date:q.data("zdp_reference_date")&&void 0!==q.data("zdp_reference_date")?q.data("zdp_reference_date"):et;if(M=void 0,F=void 0,u=nt.getMonth(),h=et.getMonth(),f=nt.getFullYear(),_=et.getFullYear(),p=nt.getDate(),g=et.getDate(),!0===$.settings.direction)M=nt;else if(!1===$.settings.direction)P=(F=nt).getMonth(),Y=F.getFullYear(),C=F.getDate();else if(!t.isArray($.settings.direction)&&it($.settings.direction)&&ct($.settings.direction)>0||t.isArray($.settings.direction)&&((K=R($.settings.direction[0]))||!0===$.settings.direction[0]||it($.settings.direction[0])&&$.settings.direction[0]>0)&&((tt=R($.settings.direction[1]))||!1===$.settings.direction[1]||it($.settings.direction[1])&&$.settings.direction[1]>=0))M=K||new Date(f,u,p+ct(t.isArray($.settings.direction)?!0===$.settings.direction[0]?0:$.settings.direction[0]:$.settings.direction)),u=M.getMonth(),f=M.getFullYear(),p=M.getDate(),tt&&+tt>=+M?F=tt:!tt&&!1!==$.settings.direction[1]&&t.isArray($.settings.direction)&&(F=new Date(f,u,p+ct($.settings.direction[1]))),F&&(P=F.getMonth(),Y=F.getFullYear(),C=F.getDate());else if(!t.isArray($.settings.direction)&&it($.settings.direction)&&ct($.settings.direction)<0||t.isArray($.settings.direction)&&(!1===$.settings.direction[0]||it($.settings.direction[0])&&$.settings.direction[0]<0)&&((K=R($.settings.direction[1]))||it($.settings.direction[1])&&$.settings.direction[1]>=0))F=new Date(f,u,p+ct(t.isArray($.settings.direction)?!1===$.settings.direction[0]?0:$.settings.direction[0]:$.settings.direction)),P=F.getMonth(),Y=F.getFullYear(),C=F.getDate(),K&&+K<+F?M=K:!K&&t.isArray($.settings.direction)&&(M=new Date(Y,P,C-ct($.settings.direction[1]))),M&&(u=M.getMonth(),f=M.getFullYear(),p=M.getDate());else if(t.isArray($.settings.disabled_dates)&&$.settings.disabled_dates.length>0)for(var ot in D)if("*"===D[ot][0]&&"*"===D[ot][1]&&"*"===D[ot][2]&&"*"===D[ot][3]){var ht=[];if(t.each(k,function(){var t=this;"*"!==t[2][0]&&ht.push(parseInt(t[2][0]+("*"===t[1][0]?"12":dt(t[1][0],2))+("*"===t[0][0]?"*"===t[1][0]?"31":new Date(t[2][0],t[1][0],0).getDate():dt(t[0][0],2)),10))}),ht.sort(),ht.length>0){var gt=(ht[0]+"").match(/([0-9]{4})([0-9]{2})([0-9]{2})/);f=parseInt(gt[1],10),u=parseInt(gt[2],10)-1,p=parseInt(gt[3],10)}break}if(st(f,u,p)){for(;st(f);)M?(f++,u=0):(f--,u=11);for(;st(f,u);)M?(u++,p=1):(u--,p=new Date(f,u+1,0).getDate()),u>11?(f++,u=0,p=1):u<0&&(f--,u=11,p=new Date(f,u+1,0).getDate());for(;st(f,u,p);)M?p++:p--,et=new Date(f,u,p),f=et.getFullYear(),u=et.getMonth(),p=et.getDate();et=new Date(f,u,p),f=et.getFullYear(),u=et.getMonth(),p=et.getDate()}var ut=R(q.val()||($.settings.start_date?$.settings.start_date:""));if(ut&&$.settings.strict&&st(ut.getFullYear(),ut.getMonth(),ut.getDate())&&q.val(""),e||void 0===M&&void 0===ut||lt(void 0!==ut?ut:M),!$.settings.always_visible){if(!e){if($.settings.show_icon){"firefox"===_t.name&&q.is('input[type="text"]')&&"inline"===q.css("display")&&q.css("display","inline-block");var ft=t('<span class="Zebra_DatePicker_Icon_Wrapper"></span>').css({display:q.css("display"),position:"static"===q.css("position")?"relative":q.css("position"),float:q.css("float"),top:q.css("top"),right:q.css("right"),bottom:q.css("bottom"),left:q.css("left")});"block"===q.css("display")&&ft.css("width",q.outerWidth(!0)),q.wrap(ft).css({position:"relative",top:"auto",right:"auto",bottom:"auto",left:"auto"}),a=t('<button type="button" class="Zebra_DatePicker_Icon'+("disabled"===q.attr("disabled")?" Zebra_DatePicker_Icon_Disabled":"")+'">Pick a date</button>'),$.icon=a,I=$.settings.open_icon_only?a:a.add(q)}else I=q;I.on("click.Zebra_DatePicker_"+T,function(t){t.preventDefault(),q.attr("disabled")||(n.hasClass("dp_visible")?$.hide():$.show())}),!$.settings.readonly_element&&$.settings.pair&&q.on("blur.Zebra_DatePicker_"+T,function(){var e;(e=R(t(this).val()))&&!st(e.getFullYear(),e.getMonth(),e.getDate())&&lt(e)}),void 0!==a&&a.insertAfter(q)}if(void 0!==a){a.attr("style",""),$.settings.inside&&a.addClass("Zebra_DatePicker_Icon_Inside_"+("right"===$.settings.icon_position?"Right":"Left"));var pt=q.outerWidth(),bt=q.outerHeight(),yt=parseInt(q.css("marginLeft"),10)||0,vt=parseInt(q.css("marginTop"),10)||0,mt=(a.outerWidth(),a.outerHeight()),wt=parseInt(a.css("marginLeft"),10)||0;parseInt(a.css("marginRight"),10),$.settings.inside?(a.css("top",vt+(bt-mt)/2),"right"===$.settings.icon_position?a.css("right",0):a.css("left",0)):a.css({top:vt+(bt-mt)/2,left:yt+pt+wt}),a.removeClass(" Zebra_DatePicker_Icon_Disabled"),"disabled"===q.attr("disabled")&&a.addClass("Zebra_DatePicker_Icon_Disabled")}}if(W=!1!==$.settings.show_select_today&&t.inArray("days",z)>-1&&!st(_,h,g)&&$.settings.show_select_today,e)return t(".dp_previous",n).html($.settings.header_navigation[0]),t(".dp_next",n).html($.settings.header_navigation[1]),t(".dp_clear",n).html($.settings.lang_clear_date),void t(".dp_today",n).html($.settings.show_select_today);t(window).on("resize.Zebra_DatePicker_"+T+", orientationchange.Zebra_DatePicker_"+T,function(){$.hide(),void 0!==a&&(clearTimeout(j),j=setTimeout(function(){$.update()},100))});var kt='<div class="Zebra_DatePicker"><table class="dp_header"><tr><td class="dp_previous">'+$.settings.header_navigation[0]+'</td><td class="dp_caption">&#032;</td><td class="dp_next">'+$.settings.header_navigation[1]+'</td></tr></table><table class="dp_daypicker"></table><table class="dp_monthpicker"></table><table class="dp_yearpicker"></table><table class="dp_footer"><tr><td class="dp_today"'+(!1!==$.settings.show_clear_date?' style="width:50%"':"")+">"+W+'</td><td class="dp_clear"'+(!1!==W?' style="width:50%"':"")+">"+$.settings.lang_clear_date+"</td></tr></table></div>";n=t(kt),$.datepicker=n,r=t("table.dp_header",n),o=t("table.dp_daypicker",n),d=t("table.dp_monthpicker",n),c=t("table.dp_yearpicker",n),O=t("table.dp_footer",n),N=t("td.dp_today",O),l=t("td.dp_clear",O),$.settings.always_visible?q.attr("disabled")||($.settings.always_visible.append(n),$.show()):$.settings.container.append(n),n.delegate("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month, .dp_week_number)","mouseover",function(){t(this).addClass("dp_hover")}).delegate("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month, .dp_week_number)","mouseout",function(){t(this).removeClass("dp_hover")}),B(t("td",r)),t(".dp_previous",r).on("click",function(){"months"===i?y--:"years"===i?y-=12:--b<0&&(b=11,y--),at()}),t(".dp_caption",r).on("click",function(){i="days"===i?t.inArray("months",z)>-1?"months":t.inArray("years",z)>-1?"years":"days":"months"===i?t.inArray("years",z)>-1?"years":t.inArray("days",z)>-1?"days":"months":t.inArray("days",z)>-1?"days":t.inArray("months",z)>-1?"months":"years",at()}),t(".dp_next",r).on("click",function(){"months"===i?y++:"years"===i?y+=12:12==++b&&(b=0,y++),at()}),o.delegate("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month, .dp_week_number)","click",function(){var e;$.settings.select_other_months&&t(this).attr("class")&&null!==(e=t(this).attr("class").match(/date\_([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])/))?rt(e[1],e[2]-1,e[3],"days",t(this)):rt(y,b,ct(t(this).html()),"days",t(this))}),d.delegate("td:not(.dp_disabled)","click",function(){var e=t(this).attr("class").match(/dp\_month\_([0-9]+)/);b=ct(e[1]),-1===t.inArray("days",z)?rt(y,b,1,"months",t(this)):(i="days",$.settings.always_visible&&q.val(""),at())}),c.delegate("td:not(.dp_disabled)","click",function(){y=ct(t(this).html()),-1===t.inArray("months",z)?rt(y,1,1,"years",t(this)):(i="months",$.settings.always_visible&&q.val(""),at())}),t(N).on("click",function(e){e.preventDefault(),rt(_,h,g,"days",t(".dp_current",o)),$.settings.always_visible&&$.show(),$.hide()}),t(l).on("click",function(e){e.preventDefault(),q.val(""),$.settings.always_visible?(v=null,m=null,w=null,t("td.dp_selected",n).removeClass("dp_selected")):(v=null,m=null,w=null,b=null,y=null),$.hide(),$.settings.onClear&&"function"==typeof $.settings.onClear&&$.settings.onClear.call(q,q)}),$.settings.always_visible||(t(document).on("mousedown.Zebra_DatePicker_"+T+", touchstart.Zebra_DatePicker_"+T,function(e){if(n.hasClass("dp_visible")){if($.settings.show_icon&&t(e.target).get(0)===a.get(0))return!0;0===t(e.target).parents().filter(".Zebra_DatePicker").length&&$.hide()}}),t(document).on("keyup.Zebra_DatePicker_"+T,function(t){n.hasClass("dp_visible")&&27===t.which&&$.hide()})),at()};$.clear_date=function(){t(l).trigger("click")},$.destroy=function(){void 0!==$.icon&&$.icon.remove(),$.datepicker.remove(),$.settings.show_icon&&!$.settings.always_visible&&q.unwrap(),q.off("click.Zebra_DatePicker_"+T),q.off("blur.Zebra_DatePicker_"+T),t(document).off("keyup.Zebra_DatePicker_"+T),t(document).off("mousedown.Zebra_DatePicker_"+T),t(window).off("resize.Zebra_DatePicker_"+T),t(window).off("orientationchange.Zebra_DatePicker_"+T),q.removeData("Zebra_DatePicker"),q.attr("readonly",V.readonly),q.attr("style",V.style?V.style:"")},$.hide=function(){$.settings.always_visible||(et("hide"),n.removeClass("dp_visible").addClass("dp_hidden"),$.settings.onClose&&"function"==typeof $.settings.onClose&&$.settings.onClose.call(q,q))},$.set_date=function(t){var e;(e=R(t))&&!st(e.getFullYear(),e.getMonth(),e.getDate())&&(q.val(t),lt(e))},$.show=function(){i=$.settings.view;var e=R(q.val()||($.settings.start_date?$.settings.start_date:""));if(e?(m=e.getMonth(),b=e.getMonth(),w=e.getFullYear(),y=e.getFullYear(),v=e.getDate(),st(w,m,v)&&($.settings.strict&&q.val(""),b=u,y=f)):(b=u,y=f),at(),$.settings.always_visible)n.removeClass("dp_hidden").addClass("dp_visible");else{if($.settings.container.is("body")){var s=n.outerWidth(),r=n.outerHeight(),o=(void 0!==a?a.offset().left+a.outerWidth(!0):q.offset().left+q.outerWidth(!0))+$.settings.offset[0],d=(void 0!==a?a.offset().top:q.offset().top)-r+$.settings.offset[1],c=t(window).width(),l=t(window).height(),h=t(window).scrollTop(),_=t(window).scrollLeft();"below"===$.settings.default_position&&(d=(void 0!==a?a.offset().top:q.offset().top)+$.settings.offset[1]),o+s>_+c&&(o=_+c-s),o<_&&(o=_),d+r>h+l&&(d=h+l-r),d<h&&(d=h),n.css({left:o,top:d})}else n.css({left:0,top:0});n.removeClass("dp_hidden").addClass("dp_visible"),et()}$.settings.onOpen&&"function"==typeof $.settings.onOpen&&$.settings.onOpen.call(q,q)},$.update=function(e){$.original_direction&&($.original_direction=$.direction),$.settings=t.extend($.settings,e),E(!0)};var R=function(e){if(e+="",""!==t.trim(e)){for(var s=Q($.settings.format),i=["d","D","j","l","N","S","w","F","m","M","n","Y","y"],n=[],a=[],r=null,o=null,d=0;d<i.length;d++)(r=s.indexOf(i[d]))>-1&&n.push({character:i[d],position:r});if(n.sort(function(t,e){return t.position-e.position}),t.each(n,function(t,e){switch(e.character){case"d":a.push("0[1-9]|[12][0-9]|3[01]");break;case"D":case"M":a.push("[a-z]{3}");break;case"j":a.push("[1-9]|[12][0-9]|3[01]");break;case"l":case"F":a.push("[a-z]+");break;case"N":a.push("[1-7]");break;case"S":a.push("st|nd|rd|th");break;case"w":a.push("[0-6]");break;case"m":a.push("0[1-9]|1[012]+");break;case"n":a.push("[1-9]|1[012]");break;case"Y":a.push("[0-9]{4}");break;case"y":a.push("[0-9]{2}")}}),a.length&&(n.reverse(),t.each(n,function(t,e){s=s.replace(e.character,"("+a[a.length-t-1]+")")}),a=new RegExp("^"+s+"$","ig"),o=a.exec(e))){var c,l=new Date,h=1,_=l.getMonth()+1,g=l.getFullYear(),u=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],f=["January","February","March","April","May","June","July","August","September","October","November","December"],p=!0;if(n.reverse(),t.each(n,function(e,s){if(!p)return!0;switch(s.character){case"m":case"n":_=ct(o[e+1]);break;case"d":case"j":h=ct(o[e+1]);break;case"D":case"l":case"F":case"M":c="D"===s.character||"l"===s.character?$.settings.days:$.settings.months,p=!1,t.each(c,function(t,i){if(p)return!0;if(o[e+1].toLowerCase()===i.substring(0,"D"===s.character||"M"===s.character?3:i.length).toLowerCase()){switch(s.character){case"D":o[e+1]=u[t].substring(0,3);break;case"l":o[e+1]=u[t];break;case"F":o[e+1]=f[t],_=t+1;break;case"M":o[e+1]=f[t].substring(0,3),_=t+1}p=!0}});break;case"Y":g=ct(o[e+1]);break;case"y":g="19"+ct(o[e+1])}}),p){var b=new Date(g,(_||1)-1,h||1);if(b.getFullYear()===g&&b.getDate()===(h||1)&&b.getMonth()===(_||1)-1)return b}}return!1}},B=function(t){"firefox"===_t.name?t.css("MozUserSelect","none"):"explorer"===_t.name?t.on("selectstart",function(){return!1}):t.mousedown(function(){return!1})},Q=function(t){return t.replace(/([-.,*+?^${}()|[\]\/\\])/g,"\\$1")},U=function(e){var s,i,n="",a=e.getDate(),r=e.getDay(),o=$.settings.days[r],d=e.getMonth()+1,c=$.settings.months[d-1],l=e.getFullYear()+"";for(s=0;s<$.settings.format.length;s++)switch(i=$.settings.format.charAt(s)){case"y":l=l.substr(2);case"Y":n+=l;break;case"m":d=dt(d,2);case"n":n+=d;break;case"M":c=t.isArray($.settings.months_abbr)&&void 0!==$.settings.months_abbr[d-1]?$.settings.months_abbr[d-1]:$.settings.months[d-1].substr(0,3);case"F":n+=c;break;case"d":a=dt(a,2);case"j":n+=a;break;case"D":o=t.isArray($.settings.days_abbr)&&void 0!==$.settings.days_abbr[r]?$.settings.days_abbr[r]:$.settings.days[r].substr(0,3);case"l":n+=o;break;case"N":r++;case"w":n+=r;break;case"S":n+=a%10==1&&"11"!==a?"st":a%10==2&&"12"!==a?"nd":a%10==3&&"13"!==a?"rd":"th";break;default:n+=i}return n},X=function(){var e,s,i,n,a,r,d,c,l,u,f=new Date(y,b+1,0).getDate(),p=new Date(y,b,1).getDay(),k=new Date(y,b,0).getDate(),D=p-$.settings.first_day_of_week;for(D=D<0?7+D:D,nt($.settings.header_captions.days),s="<tr>",$.settings.show_week_number&&(s+="<th>"+$.settings.show_week_number+"</th>"),e=0;e<7;e++)s+="<th>"+(t.isArray($.settings.days_abbr)&&void 0!==$.settings.days_abbr[($.settings.first_day_of_week+e)%7]?$.settings.days_abbr[($.settings.first_day_of_week+e)%7]:$.settings.days[($.settings.first_day_of_week+e)%7].substr(0,2))+"</th>";for(s+="</tr><tr>",e=0;e<42;e++)e>0&&e%7==0&&(s+="</tr><tr>"),e%7==0&&$.settings.show_week_number&&(s+='<td class="dp_week_number">'+ht(new Date(y,b,e-D+1))+"</td>"),i=e-D+1,$.settings.select_other_months&&(e<D||i>f)&&(a=(n=new Date(y,b,i)).getFullYear(),r=n.getMonth(),d=n.getDate(),n=a+dt(r+1,2)+dt(d,2)),e<D?s+='<td class="'+($.settings.select_other_months&&!st(a,r,d)?"dp_not_in_month_selectable date_"+n:"dp_not_in_month")+'">'+($.settings.select_other_months||$.settings.show_other_months?dt(k-D+e+1,$.settings.zero_pad?2:0):"&nbsp;")+"</td>":i>f?s+='<td class="'+($.settings.select_other_months&&!st(a,r,d)?"dp_not_in_month_selectable date_"+n:"dp_not_in_month")+'">'+($.settings.select_other_months||$.settings.show_other_months?dt(i-f,$.settings.zero_pad?2:0):"&nbsp;")+"</td>":(c=($.settings.first_day_of_week+e)%7,l="",u=tt(y,b,i),st(y,b,i)?(t.inArray(c,$.settings.weekend_days)>-1?l="dp_weekend_disabled":l+=" dp_disabled",b===h&&y===_&&g===i&&(l+=" dp_disabled_current"),""!==u&&(l+=" "+u+"_disabled")):(t.inArray(c,$.settings.weekend_days)>-1&&(l="dp_weekend"),b===m&&y===w&&v===i&&(l+=" dp_selected"),b===h&&y===_&&g===i&&(l+=" dp_current"),""!==u&&(l+=" "+u)),s+="<td"+(""!==l?' class="'+t.trim(l)+'"':"")+">"+(($.settings.zero_pad?dt(i,2):i)||"&nbsp;")+"</td>");s+="</tr>",o.html(t(s)),$.settings.always_visible&&(S=t("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month, .dp_week_number)",o)),o.show()},tt=function(e,s,i){var n,a,r;for(a in void 0!==s&&(s+=1),L)if(n=L[a],r=!1,t.isArray(J[n])&&t.each(J[n],function(){if(!r){var a,o=this;if((t.inArray(e,o[2])>-1||t.inArray("*",o[2])>-1)&&(void 0!==s&&t.inArray(s,o[1])>-1||t.inArray("*",o[1])>-1)&&(void 0!==i&&t.inArray(i,o[0])>-1||t.inArray("*",o[0])>-1)){if("*"===o[3])return r=n;if(a=new Date(e,s-1,i).getDay(),t.inArray(a,o[3])>-1)return r=n}}}),r)return r;return r||""},et=function(e){var s,i;if("explorer"===_t.name&&6===_t.version)if("hide"===(A||(s=ct(n.css("zIndex"))-1,A=t("<iframe>",{src:'javascript:document.write("")',scrolling:"no",frameborder:0,css:{zIndex:s,position:"absolute",top:-1e3,left:-1e3,width:n.outerWidth(),height:n.outerHeight(),filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)",display:"none"}}),t("body").append(A)),e))A.hide();else i=n.offset(),A.css({top:i.top,left:i.left,display:"block"})},st=function(e,s,i){var n,a,r,o;if(!(void 0!==e&&!isNaN(e)||void 0!==s&&!isNaN(s)||void 0!==i&&!isNaN(i)))return!1;if(e<1e3)return!0;if(t.isArray($.settings.direction)||0!==ct($.settings.direction)){if(8===(a=((n=ct(ot(e,void 0!==s?dt(s,2):"",void 0!==i?dt(i,2):"")))+"").length)&&(void 0!==M&&n<ct(ot(f,dt(u,2),dt(p,2)))||void 0!==F&&n>ct(ot(Y,dt(P,2),dt(C,2)))))return!0;if(6===a&&(void 0!==M&&n<ct(ot(f,dt(u,2)))||void 0!==F&&n>ct(ot(Y,dt(P,2)))))return!0;if(4===a&&(void 0!==M&&n<f||void 0!==F&&n>Y))return!0}return void 0!==s&&(s+=1),r=!1,o=!1,t.isArray(D)&&D.length&&t.each(D,function(){if(!r){var n,a=this;if((t.inArray(e,a[2])>-1||t.inArray("*",a[2])>-1)&&(void 0!==s&&t.inArray(s,a[1])>-1||t.inArray("*",a[1])>-1)&&(void 0!==i&&t.inArray(i,a[0])>-1||t.inArray("*",a[0])>-1)){if("*"===a[3])return r=!0;if(n=new Date(e,s-1,i).getDay(),t.inArray(n,a[3])>-1)return r=!0}}}),k&&t.each(k,function(){if(!o){var n,a=this;if((t.inArray(e,a[2])>-1||t.inArray("*",a[2])>-1)&&(o=!0,void 0!==s))if(o=!0,t.inArray(s,a[1])>-1||t.inArray("*",a[1])>-1){if(void 0!==i)if(o=!0,t.inArray(i,a[0])>-1||t.inArray("*",a[0])>-1){if("*"===a[3])return o=!0;if(n=new Date(e,s-1,i).getDay(),t.inArray(n,a[3])>-1)return o=!0;o=!1}else o=!1}else o=!1}}),!(k&&o||!D||!r)},it=function(t){return(t+"").match(/^\-?[0-9]+$/)},nt=function(e){!isNaN(parseFloat(b))&&isFinite(b)&&(e=e.replace(/\bm\b|\bn\b|\bF\b|\bM\b/,function(e){switch(e){case"m":return dt(b+1,2);case"n":return b+1;case"F":return $.settings.months[b];case"M":return t.isArray($.settings.months_abbr)&&void 0!==$.settings.months_abbr[b]?$.settings.months_abbr[b]:$.settings.months[b].substr(0,3);default:return e}})),!isNaN(parseFloat(y))&&isFinite(y)&&(e=e.replace(/\bY\b/,y).replace(/\by\b/,(y+"").substr(2)).replace(/\bY1\b/i,y-7).replace(/\bY2\b/i,y+4)),t(".dp_caption",r).html(e)},at=function(){var e,s,a;""===o.text()||"days"===i?(""===o.text()?($.settings.always_visible||n.css("left",-1e3),n.css("visibility","visible"),X(),e=o.outerWidth(),s=o.outerHeight(),d.css({width:e,height:s}),c.css({width:e,height:s}),r.css("width",e),O.css("width",e),n.css("visibility","").addClass("dp_hidden")):X(),d.hide(),c.hide()):"months"===i?(function(){nt($.settings.header_captions.months);var e,s,i="<tr>";for(e=0;e<12;e++)e>0&&e%3==0&&(i+="</tr><tr>"),s="dp_month_"+e,st(y,e)?s+=" dp_disabled":!1!==m&&m===e&&y===w?s+=" dp_selected":h===e&&_===y&&(s+=" dp_current"),i+='<td class="'+t.trim(s)+'">'+(t.isArray($.settings.months_abbr)&&void 0!==$.settings.months_abbr[e]?$.settings.months_abbr[e]:$.settings.months[e].substr(0,3))+"</td>";i+="</tr>",d.html(t(i)),$.settings.always_visible&&(Z=t("td:not(.dp_disabled)",d)),d.show()}(),o.hide(),c.hide()):"years"===i&&(function(){nt($.settings.header_captions.years);var e,s,i="<tr>";for(e=0;e<12;e++)e>0&&e%3==0&&(i+="</tr><tr>"),s="",st(y-7+e)?s+=" dp_disabled":w&&w===y-7+e?s+=" dp_selected":_===y-7+e&&(s+=" dp_current"),i+="<td"+(""!==t.trim(s)?' class="'+t.trim(s)+'"':"")+">"+(y-7+e)+"</td>";i+="</tr>",c.html(t(i)),$.settings.always_visible&&(x=t("td:not(.dp_disabled)",c)),c.show()}(),o.hide(),d.hide()),$.settings.onChange&&"function"==typeof $.settings.onChange&&void 0!==i&&((a="days"===i?o.find("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month)"):"months"===i?d.find("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month)"):c.find("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month)")).each(function(){var e;"days"===i?t(this).hasClass("dp_not_in_month_selectable")?(e=t(this).attr("class").match(/date\_([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])/),t(this).data("date",e[1]+"-"+e[2]+"-"+e[3])):t(this).data("date",y+"-"+dt(b+1,2)+"-"+dt(ct(t(this).text()),2)):"months"===i?(e=t(this).attr("class").match(/dp\_month\_([0-9]+)/),t(this).data("date",y+"-"+dt(ct(e[1])+1,2))):t(this).data("date",ct(t(this).text()))}),$.settings.onChange.call(q,i,a,q)),O.show(),!0===$.settings.show_clear_date||0===$.settings.show_clear_date&&""!==q.val()||$.settings.always_visible&&!1!==$.settings.show_clear_date?(l.show(),W?(N.css("width","50%"),l.css("width","50%")):(N.hide(),l.css("width","100%"))):(l.hide(),W?N.show().css("width","100%"):O.hide())},rt=function(t,e,s,i,n){var a=new Date(t,e,s,12,0,0),r="days"===i?S:"months"===i?Z:x,o=U(a);q.val(o),$.settings.always_visible&&(m=a.getMonth(),b=a.getMonth(),w=a.getFullYear(),y=a.getFullYear(),v=a.getDate(),r.removeClass("dp_selected"),n.addClass("dp_selected"),"days"===i&&n.hasClass("dp_not_in_month_selectable")&&$.show()),$.hide(),lt(a),$.settings.onSelect&&"function"==typeof $.settings.onSelect&&$.settings.onSelect.call(q,o,t+"-"+dt(e+1,2)+"-"+dt(s,2),a,q,ht(a)),q.focus()},ot=function(){var t,e="";for(t=0;t<arguments.length;t++)e+=arguments[t]+"";return e},dt=function(t,e){for(t+="";t.length<e;)t="0"+t;return t},ct=function(t){return parseInt(t,10)},lt=function(e){$.settings.pair&&t.each($.settings.pair,function(){var s,i=t(this);i.data&&i.data("Zebra_DatePicker")?((s=i.data("Zebra_DatePicker")).update({reference_date:e,direction:0===s.settings.direction?1:s.settings.direction}),s.settings.always_visible&&s.show()):i.data("zdp_reference_date",e)})},ht=function(t){var e,s,i,n,a,r,o,d=t.getFullYear(),c=t.getMonth()+1,l=t.getDate();return c<3?(i=(s=((e=d-1)/4|0)-(e/100|0)+(e/400|0))-(((e-1)/4|0)-((e-1)/100|0)+((e-1)/400|0)),n=0,a=l-1+31*(c-1)):(n=1+(i=(s=((e=d)/4|0)-(e/100|0)+(e/400|0))-(((e-1)/4|0)-((e-1)/100|0)+((e-1)/400|0))),a=l+((153*(c-3)+2)/5|0)+58+i),(o=a+3-(l=(a+(r=(e+s)%7)-n)%7))<0?53-((r-i)/5|0):o>364+i?1:1+(o/7|0)},_t={init:function(){this.name=this.searchString(this.dataBrowser)||"",this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||""},searchString:function(t){var e,s,i;for(e=0;e<t.length;e++)if(s=t[e].string,i=t[e].prop,this.versionSearchString=t[e].versionSearch||t[e].identity,s){if(-1!==s.indexOf(t[e].subString))return t[e].identity}else if(i)return t[e].identity},searchVersion:function(t){var e=t.indexOf(this.versionSearchString);if(-1!==e)return parseFloat(t.substring(e+this.versionSearchString.length+1))},dataBrowser:[{string:navigator.userAgent,subString:"Firefox",identity:"firefox"},{string:navigator.userAgent,subString:"MSIE",identity:"explorer",versionSearch:"MSIE"}]};_t.init(),E()},t.fn.Zebra_DatePicker=function(e){return this.each(function(){void 0!==t(this).data("Zebra_DatePicker")&&t(this).data("Zebra_DatePicker").destroy();var s=new t.Zebra_DatePicker(this,e);t(this).data("Zebra_DatePicker",s)})}}),function(e){"object"==typeof module&&"object"==typeof module.exports?e(require("jquery"),window,document):"undefined"!=typeof jQuery&&e(jQuery,window,document)}(function(e,t,i,n){!function(){function t(e,t,i){return new Array(i+1-e.length).join(t)+e}function n(){if(1===arguments.length){var t=arguments[0];return"string"==typeof t&&(t=e.fn.timepicker.parseTime(t)),new Date(0,0,0,t.getHours(),t.getMinutes(),t.getSeconds())}return 3===arguments.length?new Date(0,0,0,arguments[0],arguments[1],arguments[2]):2===arguments.length?new Date(0,0,0,arguments[0],arguments[1],0):new Date(0,0,0)}e.TimePicker=function(){var t=this;t.container=e(".ui-timepicker-container"),t.ui=t.container.find(".ui-timepicker"),0===t.container.length&&(t.container=e("<div></div>").addClass("ui-timepicker-container").addClass("ui-timepicker-hidden ui-helper-hidden").appendTo("body").hide(),t.ui=e("<div></div>").addClass("ui-timepicker").addClass("ui-widget ui-widget-content ui-menu").addClass("ui-corner-all").appendTo(t.container),t.viewport=e("<ul></ul>").addClass("ui-timepicker-viewport").appendTo(t.ui),e.fn.jquery>="1.4.2"&&t.ui.delegate("a","mouseenter.timepicker",function(){t.activate(!1,e(this).parent())}).delegate("a","mouseleave.timepicker",function(){t.deactivate(!1)}).delegate("a","click.timepicker",function(i){i.preventDefault(),t.select(!1,e(this).parent())}))},e.TimePicker.count=0,e.TimePicker.instance=function(){return e.TimePicker._instance||(e.TimePicker._instance=new e.TimePicker),e.TimePicker._instance},e.TimePicker.prototype={keyCode:{ALT:18,BLOQ_MAYUS:20,CTRL:17,DOWN:40,END:35,ENTER:13,HOME:36,LEFT:37,NUMPAD_ENTER:108,PAGE_DOWN:34,PAGE_UP:33,RIGHT:39,SHIFT:16,TAB:9,UP:38},_items:function(t,i){var r,a,s=e("<ul></ul>"),c=null;for(-1===t.options.timeFormat.indexOf("m")&&t.options.interval%60!=0&&(t.options.interval=60*Math.max(Math.round(t.options.interval/60),1)),r=i?n(i):t.options.startTime?n(t.options.startTime):n(t.options.startHour,t.options.startMinutes),a=new Date(r.getTime()+864e5);a>r;)this._isValidTime(t,r)&&(c=e("<li>").addClass("ui-menu-item").appendTo(s),e("<a>").addClass("ui-corner-all").text(e.fn.timepicker.formatTime(t.options.timeFormat,r)).appendTo(c),c.data("time-value",r)),r=new Date(r.getTime()+60*t.options.interval*1e3);return s.children()},_isValidTime:function(e,t){var i=null,r=null;return t=n(t),null!==e.options.minTime?i=n(e.options.minTime):null===e.options.minHour&&null===e.options.minMinutes||(i=n(e.options.minHour,e.options.minMinutes)),null!==e.options.maxTime?r=n(e.options.maxTime):null===e.options.maxHour&&null===e.options.maxMinutes||(r=n(e.options.maxHour,e.options.maxMinutes)),null!==i&&null!==r?t>=i&&r>=t:null!==i?t>=i:null===r||r>=t},_hasScroll:function(){var e=void 0!==this.ui.prop?"prop":"attr";return this.ui.height()<this.ui[e]("scrollHeight")},_move:function(e,t,i){var n=this;if(n.closed()&&n.open(e),n.active){var r=n.active[t+"All"](".ui-menu-item").eq(0);r.length?n.activate(e,r):n.activate(e,n.viewport.children(i))}else n.activate(e,n.viewport.children(i))},register:function(t,i){var n=this,r={};r.element=e(t),r.element.data("TimePicker")||(r.options=e.metadata?e.extend({},i,r.element.metadata()):e.extend({},i),r.widget=n,e.extend(r,{next:function(){return n.next(r)},previous:function(){return n.previous(r)},first:function(){return n.first(r)},last:function(){return n.last(r)},selected:function(){return n.selected(r)},open:function(){return n.open(r)},close:function(){return n.close(r)},closed:function(){return n.closed(r)},destroy:function(){return n.destroy(r)},parse:function(e){return n.parse(r,e)},format:function(e,t){return n.format(r,e,t)},getTime:function(){return n.getTime(r)},setTime:function(e,t){return n.setTime(r,e,t)},option:function(e,t){return n.option(r,e,t)}}),n._setDefaultTime(r),n._addInputEventsHandlers(r),r.element.data("TimePicker",r))},_setDefaultTime:function(t){"now"===t.options.defaultTime?t.setTime(n(new Date)):t.options.defaultTime&&t.options.defaultTime.getFullYear?t.setTime(n(t.options.defaultTime)):t.options.defaultTime&&t.setTime(e.fn.timepicker.parseTime(t.options.defaultTime))},_addInputEventsHandlers:function(t){var i=this;t.element.bind("keydown.timepicker",function(e){switch(e.which||e.keyCode){case i.keyCode.ENTER:case i.keyCode.NUMPAD_ENTER:e.preventDefault(),i.closed()?t.element.trigger("change.timepicker"):i.select(t,i.active);break;case i.keyCode.UP:t.previous();break;case i.keyCode.DOWN:t.next();break;default:i.closed()||t.close(!0)}}).bind("focus.timepicker",function(){t.open()}).bind("blur.timepicker",function(){setTimeout(function(){t.element.data("timepicker-user-clicked-outside")&&t.close()})}).bind("change.timepicker",function(){t.closed()&&t.setTime(e.fn.timepicker.parseTime(t.element.val()))})},select:function(t,i){var n=this,r=!1===t?n.instance:t;n.setTime(r,e.fn.timepicker.parseTime(i.children("a").text())),n.close(r,!0)},activate:function(e,t){var i=this;if((!1===e?i.instance:e)===i.instance){if(i.deactivate(),i._hasScroll()){var r=t.offset().top-i.ui.offset().top,a=i.ui.scrollTop(),o=i.ui.height();0>r?i.ui.scrollTop(a+r):r>=o&&i.ui.scrollTop(a+r-o+t.height())}i.active=t.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-item").end()}},deactivate:function(){var e=this;e.active&&(e.active.children("a").removeClass("ui-state-hover").removeAttr("id"),e.active=null)},next:function(e){return(this.closed()||this.instance===e)&&this._move(e,"next",".ui-menu-item:first"),e.element},previous:function(e){return(this.closed()||this.instance===e)&&this._move(e,"prev",".ui-menu-item:last"),e.element},first:function(e){return this.instance===e&&(this.active&&0===this.active.prevAll(".ui-menu-item").length)},last:function(e){return this.instance===e&&(this.active&&0===this.active.nextAll(".ui-menu-item").length)},selected:function(e){return this.instance===e&&this.active?this.active:null},open:function(t){var n=this,r=t.getTime(),a=t.options.dynamic&&r;if(!t.options.dropdown)return t.element;switch(t.element.data("timepicker-event-namespace",Math.random()),e(i).bind("click.timepicker-"+t.element.data("timepicker-event-namespace"),function(e){t.element.get(0)===e.target?t.element.data("timepicker-user-clicked-outside",!1):t.element.data("timepicker-user-clicked-outside",!0).blur()}),(t.rebuild||!t.items||a)&&(t.items=n._items(t,a?r:null)),(t.rebuild||n.instance!==t||a)&&(e.fn.jquery<"1.4.2"?(n.viewport.children().remove(),n.viewport.append(t.items),n.viewport.find("a").bind("mouseover.timepicker",function(){n.activate(t,e(this).parent())}).bind("mouseout.timepicker",function(){n.deactivate(t)}).bind("click.timepicker",function(i){i.preventDefault(),n.select(t,e(this).parent())})):(n.viewport.children().detach(),n.viewport.append(t.items))),t.rebuild=!1,n.container.removeClass("ui-helper-hidden ui-timepicker-hidden ui-timepicker-standard ui-timepicker-corners").show(),t.options.theme){case"standard":n.container.addClass("ui-timepicker-standard");break;case"standard-rounded-corners":n.container.addClass("ui-timepicker-standard ui-timepicker-corners")}n.container.hasClass("ui-timepicker-no-scrollbar")||t.options.scrollbar||(n.container.addClass("ui-timepicker-no-scrollbar"),n.viewport.css({paddingRight:40}));var o=n.container.outerHeight()-n.container.height(),s=t.options.zindex?t.options.zindex:t.element.offsetParent().css("z-index"),c=t.element.offset();n.container.css({top:c.top+t.element.outerHeight(),left:c.left}),n.container.show(),n.container.css({left:t.element.offset().left,height:n.ui.outerHeight()+o,width:t.element.outerWidth(),zIndex:s,cursor:"default"});var u=n.container.width()-(n.ui.outerWidth()-n.ui.width());return n.ui.css({width:u}),n.viewport.css({width:u}),t.items.css({width:u}),n.instance=t,r?t.items.each(function(){var a=e(this);return(e.fn.jquery<"1.4.2"?e.fn.timepicker.parseTime(a.find("a").text()):a.data("time-value")).getTime()!==r.getTime()||(n.activate(t,a),!1)}):n.deactivate(t),t.element},close:function(t){var n=this;return n.instance===t&&(n.container.addClass("ui-helper-hidden ui-timepicker-hidden").hide(),n.ui.scrollTop(0),n.ui.children().removeClass("ui-state-hover")),e(i).unbind("click.timepicker-"+t.element.data("timepicker-event-namespace")),t.element},closed:function(){return this.ui.is(":hidden")},destroy:function(e){return this.close(e,!0),e.element.unbind(".timepicker").data("TimePicker",null)},parse:function(t,i){return e.fn.timepicker.parseTime(i)},format:function(t,i,n){return n=n||t.options.timeFormat,e.fn.timepicker.formatTime(n,i)},getTime:function(t){var n=e.fn.timepicker.parseTime(t.element.val());return n instanceof Date&&!this._isValidTime(t,n)?null:n instanceof Date&&t.selectedTime?t.format(n)===t.format(t.selectedTime)?t.selectedTime:n:n instanceof Date?n:null},setTime:function(t,i,r){var o=t.selectedTime;if("string"==typeof i&&(i=t.parse(i)),i&&i.getMinutes&&this._isValidTime(t,i)){if(i=n(i),t.selectedTime=i,t.element.val(t.format(i,t.options.timeFormat)),r)return t}else t.selectedTime=null;return null===o&&null===t.selectedTime||(t.element.trigger("time-change",[i]),e.isFunction(t.options.change)&&t.options.change.apply(t.element,[i])),t.element},option:function(t,i,n){if(void 0===n)return t.options[i];var r,a,o=t.getTime();"string"==typeof i?(r={})[i]=n:r=i,a=["minHour","minMinutes","minTime","maxHour","maxMinutes","maxTime","startHour","startMinutes","startTime","timeFormat","interval","dropdown"],e.each(r,function(i){t.options[i]=r[i],t.rebuild=t.rebuild||e.inArray(i,a)>-1}),t.rebuild&&t.setTime(o)}},e.TimePicker.defaults={timeFormat:"hh:mm p",minHour:null,minMinutes:null,minTime:null,maxHour:null,maxMinutes:null,maxTime:null,startHour:null,startMinutes:null,startTime:null,interval:30,dynamic:!0,theme:"standard",zindex:null,dropdown:!0,scrollbar:!1,change:function(){}},e.TimePicker.methods={chainable:["next","previous","open","close","destroy","setTime"]},e.fn.timepicker=function(t){if("string"==typeof t){var i,n,r=Array.prototype.slice.call(arguments,1);return n=this[i="option"===t&&arguments.length>2||-1!==e.inArray(t,e.TimePicker.methods.chainable)?"each":"map"](function(){var n=e(this).data("TimePicker");return"object"==typeof n?n[t].apply(n,r):void 0}),"map"===i&&1===this.length?e.makeArray(n).shift():"map"===i?e.makeArray(n):n}if(1===this.length&&this.data("TimePicker"))return this.data("TimePicker");var a=e.extend({},e.TimePicker.defaults,t);return this.each(function(){e.TimePicker.instance().register(this,a)})},e.fn.timepicker.formatTime=function(e,i){var n=i.getHours(),r=n%12,a=i.getMinutes(),o=i.getSeconds(),s={hh:t((0===r?12:r).toString(),"0",2),HH:t(n.toString(),"0",2),mm:t(a.toString(),"0",2),ss:t(o.toString(),"0",2),h:0===r?12:r,H:n,m:a,s:o,p:n>11?"PM":"AM"},c=e,u="";for(u in s)s.hasOwnProperty(u)&&(c=c.replace(new RegExp(u,"g"),s[u]));return c.replace(new RegExp("a","g"),n>11?"pm":"am")},e.fn.timepicker.parseTime=function(){var t=[[/^(\d+)$/,"$1"],[/^:(\d)$/,"$10"],[/^:(\d+)/,"$1"],[/^(\d):([7-9])$/,"0$10$2"],[/^(\d):(\d\d)$/,"$1$2"],[/^(\d):(\d{1,})$/,"0$1$20"],[/^(\d\d):([7-9])$/,"$10$2"],[/^(\d\d):(\d)$/,"$1$20"],[/^(\d\d):(\d*)$/,"$1$2"],[/^(\d{3,}):(\d)$/,"$10$2"],[/^(\d{3,}):(\d{2,})/,"$1$2"],[/^(\d):(\d):(\d)$/,"0$10$20$3"],[/^(\d{1,2}):(\d):(\d\d)/,"$10$2$3"]],i=t.length;return function(r){var o,s,a=n(new Date),c=!1,u=!1,l=!1;if(void 0===r||!r.toLowerCase)return null;r=r.toLowerCase(),s=!(o=/a/.test(r))&&/p/.test(r),r=r.replace(/[^0-9:]/g,"").replace(/:+/g,":");for(var m=0;i>m;m+=1)if(t[m][0].test(r)){r=r.replace(t[m][0],t[m][1]);break}return 1===(r=r.replace(/:/g,"")).length||2===r.length?c=r:3===r.length||5===r.length?(c=r.substr(0,1),u=r.substr(1,2),l=r.substr(3,2)):(4===r.length||r.length>5)&&(c=r.substr(0,2),u=r.substr(2,2),l=r.substr(4,2)),r.length>0&&r.length<5&&(r.length<3&&(u=0),l=0),!1!==c&&!1!==u&&!1!==l&&(c=parseInt(c,10),u=parseInt(u,10),l=parseInt(l,10),o&&12===c?c=0:s&&12>c&&(c+=12),c>24?r.length>=6?e.fn.timepicker.parseTime(r.substr(0,5)):e.fn.timepicker.parseTime(r+"0"+(o?"a":"")+(s?"p":"")):(a.setHours(c,u,l),a))}}()}()});
1
+ $c.isMobile()?document.getElementsByTagName("html")[0].className+=" touch joesmall-size":document.getElementsByTagName("html")[0].className+=" no-touch joelarge-size",window._joeEditingHash=!1;var _webworkers=!1,_joeworker;window.Worker&&(_webworkers=!0);var joe_web_dir="//"+location.hostname+":"+(location.port||("https:"==location.protocol?443:80))+"/JsonObjectEditor/",__gotoJoeSection;function __require(file,callback){var head=document.getElementsByTagName("head")[0],script=document.createElement("script");script.src=file,script.type="text/javascript",script.onload=callback,script.onreadystatechange=function(){"complete"==this.readyState&&callback()},head.appendChild(script)}function JsonObjectEditor(specs){var self=this,htmlRef=document.getElementsByTagName("html")[0];self.initialDocumentTitle=document.title,$c.TEMPLATE_VARS.push({variable:"/textarea",value:"</textarea>"},{variable:"textarea",value:"<textarea>"},{variable:"SERVER",value:"//"+$c.SERVER});var initialized=!1,colCount=1,listMode=!1,gridMode=!1,tableMode=!1,tableSpecs,multiEdit=!1;this.VERSION="1.0.1",window._joes=window._joes||[],this.joe_index=window._joes.length,window._joes.length||(window._joe=this),this.Error={log:[],add:function(message,error,data){var payload={caller:arguments.callee.caller,callerargs:arguments.callee.caller.arguments,message:message,error:error,stack:new Error(error).stack,data:data,timestamp:(new Date).toISOString(),_id:cuid()};self.Error.log.push(payload),logit("[error]: "+message)},show:function(){self.show(self.Error.log,{schema:{title:"${message}",idprop:"_id",listView:{title:"<joe-title>${message}</joe-title><joe-subtitle>${timestamp}</joe-subtitle>",listWindowTitle:"Errors"},fields:["error:code","message","stack:code",{name:"data",type:"content",run:function(data,obj){return"<div><pre>"+tryEval(data)+"</pre></div>"}},"callerargs:code","timestamp:guid","_id"]}})}},this.uploaderSetFileRole=function(uploader_id,filename,role){try{var joe_uploader=self.uploaders&&self.uploaders[uploader_id];if(!joe_uploader||!Array.isArray(joe_uploader.files))return;var file=joe_uploader.files.where({filename:filename})[0];if(!file)return;role?file.file_role=role:delete file.file_role,joe_uploader.preview&&$(joe_uploader.preview).html(_renderUploaderFilePreviews(joe_uploader.files,joe_uploader.cuid)),"function"==typeof self.updateObject&&self.updateObject(null,null,!0)}catch(e){console.warn("uploaderSetFileRole error",e&&e.message||e)}},window._joes.push(this),this.Cache={static:{},list:[],lookup:{},clear:function(){self.Cache.lookup={},self.Cache.list=[]},remove:function(id){},get:function(id,specs){var cacheitem=self.Cache.lookup[id];if(cacheitem&&"function"==typeof cacheitem.value&&"callback"==cacheitem.type)return cacheitem.value(cacheitem.data,cacheitem.id);if(!cacheitem){var obj=self.search(id)[0]||!1;return!!obj&&(self.Cache.add(obj,{id:id}),obj)}return cacheitem.value},callback:function(id){var cacheitem=self.Cache.lookup[id];if("function"==typeof cacheitem.value)return cacheitem.value(cacheitem.data,cacheitem.id);logit("cache item is not a function")},add:function(value,specs){specs=specs||{};var obj=$.extend({id:specs.id||cuid(),value:value,parent:self.joe_index},specs);return self.Cache.list.push(obj.id),self.Cache.lookup[obj.id]=obj,obj}},this.Cache.set=this.Cache.add,this.history=[];var defaults={localStorage:!1,container:"body",joeprofile:{lockedFields:["joeUpdated"],hiddenFields:[]},profiles:{},fields:{},schemas:{rendering:{title:"HTML Rendering",callback:function(){alert("yo")}}},compact:!1,useControlEnter:!0,useEscapeKey:!1,autoInit:!1,autosave:1e4,dynamicDisplay:$(window).height()<800&&$c.isMobile()?12:20,sans:!1,listSubMenu:!0,documentTitle:!1,style:{inset:!0,cards:!1},speechRecognition:!1},goingBackFromID,goingBackQuery;for(var s in this.specs=$.extend({},defaults,specs||{}),this.specs.localStorage&&"undefined"==typeof Storage&&(alert("no local storage"),this.specs.LocalStorage=!1),this.Indexes={_add:function(idprop,dataitem){self.Indexes[idprop]=self.Indexes[idprop]||{},self.Indexes[idprop][dataitem[idprop]]=dataitem},_usage:0},this.Printer={init:function(){document.querySelector("print-joe")||document.body.appendChild(document.createElement("print-joe"))},print:function(){self.Printer.init();var cln=document.getElementsByTagName("joe-panel-content")[0].cloneNode(!0);document.querySelector("print-joe").innerHTML="",document.querySelector("print-joe").appendChild(cln);var panelContent=document.querySelector("print-joe joe-panel-content");panelContent.className="joe-panel-content";var activeNodes=document.querySelectorAll("print-joe joe-panel-content .joe-content-section.active");if(activeNodes.length){panelContent.innerHTML="";for(var i=0;i<activeNodes.length;i++)panelContent.appendChild(activeNodes[i])}window.print(),document.querySelector("print-joe").innerHTML=""}},this.Data={},this.Render={schema_icon:function(schema,classes){var icon=self.schemas[schema]&&self.schemas[schema].menuicon||"";return icon&&(icon=`<joe-icon class="${classes||""}">${icon}</joe-icon>`),icon},ref_chip:function(things,specs){specs="string"==typeof specs?{cssclass:specs}:specs||{};const items=Array.isArray(things)?things:things?.tags||[];if(!items.length)return"";const labelProp=specs.labelProp||"name",tooltipProp=!1===specs.tooltipProp?null:specs.tooltipProp||"info";let html=`<joe-chips class="${specs.cssclass||""}">`;return items.forEach(ref=>{const obj="object"==typeof ref?ref:$J.get(ref);if(!obj)return;const label=obj[labelProp]||"",title=tooltipProp&&obj[tooltipProp]?` title="${obj[tooltipProp]}"`:"";let style="";if(specs.useStatusColor&&obj.status){const statusObj=_joe.Cache.get(obj.status);statusObj?.color&&(style=` style="border-left:4px solid ${statusObj.color}"`)}else obj.color&&(style=` style="background:${obj.color}"`);html+=`<joe-chip data-id="${obj._id}"${title}${style}>${label}</joe-chip>`}),html+="</joe-chips>",html}},this.container=$(this.specs.container),this.fields=this.specs.fields,this.Fields={reset:function(propname){var field=self.Fields.get(propname);self.current.object[propname]=field.reset,self.Fields.rerender(propname)},onPanelShow:function(cur){cur=cur||_jco();var currentFields=self.current.fields;logit("current fields",currentFields),currentFields.map(f=>{f.onPanelShow&&f.onPanelShow(cur)})}},this.schemas=this.specs.schemas,_joe.schemas)_joe.schemas[s].__schemaname=_joe.schemas[s].name=s,_joe.schemas[s]._id=cuid();function createTitleObject(specs){specs=specs||{};var titleObj=$.extend({},self.current.object),list=specs.list||self.current.list;if(list){var lcount=list.length;self.current.subset&&(lcount=list.where(self.current.subset.filter).length),titleObj._listCount=lcount||"0",titleObj._subsetName=self.current.subset&&self.current.subset.name+" "||""}self.current.title=specs.title||self.getCascadingProp("title")||self.current.schema&&"new "+self.current.schema.__schemaname||"Json Object Editor",self.current.subtitle=specs.subtitle||self.getCascadingProp("subtitle");var title=fillTemplate(self.propAsFuncOrValue(self.current.title),titleObj),subtitle=fillTemplate(self.propAsFuncOrValue(self.current.subtitle),titleObj);return titleObj.docTitle=title,titleObj.subTitle=subtitle,titleObj}function renderSubmenuButtons(buttons){var content,html="";if(buttons=self.propAsFuncOrValue(buttons||listMode&&self.getCascadingProp("headerListMenu")||!listMode&&self.getCascadingProp("headerMenu"))){var h=self.renderMenuButtons(buttons,"joe-submenu-button");h&&(content=!0),html+=h}return{html:html,content:content}}function renderSectionAnchors(){var anchorhtml='<joe-submenu-section-anchors><joe-panel-button class="sections-toggle" onclick="'+getSelfStr+'.Sections.toggle(this);">'+self.SVG.icon.sections+" <joe-button-label>"+(self.current.sections&&self.current.sections.count()||"")+" sections</joe-button-label></joe-panel-button>";anchorhtml+='<div class="joe-submenu-section" onclick="_joe.Sections.gotoTop('+self.joe_index+')">^ top</div>';var section,scount=0,template='<joe-submenu-section class="joe-submenu-section f${renderTo}" data-section="${name}" data-panel="${renderTo}" '+('onclick="getJoe('+self.joe_index+").gotoSection('${id}');\"")+" "+('ondblclick="getJoe('+self.joe_index+").gotoSection('${id}',{focus:'${id}'});\"")+">${${anchor}||${name}}</joe-submenu-section>";for(var secname in self.current.sections)(section=_getSection(secname)).hidden||(anchorhtml+=fillTemplate(template,section),scount++);return{count:scount,code:anchorhtml+="<div class='clear'></div></joe-submenu-section-anchors>"}}this.current={},this.current.clear=function(){self.current.list=null,self.current.subsets=null,self.current.subset=null,self.current.filters={},self.current.fields=[],self.current.schema=null,self.current.object=null,self.current.reset={},self.current.cache={},self.current.title=null,self.current.keyword="",1==_joes.length&&(document.title=self.initialDocumentTitle)},this.defaultProfile=this.specs.defaultProfile||this.specs.joeprofile,this.current.profile=this.defaultProfile,this.ace_editors={},this.Render.stripeColor=function(opt,colorfunc){var color=self.propAsFuncOrValue(colorfunc||opt.stripecolor,opt,null,_jco()),title="";return color&&$c.isObject(color)&&(title=' title="'+color.title+'" ',color=color.color),"<joe-stripe-color "+title+(color&&'style="background-color:'+color+';"'||"")+"></joe-stripe-color>"},this.Render.bgColor=function(opt,colorfunc){var color=self.propAsFuncOrValue(colorfunc||opt.bgcolor,opt,null,_jco());return color&&$c.isObject(color)&&(color=color.color),"<joe-bg-color "+(color&&'style="background-color:'+color+';"'||"")+"></joe-bg-color>"},this.Render.itemCheckbox=function(listItem,schema,specs){specs=specs||{};var checkbox=self.propAsFuncOrValue(self.getCascadingProp("checkbox",schema),listItem),idprop=specs.idprop||self.getIDProp();if(checkbox){var cbox_prop=checkbox,cbox_percentage=null,cbox_title="";"object"==$.type(checkbox)&&(cbox_prop=checkbox.prop,cbox_title=checkbox.title||cbox_prop,cbox_percentage=self.propAsFuncOrValue(checkbox.percentage,listItem));var cb_label=self.propAsFuncOrValue(checkbox.label,listItem);checkbox='<joe-checkbox title="'+cbox_title+'" class="'+([!0,"true"].contains(listItem[cbox_prop])?"checked":"")+'"onclick="_joe.checkItem(\''+listItem[idprop]+"','"+cbox_prop+"',null,this)\">"+(!1!==cbox_percentage&&checkbox.hasOwnProperty("percentage")?"<joe-checkbox-percentage>"+Math.round(100*cbox_percentage)+"%</joe-checkbox-percentage>":"")+(cb_label&&"<joe-checkbox-label>"+cb_label+"</joe-checkbox-label>"||"")+"</joe-checkbox>"}else checkbox="";return checkbox},this.init=function(callback){if(initialized)return!1;beginLogGroup("JOE init"),self.current.clear();var respond_timeout,html=self.renderFramework(self.renderEditorHeader()+self.renderEditorContent()+self.renderEditorFooter());self.container.append(html),self.overlay=$(".joe-overlay[data-joeindex="+self.joe_index+"]"),self.panel=self.overlay.find(".joe-overlay-panel"),self.initKeyHandlers(),self.Speech.init(),self.readHashLink(),window.addEventListener("hashchange",function(newH,oldH){if(!($GET("!")||location.hash)||0!=self.joe_index||!specs.useHashlink)return!1;window._joeEditingHash||self.readHashLink()},!1),$(window).on("resize",function(){self.resizeOk()&&(clearTimeout(respond_timeout),respond_timeout=setTimeout(self.respond,200))}),self.initButtons(),initialized=!0,self.respond(),endLogGroup(),self.Components.init(),callback&&callback()},this.initButtons=function(){$(document).on("click","joe-button",function(e){e.preventDefault();var actionName=$(this).attr("action");if(actionName){var currentObject=_joe.current?_joe.current.object:null,currentSchema=_joe.current&&_joe.current.schema,currentSchemaMethods=currentSchema?currentSchema.methods:null;JOE.async&&"function"==typeof JOE.async[actionName]?JOE.async[actionName](currentObject,e):currentSchemaMethods&&"function"==typeof currentSchemaMethods[actionName]?currentSchemaMethods[actionName](currentObject,e):console.warn("No method found for joe-button action:",actionName)}else console.warn("No action defined for joe-button")})},this.resizeOk=function(){return!$c.isMobile()||"INPUT"!=document.activeElement.tagName},this.initKeyHandlers=function(){self.specs.useBackButton&&(window.onkeydown=function(e){var code=e.keyCode,isInputElement=-1!=["input","select","textarea"].indexOf(e.target&&e.target.tagName&&e.target.tagName.toLowerCase()||""),isEditable=e.target.isContentEditable||$(e.target).closest("joe-ai-chatbox").length||$(e.target).closest("joe-ai-widget").length;if(8==code)return isInputElement||isEditable?void 0:(self.goBack(),!1);if(-1==[37,39,38,40,13,16,17,27].indexOf(code)){if(e.altKey)switch(code){case 70:self.quickFind(),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault();break;case 78:self.quickAdd(),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault();break;case 80:self.Printer.print(),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()}else if(listMode){$(document.activeElement)&&$(document.activeElement)[0]!=$(".joe-submenu-search-field")[0]&&(self.overlay.find(".joe-submenu-search-field").focus(),$(".joe-panel-content-option.keyboard-selected").removeClass("keyboard-selected"))}else if((e.ctrlKey||e.metaKey)&&83===code)self.container.find(".joe-button.joe-quicksave-button").length&&(self.updateObject(null,null,!0),e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault())}else{if($(".joe-text-autocomplete.active").length){var sel=".joe-text-autocomplete-option.visible.keyboard-selected",keyboardSelected=$(sel)[0],keyboardSelectedIndex=$(sel).length?$(sel).index():-1;switch(code){case 38:--keyboardSelectedIndex>-1&&keyboardSelectOption(".joe-text-autocomplete-option.visible");break;case 40:++keyboardSelectedIndex<$(".joe-text-autocomplete-option.visible").length&&keyboardSelectOption(".joe-text-autocomplete-option.visible");break;case 13:-1!=keyboardSelectedIndex&&keyboardSelected.click()}}if(listMode)if(e.altKey){if(self.current.subsets){var subindex=self.current.subsets.indexOf(self.current.subset)+1;switch(code){case 38:$("joe-subset-option").eq(subindex-1).click();break;case 40:$("joe-subset-option").eq(subindex+1).click()}}}else{keyboardSelectedIndex=$(".joe-panel-content-option.keyboard-selected").length?$(".joe-panel-content-option.keyboard-selected").index():-1;switch(code){case 38:--keyboardSelectedIndex>-1&&keyboardSelectOption(".joe-panel-content-option",top);break;case 40:++keyboardSelectedIndex<currentListItems.length&&keyboardSelectOption(".joe-panel-content-option",top);break;case 13:-1!=keyboardSelectedIndex&&$(".joe-panel-content-option.keyboard-selected").find(".joe-panel-content-option-content").click()}}else if(e.altKey)switch(code){case 219:case 221:var sside=219==code?"left":"right";self.current.sidebars[sside].content&&!self.current.sidebars[sside].hidden&&self.toggleSidebar(sside)}else if(e.ctrlKey)switch(code){case 37:self.previous();break;case 39:self.next()}else if(13==code){var ae=$(document.activeElement);if(ae&&ae.is("input")){var fieldobj=ae.parents(".joe-object-field");if(fieldobj.length)try{fieldobj.find(".joe-plus-button").click()}catch(e){self.Error.add("adding new row to objectlist",e)}}}function keyboardSelectOption(selector,top){$(selector+".keyboard-selected").toggleClass("keyboard-selected");var el=$(selector).eq(keyboardSelectedIndex);el.addClass("keyboard-selected"),self.overlay.find(".joe-submenu-search-field").blur(),el[0].scrollIntoView(top)}}})},this.getMode=function(){return listMode&&self.current.list?"list":self.current.object?"details":!!self.current.list&&"list"},this.renderFramework=function(content){return'<joe-overlay class="joe-overlay sans cols-'+colCount+" style-variant1 "+(self.specs.compact?" compact ":"")+(self.specs.sans?" sans ":"")+'" data-joeindex="'+this.joe_index+'"><joe-panel class="joe-overlay-panel">'+(content||"")+'</joe-panel><div class="joe-mini-panel"></div></joe-overlay>'},this.populateFramework=function(data,setts){self.current.cache={},self.overlay.removeClass("multi-edit");var joePopulateBenchmarker=new Benchmarker;self.current.reset=self.current.reset||{},beginLogGroup("JOE population");var specs=setts||{};self.current.specs=setts,self.current.data=data,self.current.userSpecs=$.extend({},setts),gridMode="grid"==self.current.specs.viewMode,tableMode="table"==self.current.specs.viewMode,self.current.specs.noHistory||self.history.push({specs:self.current.userSpecs,data:self.current.data});var currentSubsets,schema=setts.schema||"",profile=setts.profile||null,callback=setts.callback||null,datatype=setts.datatype||"",title=setts.title||"";(self.current.callback=callback||null,"string"==$.type(data)&&"string"!=datatype&&self.getDataset(data,{boolean:!0})&&(!specs.schema&&self.schemas[data]&&(schema=data),data=self.getDataset(data)),specs.schema=this.setSchema(schema),colCount=self.current.specs.colCount||specs.schema&&specs.schema.colCount||1,"small-size"==self.sizeClass&&(colCount=1),specs.preformat=specs.schema&&specs.schema.preformat||specs.preformat||function(d){return d},data=specs.preformat(data),"object"!=$.type(data)&&"object"!=datatype||(specs.object=data,specs.menu=specs.menu||specs.schema&&specs.schema.menu||self.specs.menu||specs.multiedit&&__defaultMultiButtons||__defaultObjectButtons,specs.mode="object",self.current.object=data),self.toggleMultiEditMode(specs,data),listMode=!1,"array"==$.type(data)||"array"==datatype)&&(listMode=!0,specs.list=data,specs.menu=specs.listMenu||specs.schema&&specs.schema.listMenu||__defaultButtons,specs.mode="list",self.current.list=data,"function"==typeof(currentSubsets=setts.subsets||specs.schema&&specs.schema.subsets||null)&&(currentSubsets=currentSubsets()),self.current.specs.subset&&currentSubsets&&currentSubsets.where({$or:[{name:specs.subset},{id:specs.subset},{group_start:specs.subset}]}).length?self.current.subset=currentSubsets.where({$or:[{name:specs.subset},{id:specs.subset},{group_start:specs.subset}]})[0]||!1:"All"==self.current.specs.subset?self.current.subset={name:"All",filter:{}}:self.current.subset=currentSubsets&&currentSubsets.where({default:!0})[0]||null,self.current.subsets=currentSubsets,self.current.sorter=setts.sorter||self.current.subset&&self.current.subset.sorter||specs.schema&&specs.schema.sorter||"name","string"==$.type(self.current.sorter)&&(self.current.sorter=[self.current.sorter]));"list"==specs.mode?self.current.submenu=self.current.specs.listsubmenu||self.current.specs.submenu||specs.schema&&specs.schema.listSubMenu||self.specs.listSubMenu:self.current.submenu=self.current.specs.submenu||specs.schema&&specs.schema.subMenu||self.specs.subMenu,"none"==self.current.submenu&&(self.current.submenu=null),"string"==$.type(data)&&"rendering"==datatype?(specs.rendering=data,specs.menu=[__replaceBtn__],specs.mode="rendering",self.current.rendering=specs.rendering):"string"!=$.type(data)&&"string"!=datatype||(specs.text=data,specs.menu=__defaultButtons,specs.mode="text",self.current.text=specs.text),specs.listWindowTitle=specs.list&&(specs._listMenuTitle||specs._listWindowTitle||self.getCascadingProp("listWindowTitle")||getProperty("specs.list.windowTitle")||specs.schema&&(specs.schema._listMenuTitle||specs.schema._listWindowTitle))||!1,specs.title=specs.listWindowTitle||title||specs.schema&&(specs.schema.title||specs.schema._title)||"Viewing "+(self.current.schema&&self.current.schema.__schemaname||"string"==typeof self.current.userSpecs.schema&&self.current.userSpecs.schema||specs.mode).capitalize(),specs.profile=profile&&self.specs.profiles[profile]||self.specs.joeprofile,self.current.profile=specs.profile,self.cleanUp(),tableSpecs=self.current.schema&&(self.current.schema.table||self.current.schema.tableView)?$.extend({cols:["name",self.getIDProp()]},self.current.schema&&(self.current.schema.table||self.current.schema.tableView)||{}):null;var contentBM=new Benchmarker;beginLogGroup("Content");var content=self.renderEditorContent(specs);endLogGroup(),_bmResponse(contentBM,"JOE [Content]");var chromeBM=new Benchmarker,html=self.renderEditorHeader(specs)+self.renderEditorSubmenu(specs)+content+self.renderEditorFooter(specs)+self.renderMessageContainer();return _bmResponse(chromeBM,"JOE [overlay-chrome]"),self.overlay.find(".joe-overlay-panel").html(html),!self.current.specs.noHistory&&self.history.length&&$.extend(self.history[self.history.length-1],{_joeHistoryTitle:self.overlay.find(".joe-panel-title").html()}),self.updateHashLink(),_bmResponse(joePopulateBenchmarker,"----Joe Populated"),endLogGroup(),html},this.toggleMultiEditMode=function(specs,data){multiEdit=self.current.userSpecs&&self.current.userSpecs.multiedit||!1},this.Header={},this.toggleHelpMenu=function(show,target){},this.listUnsavedChanges=function(){},this.Header.Render=this.renderEditorHeader=function(specs){var BM=new Benchmarker,titleObj=createTitleObject(specs=specs||{}),title=titleObj.docTitle||self.current.schema&&"new "+self.current.schema.__schemaname;titleObj.subTitle;if(self.specs.documentTitle){var doctitle=!0===self.specs.documentTitle?self.current.title:self.propAsFuncOrValue(self.specs.documentTitle,self.current.title);document.title=fillTemplate(self.propAsFuncOrValue(doctitle),titleObj)}var close_action=specs.close_action||'onclick="getJoe('+self.joe_index+').closeButtonAction()"',reload_action=specs.reload_action||'onclick="getJoe('+self.joe_index+').reload()"';!function(){var html="";specs.minimode||(html+='<div class="jif-panel-header-button joe-panel-help" onclick="_joe.toggleHelpMenu()" title="help">'+self.SVG.icon.help+"</div>")}();var unsaved_icon=function(){var html="";return specs.minimode?"":html+='<div class="jif-panel-header-button joe-panel-unsaved" onclick="_joe.updateObject(this,null,true);" title="unsaved changes">'+self.SVG.icon.unsaved+"</div>"}(),reload_button=(specs.speech_action||self.joe_index,specs.minimode?"":'<div class="jif-panel-header-button joe-panel-reload" title="reload" '+reload_action+'><span class="jif-reload"></span></div>'),mic_button=!self.specs.speechRecognition||specs.minimode?"":'<div class="jif-panel-header-button joe-panel-speech" title="speech" id="speech-button-'+self.joe_index+'">M</div>',close_button='<div class="jif-panel-header-button joe-panel-close" title="close" '+close_action+">"+self.SVG.icon.close+"</div>",schema_button=!specs.minimode&&self.current.schema&&self.current.schema.menuicon&&'<joe-schema-icon class="clickable" title="'+self.current.schema.__schemaname+'" onclick="goJoe(\''+self.current.schema.__schemaname+"')\">"+self.current.schema.menuicon+"</joe-schema-icon>"||"",back_button=!specs.minimode&&function(){var html="";return self.history.length>1&&(html+='<div class="jif-header-back-btn jif-panel-header-button standard-button" onclick="window.history.back()" title="back">'+self.SVG.icon.left+"</div>"),html}()||"",left_buttons=[back_button,schema_button],right_buttons=[close_button,mic_button,reload_button,unsaved_icon],html="<joe-panel-header >"+(specs.schema&&specs.schema.subsets&&self.renderSubsetselector(specs.schema)||specs.subsets&&self.renderSubsetselector(specs)||"")+left_buttons.join(" ")+'<div class="joe-vcenter joe-panel-title-holder"><span class="joe-panel-title">'+(("<div>"+title+"</div>").toDomElement().innerText||title||"Json Object Editor")+'</span></div><joe-panel-header-buttons class="right-side">'+right_buttons.join(" ")+'<div class="clear"></div></joe-panel-header-buttons><div class="clear"></div></joe-panel-header>';return _bmResponse(BM,"[Header] rendered"),html},this.closeButtonAction=function(prechecked){if(this.checkChanges()){self.history=[],self.panel.addClass("centerscreen-collapse"),self.hide(500),self.current.clear(),$(self.container).trigger({type:"hideJoe",index:self.joe_index}),self.updateHashLink();var closeAction=self.getCascadingProp("onPanelHide");closeAction&&closeAction(self.getState()),self.Autosave.deactivate()}},this.goBack=function(obj){if(this.checkChanges()){if(self.current.object){var gobackItem=self.current.object[self.getIDProp()];gobackItem&&(goingBackFromID=gobackItem)}self.history.pop();var joespecs=self.history.pop();if(joespecs){if(obj&&$c.isArray(joespecs.data)){var objid=obj[self.getIDProp()];if(objid){var query={};query[self.getIDProp()]=objid;var found=joespecs.data.where(query);found.length&&$.extend(found[0],obj)}}joespecs.keyword&&(goingBackQuery=joespecs.keyword);var specs=$.extend({},joespecs.specs);specs.filters=joespecs.filters,self.show(joespecs.data,specs)}else self.closeButtonAction(!0)}},this.cleanUp=function(){self.current.fields=[],self.shiftSelecting=!1,self.allSelected=!1,self.current.userSpecs&&self.current.userSpecs.multiedit?self.overlay.addClass("multi-edit"):self.overlay.removeClass("multi-edit")},this.renderEditorSubmenu=function(specs){beginLogGroup("Submenu");var BM=new Benchmarker,sectionAnchors=renderSectionAnchors(),submenuButtons=renderSubmenuButtons();if(!(self.current.submenu||sectionAnchors.count||listMode||self.getCascadingProp("headerMenu")))return"";var subSpecs={search:!0,itemcount:!0,filters:$c.getProperty(self.current,"userSpecs.filters")||$c.getProperty(self.current,"schema.filters")||$c.getProperty(self.current,"schema.subsets")||!1,numCols:self.current.schema.columns||0},userSubmenu="object"!=$.type(self.current.submenu)?{}:self.current.submenu;if($.extend(subSpecs,userSubmenu),"list"==specs.mode)var filters_obj=self.Filter.getCached(),submenu='<div class="joe-panel-submenu">'+self.Aggregator.renderToggleButton()+self.renderViewModeButtons(subSpecs)+self.renderColumnCountSelector(subSpecs.numCols)+self.renderSorter()+(subSpecs.filters&&self.renderSubmenuFilters(subSpecs.filter)||"")+(subSpecs.search&&self.renderSubmenuSearch(subSpecs.search)||"")+(subSpecs.itemcount&&self.renderSubmenuItemcount(subSpecs.itemcount)||"")+submenuButtons.html+"</div><div class='joe-filters-holder'>"+function(){var act,sh='<div><joe-menu-label title="select one subset at a time"><b>Subsets</b></joe-menu-label>',starting=[];self.current.schema&&self.current.schema.hideAllSubset||starting.push({name:"All",filter:{}});var group=null;return starting.concat(_joe.current.subsets||[]).map(function(opt){if(opt.group_start)group=opt.group_start,sh+=renderOptionGroupStart(opt,"joe-subset-option");else if(opt.group_end)sh+="</joe-option-group>",group=null;else{var idval=opt.id||opt.name||"";if(!opt.condition||self.propAsFuncOrValue(opt.condition)){"active"==(act=self.current.subset&&self.current.subset.name==opt.name||!self.current.subset&&"All"==opt.name?"active":"")&&group&&(sh=sh.replace('<joe-option-group id="'+group+'-group" class="collapsed','<joe-option-group id="'+group+'-group" class="'));let optCount=self.current.list.where(opt.filter).length;sh+=`<joe-subset-option data-subset="${idval}" class="joe-subset-option ${act} " \n onclick="getJoe(${self.joe_index}).selectSubset('${(opt.id||opt.name||"").toString().replace(/\'/g,"\\'")}');">`+renderOptBorderColor(opt)+renderOptBGColor(opt)+renderOptStripeColor(opt)+'<span style="position:relative;">'+opt.name+"</span>"+`<option-count>${optCount}</option-count></joe-subset-option>`}}}),sh+="</div>",_bmResponse(BM,"subsets rendered"),sh}()+(filters_obj&&function(){_bmResponse(BM,"filters start");var fh='<div><joe-menu-label title="select multiple filters at once"><b>Filters</b></joe-menu-label>',filters=self.current.schema.filters;filters=self.propAsFuncOrValue(filters);var group=null;return(filters||[]).map(function(opt){if(opt.group_start)group=opt.group_start,fh+=renderOptionGroupStart(opt,"joe-filter-option");else if(opt.group_end)fh+="</joe-option-group>",group=null;else{var idval=opt.id||opt.name||"";if(!opt.condition||self.propAsFuncOrValue(opt.condition)){act="",self.current.filters&&self.current.filters[idval]?act="active":opt.hasOwnProperty("default")&&(act=self.propAsFuncOrValue(opt.default)?"active":"",self.toggleFilter(opt.name)),"active"==act&&group&&(fh=fh.replace('<joe-option-group id="'+group+'-group" class="collapsed">','<joe-option-group id="'+group+'-group" class="">'));let optCount=self.current.list.where(opt.filter).length;fh+='<joe-filter-option data-filter="'+idval+'" class="joe-filter-option '+act+'" onclick="getJoe('+self.joe_index+").toggleFilter('"+idval+"',this);\">"+renderOptBorderColor(opt)+renderOptBGColor(opt)+renderOptStripeColor(opt)+'<span class ="joe-option-checkbox"></span><span style="position:relative;">'+opt.name+"</span>"+`<option-count>${optCount}</option-count></joe-filter-option>`}}}),fh+='<joe-subset-option class="joe-subset-option clear-filters" onclick="'+getSelfStr+'.clearFilters()">clear filters</joe-subset-option>',fh+="</div>",_bmResponse(BM,"filters rendered"),fh}()||"")+"</div>"+self.Aggregator.renderAggregatorHolder(!1);else submenu='<div class="joe-panel-submenu">'+renderSidebarToggle("left")+renderSidebarToggle("right")+submenuButtons.html+(sectionAnchors.count&&sectionAnchors.code||"")+"</div>";function renderOptStripeColor(opt){var color=self.propAsFuncOrValue(opt.stripecolor||opt.stripeColor,null,null,opt),title="";return color&&$c.isObject(color.title)&&(title=' title="'+color.title+'" ',color=color.color),"<joe-stripe-color "+title+(color&&'style="background-color:'+color+';"'||"")+"></joe-stripe-color>"}function renderOptBGColor(opt){var color=self.propAsFuncOrValue(opt.bgcolor||opt.bgColor,null,null,opt);return color&&$c.isObject(color.title)&&(color=color.color),"<joe-bg-color "+(color&&'style="background-color:'+color+';"'||"")+"></joe-bg-color>"}function renderOptBorderColor(opt){var color=self.propAsFuncOrValue(opt.bordercolor||opt.borderColor,null,null,opt);return color&&$c.isObject(color.title)&&(color=color.color),"<joe-border-color "+(color&&'style="border:1px solid '+color+';"'||"")+"></joe-border-color>"}function renderOptionGroupStart(opt,childDom){var collapsed=self.propAsFuncOrValue(opt.collapsed)?"collapsed":"";if(opt.hasOwnProperty("filter")){var act,onclick,dataname,optdisplay=opt.display||opt.name||opt.group_start||"",optname=opt.id||opt.name||opt.group_start||"",cbox="";"joe-filter-option"==childDom?(dataname=' data-filter="'+optname+'" ',cbox='<span class ="joe-option-checkbox"></span>',act=self.current.filters&&self.current.filters[optname]?"active":"",onclick="getJoe("+self.joe_index+").toggleFilter('"+optname+"',this);_joe.Utils.stopPropagation();"):(dataname=' data-subset="'+optname+'" ',act=self.current.subset&&self.current.subset.name==optname||!self.current.subset&&"All"==opt.name?"active":"",onclick="getJoe("+self.joe_index+").selectSubset('"+optname.toString().replace(/\'/g,"\\'")+"');");var optiondiv="<"+childDom+" "+dataname+' class="'+childDom+" joe-group-option "+act+' " onclick='+onclick+">"+renderOptBorderColor(opt)+renderOptBGColor(opt)+renderOptStripeColor(opt)+cbox+'<span style="position:relative;">'+optdisplay+"</span></"+childDom+">";return'<joe-option-group id="'+opt.group_start+'-group" class="'+collapsed+' "><joe-menu-label onclick="$(this).parent().toggleClass(\'collapsed\');">'+optiondiv+"</joe-menu-label>"}return'<joe-option-group id="'+opt.group_start+'-group" class="'+collapsed+'"><joe-menu-label onclick="$(this).parent().toggleClass(\'collapsed\');">'+(opt.display||opt.name||opt.group_start)+"</joe-menu-label>"}return endLogGroup(),_bmResponse(BM,"[Submenu] rendered"),submenu},self.gotoSection=function(section,specs){specs=$.extend({},specs||{});if(section){var force_activation,i=specs.index||self.joe_index,sectionDom=$(".joe-overlay[data-joeindex="+i+"]").find(".joe-content-section[data-section='"+section+"']"),activated=sectionDom[0].hasClass("active");specs.hasOwnProperty("activate")&&(force_activation=specs.activate);var submenuDom=$(specs.dblclickdom)||self.overlay.find('joe-submenu-section[data-section="'+section+'"]');if(specs.focus){var tabbedmode,parent_dom=sectionDom.parents(".joe-content-sidebar,joe-panel-content");specs.hasOwnProperty("activate")?(submenuDom.toggleClass("active",force_activation),sectionDom.toggleClass("active",force_activation)):(submenuDom.toggleClass("active",!activated),sectionDom.toggleClass("active",!activated)),tabbedmode=submenuDom.parent().children(".active[data-panel="+submenuDom.data("panel")+"]").length>0,parent_dom.toggleClass("joe-tabbed-content",tabbedmode)}if(force_activation||!activated){sectionDom.removeClass("collapsed")[0].scrollIntoView();var sidebar=sectionDom.parents(".joe-content-sidebar");if(sidebar&&sidebar.length){var s=sidebar.data("side");self.toggleSidebar(s,!0),sectionDom.siblings(".joe-content-section").addClass("collapsed")}else"small-size"==self.sizeClass&&(self.toggleSidebar("left",!1),self.toggleSidebar("right",!1));$("joe-submenu-section-anchors.expanded").removeClass("expanded")}else $("joe-submenu-section-anchors.expanded").addClass("expanded")}},self.Sections={renderAchors:renderSectionAnchors,goto:self.gotoSection,gotoTop:function(index){var ajoe=getJoe(index);$(".joe-overlay[data-joeindex="+index+"]").find(".joe-panel-content").scrollTop(0),ajoe.panel.hasClass("small-size")&&(ajoe.toggleSidebar("right",!1),ajoe.toggleSidebar("left",!1)),$("joe-submenu-section-anchors.expanded").removeClass("expanded")}},self.Sections.toggleAll=function(expand){document.querySelectorAll(".joe-content-section").map(e=>{e.classList.toggle("collapsed",!expand)})},self.Sections.collapseAll=function(){document.querySelectorAll(".joe-content-section").map(e=>{e.classList.toggle("collapsed",!0)})},self.Sections.expandAll=function(){document.querySelectorAll(".joe-content-section").map(e=>{e.classList.toggle("collapsed",!1)})},self.Sections.toggleSome=function(sections,expand){sections.map(sect=>{document.querySelectorAll('.joe-content-section[data-section="'+sect+'"]').map(e=>{e.classList.toggle("collapsed",!expand)})})},self.Sections.unFocusAll=function(){self.overlay.find("joe-submenu-section").removeClass("active")},self.Sections.activate=function(sections){},self.Sections.setTabbedMode=function(show){self.overlay.find(".joe-content-sidebar,joe-panel-content").toggleClass("joe-tabbed-content",show)},self.Sections.toggle=function(dom){dom&&$(dom).parents("joe-submenu-section-anchors").toggleClass("expanded")},self.Sections.showAll=function(){self.Sections.toggleAll(!0)},this.Subset={getCached:function(list){list=list||self.current.list;var cache_query=self.current.schema.name+":"+self.current.subset.name,subcache=self.Cache.get(cache_query);return subcache||(subcache=list.where(self.current.subset.filter),self.Cache.set(subcache,{id:cache_query})),subcache}},this.Filter={refilter:function(){$c.isEmpty(self.current.filters)||self.filterListFromSubmenu(null,!0)},getCached:function(list){var BM=new Benchmarker;if(!self.current.schema||!self.current.schema.filters)return _bmResponse(BM,"filters gotten"),!1;list=list||self.current.list;var cache_query=self.current.schema.name+":filters",filtercache=self.Cache.get(cache_query);return filtercache||(filtercache=self.propAsFuncOrValue(self.current.schema.filters,self.current.list),self.Cache.set(filtercache,{id:cache_query})),_bmResponse(BM,"filters gotten"),filtercache}},this.renderSubmenuFilters=function(s){if(!(s||self.current.subsets||self.current.schema&&self.propAsFuncOrValue(self.current.schema.filters)))return"";var action=' onclick="getJoe('+self.joe_index+').toggleFiltersMenu();" ',active=self.current.subset?"active":"",count=$c.itemCount(self.current.filters);return"<div class='jif-panel-submenu-button joe-filters-toggle ' "+action+" title='show filters'>"+(active||count?'<joe-count-indicator class="'+active+(count?" count ":"")+'">'+(count||"")+"</joe-count-indicator>":"")+"</div>"};var leftMenuShowing=!1,rightMenuShowing=!1;this.toggleFiltersMenu=function(){leftMenuShowing=!leftMenuShowing,self.panel.toggleClass("show-filters",leftMenuShowing)},this.toggleAggregatorMenu=function(){rightMenuShowing=!rightMenuShowing,self.panel.toggleClass("show-aggregator",rightMenuShowing)},this.Filter.Options={datasetProperty:function(dataset,property,specs){var filters=[],groupname="string"==typeof(specs=specs||{}).group?specs.group:property;dataset=self.getDataset(self.propAsFuncOrValue(dataset)).sortBy(specs.sortby||"name");return specs.query&&(dataset=dataset.where(specs.query)),dataset.length?(specs.group&&filters.push({group_start:groupname,collapsed:specs.collapsed}),dataset.map(item=>{let props={name:item.name,filter:{}};props.filter[property]=item._id,filters.push(props)}),specs.group&&filters.push({group_end:groupname}),filters):[]},getDatasetPropertyValues:function(dataset,property,specs){var filters=[],groupname="string"==typeof(specs=specs||{}).group?specs.group:property;dataset=self.getDataset(self.propAsFuncOrValue(dataset)).sortBy(specs.sortby||"name");if(specs.query&&(dataset=dataset.where(specs.query)),!dataset.length)return[];specs.group&&filters.push({group_start:groupname,collapsed:specs.collapsed});var filterValues=specs.values||[];return dataset.map(item=>{item.hasOwnProperty(property)&&filterValues.push(item[property])}),(filterValues=Array.from(new Set(filterValues))).map(v=>{let filterObj={name:v,filter:{}};filterObj.filter[property]=v,filters.push(filterObj)}),specs.group&&filters.push({group_end:groupname}),filters},status:function(specs){specs=specs||{};"object"==$.type(schemaname)&&(specs=schemaname);var stat,schemaname=specs.schemaname||self.current.schema&&self.current.schema.name||"",stats=[],groupname="string"==typeof specs.group?specs.group:"tags";if(specs.group&&stats.push({group_start:groupname,collapsed:specs.collapsed}),self.Data.status.sortBy(specs.sortby||"index").where({datasets:{$in:[schemaname]}}).map(function(status){var sName=status.name;(stat={name:sName,id:status._id,filter:{status:status._id},title:self.propAsFuncOrValue(specs.title)||status.name})[specs.color||"bgcolor"]=status.color,stats.push(stat)}),specs.none){let noName="no status",noFil={$or:[{status:{$in:[null,""]}},{status:{$exists:!1}}]};stats.push({name:noName,filter:noFil})}return specs.group&&stats.push({group_end:groupname}),stats},tags:function(specs){var schemaname=(specs=specs||{}).schemaname||self.current.schema&&self.current.schema.name,filters=(schemaname=specs.schemaname||self.current.schema&&self.current.schema.name||"",[]),groupname="string"==typeof specs.group?specs.group:"tags";if(specs.group&&filters.push({group_start:groupname,collapsed:specs.collapsed}),_joe.Data.tag.sortBy(specs.sortby||"name").filter(function(tag){let fi={tags:{$in:[tag._id]}};if(-1!=tag.datasets.indexOf(schemaname)){let sName=tag.name;filters.push({name:sName,id:tag._id,filter:fi})}}),specs.untagged||specs.none){let noName="untagged",noFil={$or:[{tags:{$size:0}},{tags:{$exists:!1}}]};filters.push({name:noName,filter:noFil})}return specs.group&&filters.push({group_end:groupname}),filters}},this.Filter.generateQuery=this.generateFiltersQuery=function(){var filterinfo,filterobj,query={};for(var f in self.current.filters)if(!(filterinfo=(self.propAsFuncOrValue(self.current.schema.filters)||[]).where({name:f})[0]||self.current.filters[f]||{}).schema||!self.current.schema||!self.current.schema.__schemaname||filterinfo.schema==(self.current.schema.__Schemaname||self.current.schema.__schemaname))for(var ff in filterobj=filterinfo.filter)if(query[ff])switch($.type(filterobj[ff])){case"number":case"string":case"object":"string"==$.type(query[ff])||"number"==$.type(query[ff])?query[ff]={$in:[query[ff],filterobj[ff]]}:"object"==$.type(query[ff])&&query[ff].hasOwnProperty("$in")&&(query[ff].$in=query[ff].$in.concat(filterobj[ff].$in||[filterobj[ff]]))}else query[ff]=filterobj[ff];else delete self.current.filters[filterinfo.name];return logit(query),query},self.Search={schema:{title:"Search Results",name:"search",listTitle:function(item){return"<joe-full-right><joe-subtext>updated</joe-subtext><joe-subtitle>"+self.Utils.toDateString(item.joeUpdated)+"</joe-subtitle></joe-full-right>"+(_joe.schemas[item.itemtype].menuicon&&'<joe-icon class="icon-40 icon-grey fleft">'+_joe.schemas[item.itemtype].menuicon+"</joe-icon>"||"")+"<joe-subtext>${itemtype}</joe-subtext><joe-title>${name}</joe-title><joe-subtitle>${info}</joe-subtitle><joe-subtext>${_id}</joe-subtext>"},listmenu:[],sorter:["name",{name:"updated",value:"!joeUpdated"},"itemtype"],filters:function(){var f=[];return __appCollections.concat().sort().map(function(s){f.push({name:s,filter:{itemtype:s}})}),f},listAction:function(item){return"goJoeItem('"+item._id+"','"+item.itemtype+"')"}}},this.renderSubmenuSearch=function(s){return'<div class=\'joe-submenu-search \'><input class="joe-submenu-search-field" onkeyup="_joe.filterListFromSubmenu(this.value);" placeholder="search list" value="'+(self.current.keyword||$GET("keyword")||"")+'"/></div>'},this.searchTimeout;var searchTimeoutTime=$c.isMobile()?750:500,currentListItems,renderFieldTo;function renderSubmenuSelectors(specs){specs=$.extend({options:[],content:"",action:"nothing",buttonTemplate:"<div class='selection-label'>${label}</div>${name}",label:"label",cssclass:""},specs||{});var selectionTemplate="<div data-colcount='${name}' onclick='getJoe("+self.joe_index+")."+specs.action+"(${name});' class='jif-panel-button selector-button-${name} joe-selector-button '>"+specs.buttonTemplate+"</div>",onclick_action="onclick='$(this).parent().toggleClass(\"expanded\")'";return"<div class='joe-submenu-selector' >"+(specs.content||"<div class='joe-selector-button selector-label' "+onclick_action+">"+specs.label+"</div><div class='joe-selector-button selector-close joe-close-button' "+onclick_action+">&nbsp;</div><joe-submenu-selector-options>"+fillTemplate(selectionTemplate,specs.options)+"</joe-submenu-selector-options>")+"</div>"}function renderEditorStyles(){return(self.specs.style&&self.specs.style.inset?"joe-style-inset ":"")+(self.specs.style&&self.specs.style.cards?"joe-style-cards ":"")}function renderSidebarToggle(side){return self.current.sidebars[side].hidden?"":'<div class="jif-panel-submenu-button joe-sidebar-button joe-sidebar_'+side+'-button" title="toggle" onclick="getJoe('+self.joe_index+").toggleSidebar('"+side+"')\">"+self.SVG.icon["sidebar-"+side]+"</div>"}function cleanDeleted(list,schema){var query={};return query[self.getCascadingProp("deleted")||"_deleted"]={$in:[!1,"false",void 0]},list.where(query)}this.filterListFromSubmenu=function(keyword,now){function searchFilter(keyword,frominput){var searchBM=new Benchmarker;if(self.current.keyword!=keyword){keyword=keyword||$(".joe-submenu-search-field").val()||"",frominput||keyword||!self.current.keyword||(keyword=self.current.keyword,$(".joe-submenu-search-field").val(keyword));var testable,value=keyword.toLowerCase(),keywords=value.replace(/,/g," ").split(" "),filters=self.generateFiltersQuery();_joe.history[_joe.history.length-1].keyword=value,_joe.history[_joe.history.length-1].filters=self.current.filters;var id,idprop=self.getIDProp(),listables=self.current.list;self.current.subset&&(listables=self.Subset.getCached()),listables=cleanDeleted(listables);var searchables=self.current.schema&&self.current.schema.searchables;_bmResponse(searchBM,"search where"),self.current.filteredList=currentListItems=listables.where(filters).filter(function(i){if(!keyword)return!0;if(id=i[idprop],testable="",searchables){searchables.map(function(s){testable+=i[s]+" "}),testable=testable.toLowerCase()+id;for(var k=0,tot=keywords.length;k<tot;k++)if(-1==testable.indexOf(keywords[k]))return!1}else{tableMode?testable=self.renderTableItem(i,!0):gridMode||(testable=self.renderListItem(i,!0)),testable=testable.toLowerCase()+id;for(k=0,tot=keywords.length;k<tot;k++)if(-1==testable.indexOf(keywords[k]))return!1}return!0}),_bmResponse(searchBM,"search '"+keyword+"' filtered "+currentListItems.length+"/"+self.current.list.length+" items ["+listables.length+"]"),self.overlay.find(".joe-submenu-itemcount").html(currentListItems.length+" item"+(currentListItems.length>1?"s":"")),self.panel.find(".joe-panel-content").html(self.renderListItems(currentListItems,0,self.specs.dynamicDisplay))}self.current.keyword=keyword,self.current.search_schema;var titleObj=createTitleObject();titleObj.subTitle?self.panel.find(".joe-panel-title").addClass("subtitled").html(titleObj.docTitle+"<joe-subtext>"+titleObj.subTitle+"</joe-subtext>"):self.panel.find(".joe-panel-title").addClass("subtitled").html(titleObj.docTitle),self.panel.find(".joe-filters-toggle").replaceWith(self.renderSubmenuFilters()),self.Aggregator.update()}clearTimeout(self.searchTimeout),self.overlay.removeClass(".multi-edit"),now?searchFilter(keyword):self.searchTimeout=setTimeout(function(){searchFilter(keyword,!0)},searchTimeoutTime)},this.renderSubmenuItemcount=function(s){return"<div class='joe-submenu-itemcount'>items</div>"},this.nothing=function(nothing){alert(value)},this.renderViewModeButtons=function(subspecs){var gridspecs=self.current.schema&&(self.current.schema.grid||self.current.schema.gridView),tablespecs=tableSpecs;if(!gridspecs&&!tablespecs)return"";var modes=[{name:"list"}];gridspecs&&modes.push({name:"grid"}),tablespecs&&modes.push({name:"table"});var modeTemplate="<div data-view='${name}' onclick='getJoe("+self.joe_index+").setViewMode(\"${name}\");' class='jif-panel-button joe-viewmode-button ${name}-button joe-selector-button'>&nbsp;</div>",onclick_action="onclick='$(this).parent().toggleClass(\"expanded\")'";return"<div class='joe-submenu-selector joe-viewmode-selector opts-"+modes.length+"' ><div class='joe-selector-button selector-label' "+onclick_action+">view</div><div class='joe-selector-button selector-close joe-close-button' "+onclick_action+">&nbsp;</div><joe-submenu-selector-options>"+fillTemplate(modeTemplate,modes)+"</joe-submenu-selector-options></div>"},this.setViewMode=function(mode){self.reload(!0,{viewMode:mode})},this.renderColumnCountSelector=function(subspecs){if(!subspecs)return"";var modes=[{name:"1"},{name:"2"},{name:"3"},{name:"4"},{name:"5"}];"number"==typeof eval(subspecs)&&(modes=modes.slice(0,eval(subspecs)));var h=renderSubmenuSelectors({options:modes,label:"cols",value:colCount,action:"setColumnCount"});return h},this.setColumnCount=function(mode){self.overlay[0].className=self.overlay[0].className.replace(/cols-[0-9]/,"cols-"+mode),mode&&(colCount=mode);var multi=!!(mode&&mode>1);self.overlay.toggleClass("multi-col",multi)},this.Sorter={},this.Sorter.render=this.renderSorter=function(subspecs){var sorter=self.current.subset&&self.current.subset.sorter||self.current.schema&&self.current.schema.sorter||"name";if("string"==$.type(sorter)&&(sorter=sorter.split(",")),-1!=sorter.indexOf("name")||-1!=sorter.indexOf("!name")||sorter.where({field:"name"}).length||sorter.push("name"),1==sorter.length)return"";return'<label for="joe-'+self.joe_index+'-sorter" class="joe-list-sorter" ><svg onclick="getJoe('+self.joe_index+').Sorter.reverse();" class="joe-list-sorter-icon" title="reverse sort" xmlns="http://www.w3.org/2000/svg" viewBox="-20 6 40 40"><path d="M-4 16L-9.5 21.5 -8 23 -5 20 -5 28 -3 28 -3 20 0 23 1.5 21.5 -4 16zM3 16L3 18 5 18 5 16 3 16zM3 20L3 22 5 22 5 20 3 20zM3 24L3 32 0 29 -1.5 30.5 4 36 9.5 30.5 8 29 5 32 5 24 3 24zM-5 30L-5 32 -3 32 -3 30 -5 30zM-5 34L-5 36 -3 36 -3 34 -5 34z"/></svg><select title="sort" name="joe-'+self.joe_index+'-sorter" onchange="getJoe('+self.joe_index+').Sorter.resort(this.value);">'+sorter.map(function(so){var s=so,display=so;$c.isString(so)||(s=so.field||so.value,display=so.display||so.name||s),s=s.replace("!","");var valCheck=(self.current.sorter[0].field||self.current.sorter[0].value||self.current.sorter[0]).replace("!","");return"<option "+(s==valCheck?"selected":"")+' value="'+s+'">'+display+"</option>"}).join("")+"</select></label>"},this.Sorter.resort=function(sorter){self.reload(!0,{sorter:sorter})},this.Sorter.reverse=function(sorter){var curSorter=self.current.sorter;"array"==$.type(curSorter)&&(curSorter=[].concat(curSorter),"string"==$.type(curSorter[0])?0==curSorter[0].indexOf("!")?curSorter[0]=curSorter[0].substr(1):curSorter[0]="!"+curSorter[0]:"object"==$.type(curSorter[0])&&curSorter[0].value&&(0==curSorter[0].value.indexOf("!")?curSorter[0].value=curSorter[0].value.substr(1):curSorter[0].value="!"+curSorter[0].value),self.reload(!0,{sorter:curSorter}))},this.Submenu=this.Submenu||{},this.Aggregator={},this.Aggregator.renderToggleButton=function(){return s&&self.current.schema&&self.current.schema.hasOwnProperty("aggregator")?"<div class='jif-panel-submenu-button joe-aggregator-toggle ' "+(' onclick="getJoe('+self.joe_index+').toggleAggregatorMenu();" ')+" title='show aggregator'></div>":""},this.Aggregator.renderAggregatorHolder=function(contentOnly,content){if(!(s&&self.current.schema&&self.current.schema.hasOwnProperty("aggregator")))return"";var html=content=self.propAsFuncOrValue(self.current.schema.aggregator,self.current.filteredList||self.current.list);return contentOnly||(html="<div class='joe-aggregator-holder'>"+content+"</div>"),html},this.Aggregator.update=function(list){list=list||self.current.filteredList;var content=self.Aggregator.renderAggregatorHolder(!0),dom=document.querySelector('.joe-overlay[data-joeindex="0"]').getElementsByClassName("joe-aggregator-holder")[0];dom&&(dom.innerHTML=content)},this.renderEditorContent=function(specs){var content;self.current.sidebars={left:{collapsed:!1},right:{collapsed:!1}},specs||(specs={mode:"text",text:"No object or list selected"});var mode=specs.mode;switch(mode){case"text":content=self.renderTextContent(specs);break;case"rendering":content=self.renderHTMLContent(specs);break;case"list":content=self.renderListContent(specs);break;case"object":content=self.renderObjectContent(specs);break;default:content=content||""}var submenu="";specs.minimode||("list"==mode&&self.current.submenu||self.current.submenu||renderSectionAnchors().count||renderSubmenuButtons().content)&&(submenu=" with-submenu ");var scroll='onscroll="getJoe('+self.joe_index+').onListContentScroll(this);"',rightC=content.right||"",leftC=content.left||"",html='<joe-panel-content class="'+("joe-panel-content "+renderEditorStyles()+submenu)+'" '+(listMode&&scroll||"")+">"+(content.main||content)+"</joe-panel-content>"+self.renderSideBar("left",leftC,{css:submenu})+self.renderSideBar("right",rightC,{css:submenu});return self.current.sidebars.left.content=leftC,self.current.sidebars.right.content=rightC,html},this.renderSideBar=function(side,content,specs){side=side||"right";var addCss=(specs=specs||{}).css||"";return"<div class='joe-content-sidebar "+renderEditorStyles()+" joe-absolute "+side+"-side "+addCss+"' data-side='"+side+"'>"+(content||"")+__clearDiv__+"</div>"},this.toggleSidebar=function(side,hardset){if(-1==["right","left"].indexOf(side))return!1;self.panel.toggleClass(side+"-sidebar",hardset)},this.renderTextContent=function(specs){return'<div class="joe-text-content">'+((specs=specs||{}).text||specs.object||"")+"</div>"},this.renderHTMLContent=function(specs){return'<textarea class="joe-rendering-field">'+((specs=specs||{}).rendering||"")+"</textarea>"},this.Render.listContent=this.renderListContent=function(specs){var wBM=new Benchmarker;if(specs.minimode)return self.renderMiniListContent(specs);currentListItems=[],self.current.selectedListItems=[],self.current.anchorListItem=null;(specs=specs||{}).schema;var filteredList,numItemsToRender,list=specs.list||[],html="";list=cleanDeleted(list),currentListItems=list,self.current.subset&&(filteredList=currentListItems=self.Subset.getCached(list),_bmResponse(wBM,"list subsetted"));var primer=null;if(self.current.sorter&&("array"!=$.type(self.current.sorter)||self.current.sorter.length)){var sorterValues=self.current.sorter;if($c.isArray(self.current.sorter)&&self.current.sorter[0].field){sorterValues=[];for(var i=0,len=self.current.sorter.length;i<len;i++)sorterValues.push(self.current.sorter[i].field||self.current.sorter[i]),primer=self.current.sorter[i].primer||primer||null}else primer=self.current.sorter[0].primer||null;list=list.sortBy(sorterValues,null,primer)}return _bmResponse(wBM,"list sort complete"),$c.isEmpty(_joe.current.filters)||(filteredList=currentListItems.where(self.Filter.generateQuery()),currentListItems=filteredList,_bmResponse(wBM,"list filtered")),_bmResponse(wBM,"list prerender"),numItemsToRender=self.specs.dynamicDisplay||currentListItems.length,html+=self.renderListItems(currentListItems,0,numItemsToRender),_bmResponse(wBM,"list complete"),self.current.filteredList=filteredList,html},this.renderMiniListContent=function(specs){var wBM=new Benchmarker,schema=(specs=specs||{}).schema,list=specs.object||[],idprop=specs.idprop||"_id",html="",sorter=specs.sorter||"name";list=list.sortBy(sorter);for(var template,click="getJoe("+self.joe_index+").minis['"+specs.minimode+"'].callback('${"+idprop+"}')",li=0,tot=list.length;li<tot;li++){let item=list[li],schemaName=item.itemtype||item.schema||item.name;template=self.propAsFuncOrValue(specs.template,item)||"<joe-title>${name}</joe-title><joe-subtext>${"+idprop+"}</joe-subtext>",template='<joe-list-item schema="'+(schemaName||schema.name||schema)+'" class="joe-field-list-item clickable" onclick="'+click+'">'+template+"</joe-list-item>",html+=fillTemplate(template,item)}return _bmResponse(wBM,"minilist complete"),html},this.Render.listItems=this.renderListItems=function(items,start,stop){var listItem,html="",simple_sorter=(items=items||currentListItems,[]);self.current.sorter.map(function(s){simple_sorter.push(s.field||s.value||s)}),items=items.sortBy(simple_sorter);start=start||0,stop=stop||currentListItems.length-1;if(gridMode){for(var cell,colinfo,col_filter,subitems,gridspecs=self.current.schema&&(self.current.schema.grid||self.current.schema.gridView)||{},columns=self.propAsFuncOrValue(gridspecs.cols)||[],rows=self.propAsFuncOrValue(gridspecs.rows)||[],cells=[],c=0;c<columns.length;c++)col_filter=(colinfo=columns[c]).filter,subitems=items.where(col_filter),rows.length||(cell_filter=colinfo.filter,cell={name:colinfo.name,filter:col_filter,html:"",items:[]},subitems.map(function(i){cell.items.push(i),cell.html+=self.Render.gridItem(i)}),cells.push([cell]));html+='<table class="joe-grid-table"><thead>',columns.map(function(c){$c.isString(c)?html+="<th>"+c+"</th>":$c.isObject(c)&&(html+="<th>"+(c.header||c.display||c.name)+"</th>")}),html+="</thead><tbody>";for(var row_number=0,row_count=rows.length||1;row_number<row_count;)html+="<tr>",cells.map(function(cell_list){html+='<td class="joe-grid-cell">'+cell_list[row_number].html+"</td>"}),html+="</tr>",row_number++;return html+="</tbody></table>"}if(tableMode){html+='<table class="joe-item-table" cellspacing="0"><thead class="joe-table-head"><th>&nbsp;</th>',tableSpecs.cols.map(function(c){$c.isString(c)?html+="<th>"+c+"</th>":$c.isObject(c)&&(html+="<th>"+(c.header||c.display)+"</th>")}),html+="</thead><tbody>",stop=currentListItems.length;for(var i=start;i<stop;i++)(listItem=items[i])&&(html+=self.renderTableItem(listItem,!1,i+1));return html+="</tbody></table>"}for(i=start;i<stop;i++)(listItem=items[i])&&(html+=self.renderListItem(listItem,!1,i+1));return html},this.onListContentScroll=function(domObj){var listItem=self.panel.find(".joe-panel-content-option").last()[0],currentItemCount=self.panel.find(".joe-panel-content-option").length;if(currentItemCount!=currentListItems.length){var viewPortHeight=self.panel.find(".joe-panel-content").height(),html="";try{listItem.getBoundingClientRect().bottom-500<viewPortHeight&&(tableMode||(html+=self.renderListItems(null,currentItemCount,currentItemCount+self.specs.dynamicDisplay),self.panel.find(".joe-panel-content").append(html)))}catch(e){self.Error.add("error scrolling for more content: \n"+e,e,{caller:"self.onListContentScroll",domObj:domObj})}}},this.renderObjectContent=function(specs){renderFieldTo="main";var propObj,object=(specs=specs||{}).object,fields={main:"",left:"",right:""};specs.minimode||(self.current.fields=[],self.current.sections={}),specs.schema&&"string"==typeof specs.schema&&(specs.schema=self.schemas[specs.schema]);var fhtml,schemaFields=!!specs.schema&&self.propAsFuncOrValue(specs.schema.fields);if(specs.schema&&schemaFields)(schemaFields||[]).map(function(prop){fhtml=self.renderObjectPropFieldUI(prop,specs),fields[renderFieldTo]+=fhtml});else for(var prop in object)object.hasOwnProperty(prop)&&(propObj=$.extend({name:prop,type:"text",value:object[prop]},self.fields[prop],{value:object[prop]}),fields.main+=self.renderObjectField(propObj));fields.main;return fields};var rerenderingField=!1,preProp;function _getSection(secname){return self.current.sections[secname]}self.Fields.rerender=this.rerenderField=function(fieldname,valueObj){var ftype,field;fieldname&&(self.current.constructed=self.constructObjectFromFields(),self.current.constructed&&!$c.isEmpty(self.current.constructed)&&($.extend(self.current.constructed,valueObj||{}),rerenderingField=!0,$c.isArray(fieldname)&&(fieldname=fieldname.join(",")),fieldname.split(",").condense().map(function(f){var fields=self.renderObjectPropFieldUI(f);field=self.getField(f),ftype=self.propAsFuncOrValue(field.type,self.current.constructed).toLowerCase(),$(".joe-object-field[data-name="+f+"]").parent().replaceWith(fields),self.Fields[ftype]&&self.Fields[ftype].ready&&self.Fields[ftype].ready(self.current.constructed)}),rerenderingField=!1,self.current.constructed=null))},self.Set=self.Fields.set=function(field,value){if(!listMode){field=self.propAsFuncOrValue(field),value=self.propAsFuncOrValue(value);var vals={};return vals[field]=value,self.Fields.rerender(field,vals),value}logit("in list mode")},self.Get=self.Fields.get=function(field){if(!listMode)return self.constructObjectFromFields()[field];logit("in list mode")},self.renderObjectPropFieldUI=function(prop,specs){var fields="";if("string"==$.type(prop)&&prop.contains(":")){var ps=prop.split(":");prop={name:ps[0],type:ps[1]},ps[2]&&(ps[2].contains("%")&&parseInt(ps[2])?prop.width=ps[2]:prop.display=ps[2])}var schemaspec=specs&&specs.schema||self.current.schema,existingProp=(self.propAsFuncOrValue(schemaspec.fields)||[]).filter(function(s){return s.name==prop||s.extend==prop})[0];existingProp&&(prop=existingProp);var constructed=self.current.constructed||self.constructObjectFromFields();if("string"==$.type(prop)){var propObj=self.fields[prop]||self.current.fields.filter(function(f){return f.name==prop})[0]||{},fieldProp=$.extend({},propObj);propObj=extendField(prop);void 0!==constructed[prop]&&(fieldProp.value=constructed[prop]),fields+=self.renderObjectField(propObj)}else if("object"==$.type(prop)&&prop.name){fieldProp=$.extend({},prop||{}),propObj=extendField(prop.name);void 0!==constructed[prop.name]&&(fieldProp.value=constructed[prop.name]),fields+=self.renderObjectField(propObj)}else if(prop&&prop.extend){fieldProp=$.extend({},self.fields[prop.extend]||{},prop.specs||{}),propObj=extendField(prop.extend);void 0!==constructed[prop.extend]&&(fieldProp.value=constructed[prop.extend]),fields+=self.renderObjectField(propObj)}else"object"==$.type(prop)&&(prop.component?fields+=self.renderPropComponent(prop):prop.label?fields+=self.renderContentLabel(prop):prop.section_start?fields+=self.renderPropSectionStart(prop):prop.section_end?fields+=self.renderPropSectionEnd(prop):prop.sidebar_start?"main"!=(renderFieldTo=prop.sidebar_side||prop.sidebar_start||"main")&&(prop.hasOwnProperty("collapsed")&&(self.current.sidebars[renderFieldTo].collapsed=self.propAsFuncOrValue(prop.collapsed)),prop.hasOwnProperty("hidden")&&(self.current.sidebars[renderFieldTo].hidden=self.propAsFuncOrValue(prop.hidden),self.current.sidebars[renderFieldTo].hidden&&(self.current.sidebars[renderFieldTo].collapsed=!0))):prop.sidebar_end&&(renderFieldTo="main"));function extendField(propname){propname=propname||prop;var cobj=self.current.constructed||self.current.object,rerenderObj={};return rerenderingField&&(fieldProp.run||fieldProp.value)&&(fieldProp.run||(rerenderObj.value=fieldProp.value)),$.extend({name:propname,type:"text"},{onblur:schemaspec.onblur,onchange:schemaspec.onchange,onkeypress:schemaspec.onkeypress,onkeyup:schemaspec.onkeyup},fieldProp,rerenderObj,{value:cobj[propname]})}return fields},self.renderPropComponent=function(prop){var html,componentName=self.propAsFuncOrValue(prop.component),cobj=self.current.constructed||self.current.object;if(prop.specs){let specs=self.propAsFuncOrValue(prop.specs);var specHtml=Object.keys(specs).map(spec=>` ${specs}="${specs[spec]}"`);html=`<${componentName} item_id="${cobj._id}" ${specHtml} >${componentName}</${componentName}>`}else html=`<${componentName} item_id="${cobj._id}">${componentName}</${componentName}>`;return html},self.renderContentLabel=function(specs){return specs.hasOwnProperty("condition")&&!_joe.propAsFuncOrValue(specs.condition)||specs.hasOwnProperty("hidden")&&_joe.propAsFuncOrValue(specs.hidden)?"":"<div class='joe-content-label'>"+fillTemplate(specs.label,self.current.object)+"</div>"},self.renderPropSectionStart=function(prop){var show="",hidden=!1;prop.condition&&!prop.condition(self.current.object)&&(show=" no-section ",hidden=!0),self.current.sidebars[renderFieldTo]&&self.current.sidebars[renderFieldTo].hidden&&(show=" no-section ",hidden=!0);var secname=fillTemplate(self.propAsFuncOrValue(prop.display||prop.section_label||prop.section_start,self.current.object),self.current.object),secID=prop.section_start;if(!secname||!secID)return"";var section_html='<div class="joe-content-section '+show+" "+(self.propAsFuncOrValue(prop.collapsed)?"collapsed":"")+'" data-section="'+secID+'"><joe-content-section-label class="joe-content-section-label" onclick=\'$(this).parent().toggleClass("collapsed");\''+(" ondblclick=\"$('joe-submenu-section[data-section="+secID+"]').dblclick();\" ")+">"+secname+'</joe-content-section-label><div class="joe-content-section-content">';return self.current.sections[secID]={open:!0,name:secname,id:secID,hidden:hidden,renderTo:renderFieldTo,anchor:prop.anchor},section_html},self.renderPropSectionEnd=function(prop){var secID=prop.section_end,section=_getSection(secID);if(!secID||!section||!section.open)return"";var section_html=__clearDiv__+"</div></div>";return section.open=!1,section_html},this.renderEditorFooter=function(specs){var fBM=new Benchmarker,customMenu=!0,menu=(specs=specs||this.specs||{}).minimenu||listMode&&specs.schema&&specs.schema.listmenu||specs.listmenu||multiEdit&&(specs.multimenu||specs.schema&&specs.schema.multimenu||__defaultMultiButtons)||specs.menu||null;menu||(menu=__defaultObjectButtons,customMenu=!1),menu=self.propAsFuncOrValue(menu);var html='<div class="joe-panel-footer"><div class="joe-panel-menu">';return menu.map(function(m){html+=self.renderFooterMenuItem(m)},this),!specs.minimenu&&self.current.list&&"array"==$.type(self.current.data)&&(html+=self.renderFooterMenuItem(__selectAllBtn__),html+='<div class="joe-selection-indicator"></div>',customMenu||(html+=self.renderFooterMenuItem({label:"Multi-Edit",name:"multiEdit",css:"joe-multi-only",action:"getJoe("+self.joe_index+").editMultiple()"}))),html+=__clearDiv__+"</div></div>",_bmResponse(fBM,"[Footer] rendered"),html},this.renderFooterMenuItem=function(m){return self.renderMenuButtons(m,"joe-footer-button")},this.renderMenuButtons=function(button,menucss){if(!button)return"";menucss=menucss||"";for(var display,action,m,html="",b=0,tot=(button="array"==$.type(button)?button:[button]).length;b<tot;b++){m=button[b];let schema=self.propAsFuncOrValue(m.schema);m?m.condition&&!self.propAsFuncOrValue(m.condition)||(display=fillTemplate(self.propAsFuncOrValue(m.label||m.display||m.name),self.current.object),action=m.callback?"getJoe("+self.joe_index+").Cache.callback('"+m.callback+"');":fillTemplate(self.propAsFuncOrValue(m.action),self.current.object)||"alert('"+display+"')",html+=`<joe-button class="joe-button ${menucss} ${m.css||""}" action="${action}" \n data-btnid="${m.id||m.name}" \n ${schema&&`schema="${schema}"`||""} \n ${m.color&&`color="${m.color}"`||""} \n title="${m.title||display||""}">\n ${display}</joe-button>`):logit("error loading menu button")}return html};var prePropWidths=0;function _getPropPlaceholder(prop){var placeholder=self.propAsFuncOrValue(prop.placeholder||prop.display||prop.name)||"";return!1===prop.placeholder?"":placeholder&&' placeholder="'+placeholder+'"'||""}function _disableField(prop){return prop.hasOwnProperty("locked")&&self.propAsFuncOrValue(prop.locked)?" disabled ":""}function cleanString(value){return((value||"")+"").replace(/\"/g,"&quot;")}this.renderObjectField=function(prop,mini){if(prop.hasOwnProperty("condition")&&!self.propAsFuncOrValue(prop.condition))return"";var joeFieldBenchmarker=new Benchmarker;self.current.fields.push(prop),prop.value=prop.asFunction?prop.value:self.propAsFuncOrValue(prop.value),prop.format&&$.type("function"==prop.format)&&(prop.value=prop.format(prop.value,prop,self.current.item)),null==prop.value&&null!=prop.default&&(prop.value=prop.default),self.current.reset[prop.name]||(self.current.reset[prop.name]="object"==typeof prop.value?$.extend({},prop.value):prop.value),prop.reset=self.current.reset[prop.name];var hidden="",qHidden=self.propAsFuncOrValue(prop.hidden);qHidden&&(hidden=void 0===parseBoolean(qHidden)?"!"==qHidden[0]^!!$.extend({},self.current.object,self.constructObjectFromFields())[qHidden.replace("!","")]?"hidden":"":"hidden");prop.locked=self.propAsFuncOrValue(prop.locked);var cssClass=prop.cssClass?self.propAsFuncOrValue(prop.cssClass):"",required="";self.propAsFuncOrValue(prop.required)&&(required="joe-required");var html="",propdside=prop.sidebar_side||prop.side||renderFieldTo;preProp&&preProp.width&&!prop.width&&(html+='<div class="clear"></div>');var containercolor=self.propAsFuncOrValue(prop.containercolor,null,null,_jco(!0)[prop.name])||"";containercolor&&(containercolor=" background-color:"+containercolor+";");var sizestyles=" ";prop.height&&(sizestyles+="min-height:"+prop.height+"; "),prop.width?html+='<joe-field-container class="joe-field-container joe-fleft" style="width:'+prop.width+"; "+sizestyles+containercolor+'" data-side="'+propdside+'">':html+='<joe-field-container field="'+prop.name+'" class="joe-field-container" data-side="'+propdside+'" style="'+sizestyles+containercolor+'">';var proptype=self.propAsFuncOrValue(prop.type,self.current.constructed),fieldlabel=self.propAsFuncOrValue(prop.display||prop.label||prop.name),icon=self.propAsFuncOrValue(prop.icon);function renderFieldAttribute(attribute){var obj=rerenderingField?self.current.constructed:self.current.object,propval=prop[attribute];return propval&&'<joe-field-attribute class="jfa-'+attribute+'">'+fillTemplate(self.propAsFuncOrValue(propval),obj)+"</joe-field-attribute>"||""}return icon&&self.schemas[icon]&&self.schemas[icon].menuicon&&(icon=self.schemas[icon].menuicon),html+='<joe-field class="joe-object-field '+hidden+" "+required+" "+proptype+"-field "+(!1===prop.label?" hide-label ":"")+" "+cssClass+'" data-type="'+proptype+'" data-name="'+prop.name+'">'+renderFieldAttribute("before")+'<label class="joe-field-label '+(icon?"iconed":"")+' " title="'+prop.name+'">'+(icon||"")+fillTemplate(fieldlabel,self.current.object)+(required?"*":"")+self.renderFieldTooltip(prop)+self.renderFieldReloadIcon(prop)+"</label>",html+=self.renderFieldComment(prop),self.current.userSpecs&&self.current.userSpecs.multiedit&&(html+='<div class="joe-field-multiedit-toggle" onclick="$(this).parent().toggleClass(\'multi-selected\')"></div>'),html+=self.selectAndRenderFieldType(prop),html+=self.renderGotoLink(prop),html+=renderFieldAttribute("after"),html+="</joe-field>",html+="</joe-field-container>",preProp=prop,_bmResponse(joeFieldBenchmarker,"field "+prop.name+" "+prop.type),html},this.renderGotoLink=function(prop,style){var goto=self.propAsFuncOrValue(prop.goto);if(goto){var action="";"string"==$.type(goto)&&(action=goto,action="getJoe("+self.joe_index+").gotoFieldItem(this,'"+goto+"');");var btnHtml="";if("select"===(style||prop.type))btnHtml+='<div class="joe-button inline joe-view-button joe-iconed-button" onclick="'+action+'" title="view '+goto+'">view</div>';return btnHtml}return""},this.gotoFieldItem=function(dom,schema){var fieldname=$(dom).parents(".joe-object-field").data("name"),field=self.getField(fieldname),idprop=field.idprop||self.getIDProp(schema),values=self.getFieldValues(field.values,field),id=$(dom).siblings(".joe-field").val(),object=values.filter(function(v){return v[idprop]==id})[0]||!1;if(!object)return!1;self.show(object,{schema:schema})},this.renderFieldComment=function(prop){var comment=self.propAsFuncOrValue(prop.comment);return comment?'<div class="joe-field-comment">'+comment+"</div>":""},this.renderFieldTooltip=function(prop){return prop.tooltip?'<span class="joe-field-tooltip" title="'+__removeTags(prop.tooltip)+'">i</span>':""},this.renderFieldReloadIcon=function(prop){return self.propAsFuncOrValue(prop.reloadable)?` <joe-icon class="joe-reload-icon fright" title="Reload Field" onclick="_joe.Fields.rerender('${prop.name}')">⟳</joe-icon>`:""},this.selectAndRenderFieldType=function(prop){var html="",proptype=(self.propAsFuncOrValue(prop.type)||"").toLowerCase();switch(proptype||(console.error(prop),self.propAsFuncOrValue(prop.type)),proptype){case"select":html+=self.renderSelectField(prop);break;case"multisort":case"multisorter":html+=self.renderMultisorterField(prop);break;case"guid":html+=self.renderGuidField(prop);break;case"number":html+=self.renderNumberField(prop);break;case"int":html+=self.renderIntegerField(prop);break;case"date":html+=self.renderDateField(prop);break;case"boolean":html+=self.renderBooleanField(prop);break;case"geo":case"map":html+=self.renderGeoField(prop);break;case"image":case"img":html+=self.renderImageField(prop);break;case"buckets":html+=self.renderBucketsField(prop);break;case"content":html+=self.renderContentField(prop);break;case"url":html+=self.renderURLField(prop);break;case"tags":html+=self.renderTagsField(prop);break;case"color":html+=self.renderColorField(prop);break;case"button":html+=self.renderButtonField(prop);break;case"group":html+=self.renderCheckboxGroupField(prop);break;case"uploader":html+=self.renderUploaderField(prop);break;case"preview":html+=self.renderPreviewField(prop);break;case"passthrough":html+=self.renderPassthroughField(prop);break;case"userfavorite":html+=self.renderUserFavoriteField(prop);break;default:self.Fields[proptype]&&self.Fields[proptype].render?html+=self.Fields[proptype].render(prop):html+=self.renderTextField(prop)}if(prop.ai)try{var aiLabel=self.propAsFuncOrValue(prop.ai.label)||"AI";html+='<button type="button" class="joe-ai-autofill-button joe-iconed-button joe-button" onclick="if(window._joe && _joe.Ai && _joe.Ai.populateField){_joe.Ai.populateField(\''+(prop.name||"")+'\');}" title="Let AI suggest a value for this field">'+aiLabel+'</button><div class="clear"></div>'}catch(_e){}return html},this.getActionString=function(evt,prop){return(evt=prop[evt])?"string"==$.type(evt)?evt:prop[evt]?" "+self.functionName(prop[evt])+"(this); ":"":""},this.renderFieldAttributes=function(prop,evts){evts=evts||{};var bluraction="",changeaction="",keypressaction="",keyupaction="",rerender=prop.rerender?" getJoe("+self.joe_index+").rerenderField('"+prop.rerender+"'); ":"",disabled=-1==self.current.profile.lockedFields.indexOf(prop.name)?"":"disabled";return(evts.onblur||prop.onblur)&&(bluraction='onblur="'+(evts.onblur||"")+" "+self.getActionString("onblur",prop)+'"'),(evts.onchange||prop.onchange||rerender)&&(changeaction='onchange="'+rerender+(evts.onchange||"")+" "+self.getActionString("onchange",prop)+'"'),(evts.onkeypress||prop.onkeypress)&&(keypressaction='onkeypress="'+(evts.onkeypress||"")+" "+self.getActionString("onkeypress",prop)+'"'),(evts.onkeyup||prop.onkeyup)&&(keyupaction='onkeyup="'+(evts.onkeyup||"")+" "+self.getActionString("onkeyup",prop)+'"')," "+keyupaction+" "+keypressaction+" "+bluraction+" "+changeaction+" "+disabled+" "},this.renderTextField=function(prop){var autocomplete;prop.autocomplete&&prop.values&&("function"==typeof prop.values&&(prop.values=prop.values(self.current.object)),"string"==$.type(prop.values)&&self.getDataset(prop.values)&&(prop.values=self.getDataset(prop.values)),"array"!=$.type(prop.values)&&(prop.values=[prop.values]),autocomplete=prop.autocomplete);var disabled=_disableField(prop),fieldtype=prop.ftype&&"data-ftype='"+prop.ftype+"'"||"",placeholder=_getPropPlaceholder(prop),html=(prop.name,'<input class="joe-text-field joe-field '+(prop.skip?"skip-prop":"")+'" '+placeholder+'type="text" '+disabled+' name="'+prop.name+'" value="'+cleanString(prop.value||"")+'" maxlength="'+(prop.maxlength||prop.max||"")+'" '+self.renderFieldAttributes(prop)+(autocomplete?" onkeyup='this.nextSibling.search(this.value)'":"")+" "+fieldtype+"/>");return autocomplete&&(html+=`<joe-autocomplete class="joe-text-autocomplete" \n field="${prop.name}" \n itemId="${self.current.object._id}" \n schema="${self.current.object.itemType||self.current.schema&&self.current.schema.name||""}" \n joe-index=${self.joe_index}\n ">\n </joe-autocomplete>`),html};var textFieldAutocompleteHandler=function(e){e.target;$(".joe-text-autocomplete").removeClass("active"),$("body").unbind("click",textFieldAutocompleteHandler)};function getObjectlistSubProperty(prop){var subprop=prop;return"string"==$.type(prop)?(subprop={name:prop}).name=subprop.name||prop:subprop.extend&&self.fields[subprop.extend]&&((subprop=$.extend({},subprop,self.fields[subprop.extend],subprop.specs||{})).name=subprop.name||subprop.extend),subprop}function _objectlistTemplateClickHandler(templateDom,stopEditing){var templateContent,subobj,fieldname=$(templateDom).parents(".joe-object-field").data("name"),fieldObj=self.getField(fieldname),constructed=_jco(!0);if((stopEditing&&$(templateDom).parents(".joe-object-field").find(".editing")||$(templateDom).parent().siblings(".editing")).each(function(index,dom){subobj=constructed[fieldname][$(this).index()],templateContent=fillTemplate(self.propAsFuncOrValue(fieldObj.template,null,null,subobj),subobj),$(this).find(".row-template").html(templateContent),$(this).removeClass("editing")}),!stopEditing){var $row=$(templateDom).parents(".joe-objectlist-row");$row.addClass("editing"),$row.find(".joe-text-field,.joe-integer-field,.joe-number-field,select,textarea").eq(0)[0].focus()}}function _sortObjectListRows(property,sortBy){try{var overwrites={};overwrites[property]=_jco(!0)[property].sortBy(sortBy),_joe.Fields.rerender(property,overwrites)}catch(e){self.Error.add("error sorting objectlist",e,{property:property,sortBy:sortBy})}}function readyObjectListFields(){function olHelper(e,tr){var $originals=tr.children(),$helper=tr.clone();return $helper.hasClass("templated")?$helper.children().each(function(index){$(this).toggle($(this).hasClass("template-visible")).width($originals.eq(index).width())}):($helper.width(tr.width()),$helper.children().each(function(index){$(this).toggle(!$(this).hasClass("row-template")),$(this).width($originals.eq(index).width())})),$helper}self.overlay.find(".joe-objectlist-table.sortable").each(function(){$(this).find("tbody").sortable({axis:"y",handle:".joe-objectlist-object-row-handle",helper:olHelper})})}function _normalizeJsonField(fieldName,opts){opts=opts||{};var parent=getJoe(self.joe_index),$holder=parent.overlay.find('.joe-ace-holder[name="'+fieldName+'"]');if(!$holder.length)return{ok:!0};var editorId=$holder.data("ace_id"),editor=_joe.ace_editors[editorId];if(!editor)return{ok:!0};var text=editor.getValue();text&&text.trim()||(text="{}");try{var parsed=JSON.parse(text);try{var pretty=JSON.stringify(parsed,null,2);editor.setValue(pretty,-1)}catch(_e){}return $holder.removeClass("joe-field-error"),{ok:!0,parsed:parsed}}catch(e){var fixed=text;try{fixed=(fixed=(fixed=fixed.replace(/([{\[],\s*|[{]\s*|,\s*)([A-Za-z_][A-Za-z0-9_]*)\s*:/g,function(m,prefix,key){return prefix+'"'+key+'":'})).replace(/'([^'\\]*(?:\\.[^'\\]*)*)'/g,'"$1"')).replace(/,\s*([}\]])/g,"$1");var reparsed=JSON.parse(fixed);try{var prettyFixed=JSON.stringify(reparsed,null,2);editor.setValue(prettyFixed,-1)}catch(_e2){}return $holder.removeClass("joe-field-error"),{ok:!0,parsed:reparsed}}catch(_fixErr){return $holder.addClass("joe-field-error"),opts.showMessage&&parent.showMessage&&parent.showMessage("Field '"+fieldName+"' must be valid JSON (object)."),{ok:!1,error:e}}}}function _removeUploaderFile(id,filename){var joe_uploader=self.uploaders[id];file=joe_uploader.files.where({filename:filename})[0],file&&(joe_uploader.files.remove(file),joe_uploader.preview.html(_renderUploaderFilePreviews(joe_uploader.files,joe_uploader.cuid)))}function _renderUploaderFilePreviews(files,cuid){var jup_template,html="",alink="<a href='${url}${base64}' class='file-link' target='_blank'></a>",delete_btn='<joe-uploader-file-delete-btn class="svg-shadow" onclick="_joe.Fields.uploader.remove(\''+cuid+"','${filename}');\">"+self.SVG.icon.close+"</joe-uploader-delete-btn>",label="",uploader=self.uploaders&&self.uploaders[cuid],roles=uploader&&uploader.roles;return files.map(function(file){var filesize="<joe-uploader-file-label>${filename}</joe-uploader-file-label>";file.size?(file.size>1e6?filesize=`${(file.size/1e6).toFixed(2)} mb`:file.size>1e3&&(filesize=`${(file.size/1e3).toFixed(2)} kb`),filesize=`<joe-uploader-file-size>${filesize}</joe-uploader-file-size>`):filesize="",$c.isObject(file)||(file={url:file,filename:file.substr(file.lastIndexOf("/")>0&&file.lastIndexOf("/")||0)});label="<joe-uploader-file-label>"+(file.filename||"")+"</joe-uploader-file-label>",file.openai_file_id&&(label+="<joe-uploader-file-oaid >"+file.openai_file_id+"</joe-uploader-file-oaid>");var roleSelect="";if(roles&&roles.length){var currentRole=file.file_role||"",safeFilename=String(file.filename||"").replace(/'/g,"\\'"),optsHtml='<option value=""></option>';roles.forEach(function(r){if(r&&r.value){var lbl=r.label||r.value,sel=currentRole===r.value?" selected":"";optsHtml+='<option value="'+r.value.replace(/\"/g,"&quot;")+'"'+sel+">"+lbl.replace(/</g,"&lt;").replace(/>/g,"&gt;")+"</option>"}}),roleSelect='<div class="joe-uploader-file-role"><select onchange="'+("_joe.uploaderSetFileRole('"+cuid+"','"+safeFilename+"', this.value)")+'">'+optsHtml+"</select></div>"}jup_template=file.type&&file.type.contains("image")||!file.type&&(file.url||file.base64).split(".").contains(["jpg","jpeg","png","gif","svg"])?'<joe-uploader-file class="'+(file.uploaded?"uploaded":"")+'" style="background-image:url(${url}${base64})">'+alink+label+roleSelect+filesize+delete_btn+"</joe-uploader-file>":["doc","docx"].includes((file.url||file.base64).split(".").pop())?'<joe-uploader-file class="'+(file.uploaded?"uploaded":"")+'"><joe-uploader-file-extension >.'+(file.type.split("/")[1]||"docx")+"</joe-uploader-file-extension>"+alink+label+roleSelect+filesize+delete_btn+"</joe-uploader-file>":'<joe-uploader-file class="'+(file.uploaded?"uploaded":"")+'"><joe-uploader-file-extension >.'+(file.type.split("/")[1]||"???")+"</joe-uploader-file-extension>"+alink+label+roleSelect+filesize+delete_btn+"</joe-uploader-file>";var openaiBtn="",needRetry=!file.openai_file_id||"error"==file.openai_status;if(!!file.url&&needRetry){var openaiLabel="error"==file.openai_status?"Retry OpenAI":"Upload to OpenAI";safeFilename=(file.filename||"").replace(/'/g,"\\'");openaiBtn='<joe-uploader-openai-btn class="joe-button" style="margin-left:6px;" onclick="_joe.SERVER.Plugins.openaiRetryFromUrl(\''+cuid+"','"+safeFilename+"');\">"+openaiLabel+"</joe-uploader-openai-btn>"}html+=fillTemplate(jup_template,file)+openaiBtn}),html+'<div class="clear"></div>'}this.showTextFieldAutoComplete=function(dom){$("body").unbind("click",textFieldAutocompleteHandler).bind("click",textFieldAutocompleteHandler);var content,show,autocomplete=dom.next(".joe-text-autocomplete");needles=dom.val().toLowerCase().replace(/,/," ").split(" "),autocomplete.find(".joe-text-autocomplete-option").each(function(i,obj){content=void 0===obj.textContent?obj.innerText:obj.textContent,show=self.checkAutocompleteValue(needles,content.replace(/,/," ").toLowerCase(),obj),$(obj).toggleClass("visible",show)}),autocomplete.addClass("active")},this.hideTextFieldAutoComplete=function(dom){dom.next(".joe-text-autocomplete").removeClass("active")},this.autocompleteTextFieldOptionClick=function(dom){var value=$(dom).data("value"),parent=$(dom).parents("joe-autocomplete");parent.prev(".joe-text-field").val(value),parent.removeClass("active"),parent.siblings(".joe-reference-add-button").click()},this.checkAutocompleteValue=function(needles,haystack,dom,additive){$(dom);if(!needles.length)return!0;for(var n=0,tot=needles.length;n<tot;n++)if(-1==haystack.indexOf(needles[n]))return!1;return!0},encapsulateFieldType("text",self.renderTextField),this.renderPasswordField=function(prop){return'<input class="joe-password-field joe-field" type="password" '+_disableField(prop)+' name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop)+" />"},encapsulateFieldType("password",self.renderPasswordField),this.renderNumberField=function(prop){var step=prop.step||"any";return'<input class="joe-number-field joe-field" type="number" '+_disableField(prop)+" "+_getPropPlaceholder(prop)+' step="'+step+'" name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop,{onblur:"getJoe("+self.joe_index+").returnNumber(this);"})+" />"},this.returnNumber=function(dom){$(dom).val()&&$(dom).val(parseFloat($(dom).val()))},encapsulateFieldType("number",self.renderNumberField),this.renderIntegerField=function(prop){return'<input class="joe-int-field joe-field" type="text" '+_getPropPlaceholder(prop)+' name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop,{onblur:"getJoe("+self.joe_index+").returnInt(this);"})+" />"},this.returnInt=function(dom){$(dom).val()&&$(dom).val(parseInt($(dom).val()))},encapsulateFieldType("integer",self.renderIntegerField),this.renderSelectField=function(prop,subObject){var disabled=_disableField(prop),values=(subObject=subObject||{},self.getFieldValues(prop.values,prop)),valObjs=[];if(prop.blank)switch($.type(prop.blank)){case"string":valObjs.push({name:prop.blank||""});break;case"object":valObjs.push({name:prop.blank.name||"",value:prop.blank.value||""});break;default:valObjs.push({name:""})}values.map(function(v){"object"!=$.type(v)?valObjs.push({name:v}):valObjs.push(v)});var selected,mul=prop.multiple||prop.allowMultiple,multiple=mul?" multiple ":"",selectSize=prop.size||.5*valObjs.length>10?10:valObjs.length/2;prop.size||mul||(selectSize=1);var style='style="';prop.minwidth&&(style+="min-width:"+self.propAsFuncOrValue(prop.minwidth)),style+='"';var template,val,optionVal,propertyValue,prop_idprop,html="<select "+disabled+' class="joe-select-field joe-field" name="'+prop.name+'" '+style+' value="'+(prop.value||"")+'" size="'+selectSize+'"'+self.renderFieldAttributes(prop)+multiple+" >";return valObjs.map(function(v){propertyValue=subObject[prop.name]||self.propAsFuncOrValue(prop.value,null,null,v),template=self.propAsFuncOrValue(prop.template,null,null,v)||"",optionVal=template?fillTemplate(template,v):v.display||v.label||v.name,prop_idprop=prop.idprop&&self.propAsFuncOrValue(prop.idprop,v,null,_jco())||null,val=prop_idprop&&v.hasOwnProperty(prop_idprop)?v[prop_idprop]:v._id||v.value||v.name||"","array"==$.type(propertyValue)?(selected="",selected=-1!=prop.value.indexOf(val)?"selected":""):selected=propertyValue==val?"selected":"",html+='<option value="'+val+'" '+selected+(self.propAsFuncOrValue(v.disabled)?'disabled="disabled"':"")+">"+optionVal+"</option>"}),html+="</select>"},encapsulateFieldType("select",self.renderSelectField),this.renderDateField=function(prop,subObject){if(prop.native){subObject=subObject||{};var placeholder=_getPropPlaceholder(prop),dateVal=_joe.Utils.toDateString(new Date(subObject[prop.name]||prop.value||""),"Y-m-d");return html='<input class="joe-date-field joe-field" type="date" '+placeholder+" "+_disableField(prop)+' name="'+prop.name+'" value="'+dateVal+'" '+self.renderFieldAttributes(prop)+' required pattern="d{2}/d{2}/d{4}" />'}subObject=subObject||{};var html='<input class="joe-date-field joe-field jquery" type="text" '+(placeholder=_getPropPlaceholder(prop))+" "+_disableField(prop)+' name="'+prop.name+'" value="'+(subObject[prop.name]||prop.value||"")+'" '+self.renderFieldAttributes(prop)+" />";return html+='<joe-datepicker-holder id="'+prop.name+'"></joe-datepicker-holder>'},this.readyDateField=function(prop){var field;self.overlay.find(".joe-date-field.jquery").each(function(i,dom){field=_joe.getField(dom.name),$(dom).parents(".joe-objectlist-row").length?$(dom).Zebra_DatePicker({format:"m/d/Y",first_day_of_week:0,readonly_element:!1,start_date:(new Date).format("m/d/y")}):$(dom).Zebra_DatePicker({always_visible:self.propAsFuncOrValue(field.always_visible)&&$("joe-datepicker-holder#"+$(dom).attr("name"))||!1,format:"m/d/Y",first_day_of_week:0,readonly_element:!1,container:$("joe-datepicker-holder#"+$(dom).attr("name"))})})},encapsulateFieldType("date",self.renderDateField,{ready:self.readyDateField}),this.renderTimeField=function(prop){return'<input class="joe-time-field joe-field" type="text" '+_disableField(prop)+' name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop)+" />"},this.readyTimeField=function(prop){var field;self.overlay.find(".joe-time-field").each(function(i,dom){field=_joe.getField(dom.name),$(dom).timepicker({timeFormat:"h:mm p",minTime:field.minTime,maxTime:field.maxTime,startTime:field.startTime,endTime:field.endTime,dropdown:!1})})},encapsulateFieldType("time",self.renderTimeField,{ready:self.readyTimeField}),this.renderGeoField=function(prop){var propLocation;try{propLocation=prop.value&&eval(prop.value)}catch(e){self.Error.add("error finding geo for "+(prop.name||""),e,prop.value)}var zoom=prop.zoom||4,mapDiv="joeGEO_"+prop.name,geoval=tryEval(prop.value),val=prop.value||"",geometrytype=prop.geometry||"point";if(geoval&&geoval[0]&&"array"==$.type(geoval[0])){var center=prop.center||[40.513,-96.02];geometrytype="polygon"}else var center=propLocation||prop.center||[40.513,-96.02];var geofield="polygon"==geometrytype?'<textarea placeholder="enter geometry here" onchange="_joe.addMapPolygon(\''+mapDiv+'\',this.value)" class="joe-geo-field joe-field" name="'+prop.name+'" '+_disableField(prop)+">"+val.replace(/\n/g,"")+"</textarea>":'<input class="joe-geo-field joe-field" type="text" value="'+val+'" name="'+prop.name+'" '+_disableField(prop)+"/>",html='<div class="joe-geo-map joe-field" name="'+prop.name+'" id="'+mapDiv+'" data-center="'+JSON.stringify(center)+'" data-zoom="'+zoom+'" data-value="'+val+'" data-geometrytype="'+geometrytype+'"data-hideattribution="'+(prop.hideAttribution||"")+'" onload="getJoe('+self.joe_index+').initGeoMap(this);"></div>'+geofield+'<script type="text/javascript">setTimeout(function(){getJoe('+self.joe_index+').initGeoMap("'+mapDiv+'");},100)<\/script>';return html},this.initGeoMap=function(id){var mapspecs=$("#"+id).data();$("#"+id).attr("name");self.current.cache.leaflet=self.current.cache.leaflet||{};var map=self.current.cache.leaflet[id]=L.map(id).setView(mapspecs.center,mapspecs.zoom);if(L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png",{}).addTo(map),"point"==mapspecs.geometrytype)(new L.esri.Controls.Geosearch).addTo(map).on("results",function(data){var latlng=data.latlng,map=self.current.cache.leaflet[$(data.target._input).parents(".joe-geo-map").attr("id")];map.marker?map.marker.setLatLng(latlng):self.addMapIcon(map,latlng),$("input[name="+map.prop+"]").val("["+latlng.lat+","+latlng.lng+"]")}),map.on("click",self.onMapClick),mapspecs.value&&self.addMapIcon(map,mapspecs.value);else if("polygon"==mapspecs.geometrytype){var geoval=tryEval(mapspecs.value);self.addMapPolygon(map,geoval)}mapspecs.hideattribution&&$(".leaflet-control-attribution").hide(),map.prop=$("#"+id).attr("name")},this.onMapClick=function(e,s,d){var map="click"==e.type?e.target:e.target.map||self.current.leaflet,ll=e&&e.latlng&&(e.latlng.latlng||e.latlng)||this.getLatLng();map.setView(ll),"dragend"==e.type||(map.marker?map.marker.setLatLng(ll):self.addMapIcon(map,ll)),$("input[name="+map.prop+"]").val("["+ll.lat+","+ll.lng+"]")},this.addMapIcon=function(map,latlng,specs){try{if(null===tryEval(latlng))throw"could not eval"+latlng;specs=specs||{};var myIcon=L.icon({iconUrl:specs.icon||"/JsonObjectEditor/img/mapstar.png",iconSize:[30,30]});map.marker=L.marker(latlng,{draggable:!0,icon:myIcon}).addTo(map),map.marker.map=map,map.marker.on("dragend",self.onMapClick)}catch(e){self.Error.add("error adding point to map",e,{latlng:latlng}),map.marker&&map.removeLayer(map.marker)}},this.addMapPolygon=function(map,geometry,specs){map=self.getMapFieldMap(map);try{geometry=tryEval(geometry),specs=specs||{};var myPoly=L.polygon(geometry);map.polygon=myPoly.addTo(map),map.polygon.map=map,map.fitBounds(myPoly.getBounds()),$("textarea[name="+map.prop+"]").val($("textarea[name="+map.prop+"]").val().replace(/\n/g,""))}catch(e){self.Error.add("error adding polygon to map",e,{geometry:geometry}),map.polygon&&map.removeLayer(map.polygon)}},this.getMapFieldMap=function(id){return"object"==typeof id?id:(-1==id.indexOf("joeGEO_")&&(id="joeGEO_"+id),self.current.cache.leaflet[id])},encapsulateFieldType("geo",self.renderGeoField,{ready:self.initGeoMap,addPoly:this.addMapPolygon}),this.renderBooleanField=function(prop){self.current.profile;return'<label class="joe-boolean-label" for="joe_checkbox-'+prop.name+'"><input class="joe-boolean-field joe-field" type="checkbox" name="'+prop.name+'" id="joe_checkbox-'+prop.name+'" '+([!0,"true"].contains(prop.value)?"checked":"")+self.renderFieldAttributes(prop)+" "+_disableField(prop)+"/> <small>"+(prop.label||"")+"</small></label>"},encapsulateFieldType("guid",self.renderGuidField),this.renderUserFavoriteField=function(prop){return"user favorite"},this.renderGuidField=function(prop){self.current.profile;return'<input class="joe-guid-field joe-field" type="text" '+_getPropPlaceholder(prop)+' name="'+prop.name+'" value="'+(prop.value||cuid())+'" disabled />'},encapsulateFieldType("guid",self.renderGuidField),this.renderCreateField=function(prop){var schema=self.schemas[prop.schema]||prop.schema,schemaTitle="";if(!schema||!schema.name)return"schema not found";schemaTitle=schema.name.toUpperCase();prop.name;return html=`<joe-button schema="${prop.schema}" icon="plus" color="orangegrey" action="_joe.Fields.create.go('${prop.name}')" style="float:none">\n new <b>${schemaTitle}</b>\n </joe-button>`,html},this.gotoCreatedItem=function(propname){var prop=self.getField(propname);if(!prop.schema)return"no schema selected";if(self.isNewItem()){if(!prop.autosave)return void alert("please save this item before creating another");self.updateObject()}var schema=self.schemas[prop.schema]||prop.schema,overwrites=self.propAsFuncOrValue(prop.new||prop.overwrites)||{},newitem=_joe.propAsFuncOrValue(schema.new),item=$.extend({},newitem,overwrites);goJoe(item,{schema:schema})},encapsulateFieldType("create",self.renderCreateField,{go:self.gotoCreatedItem}),this.renderImageField=function(prop){var html="";return self.propAsFuncOrValue(prop.hidefield)||(html+='<input class="joe-image-field joe-field" type="text" name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop)+' onkeyup="_joe.updateImageFieldImage(this);" '+_disableField(prop)+"/>"),html+='<img class="joe-image-field-image" src="'+(prop.value||"")+'" /><span class="joe-image-field-size"></span>'},this.updateImageFieldImage=function(dom,timeout){logit("img update");var src=$(dom).val(),img=$(dom).parent().find(".joe-image-field-image");self.updateImageSize(img),img.attr("src",src)},this.updateImageSize=function(img){var jqImg=$(img);jqImg.siblings(".joe-image-field-size").html(jqImg.width()+"w x "+jqImg.height()+"h")},encapsulateFieldType("image",self.renderImageField),this.renderMultisorterField=function(prop){var li,val_index,values=self.getFieldValues(prop.values,prop),optionsHtml="",idprop=prop.idprop||"id",template=prop.template||"${name} (${"+idprop+"})",value=prop.value||[],selectionsArray=Array(value.length);values||(values=[]),values.map(function(v){li=function(v){return'<li data-id="'+v[idprop]+'" ondblclick="_joe.toggleMultisorterBin(this);">'+fillTemplate(template,v)+"</li>"}(v),-1!=(val_index=value.indexOf(v[idprop]))?selectionsArray[val_index]=li:optionsHtml+=li});var selectionsHtml=selectionsArray.join(""),height=prop.height&&"style='max-height:"+prop.height+";'"||"";return'<div class="joe-multisorter-field joe-field" name="'+prop.name+'" data-ftype="multisorter" data-multiple="'+(prop.allowMultiple||"false")+'"><div class="joe-filter-field-holder"><input type="text"class="" onkeyup="_joe.filterSorterOptions(this);"/></div><p class="joe-tooltip"> double click or drag item to switch columns.</p><ul class="joe-multisorter-bin options-bin" '+height+">"+optionsHtml+'</ul><ul class="joe-multisorter-bin selections-bin" '+height+">"+selectionsHtml+"</ul>"+__clearDiv__+"</div>"},this.filterSorterOptions=function(dom){var sorterBM=new Benchmarker,query=$(dom).val().toLowerCase();$(dom).parents(".joe-field").find(".joe-multisorter-bin.options-bin").find("li").each(function(){$(this).toggle(-1!=$(this).html().toLowerCase().indexOf(query))}),_bmResponse(sorterBM,"found results for: "+query)},this.toggleMultisorterBin=function(dom){var id=$(dom).data("id"),parent=$(dom).parents(".joe-multisorter-bin"),target=(parent.parents(".joe-multisorter-field"),parent.siblings(".joe-multisorter-bin")),newDom=parent.find("li[data-id="+id+"]").detach();target.prepend(newDom)},encapsulateFieldType("multisorter",self.renderMultisorterField),this.renderBucketsField=function(prop){for(var values=self.getFieldValues(prop.values,prop),bucketNames=self.propAsFuncOrValue(prop.bucketNames)||[],bucketCount=self.propAsFuncOrValue(prop.bucketCount)||3,optionsHtml="",bucketsHtml=[],value=prop.value||[[],[],[]],i=0;i<bucketCount;i++)bucketsHtml.push(""),value[i]||value.push([]);var lihtml,foundItem,bucketItem,idprop=prop.idprop||"_id",template=prop.template||"${name} <br/><small>(${"+idprop+"})</small>",selectedIDs=[];for(i=0;i<bucketCount;i++)for(var li=0;li<value[i].length;li++)bucketItem=value[i][li],"string"==$.type(bucketItem)?((foundItem=values.filter(function(v){return v[idprop]==bucketItem})[0]||!1)||((foundItem={})[idprop]=li),selectedIDs.push(bucketItem),lihtml=self.renderBucketItem(foundItem,prop,!1)):"object"==$.type(bucketItem)&&(foundItem=bucketItem,lihtml=self.renderBucketItem(foundItem,prop,!0)),bucketsHtml[i]+=lihtml;var optionTemplate=prop.optionTemplate||template;values.map(function(v){var resolvedTemplate=self.propAsFuncOrValue(optionTemplate,self.current.object,null,v),optionContent=fillTemplate(resolvedTemplate||"",v);lihtml='<li data-value="'+v[idprop]+'" >'+optionContent+'<div class="joe-bucket-delete cui-block joe-icon" onclick="$(this).parent().remove()"></div></li>',(-1==selectedIDs.indexOf(v[idprop])||prop.allowMultiple)&&(optionsHtml+=lihtml)});var html='<div class="joe-buckets-field joe-field" name="'+prop.name+'" data-ftype="buckets"><div class="joe-filter-field-holder"><input type="text"class="" onkeyup="_joe.filterBucketOptions(this);"/></div><div class="joe-buckets-field-holder" style="width:25%;"><ul class="joe-buckets-bin options-bin '+(prop.allowMultiple?"allow-multiple":"")+'">'+optionsHtml+'</ul></div><div class="joe-buckets-field-holder" style="width:75%;">';return bucketsHtml.map(function(b,i){html+=function(id,name,width){return'<ul class="joe-buckets-bin selections-bin" '+(width?'style="width:'+width+'"':"")+">"+(name?'<div class="joe-bucket-label">'+name+"</div>":"")+bucketsHtml[id]+"</ul>"}(i,bucketNames[i]||"",prop.bucketWidth)}),html+=__clearDiv__+"</div>"+__clearDiv__+"</div>"},this.filterBucketOptions=function(dom){var query=$(dom).val().toLowerCase();$(dom).parents(".joe-buckets-field").find(".options-bin").find("li").each(function(){$(this).toggle(-1!=$(this).html().toLowerCase().indexOf(query))}),logit(query)},this.readyBinFields=function(){try{self.overlay.find(".joe-multisorter-bin").sortable({connectWith:".joe-multisorter-bin",placeholder:"joe-sortable-highlight",items:"li"}),self.overlay.find(".joe-buckets-bin").sortable({connectWith:".joe-buckets-bin",placeholder:"joe-sortable-highlight",items:"li",start:function(event,ui){sortable_index=ui.item.index(),ui.item.parents()},update:function(event,ui){ui.sender&&ui.sender.hasClass("options-bin")&&ui.sender.hasClass("allow-multiple")&&ui.sender.find("li").eq(sortable_index).before(ui.item.clone())}})}catch(e){self.Error.add("Error creating sortables:\n"+e,e,{caller:"self.readyBinFields"})}},this.renderBucketItem=function(item,fieldnameorobject,specs){var fieldObj="object"==$.type(fieldnameorobject)?fieldnameorobject:self.getField(fieldnameorobject)||{};!0!==specs&&!1!==specs||(specs={isobject:specs});var idprop=fieldObj.idprop||specs.idprop||"_id",template=fieldObj.template||specs.template||"${name} <br/><small>(${"+idprop+"})</small>",value=fieldObj.isobject||specs.isobject?'data-isobject=true data-value="'+encodeURI(JSON.stringify(item))+'"':'data-value="'+item[idprop]+'"',resolvedTemplate=self.propAsFuncOrValue(template,self.current.object,null,item);return"<li "+value+">"+fillTemplate(resolvedTemplate||"",item)+'<div class="joe-bucket-delete cui-block joe-icon" onclick="$(this).parent().remove()"></div></li>'},encapsulateFieldType("buckets",self.renderBucketsField,{create:self.renderBucketItem,ready:self.readyBinFields}),this.renderContentField=function(prop){var html="",itemObj=self.current.object,idProp=prop.idprop||self.getIDProp(),constructedItem=self.current.constructed||{};(!self.current.object[idProp]||constructedItem[idProp]&&constructedItem[idProp]==self.current.object[idProp])&&(itemObj=constructedItem,self.current.object[idProp]&&constructedItem[idProp]==self.current.object[idProp]&&(itemObj=rerenderingField?$.extend({},self.current.object,constructedItem):$.extend({},constructedItem,self.current.object)));try{prop.run?html+=prop.run(itemObj,prop)||"":prop.template?html+=fillTemplate(self.propAsFuncOrValue(prop.template),itemObj):prop.value&&(html+=self.propAsFuncOrValue(prop.value))}catch(e){return self.Error.add("error rendering field:"+e,e,{caller:"self.renderContentField"}),"error rendering field:"+e}return html},encapsulateFieldType("content",self.renderContentField),this.Render.fieldListItem=this.renderFieldListItem=function(item,contentTemplate,schema,specs){var schemaprop=(specs=$.extend({isObject:!1,deleteButton:!1,expander:null,gotoButton:!1,itemMenu:!1,schemaprop:!1,nonclickable:!1,action:!1,stripecolor:!1,bgcolor:!1,checkbox:!1,value:"",link:!1},specs)).schemaprop&&self.propAsFuncOrValue(specs.schemaprop,item),schemaobj=(schema=schemaprop&&item[schemaprop]||schema||item.itemtype||item.type,self.schemas[schema]),idprop=(contentTemplate=self.propAsFuncOrValue(contentTemplate,null,null,item)||self.propAsFuncOrValue(schemaobj&&(schemaobj.listTitle||schemaobj.listView&&schemaobj.listView.title),item)||"<joe-title>${name}</joe-title><joe-subtext>${itemtype}</joe-subtext>",specs.idprop||schemaobj&&schemaobj.idprop||"_id"),hasMenu=specs.itemMenu&&specs.itemMenu.length,action=self.propAsFuncOrValue(specs.action,item)||" onclick=\"goJoe(_joe.search('${"+idprop+"}')[0],{schema:'"+schema+"'})\" ",nonclickable=self.propAsFuncOrValue(specs.nonclickable,item),clickablelistitem=!specs.gotoButton&&!nonclickable,deleteButton='<div class="joe-delete-button joe-block-button right" onclick="__cancelPropagation();$(this).parent().remove();'+(specs.fieldname&&"_joe.Fields.objectreference.remove('"+specs.fieldname+"');"||"")+'">&nbsp;</div>',expanderContent=renderItemExpander(item,specs.expander),click=clickablelistitem?action:"",value=specs.isObject?'data-value="'+encodeURI(JSON.stringify(specs.value))+'" data-isObject=true':'data-value="'+specs.value+'"',link=specs.link&&self.propAsFuncOrValue(specs.link,item);return fillTemplate(`<joe-list-item schema="${schema}" \n itemId="${item[idprop]}"\n idprop="${idprop}"\n ${specs.icon&&`icon="${specs.icon}"`||""}\n class="`+(clickablelistitem?"joe-field-list-item clickable":"joe-field-item")+(specs.deleteButton?" deletable":"")+(specs.gotoButton?" gotobutton":"")+(specs.itemMenu?" itemmenu":"")+(specs.stripecolor?" striped":"")+(specs.checkbox?" checkboxed":"")+(specs.expander?" expander expander-collapsed":"")+'" '+(value||"")+">"+(hasMenu&&renderItemMenu(item,specs.itemMenu)||"")+self.Render.bgColor(item,specs.bgcolor)+self.Render.itemCheckbox(item,schemaobj)+(link&&'<a class="non-link" onclick="__cancelClick();" href="'+link+'">'||"")+'<div class="joe-field-item-content '+(nonclickable?"nonclickable":"")+'" '+click+" >"+self.propAsFuncOrValue(contentTemplate+__clearDiv__,item)+__clearDiv__+"</div>"+(link?"</a>":"")+self.Render.stripeColor(item,specs.stripecolor)+self._renderExpanderButton(expanderContent,item)+(specs.deleteButton&&deleteButton||"")+(specs.gotoButton?"${RUN[_renderGotoButton]}":"")+expanderContent+"</joe-list-item>",item)},this.renderURLField=function(prop){self.current.profile;var disabled=_disableField(prop),prefix=self.propAsFuncOrValue(prop.prefix);return(prefix=fillTemplate(prefix||"",self.current.object))+`<joe-button schema="${prop.schema||""}" action="view" class="joe-button" color="green" prefix="${prefix}" ></joe-button><input class="joe-url-field joe-field" type="text" `+self.renderFieldAttributes(prop)+'name="'+prop.name+'" value="'+(prop.value||"")+'" '+disabled+" />"+__clearDiv__},this.gotoFieldURL=function(dom,prefix){var url=$(dom).siblings(".joe-url-field").val();window.open((prefix||"")+url)},encapsulateFieldType("url",self.renderURLField),this.renderColorField=function(prop){return'<input class="joe-color-field joe-field" type="text" name="'+prop.name+'" value="'+(prop.value||"")+'" '+self.renderFieldAttributes(prop)+" /><script>_joe._colorFieldListener($('input.joe-color-field[name="+prop.name+"]')[0]);$('input.joe-color-field[name="+prop.name+"]').keyup(_joe._colorFieldListener);<\/script>"},this._colorFieldListener=function(e){var field=e.delegateTarget||e,color=field.value;$(field).parents(".joe-object-field").css("background-color",color)},encapsulateFieldType("color",self.renderColorField),this.renderObjectListField=function(prop){var html="<table class='joe-objectlist-table "+(prop.hideHeadings?" hidden-heading ":"")+(!1===prop.sortable?"":" sortable ")+"' >"+self.renderObjectListHeaderProperties(prop)+self.renderObjectListObjects(prop)+"</table>",max=prop.max,pName=(prop.display||prop.name).split(" ");"s"==(pName=pName[pName.length-1])[pName.length-1]&&(pName=pName.substr(0,pName.length-1).toLowerCase());var label=prop.label||pName&&`add ${pName}`||"add item";if((!max||!prop.value||prop.value.length<max)&&!prop.locked){var addaction='onclick="getJoe('+self.joe_index+").addObjectListItem('"+prop.name+"')\"";html+='<div style="text-align:center;">';prop.hasOwnProperty("template")&&(html+='<joe-button style="" class=" joe-done-button joe-button joe-grey-button" onclick="_joe.Fields.objectlist.editHandler($(this).parents(\'.joe-object-field\').find(\'.row-template\').eq(0),true)"> - </joe-button>'),html+='<div class="joe-button joe-iconed-button joe-plus-button joe-orangegrey-button" '+addaction+"> "+label+"</div>"+__clearDiv__+"</div>"}return html},this.objectlistdefaultproperties=["name","_id"],this.renderObjectListHeaderProperties=function(prop){for(var property,subprop,width,onclick,properties=self.propAsFuncOrValue(prop.properties)||self.objectlistdefaultproperties,sortable=!1!==prop.sortable,html="<thead><tr>"+(sortable?'<th class="joe-objectlist-object-row-handle-header" ></th>':"")+'<th class="joe-objectlist-object-row-template-header"></th>',p=0,tot=properties.length;p<tot;p++)property={name:(subprop=getObjectlistSubProperty(properties[p])).display||subprop.name,type:subprop.type||"text"},onclick=sortable?'title="sort by '+property.name+" ("+subprop.name+')" onclick="_joe.Fields.objectlist.sortBy(\''+prop.name+"','"+subprop.name+"');\"":'title="('+subprop.name+')"',width=subprop.width?'width="'+subprop.width+'"':"",html+="<th "+onclick+" data-subprop='"+subprop.name+"' "+width+">"+(subprop.display||subprop.name)+"</th>";return html+="<th class='joe-objectlist-delete-header'></th>",html+="</tr></thead>"},this.renderObjectListObjects=function(prop){for(var obj,objects=prop.value||(self.current.constructed||self.current.object)[prop.name]||prop.default||[],properties=self.propAsFuncOrValue(prop.properties)||self.objectlistdefaultproperties,html="<tbody>",o=0,objecttot=objects.length;o<objecttot;o++)obj=objects[o],html+=self.renderObjectListRow(obj,properties,o,prop);return html+="</tbody>"},this.renderObjectListRow=function(object,objectListProperties,index,prop,editing){var property,properties=self.propAsFuncOrValue(objectListProperties)||self.objectlistdefaultproperties,sortable=!1!==prop.sortable,html="",templateContent=fillTemplate(self.propAsFuncOrValue(prop.template,null,null,object),object);html+="<tr class='joe-objectlist-row "+(templateContent||editing?"templated":"")+" "+(editing?"editing":"")+"' data-index='"+index+"'>"+(prop.locked?"<td class='template-visible'></td>":sortable?"<td class='sort-handle template-visible'><div class='joe-panel-button joe-objectlist-object-row-handle'>|||</div></td>":"");html+="<td class='row-template template-visible' onclick=\"_joe.Fields.objectlist.editHandler(this);\" colspan='"+(properties.length+1)+"'>"+templateContent+"</td>";for(var subprop,renderInput={text:self.renderTextField,select:self.renderSelectField,date:self.renderDateField,content:self.renderContentField,rendering:self.renderRenderingField,boolean:self.renderBooleanField,url:self.Fields.url.render},p=0,tot=properties.length;p<tot;p++)subprop=getObjectlistSubProperty(properties[p]),property=$.extend({name:subprop.name,type:subprop.type||"text",value:object[subprop.name]||""},subprop),self.Fields.objectlist.toReady.push(property.type),html+="<td>"+(renderInput[property.type]||self.Fields[property.type].render)(property,object)+"</td>";var delaction="onclick='getJoe("+self.joe_index+")._oldeleteaction(this);'";return html+=prop.locked?"<td class='template-visible'></td>":"<td class='template-visible'><div class='jif-panel-button joe-delete-button' "+delaction+">&nbsp;</div></td>",html+="</tr>"},this.addObjectListItem=function(fieldname,specs){self.Fields.objectlist.toReady=[];var fieldobj=self.getField(fieldname),index=$(".joe-object-field[data-name="+fieldname+"]").find(".joe-objectlist-row").length,content=self.renderObjectListRow(self.propAsFuncOrValue(fieldobj.new)||{},fieldobj.properties,index,fieldobj,fieldobj.hasOwnProperty("template"));$(".joe-object-field[data-name="+fieldname+"]").find("tbody").append(content),$(".joe-object-field[data-name="+fieldname+"] .joe-objectlist-row:last").find(".joe-text-field,.joe-integer-field,.joe-number-field,select,textarea").eq(0)[0].focus(),self.Fields.objectlist.toReady.map(function(fieldtype){self.Fields[fieldtype]&&self.Fields[fieldtype].ready&&self.Fields[fieldtype].ready(fieldobj)}),fieldobj.hasOwnProperty("template")&&_objectlistTemplateClickHandler($(".joe-object-field[data-name="+fieldname+"] .joe-objectlist-row:last .row-template"))},this._oldeleteaction=function(dom){$(dom).parents(".joe-objectlist-row").remove()},this.removeObjectListItem=function(fieldname,index){self.getField(fieldname);$(".joe-object-field[data-name=module_fields]").find("tbody").append(content)},encapsulateFieldType("objectlist",self.renderObjectListField,{add:self.addObjectListItem,ready:readyObjectListFields,toReady:[],editHandler:_objectlistTemplateClickHandler,sortBy:_sortObjectListRows}),this.renderCheckboxGroupField=function(prop){var checked,values=self.getFieldValues(prop.values,prop),locked=self.propAsFuncOrValue(prop.locked)?" disabled ":"",html="",propval=self.propAsFuncOrValue(prop.value);"array"!=$.type(propval)&&(propval=[propval]);var idprop=prop.idprop||"_id",cols=prop.cols||prop.numCols||2;return values.map(function(value){if("object"!=$.type(value)){var tempval={name:value};tempval[idprop]=value,value=tempval}"joe_checkbox-"+prop.name,checked=-1!=(propval||[]).indexOf(value[idprop])?" checked ":"",html+='<div class="joe-group-item '+locked+" cols-"+cols+'"><label ><div class="joe-group-item-checkbox"><input class="joe-field" '+locked+' type="checkbox" name="'+prop.name+'" '+checked+self.renderFieldAttributes(prop)+'value="'+value[idprop]+'" '+_disableField(prop)+` onchange="getJoe(${self.joe_index}).Fields.group.change('${prop.name}')" /></div>`+(prop.template&&fillTemplate(prop.template,value)||value.label||value.name||"")+"</label></div>"}),html+=__clearDiv__},this.onCheckboxGroupUpdate=function(fieldname){var fieldObj=self.Fields.get(fieldname),newTitle=_joe.propAsFuncOrValue(fieldObj.display||name);document.querySelector(`.joe-field-label[title="${fieldname}"]`).innerHTML=newTitle},encapsulateFieldType("group",self.renderCheckboxGroupField,{change:self.onCheckboxGroupUpdate}),this.renderCodeField=function(prop){self.current.profile;var height=prop.height?'style="height:'+prop.height+';"':"",code_language=(self.propAsFuncOrValue(prop.language)||"html").toLowerCase(),editor_id=cuid();return`<div>\n <joe-button class="tight" onclick="_joe.Fields.code.fullscreen('${editor_id}');"> &#x26F6; fullscreen</joe-button>\n </div><div class="clear joe-ace-holder joe-rendering-field joe-field" `+height+' data-ace_id="'+editor_id+'" data-ftype="ace" name="'+prop.name+'"><textarea class="" id="'+editor_id+'" >'+(prop.value||"")+'</textarea></div><script>var editor = ace.edit("'+editor_id+'");\t\t\teditor.setTheme("ace/theme/tomorrow");\t\t\teditor.getSession().setUseWrapMode(true);\t\t\teditor.getSession().setMode("ace/mode/'+code_language+'");\t\t\teditor.setOptions({\t\t\t\tenableBasicAutocompletion: true,\t\t\t\tenableLiveAutocompletion: false\t\t\t});\t\t\t_joe.ace_editors["'+editor_id+'"] = editor; <\/script>'},this.fullScreenCodeEditor=function(editor_id){var elem=document.querySelector(`div.joe-ace-holder[data-ace_id="${editor_id}"]`);elem.requestFullscreen?elem.requestFullscreen():elem.webkitRequestFullscreen?elem.webkitRequestFullscreen():elem.msRequestFullscreen&&elem.msRequestFullscreen()},encapsulateFieldType("code",self.renderCodeField,{fullscreen:this.fullScreenCodeEditor}),this.renderJsonField=function(prop){var displayValue,height=prop.height?'style="height:'+prop.height+';"':"",editor_id=cuid(),rawValue=void 0===prop.value?{}:prop.value;if("string"==typeof rawValue)try{rawValue=JSON.parse(rawValue)}catch(e){}if(null==rawValue&&(rawValue={}),"object"==typeof rawValue)try{displayValue=JSON.stringify(rawValue,null,2)}catch(e){displayValue="{}"}else try{displayValue=JSON.stringify(rawValue,null,2)}catch(e){displayValue="{}"}return'<div class="clear joe-ace-holder joe-rendering-field joe-field" '+height+' data-ace_id="'+editor_id+'" data-ftype="ace" name="'+prop.name+'"><textarea class="" id="'+editor_id+'" >'+(displayValue||"{}")+'</textarea></div><script>try{ var editor = ace.edit("'+editor_id+'"); editor.setTheme("ace/theme/tomorrow"); editor.getSession().setUseWrapMode(true); editor.getSession().setMode("ace/mode/json"); editor.setOptions({ enableBasicAutocompletion: true, enableLiveAutocompletion: false }); _joe.ace_editors["'+editor_id+'"] = editor; }catch(e){ console && console.warn && console.warn("ACE json init error",e);} <\/script>'},encapsulateFieldType("json",self.renderJsonField,{ready:function(){getJoe(self.joe_index).overlay.find(".joe-ace-holder[name]").each(function(){var name=$(this).attr("name"),field=self.getField(name);if(!field)return!0;if("json"!=(self.propAsFuncOrValue(field.type)||"").toLowerCase())return!0;var editorId=$(this).data("ace_id"),editor=_joe.ace_editors[editorId];if(!editor)return!0;editor.on("blur",function(){_normalizeJsonField(name,{showMessage:!1})})})},normalize:_normalizeJsonField}),this.renderQRCodeField=function(prop){prop.height&&prop.height;var size=prop.size||280,idprop=_joe.getIDProp(),template=self.propAsFuncOrValue(prop.template)||'{"${itemtype}":"${'+idprop+'}"}';fillTemplate;template=fillTemplate(template,self.current.object);var qrcode_url=prop.url||"http://www.qr-code-generator.com/phpqrcode/getCode.php?cht=qr&chl="+encodeURIComponent(template)+"&chs="+size+"x"+size+"&choe=UTF-8&chld=L|0",html='<a href="'+qrcode_url+'" target="_blank"><img class="joe-qrcode-image" src="'+qrcode_url+'" /></a>';return self.propAsFuncOrValue(prop.showContent)&&(html+="<joe-subtext>"+template+"</joe-subtext>"),html},encapsulateFieldType("qrcode",self.renderQRCodeField),this.renderRenderingField=function(prop){var locked=self.propAsFuncOrValue(prop.locked)?" disabled ":"",height=(self.current.profile,prop.height?'style="height:'+prop.height+';"':"");return'<textarea placeholder="'+(self.propAsFuncOrValue(prop.placeholder)||"")+'" class="joe-rendering-field joe-field" '+height+" "+locked+'name="'+prop.name+'" >'+(prop.value||"")+"</textarea>"},encapsulateFieldType("rendering",self.renderRenderingField),this.renderTagsField=function(prop){self.current.profile,prop.height&&prop.height;var specs=$.extend({},prop,{autocomplete:!0});return'<div class="joe-tags-container">'+self.renderTextField(specs)+'<div class="joe-text-input-button">add</div></div>'},this.uploaders={},this.renderUploaderField=function(prop){var uploader_id=cuid();"undefined"==typeof AWS&&$("body").append('<script>function none(){return; }<\/script><script type="text/javascript" src="https://sdk.amazonaws.com/js/aws-sdk-2.1.34.min.js"><\/script><script src="'+joe_web_dir+'js/libs/craydent-upload-2.0.0.js" type="text/javascript"><\/script>');var dz_message='<div style="line-height:100px;">drag files here to upload</div>',files=prop.value||[];files&&!$c.isArray(files)&&(files=[files]);var uploader_obj={cuid:uploader_id,prop:prop.name,files:files,max:prop.max||0,roles:prop.file_roles||[]};if(self.uploaders[uploader_id]=uploader_obj,prop.field&&self.current.object[prop.field]){var kfield=self.getField(prop.field),preview=self.current.object[prop.field];kfield.prefix&&(preview=fillTemplate(kfield.prefix,self.current.object)+preview),dz_message='<img src="'+preview+'"/>'}else files&&(files.length&&(dz_message=""),dz_message+=_renderUploaderFilePreviews(files,uploader_id));return'<div class="joe-uploader joe-field" data-ftype="uploader" name="'+prop.name+'" data-uploader_id="'+uploader_id+'"><div class="joe-uploader-dropzone"><div class="joe-uploader-preview">'+dz_message+'</div></div><div class="joe-uploader-message">add a file</div><div class="joe-button joe-green-button joe-upload-cofirm-button ui-helper-hidden hidden" onclick="_joe.uploaderConfirm(\''+uploader_id+"','"+prop.name+"');\">Upload File</div>"+__clearDiv__+"</div>"},this.onUserUpload=function(file,base64){var dom=$(this.dropZone).parent(),joe_uploader=self.uploaders[dom.data("uploader_id")];if(_joe.getField(joe_uploader.prop).use_legacy)file?(joe_uploader.file=file,joe_uploader.base64=base64,$(joe_uploader.dropzone).find("img,div").replaceWith('<img src="'+base64+'">'),joe_uploader.message.html("<b>"+file.name+"</b> selected"),joe_uploader.confirmBtn.removeClass("ui-helper-hidden hidden")):results.innerHTML="Nothing to upload.";else if(file){var fname=file.name.replace(/ /g,"_");if(joe_uploader.files.where({filename:fname}).length){var ext=fname.substr(fname.lastIndexOf("."));if((fname=fname.substr(0,fname.lastIndexOf("."))).lastIndexOf("_")>0){var fint=parseInt(fname.substr(fname.lastIndexOf("_")+1));fint+=1,fname=fname.substr(0,fname.lastIndexOf("_")+1)+fint}else fname+="_1";fname+=ext}var temp_file={uploaded:!1,filename:fname,extension:file.type||file.name.substr(file.name.lastIndexOf(".")),size:file.size,type:file.type,base64:base64,added:new Date};joe_uploader.files.push(temp_file),$(joe_uploader.preview).html(_renderUploaderFilePreviews(joe_uploader.files,joe_uploader.cuid)),joe_uploader.confirmBtn.removeClass("ui-helper-hidden hidden")}else results.innerHTML="Nothing to upload."},this.uploaderConfirm=function(uploader_id){var joe_uploader=self.uploaders[uploader_id],field=_joe.getField(joe_uploader.prop);if(field.use_legacy){var file=joe_uploader.file,base64=joe_uploader.base64,extension=file.name.substr(file.name.lastIndexOf(".")),callback=function(err,url){if(err)joe_uploader.message.append("<div>"+(err.message||err)+"<br/>"+err+"</div>"),alert("error uploading");else{joe_uploader.message.html("<div>uploaded</div>"+url);var nprop={};field.field&&(nprop[field.field]=url),field.url_field&&(nprop[field.url_field]=url),self.rerenderField([field.field,field.url_field],nprop),self.updateObject(null,null,!0)}};if(field.onConfirm)file&&(joe_uploader.message.append("<div>pending</div>"),field.onConfirm({extension:extension,file:file,base64:base64,field:field},callback));else{var uploadFunction=field.upload||field.onupload||function(file,callback,base64_url){callback(null,base64_url)};file&&uploadFunction(file,callback,base64)}}else{var files=joe_uploader.files.where({uploaded:!1});callback=function(err,url,filename){if(self.upload_progress_counter--,err)joe_uploader.message.append("<div>"+(err.message||err)+"<br/>"+err+"</div>"),alert("error uploading");else{var fileobj=joe_uploader.files.where({filename:filename})[0];fileobj.uploaded=new Date,fileobj.url=url;var key=self.current.object._id+"/"+filename,oi=_joe._lastOpenAI&&_joe._lastOpenAI[key];fileobj.openai_purpose="assistants",oi?(fileobj.openai_file_id=oi.openai_file_id||null,fileobj.openai_status=(oi.openai_file_id?"ok":oi.openai_error&&"error")||"not_uploaded",fileobj.openai_error=oi.openai_error||null,oi.openai_error&&joe_uploader.message.append("<div>OpenAI error: "+oi.openai_error+"</div>")):fileobj.openai_status=fileobj.openai_status||"not_uploaded",delete fileobj.base64}0==self.upload_progress_counter&&(joe_uploader.message.html("<div>uploaded "+files.length+" files</div>"),joe_uploader.preview.html(_renderUploaderFilePreviews(joe_uploader.files,joe_uploader.cuid)),self.updateObject(null,null,!0))};if(field.onConfirm)files&&files.length&&(joe_uploader.message.append("<div>"+files.length+" pending</div>"),self.upload_progress_counter=files.length,files.map(function(file){field.onConfirm({file:file,field:field},callback)}));else{uploadFunction=field.upload||field.onupload||function(file,callback,base64_url){callback(null,base64_url)};file&&uploadFunction(file,callback,base64)}}},this.readyUploaders=function(){self.panel.find(".joe-uploader").each(function(){var id=$(this).data("uploader_id"),uploader=(self.Fields.get($(this).parents(".joe-object-field").data("name")),new Upload({useInputBox:!0,target:$(this).find(".joe-uploader-dropzone")[0],deferUpload:!0,onerror:function(data,status,response){var message=data.message||data||"Server responded with error code: "+status;message=-1!=message.indexOf("bytes")?"file is too small, needs to be larger than 1MB":message,alert(message),logit(data)},onfileselected:function(inputDom){console.log(inputDom.val),self.uploaders[id].uploader.upload()},onafterfileready:self.onUserUpload}));self.uploaders[id].ready=!0,self.uploaders[id].uploader=uploader,self.uploaders[id].message=$(this).find(".joe-uploader-message").html("awaiting file, previewing current"),self.uploaders[id].preview=$(this).find(".joe-uploader-preview"),self.uploaders[id].dropzone=$(this).find(".joe-uploader-dropzone"),self.uploaders[id].confirmBtn=$(this).find(".joe-upload-cofirm-button"),(self.uploaders[id].files||[]).some(function(file){return $c.isObject(file)&&(!file.uploaded||!file.url)})&&self.uploaders[id].confirmBtn.removeClass("ui-helper-hidden hidden")})},encapsulateFieldType("uploader",self.renderUploaderField,{ready:self.readyUploaders,remove:_removeUploaderFile}),this.renderObjectReferenceField=function(prop){if(!prop.values||!prop.values.async){var values=self.getFieldValues(prop.values,prop);if(values)var value=(rerenderingField?self.current.constructed:self.current.object)[prop.name];prop.value||!self.current.object.hasOwnProperty(prop.name)&&prop.default,"array"!=$.type(value)&&(value=null!=value?[value]:[]);var disabled=_disableField(prop),idprop=prop.idprop||self.getIDProp(),template=prop.autocomplete_template||prop.template||"<joe-subtitle>${name} ${points}</joe-subtitle><joe-subtext>${${info} || ${"+idprop+"}}</joe-subtext>",html="Object Reference",specs=$.extend({},{autocomplete:{idprop:prop.idprop,template:template},values:values,skip:!0,name:prop.name,ftype:"objectReference",placeholder:prop.placeholder}),sortable=!0;prop.hasOwnProperty("sortable")&&(sortable=prop.sortable);html="";disabled||(html+='<div class="joe-references-container">'+self.renderTextField(specs)+'<div class="joe-text-input-button joe-reference-add-button" data-fieldname="'+prop.name+'"onclick="getJoe('+self.joe_index+').addObjectReferenceHandler(this);">add</div></div>'),html+=__clearDiv__+'<div class ="joe-object-references-holder '+disabled+(sortable&&!disabled?"sortable":"")+'" data-field="'+prop.name+'">';var refSpecs=$.extend({deleteButton:!disabled},prop.reference_specs||{});for(let i=0;i<value.length;i++){let v=value[i];$c.isObject(v)?html+=self.createObjectReferenceItem(v,null,prop.name,refSpecs):$c.isString(v)&&(html+=self.createObjectReferenceItem(null,v,prop.name,refSpecs))}return html+="</div>"}prop.values.search&&$.ajax("/API/search/",{data:prop.values.query||{},success:data=>{},error:err=>{}})},this.addObjectReferenceHandler=function(btn){var id=$(btn).siblings("input").val();if(!id)return!1;$(btn).siblings("input").val("");var fieldname=$(btn).data().fieldname,field=_getField(fieldname);$(".joe-object-references-holder[data-field="+fieldname+"]").append(self.createObjectReferenceItem(null,id,fieldname,field.reference_specs)),field.callback&&field.callback(_jco(!0)[fieldname])},this.removeObjectReferenceHandler=function(fieldname){var field=_getField(fieldname);field.callback&&field.callback(_jco(!0)[fieldname])},this.createObjectReferenceItem=function(item,id,fieldname,specs){var field=_getField(fieldname);specs=$.extend({expander:field.expander||field.itemExpander,gotoButton:field.gotoButton||field.goto,itemMenu:field.itemMenu,schemaprop:field.schemaprop||"itemtype",idprop:field.idprop,template:field.reference_template||field.template,deleteButton:!0,nonclickable:field.nonclickable,fieldname:fieldname,bgcolor:field.bgcolor,value:"${_id}"},specs||{});item&&"object"==typeof item&&(specs.isObject=!0,specs.value=item);var idprop=field.idprop||"_id";if(!item)for(var values=self.getFieldValues(field.values,field),i=0,tot=values.length;i<tot;i++)if(values[i][idprop]==id){item=values[i];break}if(!item)return'<div class="joe-field-item deletable" data-value="'+id+'">'+('<div class="joe-delete-button joe-block-button left" onclick="$(this).parent().remove();_joe.Fields.objectreference.remove(\''+fieldname+"');\">&nbsp;</div>")+"<div>REFERENCE NOT FOUND</div><span class='subtext'>"+id+"</span></div>";specs.link=location.href.replace(location.hash,`#/${item.itemtype}/${item._id}`);var icon=self.Render.schema_icon(item.itemtype),template=self.propAsFuncOrValue(specs.template,item,null,self.current.object)||`${icon}<joe-title>${item.name}</joe-title><joe-subtext>${item.info||item[idprop]}</joe-subtext>`,schema=item.itemtype&&_joe.schemas[item.itemtype]&&item.itemtype||"";return self.renderFieldListItem(item,template,schema,specs)},encapsulateFieldType("objectreference",self.renderObjectReferenceField,{create:self.createObjectReferenceItem,add:self.createObjectReferenceItem,remove:self.removeObjectReferenceHandler}),this.renderPreviewField=function(prop){var height=prop.height||"600px",url=self.propAsFuncOrValue(prop.url)||joe_web_dir+"pages/joe-preview.html",construct=_joe.constructObjectFromFields();obj=construct[self.getIDProp()]&&construct||self.current.object;var content=self.propAsFuncOrValue(prop.content,obj)||"",bodycontent=self.propAsFuncOrValue(prop.bodycontent,obj)||"",previewid=obj[self.getIDProp()]+"_"+prop.name;return window.__PreviewTest=function(){alert("test alert")},window.__previews=window.__previews||{},window.__previews[previewid]={content:content,bodycontent:bodycontent},url+="?pid="+previewid,'<div class="joe-button joe-reload-button joe-iconed-button" onclick="getJoe('+self.joe_index+").rerenderField('"+prop.name+'\');">Reload</div><div class="joe-preview-iframe-holder" style="height:'+height+'"><iframe class="joe-preview-field joe-field joe-preview-iframe" width="100%" height="100%" name="'+prop.name+'" src="'+url+'"></iframe></div><div class="joe-button joe-iconed-button joe-view-button multiline" onclick="window.open(\''+url+"','joe-preview-"+previewid+'\').joeparent = window;"> view fullscreen preview <p class="joe-subtext">'+url.length+" chars</p></div>"+__clearDiv__},encapsulateFieldType("preview",self.renderPreviewField);var tinyconfig={},goBackListIndex,sortable_index;function _readyCommentsField(fieldname){function updateCommentsField(payload){var html="";payload.error?html+="error:"+payload.error:html+=fillTemplate("<joe-comments-entry><joe-comments-user>${this.user.name}</joe-comments-user><joe-subtext>${RUN[_joe.Utils.prettyPrintDTS;${timestamp}]}</joe-subtext><joe-content>${comment}</joe-content></joe-comments-entry>",payload.comments.reverse()),$("joe-comments-view").html(html)}$("joe-comments-view").each(function(){$.ajax({url:"/API/comments/item/"+$(this).data().itemid,dataType:"jsonp",success:updateCommentsField})})}function _commentsAddHandler(dom,itemid){var comment=$(dom).siblings("textarea").val().trim();if($(dom).siblings("textarea").val(""),comment)try{var item=self.current.object,fieldName=$(dom).parents(".joe-object-field").data("name"),fieldObj=_joe.getField(fieldName),user=self.propAsFuncOrValue(fieldObj.user)||JOE.User||{},flag=self.propAsFuncOrValue(fieldObj.flag)||!1,payload={user:{_id:user._id,name:user.name},item:{_id:item._id,name:item.name,type:item.itemtype},comment:comment,flag:flag,timestamp:(new Date).toISOString()},action=fieldObj.action||function(payload){JOE.SERVER.socket.emit("save_comment",payload)};action(payload)}catch(e){self.Error.add("saving comment",e,{user:user,itemid:itemid,comment:comment,flag:flag})}}function encapsulateFieldType(name,render,additionalFunctions){render&&(self.Fields[name]={render:render},$.extend(self.Fields[name],additionalFunctions||{}))}function _getField(fieldname){for(var fieldobj,f=0,tot=self.current.fields.length;f<tot;f++)if((fieldobj=self.current.fields[f]).name==fieldname)return fieldobj;return!1}function renderItemMenu(item,buttons){if(!buttons)return"";if(!(buttons=self.propAsFuncOrValue(buttons,item)))return"";var oc,html='<item-menu class="joe-panel-content-option-menu"><table class=""><tbody><tr>';return buttons.map(function(b){b.hasOwnProperty("condition")&&!self.propAsFuncOrValue(b.condition,item)||(oc=b.url&&"window.open('"+fillTemplate(b.url,item)+"')"||b.action||"alert('"+b.name+"');",html+=fillTemplate('<td class="joe-option-menu-button '+(self.propAsFuncOrValue(b.css,item)||"")+'" onclick="'+oc+'">'+b.name+"</td>",item))}),html+="</tr></tbody></table></item-menu>"}function renderItemExpander(item,contentVal,specs){specs=specs||{};var content=fillTemplate(self.propAsFuncOrValue(contentVal,item,null,self.current.object),item);if(!content)return"";if(specs.onDemand)var html='<div class="joe-panel-content-option-expander on-demand" data-itemid="'+item[self.getIDProp(specs.schema)]+'" data-schema="'+(specs.schema||item.itemtype||self.current.schema)+'"></div>';else html='<div class="joe-panel-content-option-expander">'+content+"</div>";return html}function getDefaultSchema(schema){var menu=[];return(__jsu&&-1!=["super","admin","editor"].indexOf(__jsu.role)||$c.isEmpty(self.Data.user))&&(menu=[__exportBtn__,_joe.SERVER.History.button,__quicksaveBtn__,__deleteBtn__,__duplicateBtn__]),{subtitle:"${_subsetName}",callback:self.SERVER.save,onsave:function(item){let current=_jco(!0);current&&item[self.getIDProp(item.itemtype)]==current._id&&self.Fields.rerender("status,updated,timestamp")},new:function(){return{_id:cuid(),itemtype:schema,created:(new Date).toISOString()}},menu:menu}}this.renderTinyMCEField=function(prop){const locked=self.propAsFuncOrValue(prop.locked)?"disabled":"",heightStyle=prop.height?`style="height:${prop.height};"`:"",editor_id=cuid();return`<div class="joe-tinymce-holder joe-texteditor-field joe-field wysiwyg-field"\n data-texteditor_id="${editor_id}"\n data-ftype="tinymce"\n data-name="${prop.name}">\n <textarea id="${editor_id}" class="joe-tinymce" ${locked} ${heightStyle}>${prop.value||""}</textarea>\n </div>`},this.readyTinyMCEs=function(){tinymce.init({selector:".joe-tinymce",base_url:"/JsonObjectEditor/js/plugins/tinymce",suffix:".min",license_key:"gpl",browser_spellcheck:!0,contextmenu:!1,content_style:"\n body {\n font-size: 16px;\n line-height: 21px;\n }\n ",plugins:["table","wordcount","link","image","code","searchreplace","autoresize","fullscreen","lists"],toolbar:"fullscreen | undo redo | h1 h2 h3 h4 h5 |bold italic removeformat | bullist numlist outdent indent | code",skin_url:"/JsonObjectEditor/js/plugins/tinymce/skins/ui/oxide/",content_css:"/JsonObjectEditor/js/plugins/tinymce/skins/content/default/content.css",theme_url:"/JsonObjectEditor/js/plugins/tinymce/themes/silver/theme.min.js",icons_url:"/JsonObjectEditor/js/plugins/tinymce/icons/default/icons.min.js",init_instance_callback:function(editor){const fieldContainer=editor.targetElm.closest(".wysiwyg-field");if(fieldContainer){const fieldName=fieldContainer.getAttribute("data-name"),field=self.getField(fieldName);if(field&&field.height){const iframe=editor.getContainer().querySelector("iframe");iframe&&(iframe.style.height=`${field.height}px`)}}}})},this.cleanTinyMCEs=function(html){const temp=document.createElement("div");return temp.innerHTML=html,temp.querySelectorAll("*").forEach(el=>{[...el.attributes].forEach(attr=>{if(attr.name.startsWith("data-")&&el.removeAttribute(attr.name),"style"===attr.name){const styleVal=attr.value.toLowerCase();(styleVal.includes("font-weight: 400")||styleVal.includes("font-family")||styleVal.includes("white-space:pre")||styleVal.includes("line-height")||styleVal.includes("margin")||styleVal.includes("orphans")||styleVal.includes("widows"))&&el.removeAttribute("style")}}),"SPAN"===el.tagName&&0===el.attributes.length&&""===el.textContent.trim()&&el.remove()}),temp.innerHTML},self.texteditors=[],this.readyTextEditors=this.readyTinyMCEs,encapsulateFieldType("wysiwyg",self.renderTinyMCEField,{ready:self.readyTextEditors,clean:this.cleanTinyMCEs}),this.renderSubObjectField=function(prop){var action="getJoe("+self.joe_index+").Fields.subobject.openMini('"+prop.name+"');",html=prop.locked?"":'<div class="joe-button joe-view-button joe-iconed-button" onclick="'+action+'">Edit</div>';return html+="<joe-subobject-output><pre>"+JSON.stringify(prop.value,"","\t")+"</pre></joe-subobject-output>"},encapsulateFieldType("subobject",self.renderSubObjectField,{openMini:function(propname){var field=self.getField(propname),callback=self.Cache.add(function(data,id){self.getField(data.prop);self.current.object[data.prop]=self.Mini.construct(),self.Fields.rerender(data.prop)},{data:{prop:propname},type:"callback"}),specs={object:field.value,title:field.display||field.name,menu:[{name:"update",callback:callback.id}],schema:field.schema,name:self.joe_index+"-"+propname};_joe.showMiniJoe(specs)},construct:function(parentFind,outputObject){var propname;parentFind.find(".subobject-field").each(function(){propname=$(this).data("name"),outputObject[propname]=self.current.object[propname]})}}),this.renderPassthroughField=function(prop){return"passthrough"},this.renderButtonField=function(prop){var itemObj=self.current.object||{},display=self.propAsFuncOrValue(prop.display,itemObj),method=self.propAsFuncOrValue(prop.method,itemObj),onclick=self.propAsFuncOrValue(prop.onclick,itemObj),color=self.propAsFuncOrValue(prop.color,itemObj),schema=self.propAsFuncOrValue(prop.schema,itemObj),svgOverride=self.propAsFuncOrValue(prop.svg,itemObj),title=self.propAsFuncOrValue(prop.title,itemObj),bgcolor=self.propAsFuncOrValue(prop.bgcolor,itemObj),cssclass=self.propAsFuncOrValue(prop.cssclass,itemObj)||" joe-nofloat",svgMarkup="";schema&&_joe&&_joe.Schemas&&_joe.Schemas[schema]&&_joe.Schemas[schema].menuicon&&(svgMarkup=_joe.Schemas[schema].menuicon),svgOverride&&(svgMarkup='<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">'+svgOverride+"</svg>");var styleAttr=bgcolor?'style="background-color: '+bgcolor+';"':"",html='<joe-button class="joe-button joe-field '+cssclass+(color?" joe-"+color+"-button":"")+'" name="'+(prop.name||"")+'" '+(schema?'schema="'+schema+'" ':"")+(method?'action="'+method+'" ':"")+(color?'color="'+color+'" ':"")+(title?'title="'+title+'" ':"")+(onclick?'onclick="'+onclick+'" ':"")+styleAttr+' data-btnid="'+(prop.name||"")+'">';return svgMarkup&&(html+=svgMarkup+" "),html+=(display||"Button")+"</joe-button>"},encapsulateFieldType("button",self.renderButtonField),this.renderCommentsField=function(prop){var item=self.propAsFuncOrValue(prop.item)||self.current.object,idprop=self.getIDProp(),user=self.propAsFuncOrValue(prop.user)||JOE.User||{},usertemplate=prop.usertemplate||"<joe-subtext><b>${name}</b> says: </joe-subtext>";return"<joe-comments-add>"+fillTemplate(usertemplate,user)+"<textarea></textarea>"+self.renderMenuButtons({css:"joe-iconed-button joe-comments-button fright",name:"comment",action:"_joe.Fields.comments.add(this);"})+__clearDiv__+"</joe-comments-add><joe-comments-view data-itemid='"+item[idprop]+"'>loading</joe-comments-view>"},encapsulateFieldType("comments",self.renderCommentsField,{add:_commentsAddHandler,ready:_readyCommentsField}),this.getField=this.Fields.get=_getField,this._renderExpanderButton=function(expanderContent,item){return expanderContent?'<div class="joe-panel-content-option-expander-button" onclick="_joe.toggleItemExpander(this);"></div>':""},this.toggleItemExpander=function(dom,itemid){if(dom){var expander=$(dom).siblings(".joe-panel-content-option-expander");if(expander.hasClass("on-demand")&&!expander.hasClass("demanded")){var id=expander.data("itemid"),schemaname=expander.data("schema"),item=_joe.getDataItem(id,schemaname),content=self.propAsFuncOrValue(self.schemas[schemaname].itemExpander,item);expander.addClass("demanded").html(content)}$(dom).closest(".expander").toggleClass("expander-collapsed").toggleClass("expander-expanded")}},this.renderItemExpander=renderItemExpander,this.renderTableItem=function(listItem,quick,index){var colprop,idprop=self.getIDProp(),id=listItem[idprop]||null;if(quick){var searchable="";return tableSpecs.cols.map(function(c){$c.isString(c)?searchable+=(listItem[c]||"")+" ":$c.isObject(c)&&(colprop=c.property||c.name,searchable+=(c.template&&self.propAsFuncOrValue(c.template,listItem[colprop],null,listItem)||listItem[colprop]||-1!=colprop.indexOf("${")&&colprop||"")+" "),searchable=fillTemplate(searchable,listItem)}),searchable}var schemaprop=self.current.schema&&self.current.schema.listView&&self.current.schema.listView.schemaprop,ghtml='<tr class="joe-panel-content-option trans-bgcol" '+(schemaprop?'onclick="getJoe('+self.joe_index+").listItemClickHandler({dom:this,id:'"+id+"',schema:'"+schemaprop+"'});\"":'onclick="getJoe('+self.joe_index+").listItemClickHandler({dom:this,id:'"+id+"'});\"")+">";return ghtml+='<td class="joe-table-checkbox"><label>'+index+(tableSpecs.multiselect?'<input type="checkbox" />':"")+"</label></td>",tableSpecs.cols.map(function(c){$c.isString(c)?ghtml+=fillTemplate("<td>"+(listItem[c]||"")+"</td>",listItem):$c.isObject(c)&&(colprop=c.property||c.name,ghtml+=fillTemplate("<td>"+(c.template&&self.propAsFuncOrValue(c.template,listItem[colprop],null,listItem)||listItem[colprop]||-1!=colprop.indexOf("${")&&colprop||"")+"</td>",listItem))}),ghtml+="</tr>"},this.Render.gridItem=this.renderGridItem=function(item,quick,index,specs){var schema=(specs=$.extend({template:"<joe-title>${name}</joe-title><joe-content>${info}</joe-content>",bgcolor:"#fff"},self.current.schema,self.current.schema.gridView,specs)).__schemaname,schemaobj=self.schemas[schema],contentTemplate=self.propAsFuncOrValue(specs.template,item)||"<joe-title>${name}</joe-title><joe-subtext>${itemtype}</joe-subtext>",idprop=specs.idprop||schemaobj&&schemaobj.idprop||"_id",hasMenu=specs.itemMenu&&specs.itemMenu.length,action=specs.action||" onclick=\"goJoe(_joe.search('${"+idprop+"}')[0],{schema:'"+schema+"'})\" ",nonclickable=self.propAsFuncOrValue(specs.nonclickable,item),clickablelistitem=!specs.gotoButton&&!nonclickable,expanderContent=renderItemExpander(item,specs.expander),click=clickablelistitem?action:"";return fillTemplate('<joe-option class="joe-content-option '+(specs.itemMenu?" itemmenu":"")+(specs.stripecolor?" striped":"")+(specs.expander?" expander expander-collapsed":"")+'" >'+(hasMenu&&renderItemMenu(item,specs.itemMenu)||"")+self.Render.bgColor(item,specs.bgcolor)+'<div class="joe-panel-content-option-content'+(nonclickable?"nonclickable":"")+'" '+click+" >"+self.propAsFuncOrValue(contentTemplate+__clearDiv__,item)+"</div>"+self.Render.stripeColor(item,specs.stripecolor)+self._renderExpanderButton(expanderContent,item)+expanderContent+"</joe-option>",item)},this.renderListItem=function(listItem,quick,index){var action,listSchema=$.extend({_listID:"id",stripeColor:null},self.current.schema,self.current.specs),idprop=self.getIDProp(),id=listItem[idprop]||null,customAction=self.current.schema&&(self.current.schema.listView&&self.current.schema.listView.action||self.current.schema.listAction);if(customAction)action='onclick="'+self.propAsFuncOrValue(customAction,listItem)+'"';else{var schemaprop=self.current.schema&&(self.current.schema.schemaprop||self.current.schema.listView&&self.current.schema.listView.schemaprop);action=schemaprop?'onclick="getJoe('+self.joe_index+").listItemClickHandler({dom:this,id:'"+id+"',schema:'"+listItem[schemaprop]+"',idprop:'_id'});\"":'onclick="getJoe('+self.joe_index+").listItemClickHandler({dom:this,id:'"+id+"'});\""}var stripeColor=self.propAsFuncOrValue(listSchema.stripeColor||listSchema.stripecolor,listItem),stripeHTML="",stripeTitle="";stripeColor&&("object"!=typeof stripeColor&&(stripeColor={color:stripeColor}),(stripeColor.title||stripeColor.name)&&(stripeTitle=' title="'+(stripeColor.title||stripeColor.name)+'" '),stripeHTML='style="background-color:'+stripeColor.color+';" '+stripeTitle);var bgColor=self.propAsFuncOrValue(listSchema.bgColor||listSchema.bgcolor,listItem),bgHTML="";bgColor&&(bgHTML=bgColor.color?'style="background-color:'+bgColor.color+';"':'style="background-color:'+bgColor+';"');var template=listSchema.listView&&listSchema.listView.template||listSchema._listTemplate,title=self.propAsFuncOrValue(listSchema.listView&&listSchema.listView.title||listSchema._listTitle||listSchema.listTitle,listItem);if(quick)return fillTemplate(template||title||"",listItem);var borderColor=fillTemplate(self.propAsFuncOrValue(listSchema.borderColor||listSchema.bordercolor,listItem)),borderHTML="";borderColor&&(borderHTML='style="border:1px solid '+borderColor+';"');var numberHTML="";if(index&&!listSchema.hideNumbers&&(numberHTML=index),template){var dup=$c.duplicate(listItem);dup.action=action,html=fillTemplate(template,dup)}else{title=title||listItem.name||id||"untitled";var listItemMenu=renderItemMenu(listItem,listSchema.listView&&listSchema.listView.itemMenu||listSchema.itemMenu),listItemExpander=renderItemExpander(listItem,listSchema.listView&&listSchema.listView.itemExpander||listSchema.itemExpander,{onDemand:listSchema.onDemandExpander,schema:listSchema.__schemaname}),listItemExpanderButton=self._renderExpanderButton(listItemExpander,listItem),icon=listSchema.listView&&listSchema.listView.icon||listSchema.icon||listSchema._icon||"",checkbox=self.Render.itemCheckbox(listItem,listSchema,{idprop:idprop}),user_icon=self.propAsFuncOrValue(icon,listItem),listItemIcon=user_icon&&function(icon,listItem){var url=icon.url||icon;if(-1==url.indexOf("<svg")){var width=icon.width?" width:"+icon.width+"; ":"",height=icon.height?" height:"+icon.height+"; ":"",iconURL=fillTemplate(url,listItem);return"<div style=\" background-image:url('"+iconURL+'\'); " class="joe-panel-content-option-icon trans-bgcol fleft" ><img style="'+width+height+'" src="'+iconURL+'"/></div>'}return'<div class="joe-panel-content-option-svg fleft" >'+icon+"</div>"}(user_icon,listItem)||"";title="<div class='joe-panel-content-option-content ' "+action+">"+checkbox+title+"<div class='clear'></div></div>";var html="<joe-option "+borderHTML+' class="'+(self.allSelected?"selected":"")+" joe-panel-content-option trans-bgcol "+(numberHTML?"numbered":"")+" joe-no-select "+(stripeColor?"striped":"")+" "+(listItemExpanderButton?"expander expander-collapsed":"")+(listItemMenu?" item-menu":"")+'" data-id="'+id+'" ><div class="joe-panel-content-option-bg" '+bgHTML+'></div><div class="joe-panel-content-option-stripe'+(stripeTitle?" titled":"")+'" '+stripeHTML+"></div>"+(numberHTML&&'<div class="joe-panel-content-option-number" >'+numberHTML+"</div>"||numberHTML)+(listItem._protected?'<svg xmlns="http://www.w3.org/2000/svg" class="protected-icon" viewBox="-6 -4 36 36"><path d="M12 1C8.7 1 6 3.7 6 7L6 8C4.9 8 4 8.9 4 10L4 20C4 21.1 4.9 22 6 22L18 22C19.1 22 20 21.1 20 20L20 10C20 8.9 19.1 8 18 8L18 7C18 3.7 15.3 1 12 1ZM12 3C14.3 3 16 4.7 16 7L16 8 8 8 8 7C8 4.7 9.7 3 12 3ZM12 13C13.1 13 14 13.9 14 15 14 16.1 13.1 17 12 17 10.9 17 10 16.1 10 15 10 13.9 10.9 13 12 13Z"></path></svg>':"")+listItemExpanderButton+listItemIcon+listItemMenu+fillTemplate(title,listItem)+listItemExpander+"</joe-option>"}return html},this.checkItem=function(itemID,prop,schema,dom){var checkboxAction,item=self.search(itemID)[0]||!1;if((schema=schema||self.current.schema||item&&self.schemas[item.itemtype])&&schema.checkbox&&schema.checkbox.action&&(checkboxAction=schema.checkbox.action),item){$(dom).toggleClass("checked");var overwrite={joeUpdated:new Date},isChecked=$(dom).hasClass("checked");checkboxAction?$.extend(overwrite,checkboxAction(item,isChecked,$(dom))||{}):overwrite[prop]=isChecked,$.extend(item,overwrite),schema.callback(item),window.event&&window.event.stopPropagation()}},this.shiftSelecting=!1,this.listItemClickHandler=function(specs){if(goBackListIndex=null,specs&&specs.dom&&(goBackListIndex=$(specs.dom).parents(".joe-panel-content-option").index()),self.current.selectedListItems=[],window.event)if(window.event.shiftKey||window.event.ctrlKey){if(window.event.ctrlKey)$(specs.dom).hasClass("joe-panel-content-option")?$(specs.dom).toggleClass("selected"):$(specs.dom).parents(".joe-panel-content-option").toggleClass("selected"),$(".joe-panel-content-option.selected").map(function(i,listitem){self.current.selectedListItems.push($(listitem).data("id"))});else if(window.event.shiftKey){var shiftIndex;if($(specs.dom).hasClass("joe-panel-content-option")?($(specs.dom).addClass("selected"),shiftIndex=$(specs.dom).index()):($(specs.dom).parents(".joe-panel-content-option").addClass("selected"),shiftIndex=$(specs.dom).parents(".joe-panel-content-option").index()),!1!==self.shiftSelecting){if(shiftIndex<self.shiftSelecting){var t=shiftIndex,p=self.shiftSelecting;self.shiftSelecting=t,shiftIndex=p}$(".joe-panel-content-option").slice(self.shiftSelecting,shiftIndex+1).addClass("selected"),$(".joe-panel-content-option").slice(shiftIndex+1).removeClass("selected"),$(".joe-panel-content-option").slice(0,self.shiftSelecting).removeClass("selected")}else self.shiftSelecting=shiftIndex;$(".joe-panel-content-option.selected").map(function(i,listitem){self.current.selectedListItems.push($(listitem).data("id"))})}}else self.editObjectFromList(specs);else self.editObjectFromList(specs);self.updateSelectionVisuals()},this.updateSelectionVisuals=function(){self.current.selectedListItems.length?(self.overlay.addClass("multi-edit"),self.overlay.find(".joe-selection-indicator").html(self.current.selectedListItems.length+" selected")):(self.overlay.removeClass("multi-edit"),self.overlay.find(".joe-selection-indicator").html(""))},this.editObjectFromList=function(specs){specs=specs||{},self.current.schema=specs.schema||self.current.schema||null;var list=specs.list||self.current.list,id=specs.id,idprop=specs.idprop||self.getIDProp(),object=list.filter(function(li){return li[idprop]==id})[0]||!1;if(object){var setts={schema:specs.schema||self.current.schema,callback:specs.callback};goJoe(object,setts)}else alert("error finding object")},this.showList=function(view,subset,filter){"string"==$.type(view)&&(view={collection:view,schema:view}),view.subset=subset||null;var showJoeListBenchmarker=new Benchmarker;self.current.clear();var dataList=self.Data[view.collection]||[];filter&&(dataList=dataList.where(filter)),goJoe(dataList,{schema:view.schema,subset:view.subset}),_bmResponse(showJoeListBenchmarker,'Joe View: "'+view.collection+'" shown')},this.editMultiple=function(){var haystack=self.current.list,idprop=self.getIDProp(),needles=self.current.selectedListItems,items=[],protoItem={};haystack.map(function(i){-1!=needles.indexOf(i[idprop])&&($.extend(protoItem,i),items.push(i))}),goJoe(protoItem,{title:"Multi-Edit "+(self.current.schema.__schemaname||"")+": "+items.length+" items",schema:self.current.schema||null,multiedit:!0})},this.filterList=function(list,props,specs){specs=specs||{};var found=(list||self.current.list).filter(function(arrobj){for(var p in props)if(arrobj[p]!=props[p])return!1;return!0});return!!found.length&&(specs.single?found[0]:found)},this.renderSubsetselector=function(specs){return listMode?'<div class="joe-subset-selector" >'+self.renderSubsetSelectorOptions(specs)+"</div>":""},this.renderSubsetSelectorOptions=function(specs){var subsets=self.current.subsets;function renderOption(opt){var html="";if(!opt.condition||self.propAsFuncOrValue(opt.condition))html='<div class="selector-option" onclick="getJoe('+self.joe_index+").selectSubset('"+(opt.id||opt.name||"")+"');\">"+opt.name+"</div>";return html}"function"==typeof subsets&&(subsets=subsets()),self.current.specs.subset&&(self.current.subset=subsets.filter(function(s){return s.id=s.id||s.name,s.id==self.current.specs.subset})[0]||!1);var html='<div class="selector-label selector-option" onclick="$(this).parent().toggleClass(\'active\')">'+(self.current.subset&&self.current.subset.name||"All")+'</div><div class="selector-options">'+renderOption({name:"All",filter:{}});return subsets.map(function(s){html+=renderOption(s)}),html+="</div>"},this.selectSubset=function(subset){self.hide();var schemaname=self.current.schema&&self.current.schema.name;goJoe(self.current.list,$.extend({},self.current.userSpecs,{subset:subset,schema:schemaname}))},this.toggleFilter=function(filtername,dom){parseFloat(filtername)==filtername&&(filtername=parseFloat(filtername));var filter=(self.current.schema&&self.propAsFuncOrValue(self.current.schema.filters)||[]).where({$or:[{name:filtername},{id:filtername}]})[0]||!1;filter?(self.current.schema&&self.current.schema.__schemaname&&(filter.schema=self.current.schema.__schemaname),self.current.filters[filtername]?delete self.current.filters[filtername]:self.current.filters[filtername]=filter,dom&&$(dom).toggleClass("active"),self.filterListFromSubmenu(null,!0)):logit("issue finding filter: "+filtername)},this.toggleFilterObject=function(filtername,filterObj,wait){parseFloat(filtername)==filtername&&(filtername=parseFloat(filtername));var filter=self.propAsFuncOrValue(filterObj);filter?(self.current.schema&&self.current.schema.__schemaname&&(filter.schema=self.current.schema.__schemaname),self.current.filters[filtername]&&delete self.current.filters[filtername],self.current.filters[filtername]={name:filtername,filter:filterObj},self.filterListFromSubmenu(null,!wait)):logit("issue finding filter: "+filtername)},this.clearFilters=function(){self.current.filters={},self.container.find(".joe-filter-option").removeClass("active"),self.filterListFromSubmenu(null,!0)},this.replaceRendering=function(dom,specs){var rendering=dom.toString();specs={datatype:"rendering",compact:!1,dom:dom};self.show(rendering,specs)},this.updateRendering=function(dom,callback){callback=self.current.callback||self.current.schema&&self.current.schema.callback||logit;if(!self.current.specs.dom)return!1;var newVal=$(".joe-rendering-field").val();$(self.current.specs.dom).replaceWith(newVal),logit("dom updated"),self.hide(),callback(newVal)},this.showPropertyEditor=function(prop){self.current.mutant=prop},this.addPropertyToEditor=function(prop){},this.minis={},this.showMiniJoe=function(specs,joespecs,data){var mini={},object=(specs=$.extend({mode:"text"},specs||{},joespecs||{})).props||specs.object||specs.list||specs.content;if(object){var title=specs.title||"Object Focus";mini.id=cuid();var mode=specs.mode||"object";switch(specs.object=object,specs.minimenu=specs.minimenu||specs.menu,$.type(object)){case"object":mode="object";break;case"array":mode="list"}specs.mode=mode;var minimode=mini.id;specs.minimode=minimode;var html=self.renderEditorHeader({title:title,minimode:minimode,close_action:'onclick="getJoe('+self.joe_index+").hideMini('"+minimode+"');\""});html+=self.renderMiniEditorContent(specs),html+=self.renderEditorFooter({minimenu:specs.menu,minimode:minimode});var height=specs.height||self.overlay.height()/2;mini.panel=self.overlay.find(self.Mini.selector),specs.name,mini.panel.attr("name",specs.name||mini.id),mini.panel.addClass("active").addClass("focus").html(html),$(".joe-mini-panel .joe-panel-footer").find(".joe-button:visible").length||$(".joe-mini-panel").addClass("no-footer-menu"),mini.panel.css("height",height),specs.width&&mini.panel.css("width",specs.width),mini.panel.draggable({handle:"joe-panel-header",snap:".joe-overlay"}).resizable({handles:"s"}),mini.callback=specs.callback||function(itemid){alert(itemid)},mini.data=data||{},self.minis[mini.id]=mini,self.Mini.id=mini.id,self.overlay.toggleClass("mini-active",!0)}},this.hideMini=function(miniid){try{miniid?(delete self.minis[miniid],$(self.Mini.selector+".ui-resizable").resizable("destroy").draggable("destroy"),$(self.Mini.selector).removeClass("active")):($(self.Mini.selector+".ui-resizable").resizable("destroy").draggable("destroy"),$(self.Mini.selector).removeClass("active"))}catch(e){self.Error.add("hidemini error: "+e,e,{warning:!0})}self.overlay.removeClass("mini-active")},this.constructObjectFromMiniFields=function(){var prop,object={};return $(".joe-mini-panel.active .joe-object-field").find(".joe-field").each(function(){if("checkbox"===$(this).attr("type"))prop=$(this).attr("name"),$(this).is(":checked")?object[prop]=!0:object[prop]=!1;else prop=$(this).attr("name"),object[prop]=$(this).val()}),object},this.renderMiniEditorContent=function(specs){var content;self.current.sidebars={left:{collapsed:!1},right:{collapsed:!1}},specs||(specs={mode:"text",text:"No object or list selected"});var mode=specs.mode;switch(mode){case"text":content=self.renderTextContent(specs);break;case"rendering":content=self.renderHTMLContent(specs);break;case"list":content=self.renderListContent(specs);break;case"object":content=self.renderObjectContent(specs);break;default:content=content||""}var submenu="";specs.minimode||("list"==mode&&self.current.submenu||self.current.submenu||renderSectionAnchors().count)&&(submenu=" with-submenu ");var scroll='onscroll="getJoe('+self.joe_index+').onListContentScroll(this);"',rightC=content.right||"",leftC=content.left||"",html='<joe-panel-content class="'+("joe-panel-content "+renderEditorStyles()+submenu)+'" '+(listMode&&scroll||"")+">"+(content.main||content)+"</joe-panel-content>"+self.renderSideBar("left",leftC,{css:submenu})+self.renderSideBar("right",rightC,{css:submenu});return self.current.sidebars.left.content=leftC,self.current.sidebars.right.content=rightC,html},this.Mini={selector:".joe-mini-panel",show:self.showMiniJoe,hide:self.hideMini,construct:self.constructObjectFromMiniFields,get:function(){return self.minis[self.Mini.id]||!1},clear:function(){self.hideMini(),self.minis={},delete self.Mini.id}},self.quickAdd=function(itemtype){if(!1!==(itemtype=itemtype)&&(itemtype=itemtype||self.current.schema&&self.current.schema.__schemaname),itemtype)self.createObject(itemtype);else{var sch,t=[];for(var d in self.Data)(sch=_joe.schemas[d])&&t.push({name:sch.name,info:sch.info,menuicon:sch.menuicon,default_schema:sch.default_schema||!1});t.sortBy("name"),_joe.showMiniJoe({title:"Create a new:",list:t,template:"<joe-schema-icon>${menuicon}</joe-schema-icon><joe-title>${name}</joe-title><joe-subtitle>${info}</joe-subtitle>",idprop:"name",sorter:"default_schema,name",menu:[],callback:function(item_id){self.createObject(item_id)}})}},self.schemas.search={title:"Search Results",name:"search",__schemaname:"search",listTitle:function(item){return"<joe-full-right><joe-subtext>updated</joe-subtext><joe-subtitle>"+self.Utils.toDateString(item.joeUpdated)+"</joe-subtitle></joe-full-right>"+(_joe.schemas[item.itemtype].menuicon&&'<joe-icon class="icon-40 icon-grey fleft">'+_joe.schemas[item.itemtype].menuicon+"</joe-icon>"||"")+"<joe-subtext>${itemtype}</joe-subtext><joe-title>${name}</joe-title><joe-subtitle>${info}</joe-subtitle><joe-subtext>${_id}</joe-subtext>"},listmenu:[],sorter:["name",{name:"updated",value:"!joeUpdated"},"itemtype"],dataset:function(){return _joe.search({name:/[a-z0-9 _\-\!\:]*/})},filters:function(){var f=[];return __appCollections.concat().sort().map(function(s){f.push({name:s,filter:{itemtype:s}})}),f},listAction:function(item){return"goJoeItem('"+item._id+"','"+item.itemtype+"')"}},self.quickFind=function(phrase){goJoe(_joe.search({name:/[a-z0-9 _\-\!\:]*/}),{schema:"search"},function(){self.panel.find(".joe-submenu-search-field").focus()})},self.search=function(id,specs){(specs=specs||{}).collections,specs.props||specs.properties;var results,haystack=[];for(var d in self.Data)haystack=haystack.concat(self.Data[d]);return"string"==$.type(id)?results=haystack.filter(function(r){return r._id==id}):"object"==$.type(id)&&(results=haystack.where(id)),results},self.addDataset=function(name,values,specs){values=self.propAsFuncOrValue(values,name);if(name&&values&&"array"==$.type(values)){self.Data[name]=values;var idprop=self.schemas[name]&&self.schemas[name].idprop||"_id";if(self.Data[name].map(dataitem=>{self.Indexes._add(idprop,dataitem)}),!self.schemas[name])return;if(self.schemas[name].onload)try{console.log(name+" onload"),self.schemas[name].onload(self.Data[name])}catch(e){self.Error.add("schema onload error: "+name,e)}}},self.deleteDataset=function(dataset){delete self.Data[dataset]},self.dit=0,self.getData=function(specs){(new Date).getTime();var objects=[];if((specs=specs||{}).schemas)specs.schemas.map(sc=>{objects=objects.concat(self.Data[sc])});else for(var d in self.Data)objects=objects.concat(self.Data[d]);var query=specs.query||specs.filters;query&&(objects=objects.where(self.propAsFuncOrValue(query)));var sortBy=specs.sort||specs.sortBy;return sortBy&&(objects=objects.sortBy(sortBy)),specs.limit&&(objects=objects.slice(0,specs.limit)),objects},self.getDataItem=function(id,datatype,idprop){var item,st=(new Date).getTime();function addtoDIT(){var el=(new Date).getTime()-st;self.dit+=el}idprop=idprop||self.schemas[datatype]&&self.schemas[datatype].idprop||"_id";if(self.Indexes[idprop]&&self.Indexes[idprop][id])return addtoDIT(),self.Indexes._usage++,self.Indexes[idprop][id];var dataset=self.Data[datatype];if(!self.Data[datatype])return addtoDIT(),!1;for(var i=0,tot=dataset.length;i<tot;i++)if((item=dataset[i])[idprop]==id)return addtoDIT(),item;return addtoDIT(),!1},self.getDataset=function(datatype,specs){var sortby=(specs=specs||{}).sortby||"name";if(self.Data[datatype])var data=self.Data[datatype].sortBy(sortby);else{if(specs.boolean=!0)return!1;data=[]}return specs.filter&&(data=data.where(specs.filter)),specs.reverse&&data.reverse(),specs.blank?[{name:"",val:""}].concat(data):data},self.getDataItemProp=function(id,dataset,prop,specs){specs=specs||{delimiter:","};if(prop=prop||"name",!id)return"";var vals="";return $c.isArray(id)||(id=[id]),id.map(function(item_id,i){var item=self.getDataItem(item_id,dataset);i>0&&(vals+=specs.delimiter||""),item&&(vals+=item[prop])}),vals},this.setSchema=function(schemaName){if(!schemaName)return!1;var schema="object"==$.type(schemaName)?schemaName:self.schemas[schemaName]||null;return schema&&self.current.schema&&self.current.schema.name&&self.current.schema.name!=schema.name&&(listMode&&self.current.schema&&"search"==self.current.schema.name||!listMode&&schema&&"search"==schema.name||(self.current.keyword="")),self.current.schema=schema,schema},this.resetSchema=function(schemaName){var newObj=self.constructObjectFromFields(self.joe_index);self.show($.extend(self.current.object,newObj),$c.merge(self.current.userSpecs,{noHistory:!0,schema:self.setSchema(schemaName)||self.current.schema}))},this.Schema={add:function(name,config,specs){self.schemas[name]=self.propAsFuncOrValue(config);var schemaObj=self.schemas[name];return schemaObj.__schemaname=schemaObj.name=name,schemaObj._id=cuid(),schemaObj},set:this.setSchema,reset:this.resetSchema},this.toggleOverlay=function(dom){$(dom).parents(".joe-overlay").toggleClass("active")},this.showItem=function(id,schemaname,specs,show_callback){if(schemaname){specs=specs||{};var item=self.getDataItem(id,schemaname);specs=$.extend(specs,{schema:schemaname}),self.show(item,specs,show_callback)}},this.show=function(data,specs,show_callback){data=data||"";((specs=specs||{}).force||self.checkChanges())&&(self.setEditingHashLink(!0),self.current.benchmarkers={},self.showBM=new Benchmarker,clearTimeout(self.hideTimeout),specs.container&&(self.container=$(specs.container)),self.panel.attr("class","joe-overlay-panel"),!0===specs.compact&&self.overlay.addClass("compact"),!1===specs.compact&&self.overlay.removeClass("compact"),self.populateFramework(data,specs),self.overlay.removeClass("hidden"),self.overlay.addClass("active"),self.current.show_callback=show_callback,setTimeout(self.onPanelShow,0),$(self.container).trigger({type:"showJoe",schema:self.current.specs.schema,subset:self.current.specs.subset}))},this.hide=function(timeout){timeout=timeout||0,self.overlay.addClass("hidden"),self.hideTimeout=setTimeout(function(){self.overlay.removeClass("active"),self.overlay.removeClass("hidden")},timeout)},this.reload=function(hideMessage,specs){logit("reloading joe "+self.joe_index),self._reloading=!0;specs=specs||{};var reloadBM=new Benchmarker,info=self.history.pop();if("object"==$.type(info.data))if(specs.overwrite||specs.overwrites)var obj=$.extend({},info.data,specs.overwrite||specs.overwrites);else obj=info.data;else obj=info.data;delete specs.overwrite,delete specs.overwrites;specs=$.extend({},info.specs,specs);self.show(obj,specs),hideMessage||self.showMessage("reloaded in "+reloadBM.stop()+" secs"),self._reloading=!1},this.compactMode=function(compact){!0===compact&&self.overlay.addClass("compact"),!1===compact&&self.overlay.removeClass("compact")},this.printObject=function(obj){goJoe("<pre>"+JSON.stringify(obj," "," ")+"</pre>")},0==self.joe_index&&(window.joeMini=this.showMiniJoe,window.goJoe=this.show,window.goJoeItem=this.showItem,window.listJoe=this.editObjectFromList),window.$J=window.$J||{_usages:{get:0,schema:0,search:0},get:function(itemID,callback,itemtype){"string"!=typeof callback||itemtype||(itemtype=callback,callback=null),$J._usages.get++;var item=self.getDataItem(itemID,itemtype)||$J.search({_id:itemID})[0];return!!item&&(callback&&callback(item),item)},schema:function(schemaname,callback){$J._usages.schema++;var schema=_joe.schemas[schemaname];if(schema)return callback&&callback(schema),schema},search:function(query,callback){$J._usages.search++;var results=_joe.search(query);return callback&&callback(results),results}},window.getJoe=function(index){return window._joes[index]||!1},$(document).keyup(function(e){var mode=self.getMode();27==e.keyCode?("list"==mode?self.deselectAllItems():"details"==mode&&$(".joe-text-autocomplete.active").length&&$(".joe-text-autocomplete.active").removeClass("active"),self.specs.useEscapeKey&&self.closeButtonAction()):e.ctrlKey&&13==e.keyCode&&self.specs.useControlEnter&&self.overlay.find(".joe-confirm-button").click()}),this.Autosave={possibleChanges:!0,unsavedChanges:!1,activate:function(){if(self.specs.autosave){var intercnt=1e3;"number"==typeof self.specs.autosave&&(intercnt=self.specs.autosave),self.Autosave.interval=setInterval(function(){if(self.Autosave.possibleChanges){var hasChanged=self.checkChanges(!0),showUnsaved=hasChanged&&"details"==self.getMode();document.title=(showUnsaved?"*":"")+document.title.replace("*",""),self.overlay.toggleClass("unsaved-changes",showUnsaved),self.Autosave.unsavedChanges=hasChanged}},intercnt)}},deactivate:function(){self.specs.autosave&&clearInterval(self.Autosave.interval)}},this.onPanelShow=function(){var BM=new Benchmarker;if(self.respond(),self.Autosave.activate(),self.Fields.date.ready(),self.Fields.time.ready(),currentListItems&&self.overlay.find(".joe-submenu-search-field").length&&((goingBackQuery||!$c.isEmpty(self.current.userSpecs.filters)&&listMode)&&(self.overlay.find(".joe-submenu-search-field").val(goingBackQuery),self.filterListFromSubmenu(self.overlay.find(".joe-submenu-search-field")[0].value,!0),goingBackQuery=""),self.overlay.find(".joe-submenu-itemcount").html(currentListItems.length+" item"+(1!=currentListItems.length?"s":""))),listMode||self.isNewItem()&&$(".joe-object-field.text-field").eq(0).find("input").focus(),self.readyBinFields(),$(".joe-preview-iframe-holder").resizable({handles:"s"}),self.overlay.find("input.joe-image-field").each(function(){_joe.updateImageFieldImage(this)}),self.overlay.find(".joe-object-references-holder.sortable").sortable({handle:".joe-field-item-content"}),self.Fields.objectlist.ready(),self.Fields.json&&self.Fields.json.ready&&self.Fields.json.ready(),self.current.sidebars){var lsb=self.current.sidebars.left,rsb=self.current.sidebars.right;self.panel.find(".joe-sidebar_left-button").toggleClass("active",""!=lsb.content),self.panel.find(".joe-sidebar_right-button").toggleClass("active",""!=rsb.content),"small-size"!=self.sizeClass&&self.panel.toggleClass("right-sidebar",rsb.content&&!rsb.collapsed||!1),self.panel.toggleClass("left-sidebar",lsb.content&&!lsb.collapsed||!1)}if(self.Fields.comments.ready(),self.readyUploaders(),self.readyTextEditors(),self.Mini.clear(),goingBackFromID){null!=goBackListIndex&&(goBackListIndex>self.specs.dynamicDisplay&&self.panel.find(".joe-panel-content").html(self.renderListItems(currentListItems,0,goBackListIndex+1)),goBackListIndex=null);try{self.overlay.find('.joe-panel-content-option[data-id="'+goingBackFromID+'"]').addClass("keyboard-selected")[0].scrollIntoView(!0)}catch(e){self.Error.add("go back to item not ready yet:"+goingBackFromID,e)}goingBackFromID=null}self._currentListItems=currentListItems,listMode&&(self.setColumnCount(colCount),self.panel.toggleClass("list-mode",listMode)),!self.panel.hasClass("small-size")&&(self.current.subsets||self.current.schema&&self.propAsFuncOrValue(self.current.schema.filters))||(leftMenuShowing=!1),self.panel.toggleClass("show-filters",leftMenuShowing&&listMode),self.panel.toggleClass("show-aggregator",rightMenuShowing&&listMode),self.specs.speechRecognition&&self.Speech.initMic(),self.setEditingHashLink(!1),self.current.changesConfirmed=!1;var panelShowFunction=self.getCascadingProp("onPanelShow");try{var exectime=(new Date-self.showBM._start)/1e3,state=self.getState(),timing={time:exectime,warnings:self.current.benchmarkers._warnings};panelShowFunction&&panelShowFunction(state,timing),panelShowFunction&&self.specs.onPanelShow&&panelShowFunction!=self.specs.onPanelShow&&self.specs.onPanelShow(state,timing),self.current.show_callback&&self.current.show_callback(self.getState(),{time:exectime})}catch(e){self.Error.add(e,e,{warning:!0})}_bmResponse(BM,"on panel show complete"),self.Fields.onPanelShow(),_bmResponse(BM,"fields onshow complete"),_bmResponse(self.showBM,"----Joe Shown")},this.checkChanges=function(nopopup){var mode=self.getMode();if(!mode||"list"==mode)return!0;var cc_construct=_jco(!0);if(self.current.schema&&!1===self.current.schema.checkChanges)return!0;if(!0===self.current.changesConfirmed)return!0;if(!_joe.current.object||!cc_construct)return!0;var f,test_info,changes=$c.changes(_joe.current.object,cc_construct),tocheck=[],check_msg="";if(changes&&changes.$length)for(var c in changes){if(f=self.getField(c),"$"!=c[0]&&"joeUpdated"!=c&&f&&"content"!=f.type&&!parseBoolean(f.passthrough)){if("json"==(self.propAsFuncOrValue(f.type)||"").toLowerCase()){var orig=_joe.current.object[c],rawNew=cc_construct[c],sameJson=!1;try{var parsedOrig="string"==typeof orig?JSON.parse(orig):orig,parsedNew="string"==typeof rawNew?JSON.parse(rawNew):rawNew;sameJson=JSON.stringify(parsedOrig)==JSON.stringify(parsedNew)}catch(_e){sameJson=!1}if(sameJson)continue}else if(JSON.stringify(_joe.current.object[c])==JSON.stringify(cc_construct[c]))continue;if(-1!=["qrcode"].indexOf(f.type));else if((""===cc_construct[c]||null===cc_construct[c]||$c.isArray(cc_construct[c])&&!cc_construct[c].length)&&(void 0===_joe.current.object[c]||null===_joe.current.object[c]||$c.isArray(_joe.current.object[c])&&!_joe.current.object[c].length))test_info="null to blank";else if("project"==self.current.object.itemtype&&"phases"==c)test_info="project phase";else if(!1!==cc_construct[c]||_joe.current.object[c])if("wysiwyg"==f.type&&__removeTags(cc_construct[c]).trim()==__removeTags(_joe.current.object[c]).trim())test_info="wysiwyg formatting";else if("objectReference"==f.type){test_info="is an objectReference";JSON.stringify(_joe.current.object[c]),JSON.stringify(cc_construct[c])}else tocheck.push(c),check_msg+=c+"\n";else test_info="boolean false"}test_info&&logit(test_info)}if(nopopup)return $(".joe-object-field.changed").removeClass("changed"),tocheck.map(field=>{}),tocheck.length>0&&tocheck;if(self.overlay.hasClass("active")&&!listMode&&!self.current.changesConfirmed&&tocheck.length){var confirmed=confirm("Are you sure you want to navigate away from this item?\nYou have unsaved changes:\n"+check_msg);return self.current.changesConfirmed=confirmed,confirmed}return tocheck},this.renderMessageContainer=function(){return'<joe-message-holder><div class="joe-message-container left"></div></joe-message-holder>'};var messageTimeouts=Array(4);function _defaultUpdateCallback(data){self.showMessage(data.name+" updated successfully")}this.showMessage=function(message,specs){var mspecs=$.extend({timeout:3,message_class:""},specs||{});message=message||"JOE Message";self.overlay.find(".joe-message-container").hasClass("active")?self.overlay.find(".joe-message-container").html('<div class="joe-message-content">'+message+"</div>").attr("class","joe-message-container active show-message"):(self.overlay.find(".joe-message-container").html('<div class="joe-message-content">'+message+"</div>").attr("class","joe-message-container active left"),self.overlay.find("joe-message-holder").addClass("active"));var target="getJoe("+self.joe_index+").overlay.find('.joe-message-container')",holder="getJoe("+self.joe_index+").overlay.find('joe-message-holder')";clearTimeout(messageTimeouts[0]),clearTimeout(messageTimeouts[1]),clearTimeout(messageTimeouts[2]),clearTimeout(messageTimeouts[3]),clearTimeout(messageTimeouts[4]),messageTimeouts[0]=setTimeout(target+".attr('class','joe-message-container active show-message')",400),mspecs.timeout&&(messageTimeouts[1]=setTimeout(target+".attr('class','joe-message-container active ')",1e3*mspecs.timeout+400-250),messageTimeouts[2]=setTimeout(target+".attr('class','joe-message-container active right')",1e3*mspecs.timeout+400),messageTimeouts[3]=setTimeout(target+".attr('class','joe-message-container'); ",1e3*mspecs.timeout+800+50),messageTimeouts[4]=setTimeout(holder+".removeClass('active');",1e3*mspecs.timeout+800+150))},this.Object={},this.Object.create=this.createObject=function(specs,item_defaults){specs=specs||{};var schema=self.current.schema;"string"==typeof specs&&(specs={schema:specs}),schema=self.schemas[specs.schema]||self.current.schema;item_defaults=item_defaults||self.propAsFuncOrValue(schema.new)||{},specs=$.extend({schema:schema},specs||{});var overwrites=self.propAsFuncOrValue(specs.overwrites)||{};goJoe($.extend({},item_defaults,overwrites),specs)},this.Object.validate=this.validateObject=function(obj){var req_fields=[];function olistVal(olistObj){var vals="";for(var i in olistObj)vals+=olistObj[i];return vals.replace(/ /g,""),vals}_joe.current.fields.filter(f=>f.validation&&"function"==typeof f.validation),req_fields=_joe.current.fields.filter(function(prop){return!!self.propAsFuncOrValue(prop.required)});var required_missed=[];if(req_fields.map(function(f){if(!obj[f.name]||$.type("array"==obj[f.name])&&"objectList"!=f.type&&0==obj[f.name].length||"objectList"==f.type&&0==obj[f.name].filter(olistVal).length)return required_missed.push(f),!1}),$(".joe-object-field").removeClass("joe-highlighted"),required_missed.length){var req_array=[];return required_missed.map(function(of){req_array.push(of.display||of.name),$(".joe-object-field[data-name="+of.name+"]").addClass("joe-highlighted")}),req_array=req_array.condense(!0),self.showMessage("There are <b>"+req_array.length+"</b> required fields currently missing. <br/>"+req_array.join()),!1}return!0},this.updateObjectAsync=function(ajaxURL,specs){specs=$.extend({oldObj:$.extend({},self.current.object),callback:function(data){self.showMessage(data.name+" updated successfully"),self.Cache.lookup[data._id]&&(self.Cache.lookup[data._id]=data)},ajaxObj:self.constructObjectFromFields(self.joe_index),overwrites:{},skipValidation:!1},specs||{});var newObj=$.extend(ajaxObj.newObj,specs.overwrites,{joeUpdated:new Date});if(!_joe.propAsFuncOrValue(self.skipValidation)&&!self.validateObject(obj))return!1;$.ajax({url:specs.ajaxObj,data:newObj,dataType:"jsonp",success:specs.callback})},this.Object.findAndModify=function(id,modifications,specs,callback){specs=specs||{},modifications=$.extend({joeUpdated:new Date},modifications||{});var schemaObj=specs.schema&&(_joe.schemas[specs.schema]||specs.schema),idprop=specs.idprop||schemaObj&&schemaObj.idprop||"_id",object=_joe.Indexes[idprop][id];!schemaObj&&object.itemtype&&_joe.schemas[object.itemtype]&&(schemaObj=_joe.schemas[object.itemtype]);var oldObj=$.extend({},object);$.extend(object,modifications);callback=specs.callback||schemaObj.schema&&schemaObj.callback||function(data){self.showMessage((data.name||data.itemtype)+" modified successfully")};var mode=_joe.getMode();if("details"==mode&&self.current.object==object?goJoe(self.current.object,{schema:self.current.object.itemtype,force:!0}):"list"==mode&&-1!=self.current.list.indexOf(object)&&_joe.reload(),logit((obj.name||"object")+" updated"),specs.goto)if(typeof specs.goto==string)goJoe(object,{schema:schemaObj});else{var gotoObject=_joe.search(specs.goto)[0]||!1;gotoObject&&goJoe(gotoObject,{schema:gotoObject.itemtype})}callback(obj,oldObj,oldObj.changes(obj))},this.Object.update=this.updateObject=function(dom,callback,stayOnItem,overwrites,skipValidation){self.Cache.clear();var oldObj=$.extend({},self.current.object);callback=callback||self.current.callback||self.current.schema&&self.current.schema.callback||function(data){self.showMessage(data.name+" updated successfully")};var newObj=self.constructObjectFromFields(self.joe_index);if(_joe&&_joe.current&&_joe.current.fields)for(var jsonField,normResult,i=0,tot=_joe.current.fields.length;i<tot;i++)if(jsonField=_joe.current.fields[i],"json"==(self.propAsFuncOrValue(jsonField.type)||"").toLowerCase()){if(!(normResult=self.Fields.json&&self.Fields.json.normalize?self.Fields.json.normalize(jsonField.name,{showMessage:!0}):{ok:!0}).ok)return!1;var parsed=normResult.parsed||(newObj[jsonField.name]&&"object"==typeof newObj[jsonField.name]?newObj[jsonField.name]:{});newObj[jsonField.name]=parsed}newObj.joeUpdated=new Date,overwrites=overwrites||{};var obj=$.extend(newObj,overwrites);if(!_joe.propAsFuncOrValue(skipValidation)&&!self.validateObject(obj))return!1;obj=$.extend(self.current.object,newObj);var itemtype=self.current.object.itemtype&&self.Data[self.current.object.itemtype]?self.current.object.itemtype:null,index=self.current.list&&self.current.list.indexOf(obj);!self.current.list||-1!=index&&null!=index||itemtype&&self.current.list[0]&&self.current.list[0].itemtype==itemtype||itemtype||self.current.list.push(obj);var dsname=itemtype||self.current.schema.__schemaname,idprop=self.getIDProp();self.Data[dsname]&&(self.getDataItem(obj[idprop],dsname)||self.Data[dsname].push(obj),logit("item matches current schema, updating...")),logit((obj.name||"object")+" updated"),callback(obj,oldObj,oldObj.changes(obj)),stayOnItem||self.goBack(obj)},this.deleteObject=function(callback){var obj=self.current.object;if(!confirm("Are you sure you want to DELETE\n"+obj.name+"\n"+obj[self.getIDProp()]))return!1;callback=self.current.callback||self.current.schema&&self.current.schema.callback||logit;if(obj[self.getCascadingProp("deleted")||"_deleted"]=(new Date).toISOString(),!self.current.list||!obj||-1==self.current.list.indexOf(obj))return logit("object or list not found"),callback(obj),self.current.changesConfirmed=!0,void self.goBack();var index=self.current.list.indexOf(obj);self.current.list.removeAt(index),logit("object deleted"),callback(obj),self.current.changesConfirmed=!0,self.goBack()},this.Object.duplicate=this.duplicateObject=function(specs){var deletes=(specs=specs||{}).deletes||[],itemobj=$.extend({},self.current.object);delete itemobj[self.getIDProp()],delete itemobj.joeUpdated,delete itemobj.created,itemobj.name=itemobj.name+" copy",deletes.map(function(d){delete itemobj[d]}),goJoe(itemobj,self.current.userSpecs)},this.Object.construct=this.constructObjectFromFields=function(index){var constructBM=new Benchmarker,object={};self.current.object&&(object.joeUpdated=self.current.object.joeUpdated);var prop,groups={},parentFind=$(".joe-overlay.active");if(index&&(parentFind=self.overlay.find(".joe-object-field")),!parentFind.find(".joe-field").length&&self.current.object)return self.current.object;return parentFind.find(".joe-field").each(function(){if("joe-button"===this.nodeName.toLowerCase())return!0;if($(this).parents(".objectList-field,.objectlist-field").length)return!0;if($(this).parents(_joe.Mini.selector).length)return!0;if(!self.current.userSpecs||!self.current.userSpecs.multiedit||$(this).parents(".joe-object-field").hasClass("multi-selected"))switch($(this).attr("type")){case"checkbox":prop=$(this).attr("name"),groups[prop]||this.parentElement.classList.contains("joe-group-item-checkbox")?(groups[prop]=groups[prop]||[],$(this).is(":checked")&&groups[prop].push($(this).val()),object[prop]=groups[prop]):$(this).is(":checked")?object[prop]=!0:object[prop]=!1;break;default:if((prop=this.getAttribute("data-name")||this.getAttribute("name"))&&"undefined"!=prop){switch($(this).data("ftype")){case"passthrough":object[prop]=self.propAsFuncOrValue(object[prop]);break;case"ace":var editor=_joe.ace_editors[$(this).data("ace_id")];object[prop]=editor?editor.getValue():self.current.object[prop];break;case"ckeditor":editor=CKEDITOR.instances[$(this).data("ckeditor_id")];object[prop]=editor?editor.getData():self.current.object[prop];break;case"tinymce":var editorId=this.getAttribute("data-texteditor_id");editor=window.tinymce?.get(editorId);object[prop]=editor?editor.getContent():self.current.object[prop],object[prop]=self.cleanTinyMCEs(object[prop]);break;case"multisorter":var vals=[];$(this).find(".selections-bin").find("li").each(function(){vals.push($(this).data("id"))}),object[prop]=vals;break;case"uploader":var joe_uploader=self.uploaders[$(this).data("uploader_id")];object[prop]=joe_uploader.files;break;case"buckets":vals=[];$(this).find(".selections-bin").each(function(){vals.push([]),$(this).find("li").each(function(){var dom;vals[vals.length-1].push((dom=this,$(dom).data().isobject?obj=JSON.parse(decodeURI($(dom).data().value)):$(dom).data().value))})}),object[prop]=vals;break;case"objectReference":var obj;vals=[];object[prop]="objectReference",$('.objectReference-field[data-name="'+prop+'"]').find(".joe-field-list-item,.joe-field-item").each(function(){$(this).data().isobject?(obj=JSON.parse(decodeURI($(this).data().value)),vals.push(obj)):vals.push($(this).data().value)}),object[prop]=vals.condense();break;default:object[prop]=$(this).val()}break}}}),["subobject"].map(function(fieldtype){self.Fields[fieldtype].construct(parentFind,object)}),parentFind.find(".joe-object-field.content-field").each(function(){prop=$(this).data("name");var cfield=self.getField(prop);cfield.passthrough&&(!0===cfield.passthrough?object[prop]=self.current.object[prop]:object[prop]=self.propAsFuncOrValue(cfield.passthrough,self.current.object))}),parentFind.find(".objectList-field").each(function(){var subVal,subInput,ol_property=$(this).data("name"),ol_array=[],subprops=[];$(this).find("thead").find("th").each(function(i){subprops.push($(this).data("subprop"))}),$(this).find("tbody").find("tr").each(function(){var ol_array_obj={};$(this).find("td").each(function(i){var $cell=$(this),$groupCheckboxes=$cell.find('.joe-group-item-checkbox input[type="checkbox"]'),$radios=$cell.find('input[type="radio"]'),$checkboxes=$cell.find('input[type="checkbox"]');if($groupCheckboxes.length)subVal=$groupCheckboxes.filter(":checked").map(function(){return $(this).val()}).get();else if($radios.length){var r=$radios.filter(":checked").val();subVal=void 0===r?null:r}else 1===$checkboxes.length?subVal=$checkboxes.is(":checked"):$checkboxes.length>1?subVal=$checkboxes.filter(":checked").map(function(){return $(this).val()}).get():(subInput=$cell.find("input,select,textarea"),subVal=subInput.val());ol_array_obj[subprops[i]]=subVal}),delete ol_array_obj.undefined,ol_array.push(ol_array_obj)}),object[ol_property]=ol_array}),_bmResponse(constructBM,"----constructed",null,.01),!$c.isEmpty(object)&&object||!1},this.Object.getFromServer=function(id,specs,callback){var schemaName=(specs=specs||{}).schema||_joe.current.schemaName||_joe.current.schema&&_joe.current.schema.__schemaname,goto=!1!==specs.goto;if(!schemaName||!id)return console.warn("Cannot fetch object: missing schema or ID."),void(callback&&callback(!1));var url="/API/object/"+schemaName+"/_id/"+id;$.get(url,function(data){if(!data||!data._id)return console.warn("No object returned from server."),void(callback&&callback(!1));var toUpdate=_joe.search(id)[0]||!1;if(toUpdate&&$.extend(!0,toUpdate,data),goto){_joe.current.object&&_joe.current.object._id==data._id&&(_joe.current.object=data);var specs=$.extend({},_joe.current.specs||{},{schema:schemaName,force:!0});_joe.show(data,specs)}callback&&callback(!0,data)}).fail(function(err){console.error("Error fetching object from server:",err),callback&&callback(!1)})},this.Object.flatten=function(id,options={}){const{recursive:recursive=!0,depth:depth=1,visited:visited=new Set}=options;let object=null;if(id?object=$J.get(id):_joe?.current?.object&&(object=_joe.current.object),!object)return null;const flattened={},currentId=object._id||object.id;currentId&&visited.add(currentId);for(const[field,val]of Object.entries(object))if(null!=val)if("_id"!=field)if("string"==typeof val&&$c.isCuid(val)&&recursive&&depth>0)if(visited.has(val))flattened[field]=val;else{const expanded=_joe.Object.flatten(val,{recursive:recursive,depth:depth-1,visited:new Set(visited)});flattened[field]=expanded||val}else Array.isArray(val)&&val.every(v=>"string"==typeof v&&$c.isCuid(v))&&recursive&&depth>0?flattened[field]=val.map(refId=>{if(!visited.has(refId)){return _joe.Object.flatten(refId,{recursive:recursive,depth:depth-1,visited:new Set(visited)})||refId}return refId}):flattened[field]=val;else flattened[field]=val;return flattened},this.Export={},this.Export.JSON=this.exportJSON=function(object,specs){var minify=(specs=specs||{}).minify||null,objvar=specs.objvar||"",obobj=minify?JSON.stringify(object):JSON.stringify(object,""," ");goJoe("<b>"+(specs.title||objvar&&"var "+objvar+" = "||"JSON Object")+"</b><br/><pre>"+obobj+"</pre>",{schema:specs.schema}),logit(obobj)},this.Export.csv=function(schemaname,specs){for(;!schemaname;)if(null===(schemaname=prompt("schema name (itemtype)?")))return;var schema=_joe.schemas[schemaname];if(schema){var idprop=(specs=$.extend({labels:!0},specs||{})).idprop||schema.idprop||"_id",arrData=_joe.Data[schemaname].sortBy("name");specs.filter&&(arrData=arrData.where(specs.filter));var CSV="";if(CSV+=schemaname+"\r\n\n",specs.labels){var row="";for(var index in arrData[0])row+=index+",";CSV+=(row=row.slice(0,-1))+"\r\n"}for(var i=0;i<arrData.length;i++){var colval;row="";for(var index in arrData[i])colval=arrData[i][index],index!=idprop&&$c.isCuid(colval)&&(colval=_joe.Cache.get(colval).name),row+='"'+colval+'",';row.slice(0,row.length-1),CSV+=row+"\r\n"}if(""!=CSV){var fileName="JOE-"+$c.pluralize(schemaname)+"-"+$c.format(new Date,"m-d-Y")+".csv",uri="data:text/csv;charset=utf-8,"+escape(CSV),downloadLink=document.createElement("a");downloadLink.href=uri,downloadLink.download=fileName,document.body.appendChild(downloadLink),downloadLink.click(),document.body.removeChild(downloadLink)}else alert("Invalid data")}else alert('no schema "'+schemaname+'" found ')},this.updateMultipleObjects=function(dom,multipleCallback,callback){callback=callback||self.current.onUpdate||self.current.callback||self.current.schema&&(self.current.schema.onUpdate||self.current.schema.callback)||logit,multipleCallback=multipleCallback||self.current.onMultipleUpdate||self.current.multipleCallback||self.current.schema&&(self.current.schema.onMultipleUpdate||self.current.schema.multipleCallback)||logit;var idprop=self.getIDProp(),newObj=self.constructObjectFromFields(self.joe_index);if(Object&&Object.keys&&1==Object.keys(newObj).length&&"joeUpdated"==Object.keys(newObj)[0])self.showMessage("please select at least one property to update.");else{delete newObj[idprop],delete newObj.id,delete newObj._id;var haystack=self.current.list,needles=self.current.selectedListItems,updatedItems=[];haystack.map(function(i){-1!=needles.indexOf(i[idprop])&&($.extend(i,newObj),callback(i),updatedItems.push(i))}),logit(updatedItems.length+" item(s) updated"),multipleCallback(updatedItems),self.goBack(),self.showMessage(updatedItems.length+" item(s) updated")}},this.deleteMultipleObjects=function(callback){callback=self.current.callback||self.current.schema&&self.current.schema.callback||logit;var obj=self.current.object;if(!self.current.list||!obj||-1==self.current.list.indexOf(obj))return alert("object or list not found"),self.hide(),void callback(obj);var index=self.current.list.indexOf(obj);self.current.list.removeAt(index),logit("object deleted"),self.hide(),callback(obj)},this.selectAllItems=function(){self.current.selectedListItems=[];var currentItemIDs=currentListItems.map(function(item){return item[self.getIDProp()]});self.overlay.addClass("multi-edit"),self.current.selectedListItems=currentItemIDs,self.overlay.find(".joe-panel-content-option").addClass("selected"),self.allSelected=!0,self.updateSelectionVisuals()},this.deselectAllItems=function(){self.current.selectedListItems=[],self.overlay[0].classList.remove("multi-edit"),self.overlay.find(".joe-panel-content-option").removeClass("selected"),self.allSelected=!1,self.updateSelectionVisuals()},this.analyzeImportMerge=function(newArr,oldArr,idprop,specs){if(self.showMessage("Beginning Merge Analysis of "+(newArr.length+oldArr.length),{timeout:0}),_webworkers){(_joeworker=new Worker(joe_web_dir+"js/joe-worker.js")).onmessage=function(e){e.data.worker_update?(e.data.worker_update.message?self.showMessage(e.data.worker_update.message,{timeout:0}):self.showMessage("Merged "+e.data.worker_update.current+"/"+e.data.worker_update.total+" in "+e.data.worker_update.time+" secs",{timeout:0}),logit("Merged "+e.data.worker_update.current+"/"+e.data.worker_update.total+" in "+e.data.worker_update.time+" secs")):(self.showMessage("Analysis Completed in "+e.data.time+" secs",{timeout:0}),confirm("Run Merge? \n"+JSON.stringify(e.data.results,null,"\n"))?specs.callback(e.data):self.showMessage("next step cancelled"))};var safespecs=$.extend({},specs);return delete safespecs.icallback,delete safespecs.callback,void _joeworker.postMessage({action:"analyzeMerge",data:{newArr:newArr,oldArr:oldArr,idprop:idprop,specs:safespecs}})}var aimBM=new Benchmarker,defs=(idprop=idprop||"_id",{callback:function(data){self.showMiniJoe({title:"Merge results",props:JSON.stringify(data.results,null,"\n"),mode:"text",menu:[]})},deleteOld:!1,dateProp:null,icallback:null});specs=$.extend(defs,specs);var newObj,oldObj,data={add:[],update:[],same:[],delete:[]},i=(oldArr=oldArr.sortBy(idprop),newArr=newArr.sortBy(idprop),0),query={},oldIDs=[],newIDs=[];oldArr.map(function(s){oldIDs.push(s[idprop])}),newArr.map(function(s){newIDs.push(s[idprop])}),(query={})[idprop]={$nin:oldIDs},data.add=newArr.where(query),query[idprop]={$in:newIDs};var existing=oldArr.where(query);query[idprop]={$in:oldIDs};for(var onetoone=newArr.where(query),len=(i=0,existing.length);i<len;i++)newObj=onetoone[i],oldObj=existing[i],newObj?specs.dateProp&&newObj[specs.dateProp]&&oldObj[specs.dateProp]&&newObj[specs.dateProp]==oldObj[specs.dateProp]?data.same.push(newObj):data.update.push(newObj):data.same.push(oldObj);data.results={add:data.add.length,update:data.update.length,same:data.same.length},self._mergeAnalyzeResults=data,logit("Joe Analyzed in "+aimBM.stop()+" seconds"),confirm("Run Merge? \n"+JSON.stringify(data.results,null,"\n"))&&specs.callback(data)},this.analyzeClassObject=function(object,ref,maxDepth,classString){var classString=classString,maxDepth=maxDepth||10,data={methods:[],properties:[]},pReg=/function[\s*]\(([_a-z,A-Z0-9]*)\)/,curProp,params;function parseFunction(object,p,parent,depth){var parent=parent||"",curProp=object[p];params=pReg.exec(object[p]),params=params&&params[1]||"";try{var comments=/\/\*\|([\s\S]*)?\|\*\//;evalString=curProp.toString().match(comments),evalString&&evalString[1]&&(evalString=eval("("+evalString[1].replace(/\*/g,"")+")"))}catch(e){evalString={error:'Could not evalutate "'+p+'": \n'+e},self.Error.add('Could not evalutate "'+p+'": \n'+e,e,{caller:"self.analyzeClassObject"})}var funcName=parent+p,methodObj={code:object[p],name:funcName,global_function:!1,propname:p,ref:ref,class:ref,args:params,parameters:comments&&(comments.params||comments.parameters)||null,_id:ref+"_"+funcName,comments:evalString||{},itemtype:"method",parent:parent||null};if(classString)try{methodObj.count=(classString.toString().match(new RegExp((parent||".")+p,"g"))||[]).length}catch(e){self.Error.add("issue with static class: "+ref,e,{caller:"self.analyzeClassObject"})}return methodObj.comments&&(methodObj.comments.info||methodObj.comments.description)&&(methodObj.description=methodObj.comments.info||methodObj.comments.description),methodObj.comments&&methodObj.comments.tags&&(methodObj.tags=methodObj.comments.tags.split(",")),data.methods.push(methodObj),{_id:ref+"_"+funcName}}function parseProperty(object,p,parent,depth){if(!(depth>maxDepth)){depth=depth||0;depth++;parent=parent||"";var curProp=object[p],propName=parent+p,propObj={name:propName,ref:ref,class:ref,_id:ref+"_"+propName,itemtype:"property",parent:parent||null,depth:depth,propname:p};if("object"==$.type(curProp)){var subproperties=[];for(var sub in curProp)try{curProp.hasOwnProperty(sub)&&object!=window.document&&object!=window&&("function"==$.type(curProp[sub])?subproperties.push(parseFunction(curProp,sub,propName+".",depth)._id):subproperties.push(parseProperty(curProp,sub,propName+".",depth)._id))}catch(e){self.Error.add(sub+": "+e+":"+curProp[sub],e,{caller:"parseProperty"})}subproperties.length&&(propObj.subproperties=subproperties),propObj.value=object[p]}else propObj.value=object[p];return data.properties.push(propObj),{_id:ref+"_"+propName}}}for(var p in object){curProp=object[p];try{"function"==$.type(curProp)?parseFunction(object,p):parseProperty(object,p)}catch(e){self.Error.add(e,e)}}return data},this.functionName=function(func){var name=func.toString();return/function ([^\(]*)/.exec(name)[1]},this.getState=function(){return{object:_jco(),list:self.current.filteredList,schema:self.current.schema&&self.current.schema.name||null,title:self.current.title}},this.getCascadingProp=function(propname,schema){schema=schema&&(self.schemas[schema]||schema)||self.current.schema;return self.current[propname]||self.current.userSpecs&&self.current.userSpecs[propname]||schema&&(listMode&&schema.listView&&schema.listView[propname]||schema[propname])||self.specs[propname]},this.getIDProp=function(schema){return schema&&self.schemas[schema]&&self.schemas[schema].idprop||self.current.schema&&(self.current.schema.idprop||self.current.schema._listID)||"_id"},this.propAsFuncOrValue=function(prop,toPass,defaultTo,secondToPass){try{toPass=toPass||!$c.isEmpty(self.current.constructed)&&self.current.constructed||self.current.object;return prop&&"function"==typeof prop?prop(toPass,secondToPass):prop}catch(e){return self.Error.add("JOE: error parsing propAsFunction: "+e,e,{caller:"self.propAsFuncOrValue"}),""}},this.getFieldValues=function(values,prop){var vals=self.propAsFuncOrValue(values)||[];if(vals.isString()&&(vals=self.getDataset(vals)||[]),prop){var sortby=prop.sortby||prop.sortBy;sortby&&(vals=vals.sortBy(sortby))}return vals},this.Hash={},this.setEditingHashLink=function(bool){window._joeEditingHash=bool||!1};var hash_delimiter="/";function navigateItems(goto){var gotoIndex,gotoObject,dataset,objIndex=self.getObjectIndex();if(!(dataset=objIndex.dataset))return alert("no dataset set");(gotoIndex=objIndex.index+goto)>dataset.length-1?gotoIndex=0:gotoIndex<0&&(gotoIndex=dataset.length-1),gotoObject=dataset[gotoIndex],self.show(gotoObject,{schema:self.current.schema.__schemaname})}location.href&&-1!=location.href.indexOf(":::")&&(hash_delimiter=":::"),this.Hash.delimiter=hash_delimiter,this.updateHashLink=function(){if(self.specs.useHashlink){var hashInfo={};hashInfo.schema_name=self.current.schema&&self.current.schema.__schemaname,listMode?(hashInfo.object_id="",hashInfo.subset=self.current.subset&&self.current.subset.name||""):(hashInfo.subset="",hashInfo.object_id=self.current.object&&self.current.object[self.getIDProp()]||"");var hashtemplate="string"==$.type(specs.useHashlink)?specs.useHashlink:hash_delimiter+"${schema_name}"+((hashInfo.object_id||hashInfo.subset)&&hash_delimiter||"")+"${object_id}${subset}";return location.hash=fillTemplate(hashtemplate,hashInfo),location.hash}},this.Hash.update=this.updateHashLink,this.readHashLink=function(hash){if(!self.specs.useHashlink)return!1;try{if(!(useHash=hash||$GET("!")||location.hash)||0!=self.joe_index)return!1;var useHash,hashBreakdown=(useHash=useHash.replace("#","")).split(hash_delimiter).condense();if(!(hashBreakdown=hashBreakdown.filter(function(v){return""!==v})).length)return self.closeButtonAction(),!1;var dataset,hashInfo={},hashSchema=self.schemas[hashBreakdown[0]],hashItemID=hashBreakdown[1]||"";if(!hashSchema||!(hashSchema.dataset||!$.isEmptyObject(self.Data)&&self.Data[hashSchema.__schemaname]))throw error,'dataset for "'+hashSchema+'" not found';if(dataset=hashSchema.dataset?"function"==typeof hashSchema.dataset?hashSchema.dataset():hashSchema.dataset:self.Data[hashSchema.__schemaname]||[],hashInfo.schema=hashSchema,!$.isEmptyObject(self.Data)){var curkey=self.current.keyword;if(self.current.keyword=hashInfo.keyword=$GET("keyword"),self.current.keyword=self.current.keyword||curkey,hashItemID){var collectionName=hashSchema.__collection||hashSchema.__schemaname;if(-1!=hashItemID.indexOf("@")){hashItemID=hashItemID.substr(0,hashItemID.indexOf("@"))}if(-1!=hashItemID.indexOf(":")){var key=hashItemID.split(":")[0],value=hashItemID.split(":")[1];if(collectionName)(collectionItem=self.getDataItem(value,collectionName,key))&&goJoe(collectionItem,hashInfo);else hashInfo.subset=hashItemID,goJoe(dataset,hashInfo)}else{var collectionItem;if(collectionName)(collectionItem=self.getDataItem(hashItemID,collectionName))?goJoe(collectionItem,hashInfo):(hashInfo.subset=hashItemID,goJoe(dataset,hashInfo))}}else goJoe(dataset,hashInfo);var section=$GET("section")||hashBreakdown[2]||!1;section&&self.gotoSection(section)}}catch(e){return self.Error.add("error reading hashlink:"+e,e,{useHash:useHash||""}),!1}return __gotoJoeSection=self.gotoSection,!0},this.Hash.read=this.readHashLink,this.isNewItem=function(){if(listMode)return!1;var idprop=self.getIDProp();return!(self.current.object&&self.current.object[idprop]&&self.search(self.current.object[idprop]).length)},this.respond=function(e){var w=self.overlay.width(),curPanel=(self.overlay.height(),self.panel[0]),sizeClass="";-1==curPanel.className.indexOf("-size")&&(curPanel.className+=" large-size "),sizeClass=w<600?"small-size":"large-size",curPanel.className=curPanel.className.replace(/[a-z]*-size/,sizeClass),htmlRef.className=htmlRef.className.replace(/[a-z]*-size/,"joe"+sizeClass),self.sizeClass=sizeClass},this._renderGotoButton=function(id,dataset,schema){var item={};item._id=id||this._id,item.dataset=dataset||this.itemtype,item.schema=schema||item.dataset;var idprop=self.getIDProp(schema);return fillTemplate('<div class="joe-block-button goto-icon" onclick="goJoe(_joe.getDataItem(\'${'+idprop+"}','${dataset}'),{schema:'${schema}'})\"></div>",item)},window._renderGotoButton=this._renderGotoButton,this.smartSave=function(item,newItem,schema){},this.parseAPI=function(jsObj,libraryname){goJoe(self.analyzeClassObject(jsObj,libraryname).methods,{schema:"method",title:libraryname+" Methods"})},window.joeAPI=this.parseAPI,this.jsonp=function(url,dataset,callback,data){callback=callback||logit,$.ajax({url:url,data:data,dataType:"jsonp",callback:function(data){callback(data,dataset)}})},this.next=function(){navigateItems(1)},this.previous=function(){navigateItems(-1)},this.getObjectIndex=function(object){var dataset;object=object||self.current.item,self.getIDProp();if(self.current.filteredList)dataset=self.current.filteredList;else{if(!self.current.schema)return alert("no schema set");dataset=self.getDataset(self.current.schema.__schemaname).sortBy(self.current.schema.sorter||["name"])}return dataset?{index:dataset.indexOf(self.current.object),dataset:dataset}:{index:-1,dataset:null}};var getSelfStr="getJoe("+self.joe_index+")";this.IO={Export:{}},this.IO.Export.button=__exportBtn__,this.IO.Export.schema={fields:[{name:"code",type:"code"}]},this.IO.Export.json=self.exportJSON,this.IO.Export.csv=self.Export.csv,this.IO.export=function(item,json,specs){specs=$.extend({minify:!1,schema:self.IO.Export.schema,objvar:self.current.schema.__schemaname},specs),item=item||_jco();if(json)self.exportJSON(item,specs);else{var item_spec={code:JSON.stringify(item).replace(/,"/i,',\n"')};self.show(item_spec,{schema:self.IO.Export.schema})}},this.Components={loaded:{},styleTag:"joeWebComponentStyles"},this.Components.load=function(coName){if(!document.getElementById(self.Components.styleTag)){var c=document.createElement("style");c.id=self.Components.styleTag,document.body.appendChild(c)}if(!self.Components.loaded[coName]){var script=document.createElement("script");script.type="text/javascript";var wd=window.web_dir||"/JsonObjectEditor/";script.src=`${wd}web-components/${coName}.js`,document.body.appendChild(script),self.Components.loaded[coName]=!0}},this.Components.appendStyles=function(styles){var styleTag=document.getElementById(_joe.Components.styleTag);styleTag&&(styleTag.innerHTML+=styles)},this.Components.getAttributes=function(comp){for(var d={},a=0;a<comp.attributes.length;a++)d[comp.attributes[a].name]=comp.attributes[a].value;return d},this.Components.init=function(){self.Components.load("joe-button"),self.Components.load("joe-field"),self.Components.load("joe-list-item"),self.Components.load("joe-autocomplete"),self.Components.load("joe-user-cube"),self.Components.load("joe-card"),self.Components.load("capp-components")},this.buttons={create:__createBtn__,quickSave:__quicksaveBtn__,save:__saveBtn__,delete:__deleteBtn__,multiSave:__multisaveBtn__,selectAll:__selectAllBtn__,duplicate:__duplicateBtn__,export:self.IO.Export.Button},this.buttons.next={name:"next",display:"next >",css:"joe-fright",action:getSelfStr+".next()"},this.buttons.previous={name:"previous",display:"< prev",css:"joe-fleft",action:getSelfStr+".previous()"},this.Speech={init:function(force){(force||self.specs.speechRecognition)&&(self.addStylesheet(joe_web_dir+"js/plugins/microphone/microphone.min.css",{name:"microphone-css"}),self.addScript(joe_web_dir+"js/plugins/microphone/microphone.min.js",{name:"microphone-js"}))},confirm:function(){self.Mini.show({object:"hello",title:"Audio",menu:[{name:"confirm"},{name:"cancel"}]})},initMic:function(){var mic=self.Speech.mic=new Wit.Microphone(document.getElementById("speech-button-"+self.joe_index)),info=function(msg){logit(msg)},error=function(msg){logit(msg)};mic.onready=function(){info("Microphone is ready to record")},mic.onaudiostart=function(){info("Recording started"),error("")},mic.onaudioend=function(){info("Recording stopped, processing started")},mic.onresult=function(intent,entities){logit(intent)},mic.onerror=function(err){error("Error: "+err)},mic.onconnecting=function(){info("Microphone is connecting")},mic.ondisconnected=function(){info("Microphone is not connected")},mic.connect("3J7E3INLVHRRZYVTX6VBXWUXXGMRDEPS")}},this.TITLE={dom:function(){return self.panel&&self.panel.find(".joe-panel-title")||null},get:function(){return self.TITLE.dom.html()},set:function(value,specs){specs=$.extend({before:"",after:""},specs||{});if(value=self.propAsFuncOrValue(value))return self.TITLE.dom().html(specs.before+value+specs.after),value;var tempObj=self.constructObjectFromFields(),titleObj=$.extend({},tempObj,{_listCount:(currentListItems||[]).length||"0"}),cTitle=self.propAsFuncOrValue(self.current.title,tempObj),titleStr=fillTemplate(cTitle,titleObj);return self.TITLE.dom().html(specs.before+titleStr+specs.after),document.title=titleStr,titleStr}};var iceServers=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:webrtcweb.com:7788",username:"muazkh",credential:"muazkh"},{urls:"turn:webrtcweb.com:7788",username:"muazkh",credential:"muazkh"},{urls:"turn:webrtcweb.com:8877",username:"muazkh",credential:"muazkh"},{urls:"turns:webrtcweb.com:7788",username:"muazkh",credential:"muazkh"},{urls:"turns:webrtcweb.com:8877",username:"muazkh",credential:"muazkh"},{urls:"stun:webrtcweb.com:4455",username:"muazkh",credential:"muazkh"},{urls:"turns:webrtcweb.com:4455",username:"muazkh",credential:"muazkh"},{urls:"turn:webrtcweb.com:5544?transport=tcp",username:"muazkh",credential:"muazkh"}],rtcConfig={iceServers:iceServers,sdpSemantics:"plan-b"},useRTC=!1;this.CONNECT={gotStream:function(stream){logit("Received local stream"),self.CONNECT.videos.local&&(self.CONNECT.videos.local.srcObject=stream),self.CONNECT.streams.local=stream,self.CONNECT.RTC.addStream(self.CONNECT.streams.local)},RTC:useRTC&&window.RTCPeerConnection&&new RTCPeerConnection(rtcConfig)||null,newConnection:function(){self.CONNECT.RTC=new RTCPeerConnection(rtcConfig),self.CONNECT.init()},init:function(){self.CONNECT.RTC.oniceconnectionstatechange=function(){"completed"==self.CONNECT.RTC.iceConnectionState&&(logit("ICE state: "+self.CONNECT.RTC.iceConnectionState),self.CONNECT.offerinprogress||confirm("connect request received")||self.CONNECT.end(self.CONNECT.userid,!0),logit("stopping CONNECT interval -init"),clearInterval(self.CONNECT.offerinterval),self.CONNECT.offerinprogress=!1)},self.CONNECT.RTC.onaddstream=function(evt){logit("stream"),self.CONNECT.streams.remote=evt.stream,self.CONNECT.videos.remote.srcObject=self.CONNECT.streams.remote,self.CONNECT.videos.remote.play()},self.CONNECT.RTC.onremovestream=function(evt){logit("stream ended:",evt)},self.CONNECT.RTC.onicecandidate=function(evt){}},videos:{},streams:{},start:function(userid,makeoffer){if("closed"==self.CONNECT.RTC.signalingState&&(self.CONNECT.RTC=new RTCPeerConnection(iceServers)),userid){self.CONNECT.end(userid);var userobj=self.getDataItem(userid,"user"),popup=self.CONNECT.createPopup(userobj);if(self.CONNECT.videos.local=$("#"+popup.domid).find(".joe-connect-myvideo")[0],self.CONNECT.videos.remote=$("#"+popup.domid).find(".joe-connect-video")[0],navigator.mediaDevices.getUserMedia({audio:!0,video:!0}).then(self.CONNECT.gotStream).catch(function(e){alert("getUserMedia() error: "+e.name),console.log(e)}),makeoffer){var RTC=self.CONNECT.RTC;RTC.createOffer().then(function(offer){return RTC.setLocalDescription(offer)},function(data){alert("error in RTC"+data),logit(data)}).then(function(){self.SERVER.socket.emit("connect_offer",{user:_joe.User._id,target:userid,sdp:RTC.localDescription})}).catch(function(reason){console.log(reason)})}}else _joe.showMiniJoe({title:"CONNECT w/",list:self.Data.user.where({_id:{$ne:self.User._id}}),template:function(user){var template="<joe-title>${name}</joe-title><joe-subtitle>${fullname}</joe-subtitle><joe-subtext>${info}</joe-subtext>";return user.image_url&&(template='<joe-listitem-icon style="background-image:url(${image_url});"></joe-listitem-icon>'+template),template},idprop:"_id",menu:[],callback:function(item_id){self.CONNECT.start(item_id)}})},sendOfferToServer:function(offer){},end:function(userid,clear){capp.Popup.delete("connect_"+userid),clear&&(logit("stopping CONNECT interval - end"),clearInterval(self.CONNECT.offerinterval),self.CONNECT.offerinprogress=!1,self.CONNECT.userid=null,self.CONNECT.RTC.close(),self.CONNECT.streams.remote&&self.CONNECT.streams.remote.getTracks().forEach(function(track){track.stop()}),self.CONNECT.streams.local&&self.CONNECT.streams.local.getTracks().forEach(function(track){track.stop()}))},template:function(userobj){return'<joe-video-holder><video autoplay class="joe-connect-video"></video><video autoplay class="joe-connect-myvideo"></video></joe-video-holder>'+userobj.name},createPopup:function(userobj,specs){return capp.Popup.add("connect w/ <b>"+(userobj.fullname||userobj.name)+"</b>",self.propAsFuncOrValue(self.CONNECT.template,userobj),{id:"connect_"+userobj._id,active:!0,close_action:"_joe.CONNECT.end('"+userobj._id+"',true);"})}},useRTC&&window.RTCPeerConnection&&this.CONNECT.init(),this.SERVER={Plugins:{awsFileUpload:function(data,callback){var file=data.file,field=data.field;if(field.bucketname||(_joe.Data.setting.where({name:"AWS_BUCKETNAME"})[0]||{value:""}).value){var filename=file.filename,directory=_joe.current.object._id,url=field&&self.propAsFuncOrValue(field.server_url)||location.port&&"//"+__jsc.hostname+":"+__jsc.port+"/API/plugin/awsConnect/"||"//"+__jsc.hostname+"/API/plugin/awsConnect/",Key=directory+"/"+filename;$.ajax({url:url,type:"POST",data:{Key:Key,base64:file.base64,extension:file.extension,contentType:file.type,ACL:field.hasOwnProperty("ACL")?field.ACL:"public-read"},success:function(response){if(!response.error){var url;if(logit(response),!(url=response.url)){var bucket=response.bucket||(_joe.Data.setting.where({name:"AWS_BUCKETNAME"})[0]||{value:""}).value,region=(_joe.Utils.Settings("AWS_S3CONFIG")||{}).region;url=((_joe.Data.setting.where({name:"AWS_S3PREFIX"})[0]||{value:""}).value||"https://"+bucket+".s3."+(region||"")+".amazonaws.com/")+response.Key}var filename=response.Key.replace(self.current.object._id+"/","");if(_joe._lastOpenAI=_joe._lastOpenAI||{},_joe._lastOpenAI[response.Key]={openai_file_id:response.openai_file_id,openai_purpose:response.openai_purpose,openai_error:response.openai_error},field.url_field){var nprop={};_joe.current.object[field.url_field]=url,nprop[field.url_field]=url,_joe.Fields.rerender(field.url_field,nprop)}}callback(response.error,url,filename)},error:function(xhr,status,err){var message=xhr&&(xhr.responseJSON&&(xhr.responseJSON.error||xhr.responseJSON.code)||xhr.responseText)||err||status||"Upload failed";callback&&callback(message)}})}else{callback&&callback("AWS bucket not configured")}},awsConnect:function(data,callback){return _joe.SERVER.Plugins.awsFileUpload({file:{base64:data.base64,extension:data.extension,type:data.contentType,filename:_joe.current.object._id+data.extension,name:_joe.current.object._id+data.extension},field:data.field},callback)},openaiRetryFromUrl:function(uploader_id,filename){try{var joe_uploader=self.uploaders[uploader_id];if(!joe_uploader)return alert("Uploader not found");var file=joe_uploader.files.where({filename:filename})[0];if(!file)return alert("File not found");if(!file.url)return alert("No URL to upload to OpenAI");$(joe_uploader.preview).find("joe-uploader-openai-btn:contains('"+filename+"')");joe_uploader.message.append("<div>Uploading to OpenAI...</div>"),$.ajax({url:location.port&&"//"+__jsc.hostname+":"+__jsc.port+"/API/plugin/chatgpt/filesRetryFromUrl/"||"//"+__jsc.hostname+"/API/plugin/chatgpt/filesRetryFromUrl/",type:"POST",data:{url:file.url,filename:file.filename,contentType:file.type},success:function(resp){resp&&resp.success&&resp.openai_file_id?(file.openai_file_id=resp.openai_file_id,file.openai_purpose=resp.openai_purpose||"assistants",file.openai_status="ok",file.openai_error=null,joe_uploader.message.append("<div>OpenAI file attached</div>")):(file.openai_status="error",file.openai_error=resp&&resp.error||"Upload failed",joe_uploader.message.append("<div>OpenAI error: "+file.openai_error+"</div>")),$(joe_uploader.preview).html(_renderUploaderFilePreviews(joe_uploader.files,joe_uploader.cuid)),self.updateObject(null,null,!0)},error:function(xhr,status,err){var message=xhr&&(xhr.responseJSON&&(xhr.responseJSON.error||xhr.responseJSON.code)||xhr.responseText)||err||status||"Retry failed";file.openai_status="error",file.openai_error=message,joe_uploader.message.append("<div>OpenAI error: "+message+"</div>")}})}catch(e){alert(e&&e.message||e)}}},ready:{schemas:!1,datasets:!1,localstorage:!1,user:!1,app:!1},Cache:{reload:function(collections){$.ajax({url:"/API/cache/update/"+(collections||""),datatype:"jsonp",success:function(data){data.error?alert(data.error):location.reload()}})}},History:{get:function(id,callback){if(id=id||self.current.item&&self.current.item[self.getIDProp()]){callback=callback||logit;$.ajax({url:"/API/history/itemid/"+id,dataType:"jsonp",success:function(data){if(data.error)return alert(error);callback(data)}})}},show:function(history_response,specs){var results=history_response.results,item=self.search(history_response.query.itemid)[0]||{name:"not found"};goJoe(results,{schema:self.SERVER.History.schema,title:"History of ["+item.itemtype+"] "+item.name})},schema:{title:"[${collection} history] ${this.historical.name}",sorter:["!timestamp"],listTitle:function(item){return"<joe-title>"+(item.changes&&item.changes.__length||0)+" changes by ${this.user.name}</joe-title><joe-subtitle>${RUN[_joe.Utils.prettyPrintDTS;${timestamp}]}</joe-subtitle>"},checkChanges:!1,fields:["itemid:cuid","collection","timestamp",{name:"user",type:"subObject",locked:!0},{name:"historical",type:"subObject",locked:!0},{name:"changes",type:"subObject",locked:!0}]},button:{name:"history",label:"&nbsp;",title:"Item History",action:"_joe.SERVER.History.get('${_id}',_joe.SERVER.History.show)",css:"joe-history-button joe-left-button"}},User:{get:function(){$.ajax({url:"/API/user/current",dataType:"jsonp",success:function(data){data.error?alert("error getting user:\n"+data.error):data.user&&(_joe.User=data.user,self.SERVER.User.store(),self.SERVER.User.signin(),logit("logged in as "+_joe.User.name)),self.SERVER.ready.user=!0,self.SERVER.onLoadComplete()}})},store:function(){var now=new Date,expireTime=now.getTime()+36e7;now.setTime(expireTime),$("#cappUser").html(_joe.User.name),document.cookie="_j_user="+_joe.User.name+";expires="+now.toGMTString()+";path=/",document.cookie="_j_token="+_joe.User.token+";expires="+now.toGMTString()+";path=/"},signin:function(obj,oldObj,changes){self.SERVER.socket.emit("signin",{user:_joe.User}),self.SERVER.socket.on("user_info",function(data){if(data.error||!data.connected_users||!$c.itemCount(data.connected_users))return self.Error.add("improper user data returned",null,data),void logit("user info",data);logit("user info",data);var userObj=data.connected_users[_joe.User._id];if(userObj&&userObj.sockets){var imageHtml="";_joe.User&&_joe.User.image&&(imageHtml='<img class="capp-user-icon" src="'+_joe.User.image+'" />',$("#cappUser").addClass("with-image")),$("#cappUser").html(imageHtml+"<capp-user-name><b>"+_joe.User.name+"</b>"+(userObj.sockets.length>1&&"<small> x"+userObj.sockets.length+"</small>"||"")+"</capp-user-name>"),$("#cappUserMenu").find(".user-info").remove();var user,user_html="";for(var u in data.connected_users)u!=_joe.User._id&&(user_html+='<capp-menu-content class="user-info"><b onclick="_joe.CONNECT.start(\''+(user=data.connected_users[u]).user._id+"',true);\">"+user.user.name+"</b>"+fillTemplate("<span onclick=\"window.open('${url}')\"> ${app}</span>",user.sockets)+"</capp-menu-content>");$("#cappUserMenu capp-menu-panel").append(user_html)}})},Render:{cubes:function(ids,cssclass,user_dataset){"string"==typeof ids&&(ids=ids.split(","));var users=_joe.Data[user_dataset||"user"].where({_id:{$in:ids}}),html="";return users.map(function(user){html+=self.SERVER.User.Render.cube(user,cssclass)}),html},cube:function(userobj,cssclass){var css=cssclass||"fright",u=userobj,html="",name=u.fullname||u.name;return initials=name[0]+(name.indexOf(" ")>0&&name[name.indexOf(" ")+1]||""),html+='<joe-user-cube title="'+name+'" style="background-color:'+userobj.color+'" class="joe-initials '+css+'">'+initials+" <span>"+name+"</span></joe-user-cube>"},userBar:function(userid,cssclass,dataset,nameprop){var user=_joe.Data[dataset||"user"].where({_id:userid})[0]||!1;if(!user)return"";var name=user[nameprop||"name"]||user.fullname||user.name;return'<joe-user-bar title="'+name+'" style="background-color:'+user.color+'" class="joe-initials '+css+'">'+name+"</joe-user-bar>"}}},handleUpdate:function(payload){try{for(var new_item,old_item,r=0,tot=payload.results.length;r<tot;r++){var schemaname=(new_item=payload.results[r]).itemtype;schemaname&&self.schemas[schemaname]&&self.schemas[schemaname].onload&&self.schemas[schemaname].onload([new_item]),_joe.Data[new_item.itemtype]||(_joe.Data[new_item.itemtype]=[]),(old_item=_joe.Data[new_item.itemtype].where({_id:new_item._id})[0]||!1)?($.extend(old_item,new_item),_joe.current.list&&-1!=_joe.current.list.indexOf(old_item)&&listMode&&_joe.reload(!0)):(_joe.Data[new_item.itemtype].push(new_item),_joe.current.list&&-1!=_joe.current.list.indexOf(new_item)&&listMode&&_joe.reload(!0))}for(var sc in self.Data)capp&&capp.Button.update(sc+"SchemaBtn",{counter:self.Data[sc].length});specs.onServerUpdate&&specs.onServerUpdate()}catch(e){self.Error.add("error handling update",e)}},save:function(obj,oldObj,changes){self.SERVER.socket.emit("save",{item:obj})},delete:function(obj,oldObj,changes){self.SERVER.socket.emit("delete",{item:obj})},save_ajax:function(obj,oldObj,changes){ajax({url:"/API/save/",dataType:"jsonp",onsuccess:function(data){if(data.error)alert("Error Saving:\n"+data.error);else if("object"==$.type(data.results)){var result=data.results,itemtype=result.itemtype||self.current.schema.name;self.showMessage(itemtype+", "+result.name+"<br/><b>saved successfully</b>")}},data:obj})},updateObject:function(ajaxURL,specs){specs=$.extend({oldObj:$.extend({},self.current.object),callback:function(data){self.showMessage(data.name+" updated successfully")},ajaxObj:self.constructObjectFromFields(self.joe_index),overwrites:{},skipValidation:!1},specs||{});var newObj=$.extend(ajaxObj.newObj,specs.overwrites,{joeUpdated:(new Date).toISOString()});if(!_joe.propAsFuncOrValue(self.skipValidation)&&!self.validateObject(obj))return!1;$.ajax({url:specs.ajaxObj,data:newObj,dataType:"jsonp",success:specs.callback})},loadSchema:function(schemaName,schemaObj){let sobj;return sobj=$.extend({},getDefaultSchema(schemaName),schemaObj),unstringifyFunctions(sobj),sobj.error?self.Error.add(sobj.error,null):self.Schema.add(schemaName,sobj),sobj},loadSchemas:function(collectionsSTR,callback){"Array"==$.type(collectionsSTR)&&(collectionsSTR=collectionsSTR.join(",")),ajax({url:"/API/schema/"+collectionsSTR,dataType:"jsonp",onsuccess:function(data){if(data.error)alert(data.error);else{var sobj,default_schemas=[];for(var schema in data.schemas)(sobj=self.SERVER.loadSchema(schema,data.schemas[schema])).error?self.Error.add(sobj.error,null):sobj.default_schema?default_schemas.push(sobj):capp.Button.addFromSchema(self.Schema.add(schema,sobj));capp.Menu.add("<capp-button-icon >"+_joe.SVG.icon.menu+" </capp-button-icon><capp-menu-icon-label>default Schemas</capp-menu-icon-label> ",default_schemas,"capp-panel",{labelcss:"no-padding",cssclass:"default-schemas-menu",template:function(sc_btn){var so=self.schemas[sc_btn.name];return capp.Button.addFromSchema(so,{container:!1})}}),data.fields&&(unstringifyFunctions(data.fields),self.specs.fields=self.fields=data.fields)}self.SERVER.ready.schemas=!0,self.SERVER.onLoadComplete(),callback&&callback()}})},loadDatasets:function(collectionsSTR){if(self.specs.localStorage&&"undefined"!=typeof Storage){self.SERVER.LocalStorage.loadData();var toget=[];APPINFO.collections.map(function(coll){_joe.Data[coll]||toget.push(coll)}),self.SERVER.LocalStorage.getUpdates(),toget.length?(logit("retrieving "+toget.length+" datasets "),self.SERVER.getDatasets(toget)):(self.SERVER.ready.datasets=!0,self.SERVER.onLoadComplete())}else self.SERVER.ready.localstorage=!0,self.SERVER.getDatasets(collectionsSTR)},loadAdditionalItems:function(items){if(!items||!items.length)return self.SERVER.ready.additionalItems=!0,void self.SERVER.onLoadComplete();ajax({url:"/API/search/",data:{query:{_id:{$in:items}}},dataType:"jsonp",onsuccess:function(data){var items=data.results||[],schemas=[],datasets={};items.map(i=>{-1==__jsu.schemas.indexOf(i.itemtype)&&(datasets[i.itemtype]=datasets[i.itemtype]||[],datasets[i.itemtype].push(i),schemas.push(i.itemtype))}),schemas=Array.from(new Set(schemas)),ajax({url:"/API/schema/"+schemas.join(","),dataType:"jsonp",data:{mode:"additionalItems"},onsuccess:function(data){if(data.error)alert(data.error);else for(var schema in data.schemas)self.SERVER.loadSchema(schema,data.schemas[schema]),self.Data[schema]&&self.Data[schema].length||self.addDataset(schema,datasets[schema]);self.SERVER.ready.additionalItems=!0,self.SERVER.onLoadComplete()}})}})},loadApp:function(){},getDatasets:function(collectionsSTR){"Array"==$.type(collectionsSTR)&&(collectionsSTR=collectionsSTR.join(",")),ajax({url:"/API/datasets/"+collectionsSTR,dataType:"jsonp",onsuccess:function(data){if(data.error)alert(data.error);else for(var dataset in data.datasets)self.addDataset(dataset,data.datasets[dataset]),capp&&capp.Button.update(dataset+"SchemaBtn",{counter:data.datasets[dataset].length});self.SERVER.ready.datasets=!0,self.SERVER.onLoadComplete()}})},LocalStorage:{saveData:function(){localStorage.joeData=JSON.stringify(_joe.Data),localStorage.timestamp=(new Date).toISOString()},loadData:function(){if(localStorage.joeData){var allData=JSON.parse(localStorage.joeData);APPINFO.collections.map(function(coll){("user"==coll||__jsu.schemas&&-1!=__jsu.schemas.indexOf(coll))&&self.addDataset(coll,allData[coll])})}},getUpdates:function(dateISO){dateISO=dateISO||"undefined"!=typeof Storage&&localStorage.timestamp||null;var query={itemtype:{$in:APPINFO.collections}};dateISO&&(query.joeUpdated={$gte:dateISO}),$.ajax({url:"/API/search/",dataType:"jsonp",data:{query:query},success:self.SERVER.LocalStorage.handleUpdates})},handleUpdates:function(data){data.error&&alert(data.error),logit(data.results.length+" updates in "+data.benchmark),self.SERVER.handleUpdate(data),self.SERVER.ready.localstorage=!0,self.SERVER.onLoadComplete()}},onLoadComplete:function(){if(self.SERVER.ready.datasets&&self.SERVER.ready.schemas&&self.SERVER.ready.user&&self.SERVER.ready.localstorage){if(!self.SERVER.ready.additionalItems)return void self.SERVER.loadAdditionalItems(__jsu.items);for(let name in self.schemas){const schema=self.schemas[name];if(schema.onload&&self.Data[name])try{console.log(`Rerunning onload for schema: ${name}`),schema.onload(self.Data[name])}catch(e){self.Error.add("schema onload re-run error: "+name,e)}}for(var sc in self.Data)capp&&capp.Button.update(sc+"SchemaBtn",{counter:self.Data[sc].length});self.SERVER.socket.on("message",function(message){message.sender?alert(message.sender+" -\n"+message.message):alert(message)}),self.SERVER.socket.on("comments_updated",function(info){self.current.object&&info.itemid==self.current.object[self.getIDProp()]&&JOE.Fields.comments.ready()}),self.SERVER.socket.on("log_data",function(data,name){name=name||"";console.log(name,data)}),self.SERVER.socket.on("item_updated",_joe.SERVER.handleUpdate),self.SERVER.socket.on("save_successful",function(data){var result=data.results;"array"==$.type(result)&&1==result.length?(result=result[0],self.showMessage(result.itemtype+", "+result.name+"<br/><b>saved successfully</b>")):self.showMessage(result.itemtype+", "+result.name+"<br/><b>saved successfully</b>"),self.schemas[result.itemtype]&&self.schemas[result.itemtype].onsave&&self.schemas[result.itemtype].onsave(result)}),self.SERVER.socket.on("connect_answer",function(data){logit("answer received");var userid=data.user;self.CONNECT.offerinprogress||(logit("REREQUESTING: "+userid),self.CONNECT.offerinprogress=!0,self.CONNECT.offerinterval=setInterval(function(){logit("ICE state: "+self.CONNECT.RTC.iceConnectionState),"completed"!=_joe.CONNECT.RTC.iceConnectionState?_joe.CONNECT.start(userid,!0):(logit("stopping CONNECT interval - interval"),clearInterval(self.CONNECT.offerinterval),self.CONNECT.offerinprogress=!1)},3e3)),self.CONNECT.RTC.setRemoteDescription(new RTCSessionDescription(data.sdp))}),self.SERVER.socket.on("connect_offer",function(data){var RTC=self.CONNECT.RTC;self.CONNECT.userid=data.user,_joe.CONNECT.start(data.user,!1),logit(data),RTC.setRemoteDescription(new RTCSessionDescription(data.sdp)).then(function(){RTC.createAnswer().then(function(answer){RTC.setLocalDescription(new RTCSessionDescription(answer)),self.SERVER.socket.emit("connect_answer",{user:_joe.User._id,target:data.user,sdp:answer,socketid:data.socketid})},function(e){console.log(e),alert(e)})})}),_joe.Hash.read(),specs.onServerLoadComplete&&specs.onServerLoadComplete(),self.specs.localStorage&&"undefined"!=typeof Storage&&self.SERVER.LocalStorage.saveData()}},socket:self.specs.socket&&io(self.specs.socket,{rejectUnauthorized:!1})||null},this.addStylesheet=function(href,specs,cancelAppend){var s=document.createElement("link");specs=$.extend({rel:"stylesheet"},specs||{});return $.extend(s,specs),s.href=href,cancelAppend||document.head.appendChild(s),s},this.addScript=function(src,specs,cancelAppend){var s=document.createElement("script");specs=$.extend({type:"text/javascript"},specs||{});return $.extend(s,specs),s.src=src,cancelAppend||document.body.appendChild(s),s},this.nowISO=(new Date).toISOString();var nd=new Date;function parseDateTimeForGoogle(){}return this.times={},nd.setHours(0,0,0,0),this.times.SOD=nd.toISOString(),nd.setHours(24,0,0,0),this.times.EOD=nd.toISOString(),this.Utils={cleanString:function(str){return str.replace(/[^A-Z0-9]+/gi,"_")},stopPropagation:function(e){return(e=e||window.event).stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),!1},getPossibleValues:function(propertyName,schema,specs){if((specs=$.extend({format:"object"},specs||{})).static&&_joe.Cache.static[specs.static])return _joe.Cache.static[specs.static];for(var propval,types={},i=0;i<_joe.Data[schema].length;i++){propval=_joe.Data[schema][i][propertyName],(specs.allowNulls||null!=propval)&&(types[propval]=types[propval]||0,types[propval]++)}return specs.static&&(_joe.Cache.static[specs.static]=types),types},Settings:function(settingName,specs){specs=specs||{};var s=(self.Data.setting||[]).where({name:settingName})[0],setting=s||{};if(specs.object)return setting;if("code"==setting.setting_type&&!specs.raw){if(0==setting.value.trim().indexOf("function")&&specs.params){var p=tryEval(s.value);return p?p(specs.params):specs.params}return tryEval(s.value)}return setting.value},toDollars:function(amount){return parseFloat(amount).toFixed(2)},joeState:self.getState,nextDay:function(x){var now=new Date;return now.setDate(now.getDate()+(x+(7-now.getDay()))%7),now},toDateInput:function(date){var dt=date||new Date;"string"==typeof dt&&(dt=new Date(dt)),console.log(dt,date);var monthstr=dt.getUTCMonth()+1;monthstr=monthstr<10?"0"+monthstr:monthstr;var dayStr=("0"+dt.getUTCDate()).slice(-2);return`${dt.getUTCFullYear().toString()}-${monthstr}-${dayStr}`},toDateString:function(dt,specs){if("Y-m-d"==specs)return self.Utils.toDateInput(dt);specs=specs||{};"string"==typeof(dt=dt||new Date)&&(dt=new Date(dt));var dts_str="",monthstr=dt.getUTCMonth()+1,dayStr=("0"+dt.getUTCDate()).slice(-2),yearStr=dt.getUTCFullYear().toString();return dts_str+=(monthstr<10?"0"+monthstr:monthstr)+"/"+dayStr+"/"+(specs.fullyear&&yearStr||yearStr.substr(2,4))},prettyPrintDTS:function(dts,specs){specs=$.extend({showtime:!0,showdate:!0},specs||{});"string"==typeof(dts=dts||new Date)&&(dts=new Date(dts));var dts_str="";if(specs.showtime){var ampm="a",dmins=dts.getMinutes().toString(),dhours=dts.getHours();dhours>12&&(ampm="p",dhours-=12),dhours||(dhours=12),dts_str+=dhours+":"+(2==dmins.length?dmins:"0"+dmins)+ampm}return specs.showdate&&specs.showtime&&(dts_str+=" "),specs.showdate&&(dts_str+=dts.getMonth()+1+"/"+dts.getDate()+"/"+dts.getUTCFullYear().toString().substr(2,4)),dts_str},getRandomColor:function(){for(var color="#",i=0;i<6;i++)color+="0123456789ABCDEF"[Math.floor(16*Math.random())];return color},benchmarkit:function(torun,name){var bm=new Benchmarker,t=torun();return _bmResponse(bm,"benchmarker",name||""),t}},this.SVG={icon:{assistant:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">\n <path d="M294.49 618.18v64.49c0 22.42.95 35.46 2.84 39.12 2.4 4.94 6.93 8.52 12.29 9.71 9.18 2.13 18.6 3.01 28.02 2.64h17.31c18.81 0 28.22 6.04 28.22 18.11 0 13.96-9.93 22.51-29.8 25.64-24.41 2.74-48.98 3.87-73.55 3.37-29.87 0-51.01-5.79-63.44-17.38-12.42-11.59-18.66-31.41-18.7-59.47v-81.08c.85-11.33-1.15-22.68-5.81-33.04-5.69-7.66-14.07-12.88-23.46-14.6-11.09-2.78-18.54-13.19-17.58-24.58-1.07-11.43 6.42-21.9 17.58-24.58 9.41-1.95 17.77-7.32 23.46-15.07 4.7-10.35 6.7-21.71 5.81-33.04v-80.88c0-27.62 6.21-47.22 18.63-58.81 12.42-11.59 33.57-17.36 63.44-17.31 26.13-.73 52.27.66 78.17 4.16 6.92 1.05 13.37 4.16 18.5 8.92 4.27 4.08 6.66 9.75 6.61 15.66 0 12.07-9.41 18.11-28.22 18.11h-17.84c-16.04 0-27.05 1.72-33.04 5.15-5.92 3.96-9.36 10.72-9.05 17.84v92.71c-.35 31.23-8.72 52.03-25.11 62.38-1.29.88-2.06 2.34-2.05 3.9 0 2.42 2.93 6.06 8.79 10.9 6.54 5.96 11.3 13.63 13.74 22.14 3.19 11.34 4.62 23.11 4.23 34.89Zm435.01-134.4v-64.23c0-22.42-.95-35.46-2.84-39.12-2.4-4.94-6.93-8.52-12.29-9.71-9.18-2.13-18.6-3.01-28.02-2.64h-17.18c-18.81 0-28.22-6.04-28.22-18.11 0-13.96 9.93-22.42 29.8-25.37 24.42-2.73 48.98-3.86 73.55-3.37 29.87 0 51.01 5.79 63.44 17.38 12.42 11.59 18.63 31.19 18.63 58.81v81.28c-.88 11.33 1.12 22.69 5.81 33.04 5.75 7.62 14.1 12.87 23.46 14.74 11.16 2.71 18.62 13.22 17.51 24.65.74 9.18-4.03 17.93-12.16 22.27-4.09 1.86-8.33 3.34-12.69 4.43-8.51 2.69-15.35 9.08-18.63 17.38-2.71 9.15-3.85 18.69-3.37 28.22v81.01c0 27.8-6.21 47.47-18.63 59.01-12.42 11.54-33.57 17.33-63.44 17.38-26.13.74-52.27-.65-78.17-4.16-6.92-1.05-13.37-4.16-18.5-8.92-4.31-4.17-6.7-9.93-6.61-15.93 0-12.07 9.41-18.11 28.22-18.11 2.25 0 8.19.18 17.84.53 11.25.56 22.5-1.19 33.04-5.15 4.1-2.12 7.02-5.98 7.93-10.51 1.33-11.91 1.82-23.9 1.45-35.88v-64.49c-.51-12.88 1.38-25.74 5.55-37.93 4.19-9.77 11.07-18.15 19.82-24.18 1.29-.88 2.06-2.34 2.05-3.9 0-2.42-2.93-6.06-8.79-10.9-6.55-5.96-11.31-13.63-13.74-22.14-3.43-11.46-5.05-23.39-4.82-35.35Z"/>\n <rect width="74.5" height="189" x="409.75" y="456.75" rx="33.94" ry="33.94"/>\n <rect width="74.5" height="189" x="539.75" y="456.75" rx="33.94" ry="33.94"/>\n </svg>',favorite:'<?xml version="1.0" encoding="UTF-8"?><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M4 2h16a1 1 0 0 1 1 1v19.276a.5.5 0 0 1-.704.457L12 19.03l-8.296 3.702A.5.5 0 0 1 3 22.276V3a1 1 0 0 1 1-1zm8 11.5l2.939 1.545-.561-3.272 2.377-2.318-3.286-.478L12 6l-1.47 2.977-3.285.478 2.377 2.318-.56 3.272L12 13.5z"/></svg>',left:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-5 -5 36 36"><path d="M11.3 21C7.1 18.2 3.3 13.8 3.2 13.6 3.1 13.5 3 13.2 3 13 3 12.8 3.1 12.5 3.2 12.3 3.3 12.1 7.2 7.7 11.3 4.9 11.6 4.7 12 4.7 12.4 4.8 12.8 5.1 13 5.4 13 5.8L13 9.5C13 9.5 21.7 10 22.1 10.3 22.7 10.7 23 12 23 13 23 14.1 22.6 15.2 22.1 15.6 21.7 15.9 13 16.5 13 16.5L13 20.2C13 20.6 12.8 20.9 12.4 21.1 12.1 21.3 11.7 21.2 11.3 21Z"/></svg>',cancel:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-5 -5 36 36"><path d="M13 0.2C5.9 0.2 0.2 5.9 0.2 13 0.2 20.1 5.9 25.8 13 25.8 20.1 25.8 25.8 20.1 25.8 13 25.8 5.9 20.1 0.2 13 0.2ZM18.8 17.4L17.4 18.8C17.1 19 16.7 19 16.5 18.8L13 15.3 9.5 18.8C9.3 19 8.9 19 8.6 18.8L7.2 17.4C7 17.1 7 16.7 7.2 16.5L10.7 13 7.2 9.5C7 9.3 7 8.9 7.2 8.6L8.6 7.2C8.9 7 9.3 7 9.5 7.2L13 10.7 16.5 7.2C16.7 7 17.1 7 17.4 7.2L18.8 8.6C19 8.9 19 9.3 18.8 9.5L15.3 13 18.8 16.5C19 16.7 19 17.1 18.8 17.4Z"/></svg>',close:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-6 -6 44 44"><path d="M26 22.3L22.3 26c0 0-5.9-6.3-6.3-6.3C15.6 19.7 9.7 26 9.7 26L6 22.3c0 0 6.3-5.8 6.3-6.3C12.3 15.5 6 9.7 6 9.7l3.7-3.7c0 0 5.9 6.3 6.3 6.3 0.4 0 6.3-6.3 6.3-6.3L26 9.7c0 0-6.3 5.9-6.3 6.3C19.7 16.4 26 22.3 26 22.3z"/></svg>',unsaved:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-8 -8 48 48"><g data-name="Layer 2"><path d="M24.4 3.4h-21V28.6H28.6V7.5Zm-5 2.8v4.5H16.6V6.1Zm6.5 19.7H6.1V6.1h3.5v7.2H22.2V6.1h1.1l2.6 2.5Z"/><polygon points="20.9 22.5 18 19.6 20.9 16.7 18.9 14.7 16 17.6 13.1 14.7 11.1 16.7 14.1 19.6 11.1 22.5 13.1 24.5 16 21.5 18.9 24.5 20.9 22.5"/></g></svg>',"sidebar-right":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 48 48"><g><path d="M38,36H2V4H38ZM26,6H4V34H26Z"/></g></svg>',"sidebar-left":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -4 48 48"><path d="M2 4H38V36H2ZM14 34H36V6H14Z"/></svg>',menu:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-5 -5 42 42"><path d="M16 6C14.9 6 14 6.9 14 8 14 9.1 14.9 10 16 10 17.1 10 18 9.1 18 8 18 6.9 17.1 6 16 6zM16 14C14.9 14 14 14.9 14 16 14 17.1 14.9 18 16 18 17.1 18 18 17.1 18 16 18 14.9 17.1 14 16 14zM16 22C14.9 22 14 22.9 14 24 14 25.1 14.9 26 16 26 17.1 26 18 25.1 18 24 18 22.9 17.1 22 16 22z"/></svg>',sections:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="-10 -10 120 120"><polygon points="50 90 35 75 65 75 50 90"/><polygon points="50 10 65 25 35 25 50 10"/><circle cx="50" cy="50" r="10"/></svg>',help:'<svg viewBox="-384 -384 1792 1792" style=""><g><path d="M448 768h128v-128h-128v128zM512 256c-96 0-192 96-192 192h128c0-32 32-64 64-64s64 32 64 64c0 64-128 64-128 128h128c64-22 128-64 128-160s-96-160-192-160zM512 0c-283 0-512 229-512 512s229 512 512 512 512-229 512-512-229-512-512-512zM512 896c-212 0-384-172-384-384s172-384 384-384 384 172 384 384-172 384-384 384z"></path></g></svg>'}},self.getCurrentObject=function(construct,force){if(construct){if(self.current.constructed)return self.current.constructed;var obj=self.constructObjectFromFields();return obj[self.getIDProp()]||force?obj:self.current.object}return self.current.object},window._jco=self.getCurrentObject,this.Colors={ai:"#0D9488"},this.Colors.priority={1:"#cc4500",2:"#FFee33",3:"#acf"},this.Snippets={},this.Snippets.priorityStripeColor=function(item){if(item.priority&&item.priority<100)return{title:`P${item.priority}`,color:_joe.Colors.priority[item.priority]}},this.Google={Calendar:{list:function(){if(!self.Google.Calendar.calendars)return self.Google.loadCalendarApi(),void self.Google.Calendar.list();goJoe(_joe.Google.Calendar.calendars,{schema:{idprop:"id",listWindowTitle:"Google Calendars",title:"gcal: ${summary}",listTitle:"<joe-title>${summary}</joe-title><joe-subtitle>${id}</joe-subtitle>",itemMenu:function(item){return[{name:"view",action:"window.open('https://calendar.google.com/calendar/embed?mode=WEEK&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;src=${id}&amp;color=%236B3304&amp;ctz=America%2FChicago');"}]},sorter:["summary"],checkChanges:!1,stripeColor:function(cal){return cal.backgroundColor},bgColor:function(cal){return _joe.Google.Calendar&&_joe.Google.Calendar.active&&_joe.Google.Calendar.active.id==cal.id?"goldenrod":""}}})}},client_id:null,init:function(){console.log("google authed",self.Google.access_token),self.Google.listCalendars()},scopes:["https://www.googleapis.com/auth/calendar"],loadCalendarApi:function(access_token,callback){access_token&&(self.Google.access_token=access_token);callback=callback||self.Google.init;gapi.client.load("calendar","v3",callback)},listCalendars:function(){gapi.client.calendar.calendarList.list().execute(function(resp){self.Google.Calendar.calendars=resp.items,self.Google.Calendar.active=self.Utils.Settings("GOOGLE_CALENDARID")&&resp.items.where({id:self.Utils.Settings("GOOGLE_CALENDARID")})[0]||resp.items.where({primary:!0})[0]||!1,capp&&capp.Reload.all()})}},this.Google.authorize=function(immediate,callback,hidePopup){var client_id=self.Google.client_id=self.Utils.Settings("GOOGLE_CLIENTID");self.Google.access_token?self.Google.loadCalendarApi():client_id&&gapi&&gapi.auth?gapi.auth.authorize({client_id:self.Google.client_id,scope:self.Google.scopes.join(" "),immediate:!0},function(authResult){if(authResult&&!authResult.error)self.Google.loadCalendarApi(authResult.access_token);else{if(JACmode)if(!confirm("jac mode enabled, login to google?"))return;gapi.auth.authorize({client_id:self.Google.client_id,scope:self.Google.scopes.join(" "),immediate:!1},function(authResult){authResult&&!authResult.error?self.Google.loadCalendarApi(authResult.access_token):self.Error.add("google client:"+authResult.error+","+authResult.error_subtype,authResult.error+","+authResult.error_subtype,{c:client_id,g:gapi,auth:gapi.auth,authResult:authResult})})}}):self.Error.add("error in google client api",null,{c:client_id,g:gapi,auth:gapi.auth})},this.Google.Calendar.Event={buildResource:function(event){var template=self.Utils.Settings("GOOGLE_EVENT_TEMPLATE",{params:event})||"${info} \r\n ${description}",descriptionString=fillTemplate(template,$.extend({URL:"//"+__jsc.hostname+":"+__jsc.port+location.pathname+location.hash},event)),res={sendNotifications:event.sendNotifications||!1,summary:event.name||event.address+" "+(event.event_type||""),description:descriptionString,location:event.location||fillTemplate("${street_address} ${city} ${state} ${zip}",event),start:{dateTime:$c.format(new Date(event.date+" "+event.start_time),"Y-m-d")+"T"+$c.format(new Date(event.date+" "+event.start_time),"H:i:00.000")+event.timezone_offset},end:{dateTime:$c.format(new Date(event.date+" "+event.end_time),"Y-m-d")+"T"+$c.format(new Date(event.date+" "+event.end_time),"H:i:00.000")+event.timezone_offset},id:event._id.replace(/-/g,""),attendees:[]},lead_person=event.leader||event.lead;if(lead_person){var leader=self.Cache.get(lead_person);res.attendees.push({name:leader.fullname||leader.first&&leader.first+" "+leader.last||leader.name,id:leader._id,email:leader.email})}return(event.attendees||event.team_members||[]).map(function(att){var attendee=self.Cache.get(att);res.attendees.push({name:attendee.fullname||attendee.first&&attendee.first+" "+attendee.last||attendee.name,id:attendee._id,email:attendee.email})}),res},getObject:function(eventid){return self.current.object&&self.current.object._id==eventid?_jco(!0):self.getDataItem(eventid,"event")},add:function(eventid,force,saveFirst){if(!self.Google.access_token||!self.Google.Calendar.calendars)return alert("please login to your google account and then try again."),void self.Google.authorize(!0);try{var event=self.Google.Calendar.Event.getObject(eventid);if(!event)return void alert("event not found: "+eventid);if(!event.published&&!force)return void alert("event not published: "+event.name);var resource=self.Google.Calendar.Event.buildResource(event),request=gapi.client.calendar.events.insert({calendarId:self.Google.Calendar.active.id,resource:resource,sendNotifications:resource.sendNotifications});request.sendNotifications=resource.sendNotifications,request.execute(function(resp){if(resp.error&&409==resp.error.code){logit("updating");var ovr={status:"confirmed"};event.published||(ovr.status="cancelled"),ovr.save=saveFirst,self.Google.Calendar.Event.update(eventid,ovr)}else saveFirst&&(_joe.current.object.published_ts=new Date,self.updateObject(null,null,!0),_joe.rerenderField("published_ts"));logit(resp)})}catch(e){self.Error.add("error adding event",e,eventid),alert("error adding event \n"+e)}},update:function(eventid,specs){try{var saveFirst=specs.save,event=self.Google.Calendar.Event.getObject(eventid),resource=$.extend(self.Google.Calendar.Event.buildResource(event),specs||{status:"confirmed"}),request=gapi.client.calendar.events.patch({calendarId:self.Google.Calendar.active.id,resource:resource,eventId:eventid.replace(/-/g,""),sendNotifications:resource.sendNotifications});request.sendNotifications=resource.sendNotifications,request.execute(function(resp){resp.error?alert(resp.error.message||resp.error):saveFirst&&(_joe.current.object.published_ts=new Date,self.updateObject(null,null,!0),_joe.rerenderField("published_ts")),logit(resp)})}catch(e){self.Error.add("error updating event",e,eventid)}},publish:function(query){if(self.Google.Calendar.calendars&&self.Google.access_token){query=query||{published:!0};if(self.Data.event){var topublish=self.Data.event.where(query),notpublish=self.Data.event.where(function(){return!this.published});confirm("publish "+topublish.length+" events?\n you have "+notpublish.length+"/"+self.Data.event.length+" unpublished events")&&topublish.map(function(ev){self.Google.Calendar.Event.add(ev._id)})}}else gapi.auth.authorize({client_id:self.Google.client_id,scope:self.Google.scopes.join(" "),immediate:!1},function(authResult){authResult&&!authResult.error?(self.Google.loadCalendarApi(),self.Google.Calendar.Event.publish()):(alert("error authorizing calendars"),self.Error.add("google client:"+authResult.error+","+authResult.error_subtype,authResult.error+","+authResult.error_subtype,{c:client_id,g:gapi,auth:gapi.auth,authResult:authResult}))})}},self.specs.autoInit&&self.init(),this}function _classic_unstringifyFunctions(propObject){for(var p in propObject)"string"==typeof propObject[p]&&0==propObject[p].indexOf("(function")?propObject[p]=tryEval("("+propObject[p].replace(/;r\n/g,";\n").replace(/<br \/>/g,"")+")"):"object"==typeof propObject[p]&&unstringifyFunctions(propObject[p]);return propObject}function unstringifyFunctions(propObject){for(var p in propObject)if("string"==typeof propObject[p]){var trimmed=propObject[p].trim();(trimmed.startsWith("(function")||trimmed.startsWith("(async function"))&&(propObject[p]=tryEval(trimmed.replace(/;r\n/g,";\n").replace(/<br \/>/g,"")))}else"object"==typeof propObject[p]&&null!==propObject[p]&&unstringifyFunctions(propObject[p]);return propObject}location&&"file://"==location.origin&&(joe_web_dir=location.href.slice(0,location.href.lastIndexOf("/")+1)),__docWriter=function(src,type,cancelWrite){var html="";switch((type=type||"js").toLowerCase()){case"js":case"javascript":html+='<script type="text/javascript" src="'+src+'"><\/script>';break;case"css":case"stylesheet":html+='<link href="'+src+'" rel="stylesheet" type="text/css">'}return cancelWrite||document.write(html),html},__loadAdditionalFiles=function(){var bonuses="";"undefined"==typeof jQuery&&(__docWriter(joe_web_dir+"js/libs/jquery-1.11.3.min.js","js"),__docWriter(joe_web_dir+"js/libs/jquery-ui.min.js")),bonuses+=__docWriter(joe_web_dir+"js/libs/jquery.ui.touch-punch.min.js"),("undefined"==typeof Craydent||!Craydent.VERSION||Craydent.VERSION<"1.7.37")&&(bonuses+=__docWriter(joe_web_dir+"js/libs/craydent-1.8.1.js","js",!0)),document.write(bonuses)};var __clearDiv__='<div class="clear"></div>',__createBtn__={name:"create",icon:"plus",action:"create",color:"orange",schema:function(){return _joe.current.schema&&_joe.current.schema.name},css:" joe-add-button joe-iconed-button"},__quicksaveBtn__={name:"quicksave",label:"Save",action:"_joe.updateObject(this,null,true);",css:"joe-quicksave-button joe-confirm-button joe-iconed-button"},__saveBtn__={name:"save",label:"Save",action:"_joe.updateObject(this);",css:"joe-save-button joe-confirm-button joe-iconed-button"},__deleteBtn__={name:"delete",label:"Delete",action:"_joe.deleteObject(this);",css:"joe-delete-button joe-iconed-button joe-red-button",condition:function(){return _joe.isNewItem&&!_joe.isNewItem()}},__multisaveBtn__={name:"save_multi",label:"Multi Save",action:"_joe.updateMultipleObjects(this);",css:"joe-save-button joe-confirm-button joe-multi-only"},__multideleteBtn__={name:"delete_multi",label:"Multi Delete",action:"_joe.deleteMultipleObjects(this);",css:"joe-delete-button joe-multi-only"},__selectAllBtn__={name:"select_all",label:"select all",action:"_joe.selectAllItems();",css:"joe-left-button joe-multi-always"},__replaceBtn__={name:"replace",label:"Replace",action:"_joe.updateRendering(this);",css:"joe-replace-button joe-confirm-button"},__duplicateBtn__={name:"duplicate",label:"Duplicate",action:"_joe.duplicateObject();",css:"joe-left-button joe-iconed-button joe-duplicate-button"},__exportBtn__={name:"export",display:"<b>{&#8593;}</b>",condition:function(){return _joe.User&&"super"==_joe.User.role},css:"joe-export-button joe-left-button joe-grey-button joe-orangegrey-button",action:"_joe.IO.export(null,true)"},__systemFieldsSection=[{section_start:"system",collapsed:!0},"_id","created","itemtype",{section_end:"system"}],__defaultButtons=[__createBtn__],__defaultObjectButtons=[__deleteBtn__,__saveBtn__],__defaultMultiButtons=[__multisaveBtn__,__multideleteBtn__];function __removeTags(str){return str?str.replace(/<(?:.|\n)*?>/gm,""):""}function _COUNT(array){return array?array.isArray()||array.isString()?array.length:array.isFunction?array.toString().length:0:0}function showJOEWarnings(){goJoe(_joe.current.benchmarkers._warnings,{schema:{title:"benchmarker warnings",listTitle:"<joe-title>${name}</joe-title><joe-subtitle>${info}</joe-subtitle>",checkChanges:!1}})}function _bmResponse(benchmarker,message,bmname,threshhold){var t=benchmarker.stop(),m=message+" in "+t+" secs";_joe.current.benchmarkers=_joe.current.benchmarkers||{};var name=bmname||message,payload={info:t,name:name,_id:cuid()};_joe.current.benchmarkers._warnings=_joe.current.benchmarkers._warnings||[],_joe.current.benchmarkers[name]=payload,$c.DEBUG_MODE&&window.console&&window.console.warn?t>.4?(window.console.warn(m),_joe.current.benchmarkers[name].warn=!0,_joe.current.benchmarkers._warnings.push(payload)):(!threshhold||t>threshhold)&&logit(m):logit(m)}function beginLogGroup(name,expanded){$c.DEBUG_MODE&&(expanded?window.console&&window.console.group&&console.group(name):window.console&&window.console.groupCollapsed&&console.groupCollapsed(name))}function endLogGroup(){$c.DEBUG_MODE&&window.console&&window.console.groupEnd&&console.groupEnd()}function _renderUserCubes(user,cssclass,user_dataset){var title,initials,css=cssclass||"fleft",u=user,html="",color=user.color||"#cbcbcb";if(u.first&&u.last)title=u.first+" "+u.last,initials=u.first[0]+u.last[0];else{var name=u.fullname||u.name;title=name,initials=name[0]+(name.indexOf(" ")>0&&name[name.indexOf(" ")+1]||"")}return html+='<joe-user-cube title="'+title+'" class="'+css+'" style="background-color:'+color+'">'+initials+" <span>"+title+"</span></joe-user-cube>"}function warn(message){console&&console.warn&&console.warn(message)}function formatMoney(number,places,symbol,thousand,decimal){number=number||0,places=isNaN(places=Math.abs(places))?2:places,symbol=void 0!==symbol?symbol:"$",thousand=thousand||",",decimal=decimal||".";var negative=number<0?"-":"",i=parseInt(number=Math.abs(+number||0).toFixed(places),10)+"",j=(j=i.length)>3?j%3:0;return symbol+negative+(j?i.substr(0,j)+thousand:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+thousand)+(places?decimal+Math.abs(number-i).toFixed(places).slice(2):"")}!function(t,e,i){var n=t.L,o={version:"0.7.2"};"object"==typeof module&&"object"==typeof module.exports?module.exports=o:"function"==typeof define&&define.amd&&define(o),o.noConflict=function(){return t.L=n,this},t.L=o,o.Util={extend:function(t){var e,i,n,o,s=Array.prototype.slice.call(arguments,1);for(i=0,n=s.length;n>i;i++)for(e in o=s[i]||{})o.hasOwnProperty(e)&&(t[e]=o[e]);return t},bind:function(t,e){var i=arguments.length>2?Array.prototype.slice.call(arguments,2):null;return function(){return t.apply(e,i||arguments)}},stamp:function(){var t=0,e="_leaflet_id";return function(i){return i[e]=i[e]||++t,i[e]}}(),invokeEach:function(t,e,i){var n,o;if("object"==typeof t){for(n in o=Array.prototype.slice.call(arguments,3),t)e.apply(i,[n,t[n]].concat(o));return!0}return!1},limitExecByInterval:function(t,e,i){var n,o;return function s(){var a=arguments;return n?void(o=!0):(n=!0,setTimeout(function(){n=!1,o&&(s.apply(i,a),o=!1)},e),void t.apply(i,a))}},falseFn:function(){return!1},formatNum:function(t,e){var i=Math.pow(10,e||5);return Math.round(t*i)/i},trim:function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")},splitWords:function(t){return o.Util.trim(t).split(/\s+/)},setOptions:function(t,e){return t.options=o.extend({},t.options,e),t.options},getParamString:function(t,e,i){var n=[];for(var o in t)n.push(encodeURIComponent(i?o.toUpperCase():o)+"="+encodeURIComponent(t[o]));return(e&&-1!==e.indexOf("?")?"&":"?")+n.join("&")},template:function(t,e){return t.replace(/\{ *([\w_]+) *\}/g,function(t,n){var o=e[n];if(o===i)throw new Error("No value provided for variable "+t);return"function"==typeof o&&(o=o(e)),o})},isArray:Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},emptyImageUrl:"data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="},function(){function e(e){var i,n,o=["webkit","moz","o","ms"];for(i=0;i<o.length&&!n;i++)n=t[o[i]+e];return n}function i(e){var i=+new Date,o=Math.max(0,16-(i-n));return n=i+o,t.setTimeout(e,o)}var n=0,s=t.requestAnimationFrame||e("RequestAnimationFrame")||i,a=t.cancelAnimationFrame||e("CancelAnimationFrame")||e("CancelRequestAnimationFrame")||function(e){t.clearTimeout(e)};o.Util.requestAnimFrame=function(e,n,a,r){return e=o.bind(e,n),a&&s===i?void e():s.call(t,e,r)},o.Util.cancelAnimFrame=function(e){e&&a.call(t,e)}}(),o.extend=o.Util.extend,o.bind=o.Util.bind,o.stamp=o.Util.stamp,o.setOptions=o.Util.setOptions,o.Class=function(){},o.Class.extend=function(t){var e=function(){this.initialize&&this.initialize.apply(this,arguments),this._initHooks&&this.callInitHooks()},i=function(){};i.prototype=this.prototype;var n=new i;for(var s in n.constructor=e,e.prototype=n,this)this.hasOwnProperty(s)&&"prototype"!==s&&(e[s]=this[s]);t.statics&&(o.extend(e,t.statics),delete t.statics),t.includes&&(o.Util.extend.apply(null,[n].concat(t.includes)),delete t.includes),t.options&&n.options&&(t.options=o.extend({},n.options,t.options)),o.extend(n,t),n._initHooks=[];var a=this;return e.__super__=a.prototype,n.callInitHooks=function(){if(!this._initHooksCalled){a.prototype.callInitHooks&&a.prototype.callInitHooks.call(this),this._initHooksCalled=!0;for(var t=0,e=n._initHooks.length;e>t;t++)n._initHooks[t].call(this)}},e},o.Class.include=function(t){o.extend(this.prototype,t)},o.Class.mergeOptions=function(t){o.extend(this.prototype.options,t)},o.Class.addInitHook=function(t){var e=Array.prototype.slice.call(arguments,1),i="function"==typeof t?t:function(){this[t].apply(this,e)};this.prototype._initHooks=this.prototype._initHooks||[],this.prototype._initHooks.push(i)};var s="_leaflet_events";o.Mixin={},o.Mixin.Events={addEventListener:function(t,e,i){if(o.Util.invokeEach(t,this.addEventListener,this,e,i))return this;var n,a,r,h,l,u,c,d=this[s]=this[s]||{},p=i&&i!==this&&o.stamp(i);for(n=0,a=(t=o.Util.splitWords(t)).length;a>n;n++)r={action:e,context:i||this},h=t[n],p?(u=(l=h+"_idx")+"_len",(c=d[l]=d[l]||{})[p]||(c[p]=[],d[u]=(d[u]||0)+1),c[p].push(r)):(d[h]=d[h]||[],d[h].push(r));return this},hasEventListeners:function(t){var e=this[s];return!!e&&(t in e&&e[t].length>0||t+"_idx"in e&&e[t+"_idx_len"]>0)},removeEventListener:function(t,e,i){if(!this[s])return this;if(!t)return this.clearAllEventListeners();if(o.Util.invokeEach(t,this.removeEventListener,this,e,i))return this;var n,a,r,h,l,u,c,d,_=this[s],m=i&&i!==this&&o.stamp(i);for(n=0,a=(t=o.Util.splitWords(t)).length;a>n;n++)if(c=(u=(r=t[n])+"_idx")+"_len",d=_[u],e){if(h=m&&d?d[m]:_[r]){for(l=h.length-1;l>=0;l--)h[l].action!==e||i&&h[l].context!==i||(h.splice(l,1)[0].action=o.Util.falseFn);i&&d&&0===h.length&&(delete d[m],_[c]--)}}else delete _[r],delete _[u],delete _[c];return this},clearAllEventListeners:function(){return delete this[s],this},fireEvent:function(t,e){if(!this.hasEventListeners(t))return this;var i,n,a,r,h,l=o.Util.extend({},e,{type:t,target:this}),u=this[s];if(u[t])for(n=0,a=(i=u[t].slice()).length;a>n;n++)i[n].action.call(i[n].context,l);for(h in r=u[t+"_idx"])if(i=r[h].slice())for(n=0,a=i.length;a>n;n++)i[n].action.call(i[n].context,l);return this},addOneTimeEventListener:function(t,e,i){if(o.Util.invokeEach(t,this.addOneTimeEventListener,this,e,i))return this;var n=o.bind(function(){this.removeEventListener(t,e,i).removeEventListener(t,n,i)},this);return this.addEventListener(t,e,i).addEventListener(t,n,i)}},o.Mixin.Events.on=o.Mixin.Events.addEventListener,o.Mixin.Events.off=o.Mixin.Events.removeEventListener,o.Mixin.Events.once=o.Mixin.Events.addOneTimeEventListener,o.Mixin.Events.fire=o.Mixin.Events.fireEvent,function(){var n="ActiveXObject"in t,s=n&&!e.addEventListener,a=navigator.userAgent.toLowerCase(),r=-1!==a.indexOf("webkit"),h=-1!==a.indexOf("chrome"),l=-1!==a.indexOf("phantom"),u=-1!==a.indexOf("android"),c=-1!==a.search("android [23]"),d=-1!==a.indexOf("gecko"),p=typeof orientation!=i+"",_=t.navigator&&t.navigator.msPointerEnabled&&t.navigator.msMaxTouchPoints&&!t.PointerEvent,m=t.PointerEvent&&t.navigator.pointerEnabled&&t.navigator.maxTouchPoints||_,f="devicePixelRatio"in t&&t.devicePixelRatio>1||"matchMedia"in t&&t.matchMedia("(min-resolution:144dpi)")&&t.matchMedia("(min-resolution:144dpi)").matches,g=e.documentElement,v=n&&"transition"in g.style,y="WebKitCSSMatrix"in t&&"m11"in new t.WebKitCSSMatrix&&!c,P="MozPerspective"in g.style,L="OTransition"in g.style,x=!t.L_DISABLE_3D&&(v||y||P||L)&&!l,w=!t.L_NO_TOUCH&&!l&&function(){var t="ontouchstart";if(m||t in g)return!0;var i=e.createElement("div"),n=!1;return!!i.setAttribute&&(i.setAttribute(t,"return;"),"function"==typeof i[t]&&(n=!0),i.removeAttribute(t),i=null,n)}();o.Browser={ie:n,ielt9:s,webkit:r,gecko:d&&!r&&!t.opera&&!n,android:u,android23:c,chrome:h,ie3d:v,webkit3d:y,gecko3d:P,opera3d:L,any3d:x,mobile:p,mobileWebkit:p&&r,mobileWebkit3d:p&&y,mobileOpera:p&&t.opera,touch:w,msPointer:_,pointer:m,retina:f}}(),o.Point=function(t,e,i){this.x=i?Math.round(t):t,this.y=i?Math.round(e):e},o.Point.prototype={clone:function(){return new o.Point(this.x,this.y)},add:function(t){return this.clone()._add(o.point(t))},_add:function(t){return this.x+=t.x,this.y+=t.y,this},subtract:function(t){return this.clone()._subtract(o.point(t))},_subtract:function(t){return this.x-=t.x,this.y-=t.y,this},divideBy:function(t){return this.clone()._divideBy(t)},_divideBy:function(t){return this.x/=t,this.y/=t,this},multiplyBy:function(t){return this.clone()._multiplyBy(t)},_multiplyBy:function(t){return this.x*=t,this.y*=t,this},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},distanceTo:function(t){var e=(t=o.point(t)).x-this.x,i=t.y-this.y;return Math.sqrt(e*e+i*i)},equals:function(t){return(t=o.point(t)).x===this.x&&t.y===this.y},contains:function(t){return t=o.point(t),Math.abs(t.x)<=Math.abs(this.x)&&Math.abs(t.y)<=Math.abs(this.y)},toString:function(){return"Point("+o.Util.formatNum(this.x)+", "+o.Util.formatNum(this.y)+")"}},o.point=function(t,e,n){return t instanceof o.Point?t:o.Util.isArray(t)?new o.Point(t[0],t[1]):t===i||null===t?t:new o.Point(t,e,n)},o.Bounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},o.Bounds.prototype={extend:function(t){return t=o.point(t),this.min||this.max?(this.min.x=Math.min(t.x,this.min.x),this.max.x=Math.max(t.x,this.max.x),this.min.y=Math.min(t.y,this.min.y),this.max.y=Math.max(t.y,this.max.y)):(this.min=t.clone(),this.max=t.clone()),this},getCenter:function(t){return new o.Point((this.min.x+this.max.x)/2,(this.min.y+this.max.y)/2,t)},getBottomLeft:function(){return new o.Point(this.min.x,this.max.y)},getTopRight:function(){return new o.Point(this.max.x,this.min.y)},getSize:function(){return this.max.subtract(this.min)},contains:function(t){var e,i;return(t="number"==typeof t[0]||t instanceof o.Point?o.point(t):o.bounds(t))instanceof o.Bounds?(e=t.min,i=t.max):e=i=t,e.x>=this.min.x&&i.x<=this.max.x&&e.y>=this.min.y&&i.y<=this.max.y},intersects:function(t){t=o.bounds(t);var e=this.min,i=this.max,n=t.min,s=t.max,a=s.x>=e.x&&n.x<=i.x,r=s.y>=e.y&&n.y<=i.y;return a&&r},isValid:function(){return!(!this.min||!this.max)}},o.bounds=function(t,e){return!t||t instanceof o.Bounds?t:new o.Bounds(t,e)},o.Transformation=function(t,e,i,n){this._a=t,this._b=e,this._c=i,this._d=n},o.Transformation.prototype={transform:function(t,e){return this._transform(t.clone(),e)},_transform:function(t,e){return e=e||1,t.x=e*(this._a*t.x+this._b),t.y=e*(this._c*t.y+this._d),t},untransform:function(t,e){return e=e||1,new o.Point((t.x/e-this._b)/this._a,(t.y/e-this._d)/this._c)}},o.DomUtil={get:function(t){return"string"==typeof t?e.getElementById(t):t},getStyle:function(t,i){var n=t.style[i];if(!n&&t.currentStyle&&(n=t.currentStyle[i]),(!n||"auto"===n)&&e.defaultView){var o=e.defaultView.getComputedStyle(t,null);n=o?o[i]:null}return"auto"===n?null:n},getViewportOffset:function(t){var i,n=0,s=0,a=t,r=e.body,h=e.documentElement;do{if(n+=a.offsetTop||0,s+=a.offsetLeft||0,n+=parseInt(o.DomUtil.getStyle(a,"borderTopWidth"),10)||0,s+=parseInt(o.DomUtil.getStyle(a,"borderLeftWidth"),10)||0,i=o.DomUtil.getStyle(a,"position"),a.offsetParent===r&&"absolute"===i)break;if("fixed"===i){n+=r.scrollTop||h.scrollTop||0,s+=r.scrollLeft||h.scrollLeft||0;break}if("relative"===i&&!a.offsetLeft){var l=o.DomUtil.getStyle(a,"width"),u=o.DomUtil.getStyle(a,"max-width"),c=a.getBoundingClientRect();("none"!==l||"none"!==u)&&(s+=c.left+a.clientLeft),n+=c.top+(r.scrollTop||h.scrollTop||0);break}a=a.offsetParent}while(a);a=t;do{if(a===r)break;n-=a.scrollTop||0,s-=a.scrollLeft||0,a=a.parentNode}while(a);return new o.Point(s,n)},documentIsLtr:function(){return o.DomUtil._docIsLtrCached||(o.DomUtil._docIsLtrCached=!0,o.DomUtil._docIsLtr="ltr"===o.DomUtil.getStyle(e.body,"direction")),o.DomUtil._docIsLtr},create:function(t,i,n){var o=e.createElement(t);return o.className=i,n&&n.appendChild(o),o},hasClass:function(t,e){if(t.classList!==i)return t.classList.contains(e);var n=o.DomUtil._getClass(t);return n.length>0&&new RegExp("(^|\\s)"+e+"(\\s|$)").test(n)},addClass:function(t,e){if(t.classList!==i)for(var n=o.Util.splitWords(e),s=0,a=n.length;a>s;s++)t.classList.add(n[s]);else if(!o.DomUtil.hasClass(t,e)){var r=o.DomUtil._getClass(t);o.DomUtil._setClass(t,(r?r+" ":"")+e)}},removeClass:function(t,e){t.classList!==i?t.classList.remove(e):o.DomUtil._setClass(t,o.Util.trim((" "+o.DomUtil._getClass(t)+" ").replace(" "+e+" "," ")))},_setClass:function(t,e){t.className.baseVal===i?t.className=e:t.className.baseVal=e},_getClass:function(t){return t.className.baseVal===i?t.className:t.className.baseVal},setOpacity:function(t,e){if("opacity"in t.style)t.style.opacity=e;else if("filter"in t.style){var i=!1,n="DXImageTransform.Microsoft.Alpha";try{i=t.filters.item(n)}catch(o){if(1===e)return}e=Math.round(100*e),i?(i.Enabled=100!==e,i.Opacity=e):t.style.filter+=" progid:"+n+"(opacity="+e+")"}},testProp:function(t){for(var i=e.documentElement.style,n=0;n<t.length;n++)if(t[n]in i)return t[n];return!1},getTranslateString:function(t){var e=o.Browser.webkit3d,n=(e?",0":"")+")";return"translate"+(e?"3d":"")+"("+t.x+"px,"+t.y+"px"+n},getScaleString:function(t,e){return o.DomUtil.getTranslateString(e.add(e.multiplyBy(-1*t)))+(" scale("+t+") ")},setPosition:function(t,e,i){t._leaflet_pos=e,!i&&o.Browser.any3d?t.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(e):(t.style.left=e.x+"px",t.style.top=e.y+"px")},getPosition:function(t){return t._leaflet_pos}},o.DomUtil.TRANSFORM=o.DomUtil.testProp(["transform","WebkitTransform","OTransform","MozTransform","msTransform"]),o.DomUtil.TRANSITION=o.DomUtil.testProp(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),o.DomUtil.TRANSITION_END="webkitTransition"===o.DomUtil.TRANSITION||"OTransition"===o.DomUtil.TRANSITION?o.DomUtil.TRANSITION+"End":"transitionend",function(){if("onselectstart"in e)o.extend(o.DomUtil,{disableTextSelection:function(){o.DomEvent.on(t,"selectstart",o.DomEvent.preventDefault)},enableTextSelection:function(){o.DomEvent.off(t,"selectstart",o.DomEvent.preventDefault)}});else{var i=o.DomUtil.testProp(["userSelect","WebkitUserSelect","OUserSelect","MozUserSelect","msUserSelect"]);o.extend(o.DomUtil,{disableTextSelection:function(){if(i){var t=e.documentElement.style;this._userSelect=t[i],t[i]="none"}},enableTextSelection:function(){i&&(e.documentElement.style[i]=this._userSelect,delete this._userSelect)}})}o.extend(o.DomUtil,{disableImageDrag:function(){o.DomEvent.on(t,"dragstart",o.DomEvent.preventDefault)},enableImageDrag:function(){o.DomEvent.off(t,"dragstart",o.DomEvent.preventDefault)}})}(),o.LatLng=function(t,e,n){if(t=parseFloat(t),e=parseFloat(e),isNaN(t)||isNaN(e))throw new Error("Invalid LatLng object: ("+t+", "+e+")");this.lat=t,this.lng=e,n!==i&&(this.alt=parseFloat(n))},o.extend(o.LatLng,{DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,MAX_MARGIN:1e-9}),o.LatLng.prototype={equals:function(t){return!!t&&(t=o.latLng(t),Math.max(Math.abs(this.lat-t.lat),Math.abs(this.lng-t.lng))<=o.LatLng.MAX_MARGIN)},toString:function(t){return"LatLng("+o.Util.formatNum(this.lat,t)+", "+o.Util.formatNum(this.lng,t)+")"},distanceTo:function(t){t=o.latLng(t);var i=o.LatLng.DEG_TO_RAD,n=(t.lat-this.lat)*i,s=(t.lng-this.lng)*i,a=this.lat*i,r=t.lat*i,h=Math.sin(n/2),l=Math.sin(s/2),u=h*h+l*l*Math.cos(a)*Math.cos(r);return 12756274*Math.atan2(Math.sqrt(u),Math.sqrt(1-u))},wrap:function(t,e){var i=this.lng;return i=(i+(e=e||180))%(e-(t=t||-180))+(t>i||i===e?e:t),new o.LatLng(this.lat,i)}},o.latLng=function(t,e){return t instanceof o.LatLng?t:o.Util.isArray(t)?"number"==typeof t[0]||"string"==typeof t[0]?new o.LatLng(t[0],t[1],t[2]):null:t===i||null===t?t:"object"==typeof t&&"lat"in t?new o.LatLng(t.lat,"lng"in t?t.lng:t.lon):e===i?null:new o.LatLng(t,e)},o.LatLngBounds=function(t,e){if(t)for(var i=e?[t,e]:t,n=0,o=i.length;o>n;n++)this.extend(i[n])},o.LatLngBounds.prototype={extend:function(t){if(!t)return this;var e=o.latLng(t);return(t=null!==e?e:o.latLngBounds(t))instanceof o.LatLng?this._southWest||this._northEast?(this._southWest.lat=Math.min(t.lat,this._southWest.lat),this._southWest.lng=Math.min(t.lng,this._southWest.lng),this._northEast.lat=Math.max(t.lat,this._northEast.lat),this._northEast.lng=Math.max(t.lng,this._northEast.lng)):(this._southWest=new o.LatLng(t.lat,t.lng),this._northEast=new o.LatLng(t.lat,t.lng)):t instanceof o.LatLngBounds&&(this.extend(t._southWest),this.extend(t._northEast)),this},pad:function(t){var e=this._southWest,i=this._northEast,n=Math.abs(e.lat-i.lat)*t,s=Math.abs(e.lng-i.lng)*t;return new o.LatLngBounds(new o.LatLng(e.lat-n,e.lng-s),new o.LatLng(i.lat+n,i.lng+s))},getCenter:function(){return new o.LatLng((this._southWest.lat+this._northEast.lat)/2,(this._southWest.lng+this._northEast.lng)/2)},getSouthWest:function(){return this._southWest},getNorthEast:function(){return this._northEast},getNorthWest:function(){return new o.LatLng(this.getNorth(),this.getWest())},getSouthEast:function(){return new o.LatLng(this.getSouth(),this.getEast())},getWest:function(){return this._southWest.lng},getSouth:function(){return this._southWest.lat},getEast:function(){return this._northEast.lng},getNorth:function(){return this._northEast.lat},contains:function(t){t="number"==typeof t[0]||t instanceof o.LatLng?o.latLng(t):o.latLngBounds(t);var e,i,n=this._southWest,s=this._northEast;return t instanceof o.LatLngBounds?(e=t.getSouthWest(),i=t.getNorthEast()):e=i=t,e.lat>=n.lat&&i.lat<=s.lat&&e.lng>=n.lng&&i.lng<=s.lng},intersects:function(t){t=o.latLngBounds(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),s=t.getNorthEast(),a=s.lat>=e.lat&&n.lat<=i.lat,r=s.lng>=e.lng&&n.lng<=i.lng;return a&&r},toBBoxString:function(){return[this.getWest(),this.getSouth(),this.getEast(),this.getNorth()].join(",")},equals:function(t){return!!t&&(t=o.latLngBounds(t),this._southWest.equals(t.getSouthWest())&&this._northEast.equals(t.getNorthEast()))},isValid:function(){return!(!this._southWest||!this._northEast)}},o.latLngBounds=function(t,e){return!t||t instanceof o.LatLngBounds?t:new o.LatLngBounds(t,e)},o.Projection={},o.Projection.SphericalMercator={MAX_LATITUDE:85.0511287798,project:function(t){var e=o.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),s=t.lng*e,a=n*e;return a=Math.log(Math.tan(Math.PI/4+a/2)),new o.Point(s,a)},unproject:function(t){var e=o.LatLng.RAD_TO_DEG,i=t.x*e,n=(2*Math.atan(Math.exp(t.y))-Math.PI/2)*e;return new o.LatLng(n,i)}},o.Projection.LonLat={project:function(t){return new o.Point(t.lng,t.lat)},unproject:function(t){return new o.LatLng(t.y,t.x)}},o.CRS={latLngToPoint:function(t,e){var i=this.projection.project(t),n=this.scale(e);return this.transformation._transform(i,n)},pointToLatLng:function(t,e){var i=this.scale(e),n=this.transformation.untransform(t,i);return this.projection.unproject(n)},project:function(t){return this.projection.project(t)},scale:function(t){return 256*Math.pow(2,t)},getSize:function(t){var e=this.scale(t);return o.point(e,e)}},o.CRS.Simple=o.extend({},o.CRS,{projection:o.Projection.LonLat,transformation:new o.Transformation(1,0,-1,0),scale:function(t){return Math.pow(2,t)}}),o.CRS.EPSG3857=o.extend({},o.CRS,{code:"EPSG:3857",projection:o.Projection.SphericalMercator,transformation:new o.Transformation(.5/Math.PI,.5,-.5/Math.PI,.5),project:function(t){return this.projection.project(t).multiplyBy(6378137)}}),o.CRS.EPSG900913=o.extend({},o.CRS.EPSG3857,{code:"EPSG:900913"}),o.CRS.EPSG4326=o.extend({},o.CRS,{code:"EPSG:4326",projection:o.Projection.LonLat,transformation:new o.Transformation(1/360,.5,-1/360,.5)}),o.Map=o.Class.extend({includes:o.Mixin.Events,options:{crs:o.CRS.EPSG3857,fadeAnimation:o.DomUtil.TRANSITION&&!o.Browser.android23,trackResize:!0,markerZoomAnimation:o.DomUtil.TRANSITION&&o.Browser.any3d},initialize:function(t,e){e=o.setOptions(this,e),this._initContainer(t),this._initLayout(),this._onResize=o.bind(this._onResize,this),this._initEvents(),e.maxBounds&&this.setMaxBounds(e.maxBounds),e.center&&e.zoom!==i&&this.setView(o.latLng(e.center),e.zoom,{reset:!0}),this._handlers=[],this._layers={},this._zoomBoundLayers={},this._tileLayersNum=0,this.callInitHooks(),this._addLayers(e.layers)},setView:function(t,e){return e=e===i?this.getZoom():e,this._resetView(o.latLng(t),this._limitZoom(e)),this},setZoom:function(t,e){return this._loaded?this.setView(this.getCenter(),t,{zoom:e}):(this._zoom=this._limitZoom(t),this)},zoomIn:function(t,e){return this.setZoom(this._zoom+(t||1),e)},zoomOut:function(t,e){return this.setZoom(this._zoom-(t||1),e)},setZoomAround:function(t,e,i){var n=this.getZoomScale(e),s=this.getSize().divideBy(2),r=(t instanceof o.Point?t:this.latLngToContainerPoint(t)).subtract(s).multiplyBy(1-1/n),h=this.containerPointToLatLng(s.add(r));return this.setView(h,e,{zoom:i})},fitBounds:function(t,e){e=e||{},t=t.getBounds?t.getBounds():o.latLngBounds(t);var i=o.point(e.paddingTopLeft||e.padding||[0,0]),n=o.point(e.paddingBottomRight||e.padding||[0,0]),s=this.getBoundsZoom(t,!1,i.add(n)),a=n.subtract(i).divideBy(2),r=this.project(t.getSouthWest(),s),h=this.project(t.getNorthEast(),s),l=this.unproject(r.add(h).divideBy(2).add(a),s);return s=e&&e.maxZoom?Math.min(e.maxZoom,s):s,this.setView(l,s,e)},fitWorld:function(t){return this.fitBounds([[-90,-180],[90,180]],t)},panTo:function(t,e){return this.setView(t,this._zoom,{pan:e})},panBy:function(t){return this.fire("movestart"),this._rawPanBy(o.point(t)),this.fire("move"),this.fire("moveend")},setMaxBounds:function(t){return t=o.latLngBounds(t),this.options.maxBounds=t,t?(this._loaded&&this._panInsideMaxBounds(),this.on("moveend",this._panInsideMaxBounds,this)):this.off("moveend",this._panInsideMaxBounds,this)},panInsideBounds:function(t,e){var i=this.getCenter(),n=this._limitCenter(i,this._zoom,t);return i.equals(n)?this:this.panTo(n,e)},addLayer:function(t){var e=o.stamp(t);return this._layers[e]||(this._layers[e]=t,!t.options||isNaN(t.options.maxZoom)&&isNaN(t.options.minZoom)||(this._zoomBoundLayers[e]=t,this._updateZoomLevels()),this.options.zoomAnimation&&o.TileLayer&&t instanceof o.TileLayer&&(this._tileLayersNum++,this._tileLayersToLoad++,t.on("load",this._onTileLayerLoad,this)),this._loaded&&this._layerAdd(t)),this},removeLayer:function(t){var e=o.stamp(t);return this._layers[e]?(this._loaded&&t.onRemove(this),delete this._layers[e],this._loaded&&this.fire("layerremove",{layer:t}),this._zoomBoundLayers[e]&&(delete this._zoomBoundLayers[e],this._updateZoomLevels()),this.options.zoomAnimation&&o.TileLayer&&t instanceof o.TileLayer&&(this._tileLayersNum--,this._tileLayersToLoad--,t.off("load",this._onTileLayerLoad,this)),this):this},hasLayer:function(t){return!!t&&o.stamp(t)in this._layers},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},invalidateSize:function(t){if(!this._loaded)return this;t=o.extend({animate:!1,pan:!0},!0===t?{animate:!0}:t);var e=this.getSize();this._sizeChanged=!0,this._initialCenter=null;var i=this.getSize(),n=e.divideBy(2).round(),s=i.divideBy(2).round(),a=n.subtract(s);return a.x||a.y?(t.animate&&t.pan?this.panBy(a):(t.pan&&this._rawPanBy(a),this.fire("move"),t.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(o.bind(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:e,newSize:i})):this},addHandler:function(t,e){if(!e)return this;var i=this[t]=new e(this);return this._handlers.push(i),this.options[t]&&i.enable(),this},remove:function(){this._loaded&&this.fire("unload"),this._initEvents("off");try{delete this._container._leaflet}catch(t){this._container._leaflet=i}return this._clearPanes(),this._clearControlPos&&this._clearControlPos(),this._clearHandlers(),this},getCenter:function(){return this._checkIfLoaded(),this._initialCenter&&!this._moved()?this._initialCenter:this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var t=this.getPixelBounds(),e=this.unproject(t.getBottomLeft()),i=this.unproject(t.getTopRight());return new o.LatLngBounds(e,i)},getMinZoom:function(){return this.options.minZoom===i?this._layersMinZoom===i?0:this._layersMinZoom:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===i?this._layersMaxZoom===i?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(t,e,i){t=o.latLngBounds(t);var n,s=this.getMinZoom()-(e?1:0),a=this.getMaxZoom(),r=this.getSize(),h=t.getNorthWest(),l=t.getSouthEast(),u=!0;i=o.point(i||[0,0]);do{s++,n=this.project(l,s).subtract(this.project(h,s)).add(i),u=e?n.x<r.x||n.y<r.y:r.contains(n)}while(u&&a>=s);return u&&e?null:e?s:s-1},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new o.Point(this._container.clientWidth,this._container.clientHeight),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(){var t=this._getTopLeftPoint();return new o.Bounds(t,t.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._initialTopLeftPoint},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(t){var e=this.options.crs;return e.scale(t)/e.scale(this._zoom)},getScaleZoom:function(t){return this._zoom+Math.log(t)/Math.LN2},project:function(t,e){return e=e===i?this._zoom:e,this.options.crs.latLngToPoint(o.latLng(t),e)},unproject:function(t,e){return e=e===i?this._zoom:e,this.options.crs.pointToLatLng(o.point(t),e)},layerPointToLatLng:function(t){var e=o.point(t).add(this.getPixelOrigin());return this.unproject(e)},latLngToLayerPoint:function(t){return this.project(o.latLng(t))._round()._subtract(this.getPixelOrigin())},containerPointToLayerPoint:function(t){return o.point(t).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(t){return o.point(t).add(this._getMapPanePos())},containerPointToLatLng:function(t){var e=this.containerPointToLayerPoint(o.point(t));return this.layerPointToLatLng(e)},latLngToContainerPoint:function(t){return this.layerPointToContainerPoint(this.latLngToLayerPoint(o.latLng(t)))},mouseEventToContainerPoint:function(t){return o.DomEvent.getMousePosition(t,this._container)},mouseEventToLayerPoint:function(t){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))},mouseEventToLatLng:function(t){return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))},_initContainer:function(t){var e=this._container=o.DomUtil.get(t);if(!e)throw new Error("Map container not found.");if(e._leaflet)throw new Error("Map container is already initialized.");e._leaflet=!0},_initLayout:function(){var t=this._container;o.DomUtil.addClass(t,"leaflet-container"+(o.Browser.touch?" leaflet-touch":"")+(o.Browser.retina?" leaflet-retina":"")+(o.Browser.ielt9?" leaflet-oldie":"")+(this.options.fadeAnimation?" leaflet-fade-anim":""));var e=o.DomUtil.getStyle(t,"position");"absolute"!==e&&"relative"!==e&&"fixed"!==e&&(t.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var t=this._panes={};this._mapPane=t.mapPane=this._createPane("leaflet-map-pane",this._container),this._tilePane=t.tilePane=this._createPane("leaflet-tile-pane",this._mapPane),t.objectsPane=this._createPane("leaflet-objects-pane",this._mapPane),t.shadowPane=this._createPane("leaflet-shadow-pane"),t.overlayPane=this._createPane("leaflet-overlay-pane"),t.markerPane=this._createPane("leaflet-marker-pane"),t.popupPane=this._createPane("leaflet-popup-pane");var e=" leaflet-zoom-hide";this.options.markerZoomAnimation||(o.DomUtil.addClass(t.markerPane,e),o.DomUtil.addClass(t.shadowPane,e),o.DomUtil.addClass(t.popupPane,e))},_createPane:function(t,e){return o.DomUtil.create("div",t,e||this._panes.objectsPane)},_clearPanes:function(){this._container.removeChild(this._mapPane)},_addLayers:function(t){for(var e=0,i=(t=t?o.Util.isArray(t)?t:[t]:[]).length;i>e;e++)this.addLayer(t[e])},_resetView:function(t,e,i,n){var s=this._zoom!==e;n||(this.fire("movestart"),s&&this.fire("zoomstart")),this._zoom=e,this._initialCenter=t,this._initialTopLeftPoint=this._getNewTopLeftPoint(t),i?this._initialTopLeftPoint._add(this._getMapPanePos()):o.DomUtil.setPosition(this._mapPane,new o.Point(0,0)),this._tileLayersToLoad=this._tileLayersNum;var a=!this._loaded;this._loaded=!0,a&&(this.fire("load"),this.eachLayer(this._layerAdd,this)),this.fire("viewreset",{hard:!i}),this.fire("move"),(s||n)&&this.fire("zoomend"),this.fire("moveend",{hard:!i})},_rawPanBy:function(t){o.DomUtil.setPosition(this._mapPane,this._getMapPanePos().subtract(t))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_updateZoomLevels:function(){var t,e=1/0,n=-1/0,o=this._getZoomSpan();for(t in this._zoomBoundLayers){var s=this._zoomBoundLayers[t];isNaN(s.options.minZoom)||(e=Math.min(e,s.options.minZoom)),isNaN(s.options.maxZoom)||(n=Math.max(n,s.options.maxZoom))}t===i?this._layersMaxZoom=this._layersMinZoom=i:(this._layersMaxZoom=n,this._layersMinZoom=e),o!==this._getZoomSpan()&&this.fire("zoomlevelschange")},_panInsideMaxBounds:function(){this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(e){if(o.DomEvent){e=e||"on",o.DomEvent[e](this._container,"click",this._onMouseClick,this);var i,n,s=["dblclick","mousedown","mouseup","mouseenter","mouseleave","mousemove","contextmenu"];for(i=0,n=s.length;n>i;i++)o.DomEvent[e](this._container,s[i],this._fireMouseEvent,this);this.options.trackResize&&o.DomEvent[e](t,"resize",this._onResize,this)}},_onResize:function(){o.Util.cancelAnimFrame(this._resizeRequest),this._resizeRequest=o.Util.requestAnimFrame(function(){this.invalidateSize({debounceMoveend:!0})},this,!1,this._container)},_onMouseClick:function(t){!this._loaded||!t._simulated&&(this.dragging&&this.dragging.moved()||this.boxZoom&&this.boxZoom.moved())||o.DomEvent._skipped(t)||(this.fire("preclick"),this._fireMouseEvent(t))},_fireMouseEvent:function(t){if(this._loaded&&!o.DomEvent._skipped(t)){var e=t.type;if(e="mouseenter"===e?"mouseover":"mouseleave"===e?"mouseout":e,this.hasEventListeners(e)){"contextmenu"===e&&o.DomEvent.preventDefault(t);var i=this.mouseEventToContainerPoint(t),n=this.containerPointToLayerPoint(i),s=this.layerPointToLatLng(n);this.fire(e,{latlng:s,layerPoint:n,containerPoint:i,originalEvent:t})}}},_onTileLayerLoad:function(){this._tileLayersToLoad--,this._tileLayersNum&&!this._tileLayersToLoad&&this.fire("tilelayersload")},_clearHandlers:function(){for(var t=0,e=this._handlers.length;e>t;t++)this._handlers[t].disable()},whenReady:function(t,e){return this._loaded?t.call(e||this,this):this.on("load",t,e),this},_layerAdd:function(t){t.onAdd(this),this.fire("layeradd",{layer:t})},_getMapPanePos:function(){return o.DomUtil.getPosition(this._mapPane)},_moved:function(){var t=this._getMapPanePos();return t&&!t.equals([0,0])},_getTopLeftPoint:function(){return this.getPixelOrigin().subtract(this._getMapPanePos())},_getNewTopLeftPoint:function(t,e){var i=this.getSize()._divideBy(2);return this.project(t,e)._subtract(i)._round()},_latLngToNewLayerPoint:function(t,e,i){var n=this._getNewTopLeftPoint(i,e).add(this._getMapPanePos());return this.project(t,e)._subtract(n)},_getCenterLayerPoint:function(){return this.containerPointToLayerPoint(this.getSize()._divideBy(2))},_getCenterOffset:function(t){return this.latLngToLayerPoint(t).subtract(this._getCenterLayerPoint())},_limitCenter:function(t,e,i){if(!i)return t;var n=this.project(t,e),s=this.getSize().divideBy(2),a=new o.Bounds(n.subtract(s),n.add(s)),r=this._getBoundsOffset(a,i,e);return this.unproject(n.add(r),e)},_limitOffset:function(t,e){if(!e)return t;var i=this.getPixelBounds(),n=new o.Bounds(i.min.add(t),i.max.add(t));return t.add(this._getBoundsOffset(n,e))},_getBoundsOffset:function(t,e,i){var n=this.project(e.getNorthWest(),i).subtract(t.min),s=this.project(e.getSouthEast(),i).subtract(t.max),a=this._rebound(n.x,-s.x),r=this._rebound(n.y,-s.y);return new o.Point(a,r)},_rebound:function(t,e){return t+e>0?Math.round(t-e)/2:Math.max(0,Math.ceil(t))-Math.max(0,Math.floor(e))},_limitZoom:function(t){var e=this.getMinZoom(),i=this.getMaxZoom();return Math.max(e,Math.min(i,t))}}),o.map=function(t,e){return new o.Map(t,e)},o.Projection.Mercator={MAX_LATITUDE:85.0840591556,R_MINOR:6356752.314245179,R_MAJOR:6378137,project:function(t){var e=o.LatLng.DEG_TO_RAD,i=this.MAX_LATITUDE,n=Math.max(Math.min(i,t.lat),-i),s=this.R_MAJOR,a=this.R_MINOR,r=t.lng*e*s,h=n*e,l=a/s,u=Math.sqrt(1-l*l),c=u*Math.sin(h);c=Math.pow((1-c)/(1+c),.5*u);var d=Math.tan(.5*(.5*Math.PI-h))/c;return h=-s*Math.log(d),new o.Point(r,h)},unproject:function(t){for(var e,i=o.LatLng.RAD_TO_DEG,n=this.R_MAJOR,s=this.R_MINOR,a=t.x*i/n,r=s/n,h=Math.sqrt(1-r*r),l=Math.exp(-t.y/n),u=Math.PI/2-2*Math.atan(l),p=15,_=.1;Math.abs(_)>1e-7&&--p>0;)e=h*Math.sin(u),u+=_=Math.PI/2-2*Math.atan(l*Math.pow((1-e)/(1+e),.5*h))-u;return new o.LatLng(u*i,a)}},o.CRS.EPSG3395=o.extend({},o.CRS,{code:"EPSG:3395",projection:o.Projection.Mercator,transformation:function(){var e=o.Projection.Mercator.R_MAJOR,i=.5/(Math.PI*e);return new o.Transformation(i,.5,-i,.5)}()}),o.TileLayer=o.Class.extend({includes:o.Mixin.Events,options:{minZoom:0,maxZoom:18,tileSize:256,subdomains:"abc",errorTileUrl:"",attribution:"",zoomOffset:0,opacity:1,unloadInvisibleTiles:o.Browser.mobile,updateWhenIdle:o.Browser.mobile},initialize:function(t,e){(e=o.setOptions(this,e)).detectRetina&&o.Browser.retina&&e.maxZoom>0&&(e.tileSize=Math.floor(e.tileSize/2),e.zoomOffset++,e.minZoom>0&&e.minZoom--,this.options.maxZoom--),e.bounds&&(e.bounds=o.latLngBounds(e.bounds)),this._url=t;var i=this.options.subdomains;"string"==typeof i&&(this.options.subdomains=i.split(""))},onAdd:function(t){this._map=t,this._animated=t._zoomAnimated,this._initContainer(),t.on({viewreset:this._reset,moveend:this._update},this),this._animated&&t.on({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||(this._limitedUpdate=o.Util.limitExecByInterval(this._update,150,this),t.on("move",this._limitedUpdate,this)),this._reset(),this._update()},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this._container.parentNode.removeChild(this._container),t.off({viewreset:this._reset,moveend:this._update},this),this._animated&&t.off({zoomanim:this._animateZoom,zoomend:this._endZoomAnim},this),this.options.updateWhenIdle||t.off("move",this._limitedUpdate,this),this._container=null,this._map=null},bringToFront:function(){var t=this._map._panes.tilePane;return this._container&&(t.appendChild(this._container),this._setAutoZIndex(t,Math.max)),this},bringToBack:function(){var t=this._map._panes.tilePane;return this._container&&(t.insertBefore(this._container,t.firstChild),this._setAutoZIndex(t,Math.min)),this},getAttribution:function(){return this.options.attribution},getContainer:function(){return this._container},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},setZIndex:function(t){return this.options.zIndex=t,this._updateZIndex(),this},setUrl:function(t,e){return this._url=t,e||this.redraw(),this},redraw:function(){return this._map&&(this._reset({hard:!0}),this._update()),this},_updateZIndex:function(){this._container&&this.options.zIndex!==i&&(this._container.style.zIndex=this.options.zIndex)},_setAutoZIndex:function(t,e){var i,n,o,s=t.children,a=-e(1/0,-1/0);for(n=0,o=s.length;o>n;n++)s[n]!==this._container&&(i=parseInt(s[n].style.zIndex,10),isNaN(i)||(a=e(a,i)));this.options.zIndex=this._container.style.zIndex=(isFinite(a)?a:0)+e(1,-1)},_updateOpacity:function(){var t,e=this._tiles;if(o.Browser.ielt9)for(t in e)o.DomUtil.setOpacity(e[t],this.options.opacity);else o.DomUtil.setOpacity(this._container,this.options.opacity)},_initContainer:function(){var t=this._map._panes.tilePane;if(!this._container){if(this._container=o.DomUtil.create("div","leaflet-layer"),this._updateZIndex(),this._animated){var e="leaflet-tile-container";this._bgBuffer=o.DomUtil.create("div",e,this._container),this._tileContainer=o.DomUtil.create("div",e,this._container)}else this._tileContainer=this._container;t.appendChild(this._container),this.options.opacity<1&&this._updateOpacity()}},_reset:function(t){for(var e in this._tiles)this.fire("tileunload",{tile:this._tiles[e]});this._tiles={},this._tilesToLoad=0,this.options.reuseTiles&&(this._unusedTiles=[]),this._tileContainer.innerHTML="",this._animated&&t&&t.hard&&this._clearBgBuffer(),this._initContainer()},_getTileSize:function(){var t=this._map,e=t.getZoom()+this.options.zoomOffset,i=this.options.maxNativeZoom,n=this.options.tileSize;return i&&e>i&&(n=Math.round(t.getZoomScale(e)/t.getZoomScale(i)*n)),n},_update:function(){if(this._map){var t=this._map,e=t.getPixelBounds(),i=t.getZoom(),n=this._getTileSize();if(!(i>this.options.maxZoom||i<this.options.minZoom)){var s=o.bounds(e.min.divideBy(n)._floor(),e.max.divideBy(n)._floor());this._addTilesFromCenterOut(s),(this.options.unloadInvisibleTiles||this.options.reuseTiles)&&this._removeOtherTiles(s)}}},_addTilesFromCenterOut:function(t){var i,n,s,a=[],r=t.getCenter();for(i=t.min.y;i<=t.max.y;i++)for(n=t.min.x;n<=t.max.x;n++)s=new o.Point(n,i),this._tileShouldBeLoaded(s)&&a.push(s);var h=a.length;if(0!==h){a.sort(function(t,e){return t.distanceTo(r)-e.distanceTo(r)});var l=e.createDocumentFragment();for(this._tilesToLoad||this.fire("loading"),this._tilesToLoad+=h,n=0;h>n;n++)this._addTile(a[n],l);this._tileContainer.appendChild(l)}},_tileShouldBeLoaded:function(t){if(t.x+":"+t.y in this._tiles)return!1;var e=this.options;if(!e.continuousWorld){var i=this._getWrapTileNum();if(e.noWrap&&(t.x<0||t.x>=i.x)||t.y<0||t.y>=i.y)return!1}if(e.bounds){var n=e.tileSize,o=t.multiplyBy(n),s=o.add([n,n]),a=this._map.unproject(o),r=this._map.unproject(s);if(e.continuousWorld||e.noWrap||(a=a.wrap(),r=r.wrap()),!e.bounds.intersects([a,r]))return!1}return!0},_removeOtherTiles:function(t){var e,i,n,o;for(o in this._tiles)e=o.split(":"),i=parseInt(e[0],10),n=parseInt(e[1],10),(i<t.min.x||i>t.max.x||n<t.min.y||n>t.max.y)&&this._removeTile(o)},_removeTile:function(t){var e=this._tiles[t];this.fire("tileunload",{tile:e,url:e.src}),this.options.reuseTiles?(o.DomUtil.removeClass(e,"leaflet-tile-loaded"),this._unusedTiles.push(e)):e.parentNode===this._tileContainer&&this._tileContainer.removeChild(e),o.Browser.android||(e.onload=null,e.src=o.Util.emptyImageUrl),delete this._tiles[t]},_addTile:function(t,e){var i=this._getTilePos(t),n=this._getTile();o.DomUtil.setPosition(n,i,o.Browser.chrome),this._tiles[t.x+":"+t.y]=n,this._loadTile(n,t),n.parentNode!==this._tileContainer&&e.appendChild(n)},_getZoomForUrl:function(){var t=this.options,e=this._map.getZoom();return t.zoomReverse&&(e=t.maxZoom-e),e+=t.zoomOffset,t.maxNativeZoom?Math.min(e,t.maxNativeZoom):e},_getTilePos:function(t){var e=this._map.getPixelOrigin(),i=this._getTileSize();return t.multiplyBy(i).subtract(e)},getTileUrl:function(t){return o.Util.template(this._url,o.extend({s:this._getSubdomain(t),z:t.z,x:t.x,y:t.y},this.options))},_getWrapTileNum:function(){return this._map.options.crs.getSize(this._map.getZoom()).divideBy(this._getTileSize())._floor()},_adjustTilePoint:function(t){var e=this._getWrapTileNum();this.options.continuousWorld||this.options.noWrap||(t.x=(t.x%e.x+e.x)%e.x),this.options.tms&&(t.y=e.y-t.y-1),t.z=this._getZoomForUrl()},_getSubdomain:function(t){var e=Math.abs(t.x+t.y)%this.options.subdomains.length;return this.options.subdomains[e]},_getTile:function(){if(this.options.reuseTiles&&this._unusedTiles.length>0){var t=this._unusedTiles.pop();return this._resetTile(t),t}return this._createTile()},_resetTile:function(){},_createTile:function(){var t=o.DomUtil.create("img","leaflet-tile");return t.style.width=t.style.height=this._getTileSize()+"px",t.galleryimg="no",t.onselectstart=t.onmousemove=o.Util.falseFn,o.Browser.ielt9&&this.options.opacity!==i&&o.DomUtil.setOpacity(t,this.options.opacity),o.Browser.mobileWebkit3d&&(t.style.WebkitBackfaceVisibility="hidden"),t},_loadTile:function(t,e){t._layer=this,t.onload=this._tileOnLoad,t.onerror=this._tileOnError,this._adjustTilePoint(e),t.src=this.getTileUrl(e),this.fire("tileloadstart",{tile:t,url:t.src})},_tileLoaded:function(){this._tilesToLoad--,this._animated&&o.DomUtil.addClass(this._tileContainer,"leaflet-zoom-animated"),this._tilesToLoad||(this.fire("load"),this._animated&&(clearTimeout(this._clearBgBufferTimer),this._clearBgBufferTimer=setTimeout(o.bind(this._clearBgBuffer,this),500)))},_tileOnLoad:function(){var t=this._layer;this.src!==o.Util.emptyImageUrl&&(o.DomUtil.addClass(this,"leaflet-tile-loaded"),t.fire("tileload",{tile:this,url:this.src})),t._tileLoaded()},_tileOnError:function(){var t=this._layer;t.fire("tileerror",{tile:this,url:this.src});var e=t.options.errorTileUrl;e&&(this.src=e),t._tileLoaded()}}),o.tileLayer=function(t,e){return new o.TileLayer(t,e)},o.TileLayer.WMS=o.TileLayer.extend({defaultWmsParams:{service:"WMS",request:"GetMap",version:"1.1.1",layers:"",styles:"",format:"image/jpeg",transparent:!1},initialize:function(t,e){this._url=t;var i=o.extend({},this.defaultWmsParams),n=e.tileSize||this.options.tileSize;for(var s in i.width=i.height=e.detectRetina&&o.Browser.retina?2*n:n,e)this.options.hasOwnProperty(s)||"crs"===s||(i[s]=e[s]);this.wmsParams=i,o.setOptions(this,e)},onAdd:function(t){this._crs=this.options.crs||t.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var e=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[e]=this._crs.code,o.TileLayer.prototype.onAdd.call(this,t)},getTileUrl:function(t){var e=this._map,i=this.options.tileSize,n=t.multiplyBy(i),s=n.add([i,i]),a=this._crs.project(e.unproject(n,t.z)),r=this._crs.project(e.unproject(s,t.z)),h=this._wmsVersion>=1.3&&this._crs===o.CRS.EPSG4326?[r.y,a.x,a.y,r.x].join(","):[a.x,r.y,r.x,a.y].join(","),l=o.Util.template(this._url,{s:this._getSubdomain(t)});return l+o.Util.getParamString(this.wmsParams,l,!0)+"&BBOX="+h},setParams:function(t,e){return o.extend(this.wmsParams,t),e||this.redraw(),this}}),o.tileLayer.wms=function(t,e){return new o.TileLayer.WMS(t,e)},o.TileLayer.Canvas=o.TileLayer.extend({options:{async:!1},initialize:function(t){o.setOptions(this,t)},redraw:function(){for(var t in this._map&&(this._reset({hard:!0}),this._update()),this._tiles)this._redrawTile(this._tiles[t]);return this},_redrawTile:function(t){this.drawTile(t,t._tilePoint,this._map._zoom)},_createTile:function(){var t=o.DomUtil.create("canvas","leaflet-tile");return t.width=t.height=this.options.tileSize,t.onselectstart=t.onmousemove=o.Util.falseFn,t},_loadTile:function(t,e){t._layer=this,t._tilePoint=e,this._redrawTile(t),this.options.async||this.tileDrawn(t)},drawTile:function(){},tileDrawn:function(t){this._tileOnLoad.call(t)}}),o.tileLayer.canvas=function(t){return new o.TileLayer.Canvas(t)},o.ImageOverlay=o.Class.extend({includes:o.Mixin.Events,options:{opacity:1},initialize:function(t,e,i){this._url=t,this._bounds=o.latLngBounds(e),o.setOptions(this,i)},onAdd:function(t){this._map=t,this._image||this._initImage(),t._panes.overlayPane.appendChild(this._image),t.on("viewreset",this._reset,this),t.options.zoomAnimation&&o.Browser.any3d&&t.on("zoomanim",this._animateZoom,this),this._reset()},onRemove:function(t){t.getPanes().overlayPane.removeChild(this._image),t.off("viewreset",this._reset,this),t.options.zoomAnimation&&t.off("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},setOpacity:function(t){return this.options.opacity=t,this._updateOpacity(),this},bringToFront:function(){return this._image&&this._map._panes.overlayPane.appendChild(this._image),this},bringToBack:function(){var t=this._map._panes.overlayPane;return this._image&&t.insertBefore(this._image,t.firstChild),this},setUrl:function(t){this._url=t,this._image.src=this._url},getAttribution:function(){return this.options.attribution},_initImage:function(){this._image=o.DomUtil.create("img","leaflet-image-layer"),this._map.options.zoomAnimation&&o.Browser.any3d?o.DomUtil.addClass(this._image,"leaflet-zoom-animated"):o.DomUtil.addClass(this._image,"leaflet-zoom-hide"),this._updateOpacity(),o.extend(this._image,{galleryimg:"no",onselectstart:o.Util.falseFn,onmousemove:o.Util.falseFn,onload:o.bind(this._onImageLoad,this),src:this._url})},_animateZoom:function(t){var e=this._map,i=this._image,n=e.getZoomScale(t.zoom),s=this._bounds.getNorthWest(),a=this._bounds.getSouthEast(),r=e._latLngToNewLayerPoint(s,t.zoom,t.center),h=e._latLngToNewLayerPoint(a,t.zoom,t.center)._subtract(r),l=r._add(h._multiplyBy(.5*(1-1/n)));i.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(l)+" scale("+n+") "},_reset:function(){var t=this._image,e=this._map.latLngToLayerPoint(this._bounds.getNorthWest()),i=this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(e);o.DomUtil.setPosition(t,e),t.style.width=i.x+"px",t.style.height=i.y+"px"},_onImageLoad:function(){this.fire("load")},_updateOpacity:function(){o.DomUtil.setOpacity(this._image,this.options.opacity)}}),o.imageOverlay=function(t,e,i){return new o.ImageOverlay(t,e,i)},o.Icon=o.Class.extend({options:{className:""},initialize:function(t){o.setOptions(this,t)},createIcon:function(t){return this._createIcon("icon",t)},createShadow:function(t){return this._createIcon("shadow",t)},_createIcon:function(t,e){var n,i=this._getIconUrl(t);if(!i){if("icon"===t)throw new Error("iconUrl not set in Icon options (see the docs).");return null}return n=e&&"IMG"===e.tagName?this._createImg(i,e):this._createImg(i),this._setIconStyles(n,t),n},_setIconStyles:function(t,e){var i,n=this.options,s=o.point(n[e+"Size"]);!(i=o.point("shadow"===e&&n.shadowAnchor||n.iconAnchor))&&s&&(i=s.divideBy(2,!0)),t.className="leaflet-marker-"+e+" "+n.className,i&&(t.style.marginLeft=-i.x+"px",t.style.marginTop=-i.y+"px"),s&&(t.style.width=s.x+"px",t.style.height=s.y+"px")},_createImg:function(t,i){return(i=i||e.createElement("img")).src=t,i},_getIconUrl:function(t){return o.Browser.retina&&this.options[t+"RetinaUrl"]?this.options[t+"RetinaUrl"]:this.options[t+"Url"]}}),o.icon=function(t){return new o.Icon(t)},o.Icon.Default=o.Icon.extend({options:{iconSize:[25,41],iconAnchor:[12,41],popupAnchor:[1,-34],shadowSize:[41,41]},_getIconUrl:function(t){var e=t+"Url";if(this.options[e])return this.options[e];o.Browser.retina&&"icon"===t&&(t+="-2x");var i=o.Icon.Default.imagePath;if(!i)throw new Error("Couldn't autodetect L.Icon.Default.imagePath, set it manually.");return i+"/marker-"+t+".png"}}),o.Icon.Default.imagePath=function(){var t,i,n,s,a=e.getElementsByTagName("script"),r=/[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;for(t=0,i=a.length;i>t;t++)if((n=a[t].src).match(r))return((s=n.split(r)[0])?s+"/":"")+"images"}(),o.Marker=o.Class.extend({includes:o.Mixin.Events,options:{icon:new o.Icon.Default,title:"",alt:"",clickable:!0,draggable:!1,keyboard:!0,zIndexOffset:0,opacity:1,riseOnHover:!1,riseOffset:250},initialize:function(t,e){o.setOptions(this,e),this._latlng=o.latLng(t)},onAdd:function(t){this._map=t,t.on("viewreset",this.update,this),this._initIcon(),this.update(),this.fire("add"),t.options.zoomAnimation&&t.options.markerZoomAnimation&&t.on("zoomanim",this._animateZoom,this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){this.dragging&&this.dragging.disable(),this._removeIcon(),this._removeShadow(),this.fire("remove"),t.off({viewreset:this.update,zoomanim:this._animateZoom},this),this._map=null},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=o.latLng(t),this.update(),this.fire("move",{latlng:this._latlng})},setZIndexOffset:function(t){return this.options.zIndexOffset=t,this.update(),this},setIcon:function(t){return this.options.icon=t,this._map&&(this._initIcon(),this.update()),this._popup&&this.bindPopup(this._popup),this},update:function(){if(this._icon){var t=this._map.latLngToLayerPoint(this._latlng).round();this._setPos(t)}return this},_initIcon:function(){var t=this.options,e=this._map,n=e.options.zoomAnimation&&e.options.markerZoomAnimation?"leaflet-zoom-animated":"leaflet-zoom-hide",s=t.icon.createIcon(this._icon),a=!1;s!==this._icon&&(this._icon&&this._removeIcon(),a=!0,t.title&&(s.title=t.title),t.alt&&(s.alt=t.alt)),o.DomUtil.addClass(s,n),t.keyboard&&(s.tabIndex="0"),this._icon=s,this._initInteraction(),t.riseOnHover&&o.DomEvent.on(s,"mouseover",this._bringToFront,this).on(s,"mouseout",this._resetZIndex,this);var r=t.icon.createShadow(this._shadow),h=!1;r!==this._shadow&&(this._removeShadow(),h=!0),r&&o.DomUtil.addClass(r,n),this._shadow=r,t.opacity<1&&this._updateOpacity();var l=this._map._panes;a&&l.markerPane.appendChild(this._icon),r&&h&&l.shadowPane.appendChild(this._shadow)},_removeIcon:function(){this.options.riseOnHover&&o.DomEvent.off(this._icon,"mouseover",this._bringToFront).off(this._icon,"mouseout",this._resetZIndex),this._map._panes.markerPane.removeChild(this._icon),this._icon=null},_removeShadow:function(){this._shadow&&this._map._panes.shadowPane.removeChild(this._shadow),this._shadow=null},_setPos:function(t){o.DomUtil.setPosition(this._icon,t),this._shadow&&o.DomUtil.setPosition(this._shadow,t),this._zIndex=t.y+this.options.zIndexOffset,this._resetZIndex()},_updateZIndex:function(t){this._icon.style.zIndex=this._zIndex+t},_animateZoom:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center).round();this._setPos(e)},_initInteraction:function(){if(this.options.clickable){var t=this._icon,e=["dblclick","mousedown","mouseover","mouseout","contextmenu"];o.DomUtil.addClass(t,"leaflet-clickable"),o.DomEvent.on(t,"click",this._onMouseClick,this),o.DomEvent.on(t,"keypress",this._onKeyPress,this);for(var i=0;i<e.length;i++)o.DomEvent.on(t,e[i],this._fireMouseEvent,this);o.Handler.MarkerDrag&&(this.dragging=new o.Handler.MarkerDrag(this),this.options.draggable&&this.dragging.enable())}},_onMouseClick:function(t){var e=this.dragging&&this.dragging.moved();(this.hasEventListeners(t.type)||e)&&o.DomEvent.stopPropagation(t),e||(this.dragging&&this.dragging._enabled||!this._map.dragging||!this._map.dragging.moved())&&this.fire(t.type,{originalEvent:t,latlng:this._latlng})},_onKeyPress:function(t){13===t.keyCode&&this.fire("click",{originalEvent:t,latlng:this._latlng})},_fireMouseEvent:function(t){this.fire(t.type,{originalEvent:t,latlng:this._latlng}),"contextmenu"===t.type&&this.hasEventListeners(t.type)&&o.DomEvent.preventDefault(t),"mousedown"!==t.type?o.DomEvent.stopPropagation(t):o.DomEvent.preventDefault(t)},setOpacity:function(t){return this.options.opacity=t,this._map&&this._updateOpacity(),this},_updateOpacity:function(){o.DomUtil.setOpacity(this._icon,this.options.opacity),this._shadow&&o.DomUtil.setOpacity(this._shadow,this.options.opacity)},_bringToFront:function(){this._updateZIndex(this.options.riseOffset)},_resetZIndex:function(){this._updateZIndex(0)}}),o.marker=function(t,e){return new o.Marker(t,e)},o.DivIcon=o.Icon.extend({options:{iconSize:[12,12],className:"leaflet-div-icon",html:!1},createIcon:function(t){var i=t&&"DIV"===t.tagName?t:e.createElement("div"),n=this.options;return i.innerHTML=!1!==n.html?n.html:"",n.bgPos&&(i.style.backgroundPosition=-n.bgPos.x+"px "+-n.bgPos.y+"px"),this._setIconStyles(i,"icon"),i},createShadow:function(){return null}}),o.divIcon=function(t){return new o.DivIcon(t)},o.Map.mergeOptions({closePopupOnClick:!0}),o.Popup=o.Class.extend({includes:o.Mixin.Events,options:{minWidth:50,maxWidth:300,autoPan:!0,closeButton:!0,offset:[0,7],autoPanPadding:[5,5],keepInView:!1,className:"",zoomAnimation:!0},initialize:function(t,e){o.setOptions(this,t),this._source=e,this._animated=o.Browser.any3d&&this.options.zoomAnimation,this._isOpen=!1},onAdd:function(t){this._map=t,this._container||this._initLayout();var e=t.options.fadeAnimation;e&&o.DomUtil.setOpacity(this._container,0),t._panes.popupPane.appendChild(this._container),t.on(this._getEvents(),this),this.update(),e&&o.DomUtil.setOpacity(this._container,1),this.fire("open"),t.fire("popupopen",{popup:this}),this._source&&this._source.fire("popupopen",{popup:this})},addTo:function(t){return t.addLayer(this),this},openOn:function(t){return t.openPopup(this),this},onRemove:function(t){t._panes.popupPane.removeChild(this._container),o.Util.falseFn(this._container.offsetWidth),t.off(this._getEvents(),this),t.options.fadeAnimation&&o.DomUtil.setOpacity(this._container,0),this._map=null,this.fire("close"),t.fire("popupclose",{popup:this}),this._source&&this._source.fire("popupclose",{popup:this})},getLatLng:function(){return this._latlng},setLatLng:function(t){return this._latlng=o.latLng(t),this._map&&(this._updatePosition(),this._adjustPan()),this},getContent:function(){return this._content},setContent:function(t){return this._content=t,this.update(),this},update:function(){this._map&&(this._container.style.visibility="hidden",this._updateContent(),this._updateLayout(),this._updatePosition(),this._container.style.visibility="",this._adjustPan())},_getEvents:function(){var t={viewreset:this._updatePosition};return this._animated&&(t.zoomanim=this._zoomAnimation),("closeOnClick"in this.options?this.options.closeOnClick:this._map.options.closePopupOnClick)&&(t.preclick=this._close),this.options.keepInView&&(t.moveend=this._adjustPan),t},_close:function(){this._map&&this._map.closePopup(this)},_initLayout:function(){var t,e="leaflet-popup",i=e+" "+this.options.className+" leaflet-zoom-"+(this._animated?"animated":"hide"),n=this._container=o.DomUtil.create("div",i);this.options.closeButton&&((t=this._closeButton=o.DomUtil.create("a",e+"-close-button",n)).href="#close",t.innerHTML="&#215;",o.DomEvent.disableClickPropagation(t),o.DomEvent.on(t,"click",this._onCloseButtonClick,this));var s=this._wrapper=o.DomUtil.create("div",e+"-content-wrapper",n);o.DomEvent.disableClickPropagation(s),this._contentNode=o.DomUtil.create("div",e+"-content",s),o.DomEvent.disableScrollPropagation(this._contentNode),o.DomEvent.on(s,"contextmenu",o.DomEvent.stopPropagation),this._tipContainer=o.DomUtil.create("div",e+"-tip-container",n),this._tip=o.DomUtil.create("div",e+"-tip",this._tipContainer)},_updateContent:function(){if(this._content){if("string"==typeof this._content)this._contentNode.innerHTML=this._content;else{for(;this._contentNode.hasChildNodes();)this._contentNode.removeChild(this._contentNode.firstChild);this._contentNode.appendChild(this._content)}this.fire("contentupdate")}},_updateLayout:function(){var t=this._contentNode,e=t.style;e.width="",e.whiteSpace="nowrap";var i=t.offsetWidth;i=Math.min(i,this.options.maxWidth),i=Math.max(i,this.options.minWidth),e.width=i+1+"px",e.whiteSpace="",e.height="";var n=t.offsetHeight,s=this.options.maxHeight,a="leaflet-popup-scrolled";s&&n>s?(e.height=s+"px",o.DomUtil.addClass(t,a)):o.DomUtil.removeClass(t,a),this._containerWidth=this._container.offsetWidth},_updatePosition:function(){if(this._map){var t=this._map.latLngToLayerPoint(this._latlng),e=this._animated,i=o.point(this.options.offset);e&&o.DomUtil.setPosition(this._container,t),this._containerBottom=-i.y-(e?0:t.y),this._containerLeft=-Math.round(this._containerWidth/2)+i.x+(e?0:t.x),this._container.style.bottom=this._containerBottom+"px",this._container.style.left=this._containerLeft+"px"}},_zoomAnimation:function(t){var e=this._map._latLngToNewLayerPoint(this._latlng,t.zoom,t.center);o.DomUtil.setPosition(this._container,e)},_adjustPan:function(){if(this.options.autoPan){var t=this._map,e=this._container.offsetHeight,i=this._containerWidth,n=new o.Point(this._containerLeft,-e-this._containerBottom);this._animated&&n._add(o.DomUtil.getPosition(this._container));var s=t.layerPointToContainerPoint(n),a=o.point(this.options.autoPanPadding),r=o.point(this.options.autoPanPaddingTopLeft||a),h=o.point(this.options.autoPanPaddingBottomRight||a),l=t.getSize(),u=0,c=0;s.x+i+h.x>l.x&&(u=s.x+i-l.x+h.x),s.x-u-r.x<0&&(u=s.x-r.x),s.y+e+h.y>l.y&&(c=s.y+e-l.y+h.y),s.y-c-r.y<0&&(c=s.y-r.y),(u||c)&&t.fire("autopanstart").panBy([u,c])}},_onCloseButtonClick:function(t){this._close(),o.DomEvent.stop(t)}}),o.popup=function(t,e){return new o.Popup(t,e)},o.Map.include({openPopup:function(t,e,i){if(this.closePopup(),!(t instanceof o.Popup)){var n=t;t=new o.Popup(i).setLatLng(e).setContent(n)}return t._isOpen=!0,this._popup=t,this.addLayer(t)},closePopup:function(t){return t&&t!==this._popup||(t=this._popup,this._popup=null),t&&(this.removeLayer(t),t._isOpen=!1),this}}),o.Marker.include({openPopup:function(){return this._popup&&this._map&&!this._map.hasLayer(this._popup)&&(this._popup.setLatLng(this._latlng),this._map.openPopup(this._popup)),this},closePopup:function(){return this._popup&&this._popup._close(),this},togglePopup:function(){return this._popup&&(this._popup._isOpen?this.closePopup():this.openPopup()),this},bindPopup:function(t,e){var i=o.point(this.options.icon.options.popupAnchor||[0,0]);return i=i.add(o.Popup.prototype.options.offset),e&&e.offset&&(i=i.add(e.offset)),e=o.extend({offset:i},e),this._popupHandlersAdded||(this.on("click",this.togglePopup,this).on("remove",this.closePopup,this).on("move",this._movePopup,this),this._popupHandlersAdded=!0),t instanceof o.Popup?(o.setOptions(t,e),this._popup=t):this._popup=new o.Popup(e,this).setContent(t),this},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this.togglePopup,this).off("remove",this.closePopup,this).off("move",this._movePopup,this),this._popupHandlersAdded=!1),this},getPopup:function(){return this._popup},_movePopup:function(t){this._popup.setLatLng(t.latlng)}}),o.LayerGroup=o.Class.extend({initialize:function(t){var e,i;if(this._layers={},t)for(e=0,i=t.length;i>e;e++)this.addLayer(t[e])},addLayer:function(t){var e=this.getLayerId(t);return this._layers[e]=t,this._map&&this._map.addLayer(t),this},removeLayer:function(t){var e=t in this._layers?t:this.getLayerId(t);return this._map&&this._layers[e]&&this._map.removeLayer(this._layers[e]),delete this._layers[e],this},hasLayer:function(t){return!!t&&(t in this._layers||this.getLayerId(t)in this._layers)},clearLayers:function(){return this.eachLayer(this.removeLayer,this),this},invoke:function(t){var e,i,n=Array.prototype.slice.call(arguments,1);for(e in this._layers)(i=this._layers[e])[t]&&i[t].apply(i,n);return this},onAdd:function(t){this._map=t,this.eachLayer(t.addLayer,t)},onRemove:function(t){this.eachLayer(t.removeLayer,t),this._map=null},addTo:function(t){return t.addLayer(this),this},eachLayer:function(t,e){for(var i in this._layers)t.call(e,this._layers[i]);return this},getLayer:function(t){return this._layers[t]},getLayers:function(){var t=[];for(var e in this._layers)t.push(this._layers[e]);return t},setZIndex:function(t){return this.invoke("setZIndex",t)},getLayerId:function(t){return o.stamp(t)}}),o.layerGroup=function(t){return new o.LayerGroup(t)},o.FeatureGroup=o.LayerGroup.extend({includes:o.Mixin.Events,statics:{EVENTS:"click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose"},addLayer:function(t){return this.hasLayer(t)?this:("on"in t&&t.on(o.FeatureGroup.EVENTS,this._propagateEvent,this),o.LayerGroup.prototype.addLayer.call(this,t),this._popupContent&&t.bindPopup&&t.bindPopup(this._popupContent,this._popupOptions),this.fire("layeradd",{layer:t}))},removeLayer:function(t){return this.hasLayer(t)?(t in this._layers&&(t=this._layers[t]),t.off(o.FeatureGroup.EVENTS,this._propagateEvent,this),o.LayerGroup.prototype.removeLayer.call(this,t),this._popupContent&&this.invoke("unbindPopup"),this.fire("layerremove",{layer:t})):this},bindPopup:function(t,e){return this._popupContent=t,this._popupOptions=e,this.invoke("bindPopup",t,e)},openPopup:function(t){for(var e in this._layers){this._layers[e].openPopup(t);break}return this},setStyle:function(t){return this.invoke("setStyle",t)},bringToFront:function(){return this.invoke("bringToFront")},bringToBack:function(){return this.invoke("bringToBack")},getBounds:function(){var t=new o.LatLngBounds;return this.eachLayer(function(e){t.extend(e instanceof o.Marker?e.getLatLng():e.getBounds())}),t},_propagateEvent:function(t){t=o.extend({layer:t.target,target:this},t),this.fire(t.type,t)}}),o.featureGroup=function(t){return new o.FeatureGroup(t)},o.Path=o.Class.extend({includes:[o.Mixin.Events],statics:{CLIP_PADDING:function(){var i=((o.Browser.mobile?1280:2e3)/Math.max(t.outerWidth,t.outerHeight)-1)/2;return Math.max(0,Math.min(.5,i))}()},options:{stroke:!0,color:"#0033ff",dashArray:null,lineCap:null,lineJoin:null,weight:5,opacity:.5,fill:!1,fillColor:null,fillOpacity:.2,clickable:!0},initialize:function(t){o.setOptions(this,t)},onAdd:function(t){this._map=t,this._container||(this._initElements(),this._initEvents()),this.projectLatlngs(),this._updatePath(),this._container&&this._map._pathRoot.appendChild(this._container),this.fire("add"),t.on({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},addTo:function(t){return t.addLayer(this),this},onRemove:function(t){t._pathRoot.removeChild(this._container),this.fire("remove"),this._map=null,o.Browser.vml&&(this._container=null,this._stroke=null,this._fill=null),t.off({viewreset:this.projectLatlngs,moveend:this._updatePath},this)},projectLatlngs:function(){},setStyle:function(t){return o.setOptions(this,t),this._container&&this._updateStyle(),this},redraw:function(){return this._map&&(this.projectLatlngs(),this._updatePath()),this}}),o.Map.include({_updatePathViewport:function(){var t=o.Path.CLIP_PADDING,e=this.getSize(),n=o.DomUtil.getPosition(this._mapPane).multiplyBy(-1)._subtract(e.multiplyBy(t)._round()),s=n.add(e.multiplyBy(1+2*t)._round());this._pathViewport=new o.Bounds(n,s)}}),o.Path.SVG_NS="http://www.w3.org/2000/svg",o.Browser.svg=!(!e.createElementNS||!e.createElementNS(o.Path.SVG_NS,"svg").createSVGRect),o.Path=o.Path.extend({statics:{SVG:o.Browser.svg},bringToFront:function(){var t=this._map._pathRoot,e=this._container;return e&&t.lastChild!==e&&t.appendChild(e),this},bringToBack:function(){var t=this._map._pathRoot,e=this._container,i=t.firstChild;return e&&i!==e&&t.insertBefore(e,i),this},getPathString:function(){},_createElement:function(t){return e.createElementNS(o.Path.SVG_NS,t)},_initElements:function(){this._map._initPathRoot(),this._initPath(),this._initStyle()},_initPath:function(){this._container=this._createElement("g"),this._path=this._createElement("path"),this.options.className&&o.DomUtil.addClass(this._path,this.options.className),this._container.appendChild(this._path)},_initStyle:function(){this.options.stroke&&(this._path.setAttribute("stroke-linejoin","round"),this._path.setAttribute("stroke-linecap","round")),this.options.fill&&this._path.setAttribute("fill-rule","evenodd"),this.options.pointerEvents&&this._path.setAttribute("pointer-events",this.options.pointerEvents),this.options.clickable||this.options.pointerEvents||this._path.setAttribute("pointer-events","none"),this._updateStyle()},_updateStyle:function(){this.options.stroke?(this._path.setAttribute("stroke",this.options.color),this._path.setAttribute("stroke-opacity",this.options.opacity),this._path.setAttribute("stroke-width",this.options.weight),this.options.dashArray?this._path.setAttribute("stroke-dasharray",this.options.dashArray):this._path.removeAttribute("stroke-dasharray"),this.options.lineCap&&this._path.setAttribute("stroke-linecap",this.options.lineCap),this.options.lineJoin&&this._path.setAttribute("stroke-linejoin",this.options.lineJoin)):this._path.setAttribute("stroke","none"),this.options.fill?(this._path.setAttribute("fill",this.options.fillColor||this.options.color),this._path.setAttribute("fill-opacity",this.options.fillOpacity)):this._path.setAttribute("fill","none")},_updatePath:function(){var t=this.getPathString();t||(t="M0 0"),this._path.setAttribute("d",t)},_initEvents:function(){if(this.options.clickable){(o.Browser.svg||!o.Browser.vml)&&o.DomUtil.addClass(this._path,"leaflet-clickable"),o.DomEvent.on(this._container,"click",this._onMouseClick,this);for(var t=["dblclick","mousedown","mouseover","mouseout","mousemove","contextmenu"],e=0;e<t.length;e++)o.DomEvent.on(this._container,t[e],this._fireMouseEvent,this)}},_onMouseClick:function(t){this._map.dragging&&this._map.dragging.moved()||this._fireMouseEvent(t)},_fireMouseEvent:function(t){if(this.hasEventListeners(t.type)){var e=this._map,i=e.mouseEventToContainerPoint(t),n=e.containerPointToLayerPoint(i),s=e.layerPointToLatLng(n);this.fire(t.type,{latlng:s,layerPoint:n,containerPoint:i,originalEvent:t}),"contextmenu"===t.type&&o.DomEvent.preventDefault(t),"mousemove"!==t.type&&o.DomEvent.stopPropagation(t)}}}),o.Map.include({_initPathRoot:function(){this._pathRoot||(this._pathRoot=o.Path.prototype._createElement("svg"),this._panes.overlayPane.appendChild(this._pathRoot),this.options.zoomAnimation&&o.Browser.any3d?(o.DomUtil.addClass(this._pathRoot,"leaflet-zoom-animated"),this.on({zoomanim:this._animatePathZoom,zoomend:this._endPathZoom})):o.DomUtil.addClass(this._pathRoot,"leaflet-zoom-hide"),this.on("moveend",this._updateSvgViewport),this._updateSvgViewport())},_animatePathZoom:function(t){var e=this.getZoomScale(t.zoom),i=this._getCenterOffset(t.center)._multiplyBy(-e)._add(this._pathViewport.min);this._pathRoot.style[o.DomUtil.TRANSFORM]=o.DomUtil.getTranslateString(i)+" scale("+e+") ",this._pathZooming=!0},_endPathZoom:function(){this._pathZooming=!1},_updateSvgViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max,n=i.x-e.x,s=i.y-e.y,a=this._pathRoot,r=this._panes.overlayPane;o.Browser.mobileWebkit&&r.removeChild(a),o.DomUtil.setPosition(a,e),a.setAttribute("width",n),a.setAttribute("height",s),a.setAttribute("viewBox",[e.x,e.y,n,s].join(" ")),o.Browser.mobileWebkit&&r.appendChild(a)}}}),o.Path.include({bindPopup:function(t,e){return t instanceof o.Popup?this._popup=t:((!this._popup||e)&&(this._popup=new o.Popup(e,this)),this._popup.setContent(t)),this._popupHandlersAdded||(this.on("click",this._openPopup,this).on("remove",this.closePopup,this),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this._popup=null,this.off("click",this._openPopup).off("remove",this.closePopup),this._popupHandlersAdded=!1),this},openPopup:function(t){return this._popup&&(t=t||this._latlng||this._latlngs[Math.floor(this._latlngs.length/2)],this._openPopup({latlng:t})),this},closePopup:function(){return this._popup&&this._popup._close(),this},_openPopup:function(t){this._popup.setLatLng(t.latlng),this._map.openPopup(this._popup)}}),o.Browser.vml=!o.Browser.svg&&function(){try{var t=e.createElement("div");t.innerHTML='<v:shape adj="1"/>';var i=t.firstChild;return i.style.behavior="url(#default#VML)",i&&"object"==typeof i.adj}catch(n){return!1}}(),o.Path=o.Browser.svg||!o.Browser.vml?o.Path:o.Path.extend({statics:{VML:!0,CLIP_PADDING:.02},_createElement:function(){try{return e.namespaces.add("lvml","urn:schemas-microsoft-com:vml"),function(t){return e.createElement("<lvml:"+t+' class="lvml">')}}catch(t){return function(t){return e.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}}(),_initPath:function(){var t=this._container=this._createElement("shape");o.DomUtil.addClass(t,"leaflet-vml-shape"+(this.options.className?" "+this.options.className:"")),this.options.clickable&&o.DomUtil.addClass(t,"leaflet-clickable"),t.coordsize="1 1",this._path=this._createElement("path"),t.appendChild(this._path),this._map._pathRoot.appendChild(t)},_initStyle:function(){this._updateStyle()},_updateStyle:function(){var t=this._stroke,e=this._fill,i=this.options,n=this._container;n.stroked=i.stroke,n.filled=i.fill,i.stroke?(t||((t=this._stroke=this._createElement("stroke")).endcap="round",n.appendChild(t)),t.weight=i.weight+"px",t.color=i.color,t.opacity=i.opacity,t.dashStyle=i.dashArray?o.Util.isArray(i.dashArray)?i.dashArray.join(" "):i.dashArray.replace(/( *, *)/g," "):"",i.lineCap&&(t.endcap=i.lineCap.replace("butt","flat")),i.lineJoin&&(t.joinstyle=i.lineJoin)):t&&(n.removeChild(t),this._stroke=null),i.fill?(e||(e=this._fill=this._createElement("fill"),n.appendChild(e)),e.color=i.fillColor||i.color,e.opacity=i.fillOpacity):e&&(n.removeChild(e),this._fill=null)},_updatePath:function(){var t=this._container.style;t.display="none",this._path.v=this.getPathString()+" ",t.display=""}}),o.Map.include(o.Browser.svg||!o.Browser.vml?{}:{_initPathRoot:function(){if(!this._pathRoot){var t=this._pathRoot=e.createElement("div");t.className="leaflet-vml-container",this._panes.overlayPane.appendChild(t),this.on("moveend",this._updatePathViewport),this._updatePathViewport()}}}),o.Browser.canvas=!!e.createElement("canvas").getContext,o.Path=o.Path.SVG&&!t.L_PREFER_CANVAS||!o.Browser.canvas?o.Path:o.Path.extend({statics:{CANVAS:!0,SVG:!1},redraw:function(){return this._map&&(this.projectLatlngs(),this._requestUpdate()),this},setStyle:function(t){return o.setOptions(this,t),this._map&&(this._updateStyle(),this._requestUpdate()),this},onRemove:function(t){t.off("viewreset",this.projectLatlngs,this).off("moveend",this._updatePath,this),this.options.clickable&&(this._map.off("click",this._onClick,this),this._map.off("mousemove",this._onMouseMove,this)),this._requestUpdate(),this._map=null},_requestUpdate:function(){this._map&&!o.Path._updateRequest&&(o.Path._updateRequest=o.Util.requestAnimFrame(this._fireMapMoveEnd,this._map))},_fireMapMoveEnd:function(){o.Path._updateRequest=null,this.fire("moveend")},_initElements:function(){this._map._initPathRoot(),this._ctx=this._map._canvasCtx},_updateStyle:function(){var t=this.options;t.stroke&&(this._ctx.lineWidth=t.weight,this._ctx.strokeStyle=t.color),t.fill&&(this._ctx.fillStyle=t.fillColor||t.color)},_drawPath:function(){var t,e,i,n,s,a;for(this._ctx.beginPath(),t=0,i=this._parts.length;i>t;t++){for(e=0,n=this._parts[t].length;n>e;e++)s=this._parts[t][e],a=(0===e?"move":"line")+"To",this._ctx[a](s.x,s.y);this instanceof o.Polygon&&this._ctx.closePath()}},_checkIfEmpty:function(){return!this._parts.length},_updatePath:function(){if(!this._checkIfEmpty()){var t=this._ctx,e=this.options;this._drawPath(),t.save(),this._updateStyle(),e.fill&&(t.globalAlpha=e.fillOpacity,t.fill()),e.stroke&&(t.globalAlpha=e.opacity,t.stroke()),t.restore()}},_initEvents:function(){this.options.clickable&&(this._map.on("mousemove",this._onMouseMove,this),this._map.on("click",this._onClick,this))},_onClick:function(t){this._containsPoint(t.layerPoint)&&this.fire("click",t)},_onMouseMove:function(t){this._map&&!this._map._animatingZoom&&(this._containsPoint(t.layerPoint)?(this._ctx.canvas.style.cursor="pointer",this._mouseInside=!0,this.fire("mouseover",t)):this._mouseInside&&(this._ctx.canvas.style.cursor="",this._mouseInside=!1,this.fire("mouseout",t)))}}),o.Map.include(o.Path.SVG&&!t.L_PREFER_CANVAS||!o.Browser.canvas?{}:{_initPathRoot:function(){var t,i=this._pathRoot;i||((i=this._pathRoot=e.createElement("canvas")).style.position="absolute",(t=this._canvasCtx=i.getContext("2d")).lineCap="round",t.lineJoin="round",this._panes.overlayPane.appendChild(i),this.options.zoomAnimation&&(this._pathRoot.className="leaflet-zoom-animated",this.on("zoomanim",this._animatePathZoom),this.on("zoomend",this._endPathZoom)),this.on("moveend",this._updateCanvasViewport),this._updateCanvasViewport())},_updateCanvasViewport:function(){if(!this._pathZooming){this._updatePathViewport();var t=this._pathViewport,e=t.min,i=t.max.subtract(e),n=this._pathRoot;o.DomUtil.setPosition(n,e),n.width=i.x,n.height=i.y,n.getContext("2d").translate(-e.x,-e.y)}}}),o.LineUtil={simplify:function(t,e){if(!e||!t.length)return t.slice();var i=e*e;return t=this._reducePoints(t,i),this._simplifyDP(t,i)},pointToSegmentDistance:function(t,e,i){return Math.sqrt(this._sqClosestPointOnSegment(t,e,i,!0))},closestPointOnSegment:function(t,e,i){return this._sqClosestPointOnSegment(t,e,i)},_simplifyDP:function(t,e){var n=t.length,s=new(typeof Uint8Array!=i+""?Uint8Array:Array)(n);s[0]=s[n-1]=1,this._simplifyDPStep(t,s,e,0,n-1);var a,r=[];for(a=0;n>a;a++)s[a]&&r.push(t[a]);return r},_simplifyDPStep:function(t,e,i,n,o){var s,a,r,h=0;for(a=n+1;o-1>=a;a++)(r=this._sqClosestPointOnSegment(t[a],t[n],t[o],!0))>h&&(s=a,h=r);h>i&&(e[s]=1,this._simplifyDPStep(t,e,i,n,s),this._simplifyDPStep(t,e,i,s,o))},_reducePoints:function(t,e){for(var i=[t[0]],n=1,o=0,s=t.length;s>n;n++)this._sqDist(t[n],t[o])>e&&(i.push(t[n]),o=n);return s-1>o&&i.push(t[s-1]),i},clipSegment:function(t,e,i,n){var o,s,a,r=n?this._lastCode:this._getBitCode(t,i),h=this._getBitCode(e,i);for(this._lastCode=h;;){if(!(r|h))return[t,e];if(r&h)return!1;o=r||h,s=this._getEdgeIntersection(t,e,o,i),a=this._getBitCode(s,i),o===r?(t=s,r=a):(e=s,h=a)}},_getEdgeIntersection:function(t,e,i,n){var s=e.x-t.x,a=e.y-t.y,r=n.min,h=n.max;return 8&i?new o.Point(t.x+s*(h.y-t.y)/a,h.y):4&i?new o.Point(t.x+s*(r.y-t.y)/a,r.y):2&i?new o.Point(h.x,t.y+a*(h.x-t.x)/s):1&i?new o.Point(r.x,t.y+a*(r.x-t.x)/s):void 0},_getBitCode:function(t,e){var i=0;return t.x<e.min.x?i|=1:t.x>e.max.x&&(i|=2),t.y<e.min.y?i|=4:t.y>e.max.y&&(i|=8),i},_sqDist:function(t,e){var i=e.x-t.x,n=e.y-t.y;return i*i+n*n},_sqClosestPointOnSegment:function(t,e,i,n){var s,a=e.x,r=e.y,h=i.x-a,l=i.y-r,u=h*h+l*l;return u>0&&((s=((t.x-a)*h+(t.y-r)*l)/u)>1?(a=i.x,r=i.y):s>0&&(a+=h*s,r+=l*s)),h=t.x-a,l=t.y-r,n?h*h+l*l:new o.Point(a,r)}},o.Polyline=o.Path.extend({initialize:function(t,e){o.Path.prototype.initialize.call(this,e),this._latlngs=this._convertLatLngs(t)},options:{smoothFactor:1,noClip:!1},projectLatlngs:function(){this._originalPoints=[];for(var t=0,e=this._latlngs.length;e>t;t++)this._originalPoints[t]=this._map.latLngToLayerPoint(this._latlngs[t])},getPathString:function(){for(var t=0,e=this._parts.length,i="";e>t;t++)i+=this._getPathPartStr(this._parts[t]);return i},getLatLngs:function(){return this._latlngs},setLatLngs:function(t){return this._latlngs=this._convertLatLngs(t),this.redraw()},addLatLng:function(t){return this._latlngs.push(o.latLng(t)),this.redraw()},spliceLatLngs:function(){var t=[].splice.apply(this._latlngs,arguments);return this._convertLatLngs(this._latlngs,!0),this.redraw(),t},closestLayerPoint:function(t){for(var e,i,n=1/0,s=this._parts,a=null,r=0,h=s.length;h>r;r++)for(var l=s[r],u=1,c=l.length;c>u;u++){e=l[u-1],i=l[u];var d=o.LineUtil._sqClosestPointOnSegment(t,e,i,!0);n>d&&(n=d,a=o.LineUtil._sqClosestPointOnSegment(t,e,i))}return a&&(a.distance=Math.sqrt(n)),a},getBounds:function(){return new o.LatLngBounds(this.getLatLngs())},_convertLatLngs:function(t,e){var i,n,s=e?t:[];for(i=0,n=t.length;n>i;i++){if(o.Util.isArray(t[i])&&"number"!=typeof t[i][0])return;s[i]=o.latLng(t[i])}return s},_initEvents:function(){o.Path.prototype._initEvents.call(this)},_getPathPartStr:function(t){for(var e,i=o.Path.VML,n=0,s=t.length,a="";s>n;n++)e=t[n],i&&e._round(),a+=(n?"L":"M")+e.x+" "+e.y;return a},_clipPoints:function(){var t,e,i,n=this._originalPoints,s=n.length;if(this.options.noClip)this._parts=[n];else{this._parts=[];var a=this._parts,r=this._map._pathViewport,h=o.LineUtil;for(t=0,e=0;s-1>t;t++)(i=h.clipSegment(n[t],n[t+1],r,t))&&(a[e]=a[e]||[],a[e].push(i[0]),(i[1]!==n[t+1]||t===s-2)&&(a[e].push(i[1]),e++))}},_simplifyPoints:function(){for(var t=this._parts,e=o.LineUtil,i=0,n=t.length;n>i;i++)t[i]=e.simplify(t[i],this.options.smoothFactor)},_updatePath:function(){this._map&&(this._clipPoints(),this._simplifyPoints(),o.Path.prototype._updatePath.call(this))}}),o.polyline=function(t,e){return new o.Polyline(t,e)},o.PolyUtil={},o.PolyUtil.clipPolygon=function(t,e){var i,n,s,a,r,h,l,u,c,d=[1,4,2,8],p=o.LineUtil;for(n=0,l=t.length;l>n;n++)t[n]._code=p._getBitCode(t[n],e);for(a=0;4>a;a++){for(u=d[a],i=[],n=0,s=(l=t.length)-1;l>n;s=n++)r=t[n],h=t[s],r._code&u?h._code&u||((c=p._getEdgeIntersection(h,r,u,e))._code=p._getBitCode(c,e),i.push(c)):(h._code&u&&((c=p._getEdgeIntersection(h,r,u,e))._code=p._getBitCode(c,e),i.push(c)),i.push(r));t=i}return t},o.Polygon=o.Polyline.extend({options:{fill:!0},initialize:function(t,e){o.Polyline.prototype.initialize.call(this,t,e),this._initWithHoles(t)},_initWithHoles:function(t){var e,i,n;if(t&&o.Util.isArray(t[0])&&"number"!=typeof t[0][0])for(this._latlngs=this._convertLatLngs(t[0]),this._holes=t.slice(1),e=0,i=this._holes.length;i>e;e++)(n=this._holes[e]=this._convertLatLngs(this._holes[e]))[0].equals(n[n.length-1])&&n.pop();(t=this._latlngs).length>=2&&t[0].equals(t[t.length-1])&&t.pop()},projectLatlngs:function(){var t,e,i,n;if(o.Polyline.prototype.projectLatlngs.call(this),this._holePoints=[],this._holes)for(t=0,i=this._holes.length;i>t;t++)for(this._holePoints[t]=[],e=0,n=this._holes[t].length;n>e;e++)this._holePoints[t][e]=this._map.latLngToLayerPoint(this._holes[t][e])},setLatLngs:function(t){return t&&o.Util.isArray(t[0])&&"number"!=typeof t[0][0]?(this._initWithHoles(t),this.redraw()):o.Polyline.prototype.setLatLngs.call(this,t)},_clipPoints:function(){var t=this._originalPoints,e=[];if(this._parts=[t].concat(this._holePoints),!this.options.noClip){for(var i=0,n=this._parts.length;n>i;i++){var s=o.PolyUtil.clipPolygon(this._parts[i],this._map._pathViewport);s.length&&e.push(s)}this._parts=e}},_getPathPartStr:function(t){return o.Polyline.prototype._getPathPartStr.call(this,t)+(o.Browser.svg?"z":"x")}}),o.polygon=function(t,e){return new o.Polygon(t,e)},function(){function t(t){return o.FeatureGroup.extend({initialize:function(t,e){this._layers={},this._options=e,this.setLatLngs(t)},setLatLngs:function(e){var i=0,n=e.length;for(this.eachLayer(function(t){n>i?t.setLatLngs(e[i++]):this.removeLayer(t)},this);n>i;)this.addLayer(new t(e[i++],this._options));return this},getLatLngs:function(){var t=[];return this.eachLayer(function(e){t.push(e.getLatLngs())}),t}})}o.MultiPolyline=t(o.Polyline),o.MultiPolygon=t(o.Polygon),o.multiPolyline=function(t,e){return new o.MultiPolyline(t,e)},o.multiPolygon=function(t,e){return new o.MultiPolygon(t,e)}}(),o.Rectangle=o.Polygon.extend({initialize:function(t,e){o.Polygon.prototype.initialize.call(this,this._boundsToLatLngs(t),e)},setBounds:function(t){this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return[(t=o.latLngBounds(t)).getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}}),o.rectangle=function(t,e){return new o.Rectangle(t,e)},o.Circle=o.Path.extend({initialize:function(t,e,i){o.Path.prototype.initialize.call(this,i),this._latlng=o.latLng(t),this._mRadius=e},options:{fill:!0},setLatLng:function(t){return this._latlng=o.latLng(t),this.redraw()},setRadius:function(t){return this._mRadius=t,this.redraw()},projectLatlngs:function(){var t=this._getLngRadius(),e=this._latlng,i=this._map.latLngToLayerPoint([e.lat,e.lng-t]);this._point=this._map.latLngToLayerPoint(e),this._radius=Math.max(this._point.x-i.x,1)},getBounds:function(){var t=this._getLngRadius(),e=this._mRadius/40075017*360,i=this._latlng;return new o.LatLngBounds([i.lat-e,i.lng-t],[i.lat+e,i.lng+t])},getLatLng:function(){return this._latlng},getPathString:function(){var t=this._point,e=this._radius;return this._checkIfEmpty()?"":o.Browser.svg?"M"+t.x+","+(t.y-e)+"A"+e+","+e+",0,1,1,"+(t.x-.1)+","+(t.y-e)+" z":(t._round(),e=Math.round(e),"AL "+t.x+","+t.y+" "+e+","+e+" 0,23592600")},getRadius:function(){return this._mRadius},_getLatRadius:function(){return this._mRadius/40075017*360},_getLngRadius:function(){return this._getLatRadius()/Math.cos(o.LatLng.DEG_TO_RAD*this._latlng.lat)},_checkIfEmpty:function(){if(!this._map)return!1;var t=this._map._pathViewport,e=this._radius,i=this._point;return i.x-e>t.max.x||i.y-e>t.max.y||i.x+e<t.min.x||i.y+e<t.min.y}}),o.circle=function(t,e,i){return new o.Circle(t,e,i)},o.CircleMarker=o.Circle.extend({options:{radius:10,weight:2},initialize:function(t,e){o.Circle.prototype.initialize.call(this,t,null,e),this._radius=this.options.radius},projectLatlngs:function(){this._point=this._map.latLngToLayerPoint(this._latlng)},_updateStyle:function(){o.Circle.prototype._updateStyle.call(this),this.setRadius(this.options.radius)},setLatLng:function(t){return o.Circle.prototype.setLatLng.call(this,t),this._popup&&this._popup._isOpen&&this._popup.setLatLng(t),this},setRadius:function(t){return this.options.radius=this._radius=t,this.redraw()},getRadius:function(){return this._radius}}),o.circleMarker=function(t,e){return new o.CircleMarker(t,e)},o.Polyline.include(o.Path.CANVAS?{_containsPoint:function(t,e){var i,n,s,a,r,l,u=this.options.weight/2;for(o.Browser.touch&&(u+=10),i=0,a=this._parts.length;a>i;i++)for(n=0,s=(r=(l=this._parts[i]).length)-1;r>n;s=n++)if((e||0!==n)&&u>=o.LineUtil.pointToSegmentDistance(t,l[s],l[n]))return!0;return!1}}:{}),o.Polygon.include(o.Path.CANVAS?{_containsPoint:function(t){var e,i,n,s,a,r,h,l,u=!1;if(o.Polyline.prototype._containsPoint.call(this,t,!0))return!0;for(s=0,h=this._parts.length;h>s;s++)for(a=0,r=(l=(e=this._parts[s]).length)-1;l>a;r=a++)i=e[a],n=e[r],i.y>t.y!=n.y>t.y&&t.x<(n.x-i.x)*(t.y-i.y)/(n.y-i.y)+i.x&&(u=!u);return u}}:{}),o.Circle.include(o.Path.CANVAS?{_drawPath:function(){var t=this._point;this._ctx.beginPath(),this._ctx.arc(t.x,t.y,this._radius,0,2*Math.PI,!1)},_containsPoint:function(t){var e=this._point,i=this.options.stroke?this.options.weight/2:0;return t.distanceTo(e)<=this._radius+i}}:{}),o.CircleMarker.include(o.Path.CANVAS?{_updateStyle:function(){o.Path.prototype._updateStyle.call(this)}}:{}),o.GeoJSON=o.FeatureGroup.extend({initialize:function(t,e){o.setOptions(this,e),this._layers={},t&&this.addData(t)},addData:function(t){var e,i,n,s=o.Util.isArray(t)?t:t.features;if(s){for(e=0,i=s.length;i>e;e++)((n=s[e]).geometries||n.geometry||n.features||n.coordinates)&&this.addData(s[e]);return this}var a=this.options;if(!a.filter||a.filter(t)){var r=o.GeoJSON.geometryToLayer(t,a.pointToLayer,a.coordsToLatLng,a);return r.feature=o.GeoJSON.asFeature(t),r.defaultOptions=r.options,this.resetStyle(r),a.onEachFeature&&a.onEachFeature(t,r),this.addLayer(r)}},resetStyle:function(t){var e=this.options.style;e&&(o.Util.extend(t.options,t.defaultOptions),this._setLayerStyle(t,e))},setStyle:function(t){this.eachLayer(function(e){this._setLayerStyle(e,t)},this)},_setLayerStyle:function(t,e){"function"==typeof e&&(e=e(t.feature)),t.setStyle&&t.setStyle(e)}}),o.extend(o.GeoJSON,{geometryToLayer:function(t,e,i,n){var s,a,r,h,l="Feature"===t.type?t.geometry:t,u=l.coordinates,c=[];switch(i=i||this.coordsToLatLng,l.type){case"Point":return s=i(u),e?e(t,s):new o.Marker(s);case"MultiPoint":for(r=0,h=u.length;h>r;r++)s=i(u[r]),c.push(e?e(t,s):new o.Marker(s));return new o.FeatureGroup(c);case"LineString":return a=this.coordsToLatLngs(u,0,i),new o.Polyline(a,n);case"Polygon":if(2===u.length&&!u[1].length)throw new Error("Invalid GeoJSON object.");return a=this.coordsToLatLngs(u,1,i),new o.Polygon(a,n);case"MultiLineString":return a=this.coordsToLatLngs(u,1,i),new o.MultiPolyline(a,n);case"MultiPolygon":return a=this.coordsToLatLngs(u,2,i),new o.MultiPolygon(a,n);case"GeometryCollection":for(r=0,h=l.geometries.length;h>r;r++)c.push(this.geometryToLayer({geometry:l.geometries[r],type:"Feature",properties:t.properties},e,i,n));return new o.FeatureGroup(c);default:throw new Error("Invalid GeoJSON object.")}},coordsToLatLng:function(t){return new o.LatLng(t[1],t[0],t[2])},coordsToLatLngs:function(t,e,i){var n,o,s,a=[];for(o=0,s=t.length;s>o;o++)n=e?this.coordsToLatLngs(t[o],e-1,i):(i||this.coordsToLatLng)(t[o]),a.push(n);return a},latLngToCoords:function(t){var e=[t.lng,t.lat];return t.alt!==i&&e.push(t.alt),e},latLngsToCoords:function(t){for(var e=[],i=0,n=t.length;n>i;i++)e.push(o.GeoJSON.latLngToCoords(t[i]));return e},getFeature:function(t,e){return t.feature?o.extend({},t.feature,{geometry:e}):o.GeoJSON.asFeature(e)},asFeature:function(t){return"Feature"===t.type?t:{type:"Feature",properties:{},geometry:t}}});var a={toGeoJSON:function(){return o.GeoJSON.getFeature(this,{type:"Point",coordinates:o.GeoJSON.latLngToCoords(this.getLatLng())})}};o.Marker.include(a),o.Circle.include(a),o.CircleMarker.include(a),o.Polyline.include({toGeoJSON:function(){return o.GeoJSON.getFeature(this,{type:"LineString",coordinates:o.GeoJSON.latLngsToCoords(this.getLatLngs())})}}),o.Polygon.include({toGeoJSON:function(){var t,e,i,n=[o.GeoJSON.latLngsToCoords(this.getLatLngs())];if(n[0].push(n[0][0]),this._holes)for(t=0,e=this._holes.length;e>t;t++)(i=o.GeoJSON.latLngsToCoords(this._holes[t])).push(i[0]),n.push(i);return o.GeoJSON.getFeature(this,{type:"Polygon",coordinates:n})}}),function(){function t(t){return function(){var e=[];return this.eachLayer(function(t){e.push(t.toGeoJSON().geometry.coordinates)}),o.GeoJSON.getFeature(this,{type:t,coordinates:e})}}o.MultiPolyline.include({toGeoJSON:t("MultiLineString")}),o.MultiPolygon.include({toGeoJSON:t("MultiPolygon")}),o.LayerGroup.include({toGeoJSON:function(){var e,i=this.feature&&this.feature.geometry,n=[];if(i&&"MultiPoint"===i.type)return t("MultiPoint").call(this);var s=i&&"GeometryCollection"===i.type;return this.eachLayer(function(t){t.toGeoJSON&&(e=t.toGeoJSON(),n.push(s?e.geometry:o.GeoJSON.asFeature(e)))}),s?o.GeoJSON.getFeature(this,{geometries:n,type:"GeometryCollection"}):{type:"FeatureCollection",features:n}}})}(),o.geoJson=function(t,e){return new o.GeoJSON(t,e)},o.DomEvent={addListener:function(t,e,i,n){var s,a,r,h=o.stamp(i),l="_leaflet_"+e+h;return t[l]?this:(s=function(e){return i.call(n||t,e||o.DomEvent._getEvent())},o.Browser.pointer&&0===e.indexOf("touch")?this.addPointerListener(t,e,s,h):(o.Browser.touch&&"dblclick"===e&&this.addDoubleTapListener&&this.addDoubleTapListener(t,s,h),"addEventListener"in t?"mousewheel"===e?(t.addEventListener("DOMMouseScroll",s,!1),t.addEventListener(e,s,!1)):"mouseenter"===e||"mouseleave"===e?(a=s,r="mouseenter"===e?"mouseover":"mouseout",s=function(e){return o.DomEvent._checkMouse(t,e)?a(e):void 0},t.addEventListener(r,s,!1)):"click"===e&&o.Browser.android?(a=s,s=function(t){return o.DomEvent._filterClick(t,a)},t.addEventListener(e,s,!1)):t.addEventListener(e,s,!1):"attachEvent"in t&&t.attachEvent("on"+e,s),t[l]=s,this))},removeListener:function(t,e,i){var n=o.stamp(i),s="_leaflet_"+e+n,a=t[s];return a?(o.Browser.pointer&&0===e.indexOf("touch")?this.removePointerListener(t,e,n):o.Browser.touch&&"dblclick"===e&&this.removeDoubleTapListener?this.removeDoubleTapListener(t,n):"removeEventListener"in t?"mousewheel"===e?(t.removeEventListener("DOMMouseScroll",a,!1),t.removeEventListener(e,a,!1)):"mouseenter"===e||"mouseleave"===e?t.removeEventListener("mouseenter"===e?"mouseover":"mouseout",a,!1):t.removeEventListener(e,a,!1):"detachEvent"in t&&t.detachEvent("on"+e,a),t[s]=null,this):this},stopPropagation:function(t){return t.stopPropagation?t.stopPropagation():t.cancelBubble=!0,o.DomEvent._skipped(t),this},disableScrollPropagation:function(t){var e=o.DomEvent.stopPropagation;return o.DomEvent.on(t,"mousewheel",e).on(t,"MozMousePixelScroll",e)},disableClickPropagation:function(t){for(var e=o.DomEvent.stopPropagation,i=o.Draggable.START.length-1;i>=0;i--)o.DomEvent.on(t,o.Draggable.START[i],e);return o.DomEvent.on(t,"click",o.DomEvent._fakeStop).on(t,"dblclick",e)},preventDefault:function(t){return t.preventDefault?t.preventDefault():t.returnValue=!1,this},stop:function(t){return o.DomEvent.preventDefault(t).stopPropagation(t)},getMousePosition:function(t,e){if(!e)return new o.Point(t.clientX,t.clientY);var i=e.getBoundingClientRect();return new o.Point(t.clientX-i.left-e.clientLeft,t.clientY-i.top-e.clientTop)},getWheelDelta:function(t){var e=0;return t.wheelDelta&&(e=t.wheelDelta/120),t.detail&&(e=-t.detail/3),e},_skipEvents:{},_fakeStop:function(t){o.DomEvent._skipEvents[t.type]=!0},_skipped:function(t){var e=this._skipEvents[t.type];return this._skipEvents[t.type]=!1,e},_checkMouse:function(t,e){var i=e.relatedTarget;if(!i)return!0;try{for(;i&&i!==t;)i=i.parentNode}catch(n){return!1}return i!==t},_getEvent:function(){var e=t.event;if(!e)for(var i=arguments.callee.caller;i&&(!(e=i.arguments[0])||t.Event!==e.constructor);)i=i.caller;return e},_filterClick:function(t,e){var i=t.timeStamp||t.originalEvent.timeStamp,n=o.DomEvent._lastClick&&i-o.DomEvent._lastClick;return n&&n>100&&1e3>n||t.target._simulatedClick&&!t._simulated?void o.DomEvent.stop(t):(o.DomEvent._lastClick=i,e(t))}},o.DomEvent.on=o.DomEvent.addListener,o.DomEvent.off=o.DomEvent.removeListener,o.Draggable=o.Class.extend({includes:o.Mixin.Events,statics:{START:o.Browser.touch?["touchstart","mousedown"]:["mousedown"],END:{mousedown:"mouseup",touchstart:"touchend",pointerdown:"touchend",MSPointerDown:"touchend"},MOVE:{mousedown:"mousemove",touchstart:"touchmove",pointerdown:"touchmove",MSPointerDown:"touchmove"}},initialize:function(t,e){this._element=t,this._dragStartTarget=e||t},enable:function(){if(!this._enabled){for(var t=o.Draggable.START.length-1;t>=0;t--)o.DomEvent.on(this._dragStartTarget,o.Draggable.START[t],this._onDown,this);this._enabled=!0}},disable:function(){if(this._enabled){for(var t=o.Draggable.START.length-1;t>=0;t--)o.DomEvent.off(this._dragStartTarget,o.Draggable.START[t],this._onDown,this);this._enabled=!1,this._moved=!1}},_onDown:function(t){if(this._moved=!1,!(t.shiftKey||1!==t.which&&1!==t.button&&!t.touches||(o.DomEvent.stopPropagation(t),o.Draggable._disabled||(o.DomUtil.disableImageDrag(),o.DomUtil.disableTextSelection(),this._moving)))){var i=t.touches?t.touches[0]:t;this._startPoint=new o.Point(i.clientX,i.clientY),this._startPos=this._newPos=o.DomUtil.getPosition(this._element),o.DomEvent.on(e,o.Draggable.MOVE[t.type],this._onMove,this).on(e,o.Draggable.END[t.type],this._onUp,this)}},_onMove:function(t){if(t.touches&&t.touches.length>1)this._moved=!0;else{var i=t.touches&&1===t.touches.length?t.touches[0]:t,s=new o.Point(i.clientX,i.clientY).subtract(this._startPoint);(s.x||s.y)&&(o.DomEvent.preventDefault(t),this._moved||(this.fire("dragstart"),this._moved=!0,this._startPos=o.DomUtil.getPosition(this._element).subtract(s),o.DomUtil.addClass(e.body,"leaflet-dragging"),o.DomUtil.addClass(t.target||t.srcElement,"leaflet-drag-target")),this._newPos=this._startPos.add(s),this._moving=!0,o.Util.cancelAnimFrame(this._animRequest),this._animRequest=o.Util.requestAnimFrame(this._updatePosition,this,!0,this._dragStartTarget))}},_updatePosition:function(){this.fire("predrag"),o.DomUtil.setPosition(this._element,this._newPos),this.fire("drag")},_onUp:function(t){for(var i in o.DomUtil.removeClass(e.body,"leaflet-dragging"),o.DomUtil.removeClass(t.target||t.srcElement,"leaflet-drag-target"),o.Draggable.MOVE)o.DomEvent.off(e,o.Draggable.MOVE[i],this._onMove).off(e,o.Draggable.END[i],this._onUp);o.DomUtil.enableImageDrag(),o.DomUtil.enableTextSelection(),this._moved&&this._moving&&(o.Util.cancelAnimFrame(this._animRequest),this.fire("dragend",{distance:this._newPos.distanceTo(this._startPos)})),this._moving=!1}}),o.Handler=o.Class.extend({initialize:function(t){this._map=t},enable:function(){this._enabled||(this._enabled=!0,this.addHooks())},disable:function(){this._enabled&&(this._enabled=!1,this.removeHooks())},enabled:function(){return!!this._enabled}}),o.Map.mergeOptions({dragging:!0,inertia:!o.Browser.android23,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,inertiaThreshold:o.Browser.touch?32:18,easeLinearity:.25,worldCopyJump:!1}),o.Map.Drag=o.Handler.extend({addHooks:function(){if(!this._draggable){var t=this._map;this._draggable=new o.Draggable(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDrag,this),t.on("viewreset",this._onViewReset,this),t.whenReady(this._onViewReset,this))}this._draggable.enable()},removeHooks:function(){this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){var t=this._map;t._panAnim&&t._panAnim.stop(),t.fire("movestart").fire("dragstart"),t.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(){if(this._map.options.inertia){var t=this._lastTime=+new Date,e=this._lastPos=this._draggable._newPos;this._positions.push(e),this._times.push(t),t-this._times[0]>200&&(this._positions.shift(),this._times.shift())}this._map.fire("move").fire("drag")},_onViewReset:function(){var t=this._map.getSize()._divideBy(2),e=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=e.subtract(t).x,this._worldWidth=this._map.project([0,180]).x},_onPreDrag:function(){var t=this._worldWidth,e=Math.round(t/2),i=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-e+i)%t+e-i,s=(n+e+i)%t-e-i,a=Math.abs(o+i)<Math.abs(s+i)?o:s;this._draggable._newPos.x=a},_onDragEnd:function(t){var e=this._map,i=e.options,n=+new Date-this._lastTime,s=!i.inertia||n>i.inertiaThreshold||!this._positions[0];if(e.fire("dragend",t),s)e.fire("moveend");else{var a=this._lastPos.subtract(this._positions[0]),r=(this._lastTime+n-this._times[0])/1e3,h=i.easeLinearity,l=a.multiplyBy(h/r),u=l.distanceTo([0,0]),c=Math.min(i.inertiaMaxSpeed,u),d=l.multiplyBy(c/u),p=c/(i.inertiaDeceleration*h),_=d.multiplyBy(-p/2).round();_.x&&_.y?(_=e._limitOffset(_,e.options.maxBounds),o.Util.requestAnimFrame(function(){e.panBy(_,{duration:p,easeLinearity:h,noMoveStart:!0})})):e.fire("moveend")}}}),o.Map.addInitHook("addHandler","dragging",o.Map.Drag),o.Map.mergeOptions({doubleClickZoom:!0}),o.Map.DoubleClickZoom=o.Handler.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var e=this._map,i=e.getZoom()+(t.originalEvent.shiftKey?-1:1);"center"===e.options.doubleClickZoom?e.setZoom(i):e.setZoomAround(t.containerPoint,i)}}),o.Map.addInitHook("addHandler","doubleClickZoom",o.Map.DoubleClickZoom),o.Map.mergeOptions({scrollWheelZoom:!0}),o.Map.ScrollWheelZoom=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"mousewheel",this._onWheelScroll,this),o.DomEvent.on(this._map._container,"MozMousePixelScroll",o.DomEvent.preventDefault),this._delta=0},removeHooks:function(){o.DomEvent.off(this._map._container,"mousewheel",this._onWheelScroll),o.DomEvent.off(this._map._container,"MozMousePixelScroll",o.DomEvent.preventDefault)},_onWheelScroll:function(t){var e=o.DomEvent.getWheelDelta(t);this._delta+=e,this._lastMousePos=this._map.mouseEventToContainerPoint(t),this._startTime||(this._startTime=+new Date);var i=Math.max(40-(+new Date-this._startTime),0);clearTimeout(this._timer),this._timer=setTimeout(o.bind(this._performZoom,this),i),o.DomEvent.preventDefault(t),o.DomEvent.stopPropagation(t)},_performZoom:function(){var t=this._map,e=this._delta,i=t.getZoom();e=e>0?Math.ceil(e):Math.floor(e),e=Math.max(Math.min(e,4),-4),e=t._limitZoom(i+e)-i,this._delta=0,this._startTime=null,e&&("center"===t.options.scrollWheelZoom?t.setZoom(i+e):t.setZoomAround(this._lastMousePos,i+e))}}),o.Map.addInitHook("addHandler","scrollWheelZoom",o.Map.ScrollWheelZoom),o.extend(o.DomEvent,{_touchstart:o.Browser.msPointer?"MSPointerDown":o.Browser.pointer?"pointerdown":"touchstart",_touchend:o.Browser.msPointer?"MSPointerUp":o.Browser.pointer?"pointerup":"touchend",addDoubleTapListener:function(t,i,n){function s(t){var e;if(o.Browser.pointer?(_.push(t.pointerId),e=_.length):e=t.touches.length,!(e>1)){var i=Date.now(),n=i-(r||i);h=t.touches?t.touches[0]:t,l=n>0&&u>=n,r=i}}function a(t){if(o.Browser.pointer){var e=_.indexOf(t.pointerId);if(-1===e)return;_.splice(e,1)}if(l){if(o.Browser.pointer){var n,s={};for(var a in h)n=h[a],s[a]="function"==typeof n?n.bind(h):n;h=s}h.type="dblclick",i(h),r=null}}var r,h,l=!1,u=250,c="_leaflet_",d=this._touchstart,p=this._touchend,_=[];t[c+d+n]=s,t[c+p+n]=a;var m=o.Browser.pointer?e.documentElement:t;return t.addEventListener(d,s,!1),m.addEventListener(p,a,!1),o.Browser.pointer&&m.addEventListener(o.DomEvent.POINTER_CANCEL,a,!1),this},removeDoubleTapListener:function(t,i){var n="_leaflet_";return t.removeEventListener(this._touchstart,t[n+this._touchstart+i],!1),(o.Browser.pointer?e.documentElement:t).removeEventListener(this._touchend,t[n+this._touchend+i],!1),o.Browser.pointer&&e.documentElement.removeEventListener(o.DomEvent.POINTER_CANCEL,t[n+this._touchend+i],!1),this}}),o.extend(o.DomEvent,{POINTER_DOWN:o.Browser.msPointer?"MSPointerDown":"pointerdown",POINTER_MOVE:o.Browser.msPointer?"MSPointerMove":"pointermove",POINTER_UP:o.Browser.msPointer?"MSPointerUp":"pointerup",POINTER_CANCEL:o.Browser.msPointer?"MSPointerCancel":"pointercancel",_pointers:[],_pointerDocumentListener:!1,addPointerListener:function(t,e,i,n){switch(e){case"touchstart":return this.addPointerListenerStart(t,e,i,n);case"touchend":return this.addPointerListenerEnd(t,e,i,n);case"touchmove":return this.addPointerListenerMove(t,e,i,n);default:throw"Unknown touch event type"}},addPointerListenerStart:function(t,i,n,s){var r=this._pointers,h=function(t){o.DomEvent.preventDefault(t);for(var e=!1,i=0;i<r.length;i++)if(r[i].pointerId===t.pointerId){e=!0;break}e||r.push(t),t.touches=r.slice(),t.changedTouches=[t],n(t)};if(t["_leaflet_touchstart"+s]=h,t.addEventListener(this.POINTER_DOWN,h,!1),!this._pointerDocumentListener){var l=function(t){for(var e=0;e<r.length;e++)if(r[e].pointerId===t.pointerId){r.splice(e,1);break}};e.documentElement.addEventListener(this.POINTER_UP,l,!1),e.documentElement.addEventListener(this.POINTER_CANCEL,l,!1),this._pointerDocumentListener=!0}return this},addPointerListenerMove:function(t,e,i,n){function o(t){if(t.pointerType!==t.MSPOINTER_TYPE_MOUSE&&"mouse"!==t.pointerType||0!==t.buttons){for(var e=0;e<a.length;e++)if(a[e].pointerId===t.pointerId){a[e]=t;break}t.touches=a.slice(),t.changedTouches=[t],i(t)}}var a=this._pointers;return t["_leaflet_touchmove"+n]=o,t.addEventListener(this.POINTER_MOVE,o,!1),this},addPointerListenerEnd:function(t,e,i,n){var s=this._pointers,a=function(t){for(var e=0;e<s.length;e++)if(s[e].pointerId===t.pointerId){s.splice(e,1);break}t.touches=s.slice(),t.changedTouches=[t],i(t)};return t["_leaflet_touchend"+n]=a,t.addEventListener(this.POINTER_UP,a,!1),t.addEventListener(this.POINTER_CANCEL,a,!1),this},removePointerListener:function(t,e,i){var o=t["_leaflet_"+e+i];switch(e){case"touchstart":t.removeEventListener(this.POINTER_DOWN,o,!1);break;case"touchmove":t.removeEventListener(this.POINTER_MOVE,o,!1);break;case"touchend":t.removeEventListener(this.POINTER_UP,o,!1),t.removeEventListener(this.POINTER_CANCEL,o,!1)}return this}}),o.Map.mergeOptions({touchZoom:o.Browser.touch&&!o.Browser.android23,bounceAtZoomLimits:!0}),o.Map.TouchZoom=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){o.DomEvent.off(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(t){var i=this._map;if(t.touches&&2===t.touches.length&&!i._animatingZoom&&!this._zooming){var n=i.mouseEventToLayerPoint(t.touches[0]),s=i.mouseEventToLayerPoint(t.touches[1]),a=i._getCenterLayerPoint();this._startCenter=n.add(s)._divideBy(2),this._startDist=n.distanceTo(s),this._moved=!1,this._zooming=!0,this._centerOffset=a.subtract(this._startCenter),i._panAnim&&i._panAnim.stop(),o.DomEvent.on(e,"touchmove",this._onTouchMove,this).on(e,"touchend",this._onTouchEnd,this),o.DomEvent.preventDefault(t)}},_onTouchMove:function(t){var e=this._map;if(t.touches&&2===t.touches.length&&this._zooming){var i=e.mouseEventToLayerPoint(t.touches[0]),n=e.mouseEventToLayerPoint(t.touches[1]);this._scale=i.distanceTo(n)/this._startDist,this._delta=i._add(n)._divideBy(2)._subtract(this._startCenter),1!==this._scale&&(e.options.bounceAtZoomLimits||!(e.getZoom()===e.getMinZoom()&&this._scale<1||e.getZoom()===e.getMaxZoom()&&this._scale>1))&&(this._moved||(o.DomUtil.addClass(e._mapPane,"leaflet-touching"),e.fire("movestart").fire("zoomstart"),this._moved=!0),o.Util.cancelAnimFrame(this._animRequest),this._animRequest=o.Util.requestAnimFrame(this._updateOnMove,this,!0,this._map._container),o.DomEvent.preventDefault(t))}},_updateOnMove:function(){var t=this._map,e=this._getScaleOrigin(),i=t.layerPointToLatLng(e),n=t.getScaleZoom(this._scale);t._animateZoom(i,n,this._startCenter,this._scale,this._delta)},_onTouchEnd:function(){if(this._moved&&this._zooming){var t=this._map;this._zooming=!1,o.DomUtil.removeClass(t._mapPane,"leaflet-touching"),o.Util.cancelAnimFrame(this._animRequest),o.DomEvent.off(e,"touchmove",this._onTouchMove).off(e,"touchend",this._onTouchEnd);var i=this._getScaleOrigin(),n=t.layerPointToLatLng(i),s=t.getZoom(),a=t.getScaleZoom(this._scale)-s,r=a>0?Math.ceil(a):Math.floor(a),h=t._limitZoom(s+r),l=t.getZoomScale(h)/this._scale;t._animateZoom(n,h,i,l)}else this._zooming=!1},_getScaleOrigin:function(){var t=this._centerOffset.subtract(this._delta).divideBy(this._scale);return this._startCenter.add(t)}}),o.Map.addInitHook("addHandler","touchZoom",o.Map.TouchZoom),o.Map.mergeOptions({tap:!0,tapTolerance:15}),o.Map.Tap=o.Handler.extend({addHooks:function(){o.DomEvent.on(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){o.DomEvent.off(this._map._container,"touchstart",this._onDown,this)},_onDown:function(t){if(t.touches){if(o.DomEvent.preventDefault(t),this._fireClick=!0,t.touches.length>1)return this._fireClick=!1,void clearTimeout(this._holdTimeout);var i=t.touches[0],n=i.target;this._startPos=this._newPos=new o.Point(i.clientX,i.clientY),n.tagName&&"a"===n.tagName.toLowerCase()&&o.DomUtil.addClass(n,"leaflet-active"),this._holdTimeout=setTimeout(o.bind(function(){this._isTapValid()&&(this._fireClick=!1,this._onUp(),this._simulateEvent("contextmenu",i))},this),1e3),o.DomEvent.on(e,"touchmove",this._onMove,this).on(e,"touchend",this._onUp,this)}},_onUp:function(t){if(clearTimeout(this._holdTimeout),o.DomEvent.off(e,"touchmove",this._onMove,this).off(e,"touchend",this._onUp,this),this._fireClick&&t&&t.changedTouches){var i=t.changedTouches[0],n=i.target;n&&n.tagName&&"a"===n.tagName.toLowerCase()&&o.DomUtil.removeClass(n,"leaflet-active"),this._isTapValid()&&this._simulateEvent("click",i)}},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_onMove:function(t){var e=t.touches[0];this._newPos=new o.Point(e.clientX,e.clientY)},_simulateEvent:function(i,n){var o=e.createEvent("MouseEvents");o._simulated=!0,n.target._simulatedClick=!0,o.initMouseEvent(i,!0,!0,t,1,n.screenX,n.screenY,n.clientX,n.clientY,!1,!1,!1,!1,0,null),n.target.dispatchEvent(o)}}),o.Browser.touch&&!o.Browser.pointer&&o.Map.addInitHook("addHandler","tap",o.Map.Tap),o.Map.mergeOptions({boxZoom:!0}),o.Map.BoxZoom=o.Handler.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._moved=!1},addHooks:function(){o.DomEvent.on(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){o.DomEvent.off(this._container,"mousedown",this._onMouseDown),this._moved=!1},moved:function(){return this._moved},_onMouseDown:function(t){return this._moved=!1,!(!t.shiftKey||1!==t.which&&1!==t.button)&&(o.DomUtil.disableTextSelection(),o.DomUtil.disableImageDrag(),this._startLayerPoint=this._map.mouseEventToLayerPoint(t),void o.DomEvent.on(e,"mousemove",this._onMouseMove,this).on(e,"mouseup",this._onMouseUp,this).on(e,"keydown",this._onKeyDown,this))},_onMouseMove:function(t){this._moved||(this._box=o.DomUtil.create("div","leaflet-zoom-box",this._pane),o.DomUtil.setPosition(this._box,this._startLayerPoint),this._container.style.cursor="crosshair",this._map.fire("boxzoomstart"));var e=this._startLayerPoint,i=this._box,n=this._map.mouseEventToLayerPoint(t),s=n.subtract(e),a=new o.Point(Math.min(n.x,e.x),Math.min(n.y,e.y));o.DomUtil.setPosition(i,a),this._moved=!0,i.style.width=Math.max(0,Math.abs(s.x)-4)+"px",i.style.height=Math.max(0,Math.abs(s.y)-4)+"px"},_finish:function(){this._moved&&(this._pane.removeChild(this._box),this._container.style.cursor=""),o.DomUtil.enableTextSelection(),o.DomUtil.enableImageDrag(),o.DomEvent.off(e,"mousemove",this._onMouseMove).off(e,"mouseup",this._onMouseUp).off(e,"keydown",this._onKeyDown)},_onMouseUp:function(t){this._finish();var e=this._map,i=e.mouseEventToLayerPoint(t);if(!this._startLayerPoint.equals(i)){var n=new o.LatLngBounds(e.layerPointToLatLng(this._startLayerPoint),e.layerPointToLatLng(i));e.fitBounds(n),e.fire("boxzoomend",{boxZoomBounds:n})}},_onKeyDown:function(t){27===t.keyCode&&this._finish()}}),o.Map.addInitHook("addHandler","boxZoom",o.Map.BoxZoom),o.Map.mergeOptions({keyboard:!0,keyboardPanOffset:80,keyboardZoomOffset:1}),o.Map.Keyboard=o.Handler.extend({keyCodes:{left:[37],right:[39],down:[40],up:[38],zoomIn:[187,107,61,171],zoomOut:[189,109,173]},initialize:function(t){this._map=t,this._setPanOffset(t.options.keyboardPanOffset),this._setZoomOffset(t.options.keyboardZoomOffset)},addHooks:function(){var t=this._map._container;-1===t.tabIndex&&(t.tabIndex="0"),o.DomEvent.on(t,"focus",this._onFocus,this).on(t,"blur",this._onBlur,this).on(t,"mousedown",this._onMouseDown,this),this._map.on("focus",this._addHooks,this).on("blur",this._removeHooks,this)},removeHooks:function(){this._removeHooks();var t=this._map._container;o.DomEvent.off(t,"focus",this._onFocus,this).off(t,"blur",this._onBlur,this).off(t,"mousedown",this._onMouseDown,this),this._map.off("focus",this._addHooks,this).off("blur",this._removeHooks,this)},_onMouseDown:function(){if(!this._focused){var i=e.body,n=e.documentElement,o=i.scrollTop||n.scrollTop,s=i.scrollLeft||n.scrollLeft;this._map._container.focus(),t.scrollTo(s,o)}},_onFocus:function(){this._focused=!0,this._map.fire("focus")},_onBlur:function(){this._focused=!1,this._map.fire("blur")},_setPanOffset:function(t){var e,i,n=this._panKeys={},o=this.keyCodes;for(e=0,i=o.left.length;i>e;e++)n[o.left[e]]=[-1*t,0];for(e=0,i=o.right.length;i>e;e++)n[o.right[e]]=[t,0];for(e=0,i=o.down.length;i>e;e++)n[o.down[e]]=[0,t];for(e=0,i=o.up.length;i>e;e++)n[o.up[e]]=[0,-1*t]},_setZoomOffset:function(t){var e,i,n=this._zoomKeys={},o=this.keyCodes;for(e=0,i=o.zoomIn.length;i>e;e++)n[o.zoomIn[e]]=t;for(e=0,i=o.zoomOut.length;i>e;e++)n[o.zoomOut[e]]=-t},_addHooks:function(){o.DomEvent.on(e,"keydown",this._onKeyDown,this)},_removeHooks:function(){o.DomEvent.off(e,"keydown",this._onKeyDown,this)},_onKeyDown:function(t){var e=t.keyCode,i=this._map;if(e in this._panKeys){if(i._panAnim&&i._panAnim._inProgress)return;i.panBy(this._panKeys[e]),i.options.maxBounds&&i.panInsideBounds(i.options.maxBounds)}else{if(!(e in this._zoomKeys))return;i.setZoom(i.getZoom()+this._zoomKeys[e])}o.DomEvent.stop(t)}}),o.Map.addInitHook("addHandler","keyboard",o.Map.Keyboard),o.Handler.MarkerDrag=o.Handler.extend({initialize:function(t){this._marker=t},addHooks:function(){var t=this._marker._icon;this._draggable||(this._draggable=new o.Draggable(t,t)),this._draggable.on("dragstart",this._onDragStart,this).on("drag",this._onDrag,this).on("dragend",this._onDragEnd,this),this._draggable.enable(),o.DomUtil.addClass(this._marker._icon,"leaflet-marker-draggable")},removeHooks:function(){this._draggable.off("dragstart",this._onDragStart,this).off("drag",this._onDrag,this).off("dragend",this._onDragEnd,this),this._draggable.disable(),o.DomUtil.removeClass(this._marker._icon,"leaflet-marker-draggable")},moved:function(){return this._draggable&&this._draggable._moved},_onDragStart:function(){this._marker.closePopup().fire("movestart").fire("dragstart")},_onDrag:function(){var t=this._marker,e=t._shadow,i=o.DomUtil.getPosition(t._icon),n=t._map.layerPointToLatLng(i);e&&o.DomUtil.setPosition(e,i),t._latlng=n,t.fire("move",{latlng:n}).fire("drag")},_onDragEnd:function(t){this._marker.fire("moveend").fire("dragend",t)}}),o.Control=o.Class.extend({options:{position:"topright"},initialize:function(t){o.setOptions(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var e=this._map;return e&&e.removeControl(this),this.options.position=t,e&&e.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this._map=t;var e=this._container=this.onAdd(t),i=this.getPosition(),n=t._controlCorners[i];return o.DomUtil.addClass(e,"leaflet-control"),-1!==i.indexOf("bottom")?n.insertBefore(e,n.firstChild):n.appendChild(e),this},removeFrom:function(t){var e=this.getPosition();return t._controlCorners[e].removeChild(this._container),this._map=null,this.onRemove&&this.onRemove(t),this},_refocusOnMap:function(){this._map&&this._map.getContainer().focus()}}),o.control=function(t){return new o.Control(t)},o.Map.include({addControl:function(t){return t.addTo(this),this},removeControl:function(t){return t.removeFrom(this),this},_initControlPos:function(){function t(t,s){var a=i+t+" "+i+s;e[t+s]=o.DomUtil.create("div",a,n)}var e=this._controlCorners={},i="leaflet-",n=this._controlContainer=o.DomUtil.create("div",i+"control-container",this._container);t("top","left"),t("top","right"),t("bottom","left"),t("bottom","right")},_clearControlPos:function(){this._container.removeChild(this._controlContainer)}}),o.Control.Zoom=o.Control.extend({options:{position:"topleft",zoomInText:"+",zoomInTitle:"Zoom in",zoomOutText:"-",zoomOutTitle:"Zoom out"},onAdd:function(t){var e="leaflet-control-zoom",i=o.DomUtil.create("div",e+" leaflet-bar");return this._map=t,this._zoomInButton=this._createButton(this.options.zoomInText,this.options.zoomInTitle,e+"-in",i,this._zoomIn,this),this._zoomOutButton=this._createButton(this.options.zoomOutText,this.options.zoomOutTitle,e+"-out",i,this._zoomOut,this),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),i},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},_zoomIn:function(t){this._map.zoomIn(t.shiftKey?3:1)},_zoomOut:function(t){this._map.zoomOut(t.shiftKey?3:1)},_createButton:function(t,e,i,n,s,a){var r=o.DomUtil.create("a",i,n);r.innerHTML=t,r.href="#",r.title=e;var h=o.DomEvent.stopPropagation;return o.DomEvent.on(r,"click",h).on(r,"mousedown",h).on(r,"dblclick",h).on(r,"click",o.DomEvent.preventDefault).on(r,"click",s,a).on(r,"click",this._refocusOnMap,a),r},_updateDisabled:function(){var t=this._map,e="leaflet-disabled";o.DomUtil.removeClass(this._zoomInButton,e),o.DomUtil.removeClass(this._zoomOutButton,e),t._zoom===t.getMinZoom()&&o.DomUtil.addClass(this._zoomOutButton,e),t._zoom===t.getMaxZoom()&&o.DomUtil.addClass(this._zoomInButton,e)}}),o.Map.mergeOptions({zoomControl:!0}),o.Map.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new o.Control.Zoom,this.addControl(this.zoomControl))}),o.control.zoom=function(t){return new o.Control.Zoom(t)},o.Control.Attribution=o.Control.extend({options:{position:"bottomright",prefix:'<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'},initialize:function(t){o.setOptions(this,t),this._attributions={}},onAdd:function(t){for(var e in this._container=o.DomUtil.create("div","leaflet-control-attribution"),o.DomEvent.disableClickPropagation(this._container),t._layers)t._layers[e].getAttribution&&this.addAttribution(t._layers[e].getAttribution());return t.on("layeradd",this._onLayerAdd,this).on("layerremove",this._onLayerRemove,this),this._update(),this._container},onRemove:function(t){t.off("layeradd",this._onLayerAdd).off("layerremove",this._onLayerRemove)},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t?(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update(),this):void 0},removeAttribution:function(t){return t?(this._attributions[t]&&(this._attributions[t]--,this._update()),this):void 0},_update:function(){if(this._map){var t=[];for(var e in this._attributions)this._attributions[e]&&t.push(e);var i=[];this.options.prefix&&i.push(this.options.prefix),t.length&&i.push(t.join(", ")),this._container.innerHTML=i.join(" | ")}},_onLayerAdd:function(t){t.layer.getAttribution&&this.addAttribution(t.layer.getAttribution())},_onLayerRemove:function(t){t.layer.getAttribution&&this.removeAttribution(t.layer.getAttribution())}}),o.Map.mergeOptions({attributionControl:!0}),o.Map.addInitHook(function(){this.options.attributionControl&&(this.attributionControl=(new o.Control.Attribution).addTo(this))}),o.control.attribution=function(t){return new o.Control.Attribution(t)},o.Control.Scale=o.Control.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0,updateWhenIdle:!1},onAdd:function(t){this._map=t;var e="leaflet-control-scale",i=o.DomUtil.create("div",e),n=this.options;return this._addScales(n,e,i),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),i},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,e,i){t.metric&&(this._mScale=o.DomUtil.create("div",e+"-line",i)),t.imperial&&(this._iScale=o.DomUtil.create("div",e+"-line",i))},_update:function(){var t=this._map.getBounds(),e=t.getCenter().lat,n=6378137*Math.PI*Math.cos(e*Math.PI/180)*(t.getNorthEast().lng-t.getSouthWest().lng)/180,o=this._map.getSize(),s=this.options,a=0;o.x>0&&(a=n*(s.maxWidth/o.x)),this._updateScales(s,a)},_updateScales:function(t,e){t.metric&&e&&this._updateMetric(e),t.imperial&&e&&this._updateImperial(e)},_updateMetric:function(t){var e=this._getRoundNum(t);this._mScale.style.width=this._getScaleWidth(e/t)+"px",this._mScale.innerHTML=1e3>e?e+" m":e/1e3+" km"},_updateImperial:function(t){var e,i,n,o=3.2808399*t,s=this._iScale;o>5280?(e=o/5280,i=this._getRoundNum(e),s.style.width=this._getScaleWidth(i/e)+"px",s.innerHTML=i+" mi"):(n=this._getRoundNum(o),s.style.width=this._getScaleWidth(n/o)+"px",s.innerHTML=n+" ft")},_getScaleWidth:function(t){return Math.round(this.options.maxWidth*t)-10},_getRoundNum:function(t){var e=Math.pow(10,(Math.floor(t)+"").length-1),i=t/e;return e*(i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:1)}}),o.control.scale=function(t){return new o.Control.Scale(t)},o.Control.Layers=o.Control.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0},initialize:function(t,e,i){for(var n in o.setOptions(this,i),this._layers={},this._lastZIndex=0,this._handlingClick=!1,t)this._addLayer(t[n],n);for(n in e)this._addLayer(e[n],n,!0)},onAdd:function(t){return this._initLayout(),this._update(),t.on("layeradd",this._onLayerChange,this).on("layerremove",this._onLayerChange,this),this._container},onRemove:function(t){t.off("layeradd",this._onLayerChange).off("layerremove",this._onLayerChange)},addBaseLayer:function(t,e){return this._addLayer(t,e),this._update(),this},addOverlay:function(t,e){return this._addLayer(t,e,!0),this._update(),this},removeLayer:function(t){var e=o.stamp(t);return delete this._layers[e],this._update(),this},_initLayout:function(){var t="leaflet-control-layers",e=this._container=o.DomUtil.create("div",t);e.setAttribute("aria-haspopup",!0),o.Browser.touch?o.DomEvent.on(e,"click",o.DomEvent.stopPropagation):o.DomEvent.disableClickPropagation(e).disableScrollPropagation(e);var i=this._form=o.DomUtil.create("form",t+"-list");if(this.options.collapsed){o.Browser.android||o.DomEvent.on(e,"mouseover",this._expand,this).on(e,"mouseout",this._collapse,this);var n=this._layersLink=o.DomUtil.create("a",t+"-toggle",e);n.href="#",n.title="Layers",o.Browser.touch?o.DomEvent.on(n,"click",o.DomEvent.stop).on(n,"click",this._expand,this):o.DomEvent.on(n,"focus",this._expand,this),o.DomEvent.on(i,"click",function(){setTimeout(o.bind(this._onInputClick,this),0)},this),this._map.on("click",this._collapse,this)}else this._expand();this._baseLayersList=o.DomUtil.create("div",t+"-base",i),this._separator=o.DomUtil.create("div",t+"-separator",i),this._overlaysList=o.DomUtil.create("div",t+"-overlays",i),e.appendChild(i)},_addLayer:function(t,e,i){var n=o.stamp(t);this._layers[n]={layer:t,name:e,overlay:i},this.options.autoZIndex&&t.setZIndex&&(this._lastZIndex++,t.setZIndex(this._lastZIndex))},_update:function(){if(this._container){this._baseLayersList.innerHTML="",this._overlaysList.innerHTML="";var t,e,i=!1,n=!1;for(t in this._layers)e=this._layers[t],this._addItem(e),n=n||e.overlay,i=i||!e.overlay;this._separator.style.display=n&&i?"":"none"}},_onLayerChange:function(t){var e=this._layers[o.stamp(t.layer)];if(e){this._handlingClick||this._update();var i=e.overlay?"layeradd"===t.type?"overlayadd":"overlayremove":"layeradd"===t.type?"baselayerchange":null;i&&this._map.fire(i,e)}},_createRadioElement:function(t,i){var n='<input type="radio" class="leaflet-control-layers-selector" name="'+t+'"';i&&(n+=' checked="checked"'),n+="/>";var o=e.createElement("div");return o.innerHTML=n,o.firstChild},_addItem:function(t){var i,n=e.createElement("label"),s=this._map.hasLayer(t.layer);t.overlay?((i=e.createElement("input")).type="checkbox",i.className="leaflet-control-layers-selector",i.defaultChecked=s):i=this._createRadioElement("leaflet-base-layers",s),i.layerId=o.stamp(t.layer),o.DomEvent.on(i,"click",this._onInputClick,this);var a=e.createElement("span");return a.innerHTML=" "+t.name,n.appendChild(i),n.appendChild(a),(t.overlay?this._overlaysList:this._baseLayersList).appendChild(n),n},_onInputClick:function(){var t,e,i,n=this._form.getElementsByTagName("input"),o=n.length;for(this._handlingClick=!0,t=0;o>t;t++)e=n[t],i=this._layers[e.layerId],e.checked&&!this._map.hasLayer(i.layer)?this._map.addLayer(i.layer):!e.checked&&this._map.hasLayer(i.layer)&&this._map.removeLayer(i.layer);this._handlingClick=!1,this._refocusOnMap()},_expand:function(){o.DomUtil.addClass(this._container,"leaflet-control-layers-expanded")},_collapse:function(){this._container.className=this._container.className.replace(" leaflet-control-layers-expanded","")}}),o.control.layers=function(t,e,i){return new o.Control.Layers(t,e,i)},o.PosAnimation=o.Class.extend({includes:o.Mixin.Events,run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._newPos=e,this.fire("start"),t.style[o.DomUtil.TRANSITION]="all "+(i||.25)+"s cubic-bezier(0,0,"+(n||.5)+",1)",o.DomEvent.on(t,o.DomUtil.TRANSITION_END,this._onTransitionEnd,this),o.DomUtil.setPosition(t,e),o.Util.falseFn(t.offsetWidth),this._stepTimer=setInterval(o.bind(this._onStep,this),50)},stop:function(){this._inProgress&&(o.DomUtil.setPosition(this._el,this._getPos()),this._onTransitionEnd(),o.Util.falseFn(this._el.offsetWidth))},_onStep:function(){var t=this._getPos();return t?(this._el._leaflet_pos=t,void this.fire("step")):void this._onTransitionEnd()},_transformRe:/([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,_getPos:function(){var e,i,n,s=this._el,a=t.getComputedStyle(s);if(o.Browser.any3d){if(!(n=a[o.DomUtil.TRANSFORM].match(this._transformRe)))return;e=parseFloat(n[1]),i=parseFloat(n[2])}else e=parseFloat(a.left),i=parseFloat(a.top);return new o.Point(e,i,!0)},_onTransitionEnd:function(){o.DomEvent.off(this._el,o.DomUtil.TRANSITION_END,this._onTransitionEnd,this),this._inProgress&&(this._inProgress=!1,this._el.style[o.DomUtil.TRANSITION]="",this._el._leaflet_pos=this._newPos,clearInterval(this._stepTimer),this.fire("step").fire("end"))}}),o.Map.include({setView:function(t,e,n){if((e=e===i?this._zoom:this._limitZoom(e),t=this._limitCenter(o.latLng(t),e,this.options.maxBounds),n=n||{},this._panAnim&&this._panAnim.stop(),this._loaded&&!n.reset&&!0!==n)&&(n.animate!==i&&(n.zoom=o.extend({animate:n.animate},n.zoom),n.pan=o.extend({animate:n.animate},n.pan)),this._zoom!==e?this._tryAnimatedZoom&&this._tryAnimatedZoom(t,e,n.zoom):this._tryAnimatedPan(t,n.pan)))return clearTimeout(this._sizeTimer),this;return this._resetView(t,e),this},panBy:function(t,e){if(e=e||{},!(t=o.point(t).round()).x&&!t.y)return this;if(this._panAnim||(this._panAnim=new o.PosAnimation,this._panAnim.on({step:this._onPanTransitionStep,end:this._onPanTransitionEnd},this)),e.noMoveStart||this.fire("movestart"),!1!==e.animate){o.DomUtil.addClass(this._mapPane,"leaflet-pan-anim");var i=this._getMapPanePos().subtract(t);this._panAnim.run(this._mapPane,i,e.duration||.25,e.easeLinearity)}else this._rawPanBy(t),this.fire("move").fire("moveend");return this},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){o.DomUtil.removeClass(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(t,e){var i=this._getCenterOffset(t)._floor();return!(!0!==(e&&e.animate)&&!this.getSize().contains(i))&&(this.panBy(i,e),!0)}}),o.PosAnimation=o.DomUtil.TRANSITION?o.PosAnimation:o.PosAnimation.extend({run:function(t,e,i,n){this.stop(),this._el=t,this._inProgress=!0,this._duration=i||.25,this._easeOutPower=1/Math.max(n||.5,.2),this._startPos=o.DomUtil.getPosition(t),this._offset=e.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){this._inProgress&&(this._step(),this._complete())},_animate:function(){this._animId=o.Util.requestAnimFrame(this._animate,this),this._step()},_step:function(){var t=+new Date-this._startTime,e=1e3*this._duration;e>t?this._runFrame(this._easeOut(t/e)):(this._runFrame(1),this._complete())},_runFrame:function(t){var e=this._startPos.add(this._offset.multiplyBy(t));o.DomUtil.setPosition(this._el,e),this.fire("step")},_complete:function(){o.Util.cancelAnimFrame(this._animId),this._inProgress=!1,this.fire("end")},_easeOut:function(t){return 1-Math.pow(1-t,this._easeOutPower)}}),o.Map.mergeOptions({zoomAnimation:!0,zoomAnimationThreshold:4}),o.DomUtil.TRANSITION&&o.Map.addInitHook(function(){this._zoomAnimated=this.options.zoomAnimation&&o.DomUtil.TRANSITION&&o.Browser.any3d&&!o.Browser.android23&&!o.Browser.mobileOpera,this._zoomAnimated&&o.DomEvent.on(this._mapPane,o.DomUtil.TRANSITION_END,this._catchTransitionEnd,this)}),o.Map.include(o.DomUtil.TRANSITION?{_catchTransitionEnd:function(t){this._animatingZoom&&t.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(t,e,i){if(this._animatingZoom)return!0;if(i=i||{},!this._zoomAnimated||!1===i.animate||this._nothingToAnimate()||Math.abs(e-this._zoom)>this.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(e),o=this._getCenterOffset(t)._divideBy(1-1/n),s=this._getCenterLayerPoint()._add(o);return!(!0!==i.animate&&!this.getSize().contains(o))&&(this.fire("movestart").fire("zoomstart"),this._animateZoom(t,e,s,n,null,!0),!0)},_animateZoom:function(t,e,i,n,s,a){this._animatingZoom=!0,o.DomUtil.addClass(this._mapPane,"leaflet-zoom-anim"),this._animateToCenter=t,this._animateToZoom=e,o.Draggable&&(o.Draggable._disabled=!0),this.fire("zoomanim",{center:t,zoom:e,origin:i,scale:n,delta:s,backwards:a})},_onZoomTransitionEnd:function(){this._animatingZoom=!1,o.DomUtil.removeClass(this._mapPane,"leaflet-zoom-anim"),this._resetView(this._animateToCenter,this._animateToZoom,!0,!0),o.Draggable&&(o.Draggable._disabled=!1)}}:{}),o.TileLayer.include({_animateZoom:function(t){this._animating||(this._animating=!0,this._prepareBgBuffer());var e=this._bgBuffer,i=o.DomUtil.TRANSFORM,n=t.delta?o.DomUtil.getTranslateString(t.delta):e.style[i],s=o.DomUtil.getScaleString(t.scale,t.origin);e.style[i]=t.backwards?s+" "+n:n+" "+s},_endZoomAnim:function(){var t=this._tileContainer,e=this._bgBuffer;t.style.visibility="",t.parentNode.appendChild(t),o.Util.falseFn(e.offsetWidth),this._animating=!1},_clearBgBuffer:function(){var t=this._map;!t||t._animatingZoom||t.touchZoom._zooming||(this._bgBuffer.innerHTML="",this._bgBuffer.style[o.DomUtil.TRANSFORM]="")},_prepareBgBuffer:function(){var t=this._tileContainer,e=this._bgBuffer,i=this._getLoadedTilesPercentage(e),n=this._getLoadedTilesPercentage(t);return e&&i>.5&&.5>n?(t.style.visibility="hidden",void this._stopLoadingImages(t)):(e.style.visibility="hidden",e.style[o.DomUtil.TRANSFORM]="",this._tileContainer=e,e=this._bgBuffer=t,this._stopLoadingImages(e),void clearTimeout(this._clearBgBufferTimer))},_getLoadedTilesPercentage:function(t){var e,i,n=t.getElementsByTagName("img"),o=0;for(e=0,i=n.length;i>e;e++)n[e].complete&&o++;return o/i},_stopLoadingImages:function(t){var e,i,n,s=Array.prototype.slice.call(t.getElementsByTagName("img"));for(e=0,i=s.length;i>e;e++)(n=s[e]).complete||(n.onload=o.Util.falseFn,n.onerror=o.Util.falseFn,n.src=o.Util.emptyImageUrl,n.parentNode.removeChild(n))}}),o.Map.include({_defaultLocateOptions:{watch:!1,setView:!1,maxZoom:1/0,timeout:1e4,maximumAge:0,enableHighAccuracy:!1},locate:function(t){if(t=this._locateOptions=o.extend(this._defaultLocateOptions,t),!navigator.geolocation)return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var e=o.bind(this._handleGeolocationResponse,this),i=o.bind(this._handleGeolocationError,this);return t.watch?this._locationWatchId=navigator.geolocation.watchPosition(e,i,t):navigator.geolocation.getCurrentPosition(e,i,t),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(t){var e=t.code,i=t.message||(1===e?"permission denied":2===e?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:e,message:"Geolocation error: "+i+"."})},_handleGeolocationResponse:function(t){var e=t.coords.latitude,i=t.coords.longitude,n=new o.LatLng(e,i),s=180*t.coords.accuracy/40075017,a=s/Math.cos(o.LatLng.DEG_TO_RAD*e),r=o.latLngBounds([e-s,i-a],[e+s,i+a]),h=this._locateOptions;if(h.setView){var l=Math.min(this.getBoundsZoom(r),h.maxZoom);this.setView(n,l)}var u={latlng:n,bounds:r,timestamp:t.timestamp};for(var c in t.coords)"number"==typeof t.coords[c]&&(u[c]=t.coords[c]);this.fire("locationfound",u)}})}(window,document),function(a){function b(a,b){for(var c,d=b=b||window,e=a.split(".");c=e.shift();)d[c]||(d[c]={}),d=d[c];return d}b("L.esri.Services.Geocoding"),b("L.esri.Controls.Geosearch"),a.esri.Services.Geocoding=a.Class.extend({includes:a.Mixin.Events,options:{url:"https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/",outFields:"Subregion, Region, PlaceName, Match_addr, Country, Addr_type, City, Place_addr"},initialize:function(b){a.Util.setOptions(this,b)},request:function(b,d,e){var f="c"+(1e9*Math.random()).toString(36).replace(".","_");d.f="json",d.callback="L.esri.Services.Geocoding._callback."+f;var g=document.createElement("script");g.type="text/javascript",g.src=b+function(a){var b="?";for(var c in a)if(a.hasOwnProperty(c)){var d=c,e=a[c];b+=encodeURIComponent(d),b+="=",b+=encodeURIComponent(e),b+="&"}return b.substring(0,b.length-1)}(d),g.id=f,this.fire("loading"),a.esri.Services.Geocoding._callback[f]=a.Util.bind(function(b){this.fire("load"),e(b),document.body.removeChild(g),delete a.esri.Services.Geocoding._callback[f]},this),document.body.appendChild(g)},geocode:function(b,c,d){var e={outFields:this.options.outFields},f=a.extend(e,c);f.text=b,this.request(this.options.url+"find",f,d)},suggest:function(a,b,c){var d=b||{};d.text=a,this.request(this.options.url+"suggest",d,c)}}),a.esri.Services.geocoding=function(b){return new a.esri.Services.Geocoding(b)},a.esri.Services.Geocoding._callback={},a.esri.Controls.Geosearch=a.Control.extend({includes:a.Mixin.Events,options:{position:"topleft",zoomToResult:!0,useMapBounds:11,collapseAfterResult:!0,expanded:!1,maxResults:25},initialize:function(b){a.Util.setOptions(this,b),this._service=new a.esri.Services.Geocoding},_processMatch:function(b,c){var e=c.feature.attributes,f=function(b){var c=new a.LatLng(b.ymin,b.xmin),d=new a.LatLng(b.ymax,b.xmax);return new a.LatLngBounds(c,d)}(c.extent);return{text:b,bounds:f,latlng:new a.LatLng(c.feature.geometry.y,c.feature.geometry.x),name:e.PlaceName,match:e.Addr_type,country:e.Country,region:e.Region,subregion:e.Subregion,city:e.City,address:e.Place_addr?e.Place_addr:e.Match_addr}},_geocode:function(b,c){var d={};if(c)d.magicKey=c;else{var e=this._map.getBounds(),f=e.getCenter(),g=e.getNorthWest();d.bbox=e.toBBoxString(),d.maxLocations=this.options.maxResults,d.location=f.lng+","+f.lat,d.distance=Math.min(Math.max(f.distanceTo(g),2e3),5e4)}a.DomUtil.addClass(this._input,"geocoder-control-loading"),this.fire("loading"),this._service.geocode(b,d,a.Util.bind(function(c){if(c.error)this.fire("error",{code:c.error.code,message:c.error.messsage});else if(c.locations.length){var d,e=[],f=new a.LatLngBounds;for(d=c.locations.length-1;d>=0;d--)e.push(this._processMatch(b,c.locations[d]));for(d=e.length-1;d>=0;d--)f.extend(e[d].bounds);this.fire("results",{results:e,bounds:f,latlng:f.getCenter()}),this.options.zoomToResult&&this._map.fitBounds(f)}else this.fire("results",{results:[],bounds:null,latlng:null,text:b});a.DomUtil.removeClass(this._input,"geocoder-control-loading"),this.fire("load"),this.clear(),this._input.blur()},this))},_suggest:function(b){a.DomUtil.addClass(this._input,"geocoder-control-loading");var c={};if(!0===this.options.useMapBounds||this._map.getZoom()>=this.options.useMapBounds){var d=this._map.getBounds(),e=d.getCenter(),f=d.getNorthWest();c.location=e.lng+","+e.lat,c.distance=Math.min(Math.max(e.distanceTo(f),2e3),5e4)}this._service.suggest(b,c,a.Util.bind(function(b){if(this._input.value){if(this._suggestions.innerHTML="",this._suggestions.style.display="none",b.suggestions){this._suggestions.style.display="block";for(var c=0;c<b.suggestions.length;c++){var d=a.DomUtil.create("li","geocoder-control-suggestion",this._suggestions);d.innerHTML=b.suggestions[c].text,d["data-magic-key"]=b.suggestions[c].magicKey}}a.DomUtil.removeClass(this._input,"geocoder-control-loading")}},this))},clear:function(){this._suggestions.innerHTML="",this._suggestions.style.display="none",this._input.value="",this.options.collapseAfterResult&&a.DomUtil.removeClass(this._container,"geocoder-control-expanded")},onAdd:function(b){return this._map=b,b.attributionControl?b.attributionControl.addAttribution("Geocoding by Esri"):a.control.attribution().addAttribution("Geocoding by Esri").addTo(b),this._container=a.DomUtil.create("div","geocoder-control"+(this.options.expanded?" geocoder-control-expanded":"")),this._input=a.DomUtil.create("input","geocoder-control-input leaflet-bar",this._container),this._suggestions=a.DomUtil.create("ul","geocoder-control-suggestions leaflet-bar",this._container),a.DomEvent.addListener(this._input,"focus",function(){a.DomUtil.addClass(this._container,"geocoder-control-expanded")},this),a.DomEvent.addListener(this._container,"click",function(){a.DomUtil.addClass(this._container,"geocoder-control-expanded"),this._input.focus()},this),a.DomEvent.addListener(this._suggestions,"mousedown",function(a){var b=a.target||a.srcElement;this._geocode(b.innerHTML,b["data-magic-key"]),this.clear()},this),a.DomEvent.addListener(this._input,"blur",function(){this.clear()},this),a.DomEvent.addListener(this._input,"keydown",function(b){var c=this._suggestions.querySelectorAll(".geocoder-control-selected")[0];switch(b.keyCode){case 13:c?(this._geocode(c.innerHTML,c["data-magic-key"]),this.clear()):this.options.allowMultipleResults?this._geocode(this._input.value):a.DomUtil.addClass(this._suggestions.childNodes[0],"geocoder-control-selected"),this.clear(),a.DomEvent.preventDefault(b);break;case 38:c&&a.DomUtil.removeClass(c,"geocoder-control-selected"),c&&c.previousSibling?a.DomUtil.addClass(c.previousSibling,"geocoder-control-selected"):a.DomUtil.addClass(this._suggestions.childNodes[this._suggestions.childNodes.length-1],"geocoder-control-selected"),a.DomEvent.preventDefault(b);break;case 40:c&&a.DomUtil.removeClass(c,"geocoder-control-selected"),c&&c.nextSibling?a.DomUtil.addClass(c.nextSibling,"geocoder-control-selected"):a.DomUtil.addClass(this._suggestions.childNodes[0],"geocoder-control-selected"),a.DomEvent.preventDefault(b)}},this),a.DomEvent.addListener(this._input,"keyup",function(a){var b=a.which||a.keyCode,c=(a.target||a.srcElement).value;return c.length<2?void 0:27===b?(this._suggestions.innerHTML="",void(this._suggestions.style.display="none")):void(13!==b&&38!==b&&40!==b&&this._suggest(c))},this),a.DomEvent.disableClickPropagation(this._container),this._container},onRemove:function(a){a.attributionControl.removeAttribution("Geocoding by Esri")}}),a.esri.Controls.geosearch=function(b){return new a.esri.Controls.Geosearch(b)}}(L),function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(t){"use strict";t.Zebra_DatePicker=function(e,s){var i,n,a,r,o,d,c,l,h,_,g,u,f,p,b,y,v,m,w,k,D,A,M,F,C,Y,P,S,Z,x,z,I,N,O,W,j,T,J,L,H={always_visible:!1,container:t("body"),custom_classes:!1,days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],days_abbr:!1,default_position:"above",direction:0,disabled_dates:!1,enabled_dates:!1,first_day_of_week:1,format:"Y-m-d",header_captions:{days:"F, Y",months:"Y",years:"Y1 - Y2"},header_navigation:["&#171;","&#187;"],icon_position:"right",inside:!0,lang_clear_date:"Clear date",months:["January","February","March","April","May","June","July","August","September","October","November","December"],months_abbr:!1,offset:[5,-5],open_icon_only:!1,pair:!1,readonly_element:!0,select_other_months:!1,show_clear_date:0,show_icon:!0,show_other_months:!0,show_select_today:"Today",show_week_number:!1,start_date:!1,strict:!1,view:"days",weekend_days:[0,6],zero_pad:!1,onChange:null,onClear:null,onOpen:null,onClose:null,onSelect:null},V={},$=this;$.settings={};var q=t(e),E=function(e){var A,S,Z,x,E={days:["d","j","D"],months:["F","m","M","n","t"],years:["o","Y","y"]},Q=!1,U=!1,X=!1,G=null;if(T=Math.floor(65536*(1+Math.random())).toString(16),!e)for(A in $.settings=t.extend({},H,s),V.readonly=q.attr("readonly"),V.style=q.attr("style"),q.data())0===A.indexOf("zdp_")&&(A=A.replace(/^zdp\_/,""),void 0!==H[A]&&($.settings[A]="pair"===A?t(q.data("zdp_"+A)):q.data("zdp_"+A)));for(G in $.settings.readonly_element&&q.attr("readonly","readonly"),E)t.each(E[G],function(t,e){$.settings.format.indexOf(e)>-1&&("days"===G?Q=!0:"months"===G?U=!0:"years"===G&&(X=!0))});for(Z in z=Q&&U&&X?["years","months","days"]:!Q&&U&&X?["years","months"]:Q&&U&&!X?["months","days"]:Q||U||!X?Q||!U||X?["years","months","days"]:["months"]:["years"],-1===t.inArray($.settings.view,z)&&($.settings.view=z[z.length-1]),D=[],k=[],J={},L=[],$.settings.custom_classes)$.settings.custom_classes.hasOwnProperty(Z)&&L.push(Z);for(x=0;x<2+L.length;x++)S=0===x?$.settings.disabled_dates:1===x?$.settings.enabled_dates:$.settings.custom_classes[L[x-2]],t.isArray(S)&&S.length>0&&t.each(S,function(){var e,s,i,n,a=this.split(" ");for(e=0;e<4;e++){for(a[e]||(a[e]="*"),a[e]=a[e].indexOf(",")>-1?a[e].split(","):new Array(a[e]),s=0;s<a[e].length;s++)if(a[e][s].indexOf("-")>-1&&null!==(n=a[e][s].match(/^([0-9]+)\-([0-9]+)/))){for(i=ct(n[1]);i<=ct(n[2]);i++)-1===t.inArray(i,a[e])&&a[e].push(i+"");a[e].splice(s,1)}for(s=0;s<a[e].length;s++)a[e][s]=isNaN(ct(a[e][s]))?a[e][s]:ct(a[e][s])}0===x?D.push(a):1===x?k.push(a):(void 0===J[L[x-2]]&&(J[L[x-2]]=[]),J[L[x-2]].push(a))});var K,tt,et=new Date,nt=$.settings.reference_date?$.settings.reference_date:q.data("zdp_reference_date")&&void 0!==q.data("zdp_reference_date")?q.data("zdp_reference_date"):et;if(M=void 0,F=void 0,u=nt.getMonth(),h=et.getMonth(),f=nt.getFullYear(),_=et.getFullYear(),p=nt.getDate(),g=et.getDate(),!0===$.settings.direction)M=nt;else if(!1===$.settings.direction)P=(F=nt).getMonth(),Y=F.getFullYear(),C=F.getDate();else if(!t.isArray($.settings.direction)&&it($.settings.direction)&&ct($.settings.direction)>0||t.isArray($.settings.direction)&&((K=R($.settings.direction[0]))||!0===$.settings.direction[0]||it($.settings.direction[0])&&$.settings.direction[0]>0)&&((tt=R($.settings.direction[1]))||!1===$.settings.direction[1]||it($.settings.direction[1])&&$.settings.direction[1]>=0))M=K||new Date(f,u,p+ct(t.isArray($.settings.direction)?!0===$.settings.direction[0]?0:$.settings.direction[0]:$.settings.direction)),u=M.getMonth(),f=M.getFullYear(),p=M.getDate(),tt&&+tt>=+M?F=tt:!tt&&!1!==$.settings.direction[1]&&t.isArray($.settings.direction)&&(F=new Date(f,u,p+ct($.settings.direction[1]))),F&&(P=F.getMonth(),Y=F.getFullYear(),C=F.getDate());else if(!t.isArray($.settings.direction)&&it($.settings.direction)&&ct($.settings.direction)<0||t.isArray($.settings.direction)&&(!1===$.settings.direction[0]||it($.settings.direction[0])&&$.settings.direction[0]<0)&&((K=R($.settings.direction[1]))||it($.settings.direction[1])&&$.settings.direction[1]>=0))F=new Date(f,u,p+ct(t.isArray($.settings.direction)?!1===$.settings.direction[0]?0:$.settings.direction[0]:$.settings.direction)),P=F.getMonth(),Y=F.getFullYear(),C=F.getDate(),K&&+K<+F?M=K:!K&&t.isArray($.settings.direction)&&(M=new Date(Y,P,C-ct($.settings.direction[1]))),M&&(u=M.getMonth(),f=M.getFullYear(),p=M.getDate());else if(t.isArray($.settings.disabled_dates)&&$.settings.disabled_dates.length>0)for(var ot in D)if("*"===D[ot][0]&&"*"===D[ot][1]&&"*"===D[ot][2]&&"*"===D[ot][3]){var ht=[];if(t.each(k,function(){var t=this;"*"!==t[2][0]&&ht.push(parseInt(t[2][0]+("*"===t[1][0]?"12":dt(t[1][0],2))+("*"===t[0][0]?"*"===t[1][0]?"31":new Date(t[2][0],t[1][0],0).getDate():dt(t[0][0],2)),10))}),ht.sort(),ht.length>0){var gt=(ht[0]+"").match(/([0-9]{4})([0-9]{2})([0-9]{2})/);f=parseInt(gt[1],10),u=parseInt(gt[2],10)-1,p=parseInt(gt[3],10)}break}if(st(f,u,p)){for(;st(f);)M?(f++,u=0):(f--,u=11);for(;st(f,u);)M?(u++,p=1):(u--,p=new Date(f,u+1,0).getDate()),u>11?(f++,u=0,p=1):u<0&&(f--,u=11,p=new Date(f,u+1,0).getDate());for(;st(f,u,p);)M?p++:p--,et=new Date(f,u,p),f=et.getFullYear(),u=et.getMonth(),p=et.getDate();et=new Date(f,u,p),f=et.getFullYear(),u=et.getMonth(),p=et.getDate()}var ut=R(q.val()||($.settings.start_date?$.settings.start_date:""));if(ut&&$.settings.strict&&st(ut.getFullYear(),ut.getMonth(),ut.getDate())&&q.val(""),e||void 0===M&&void 0===ut||lt(void 0!==ut?ut:M),!$.settings.always_visible){if(!e){if($.settings.show_icon){"firefox"===_t.name&&q.is('input[type="text"]')&&"inline"===q.css("display")&&q.css("display","inline-block");var ft=t('<span class="Zebra_DatePicker_Icon_Wrapper"></span>').css({display:q.css("display"),position:"static"===q.css("position")?"relative":q.css("position"),float:q.css("float"),top:q.css("top"),right:q.css("right"),bottom:q.css("bottom"),left:q.css("left")});"block"===q.css("display")&&ft.css("width",q.outerWidth(!0)),q.wrap(ft).css({position:"relative",top:"auto",right:"auto",bottom:"auto",left:"auto"}),a=t('<button type="button" class="Zebra_DatePicker_Icon'+("disabled"===q.attr("disabled")?" Zebra_DatePicker_Icon_Disabled":"")+'">Pick a date</button>'),$.icon=a,I=$.settings.open_icon_only?a:a.add(q)}else I=q;I.on("click.Zebra_DatePicker_"+T,function(t){t.preventDefault(),q.attr("disabled")||(n.hasClass("dp_visible")?$.hide():$.show())}),!$.settings.readonly_element&&$.settings.pair&&q.on("blur.Zebra_DatePicker_"+T,function(){var e;(e=R(t(this).val()))&&!st(e.getFullYear(),e.getMonth(),e.getDate())&&lt(e)}),void 0!==a&&a.insertAfter(q)}if(void 0!==a){a.attr("style",""),$.settings.inside&&a.addClass("Zebra_DatePicker_Icon_Inside_"+("right"===$.settings.icon_position?"Right":"Left"));var pt=q.outerWidth(),bt=q.outerHeight(),yt=parseInt(q.css("marginLeft"),10)||0,vt=parseInt(q.css("marginTop"),10)||0,mt=(a.outerWidth(),a.outerHeight()),wt=parseInt(a.css("marginLeft"),10)||0;parseInt(a.css("marginRight"),10),$.settings.inside?(a.css("top",vt+(bt-mt)/2),"right"===$.settings.icon_position?a.css("right",0):a.css("left",0)):a.css({top:vt+(bt-mt)/2,left:yt+pt+wt}),a.removeClass(" Zebra_DatePicker_Icon_Disabled"),"disabled"===q.attr("disabled")&&a.addClass("Zebra_DatePicker_Icon_Disabled")}}if(W=!1!==$.settings.show_select_today&&t.inArray("days",z)>-1&&!st(_,h,g)&&$.settings.show_select_today,e)return t(".dp_previous",n).html($.settings.header_navigation[0]),t(".dp_next",n).html($.settings.header_navigation[1]),t(".dp_clear",n).html($.settings.lang_clear_date),void t(".dp_today",n).html($.settings.show_select_today);t(window).on("resize.Zebra_DatePicker_"+T+", orientationchange.Zebra_DatePicker_"+T,function(){$.hide(),void 0!==a&&(clearTimeout(j),j=setTimeout(function(){$.update()},100))});var kt='<div class="Zebra_DatePicker"><table class="dp_header"><tr><td class="dp_previous">'+$.settings.header_navigation[0]+'</td><td class="dp_caption">&#032;</td><td class="dp_next">'+$.settings.header_navigation[1]+'</td></tr></table><table class="dp_daypicker"></table><table class="dp_monthpicker"></table><table class="dp_yearpicker"></table><table class="dp_footer"><tr><td class="dp_today"'+(!1!==$.settings.show_clear_date?' style="width:50%"':"")+">"+W+'</td><td class="dp_clear"'+(!1!==W?' style="width:50%"':"")+">"+$.settings.lang_clear_date+"</td></tr></table></div>";n=t(kt),$.datepicker=n,r=t("table.dp_header",n),o=t("table.dp_daypicker",n),d=t("table.dp_monthpicker",n),c=t("table.dp_yearpicker",n),O=t("table.dp_footer",n),N=t("td.dp_today",O),l=t("td.dp_clear",O),$.settings.always_visible?q.attr("disabled")||($.settings.always_visible.append(n),$.show()):$.settings.container.append(n),n.delegate("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month, .dp_week_number)","mouseover",function(){t(this).addClass("dp_hover")}).delegate("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month, .dp_week_number)","mouseout",function(){t(this).removeClass("dp_hover")}),B(t("td",r)),t(".dp_previous",r).on("click",function(){"months"===i?y--:"years"===i?y-=12:--b<0&&(b=11,y--),at()}),t(".dp_caption",r).on("click",function(){i="days"===i?t.inArray("months",z)>-1?"months":t.inArray("years",z)>-1?"years":"days":"months"===i?t.inArray("years",z)>-1?"years":t.inArray("days",z)>-1?"days":"months":t.inArray("days",z)>-1?"days":t.inArray("months",z)>-1?"months":"years",at()}),t(".dp_next",r).on("click",function(){"months"===i?y++:"years"===i?y+=12:12==++b&&(b=0,y++),at()}),o.delegate("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month, .dp_week_number)","click",function(){var e;$.settings.select_other_months&&t(this).attr("class")&&null!==(e=t(this).attr("class").match(/date\_([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])/))?rt(e[1],e[2]-1,e[3],"days",t(this)):rt(y,b,ct(t(this).html()),"days",t(this))}),d.delegate("td:not(.dp_disabled)","click",function(){var e=t(this).attr("class").match(/dp\_month\_([0-9]+)/);b=ct(e[1]),-1===t.inArray("days",z)?rt(y,b,1,"months",t(this)):(i="days",$.settings.always_visible&&q.val(""),at())}),c.delegate("td:not(.dp_disabled)","click",function(){y=ct(t(this).html()),-1===t.inArray("months",z)?rt(y,1,1,"years",t(this)):(i="months",$.settings.always_visible&&q.val(""),at())}),t(N).on("click",function(e){e.preventDefault(),rt(_,h,g,"days",t(".dp_current",o)),$.settings.always_visible&&$.show(),$.hide()}),t(l).on("click",function(e){e.preventDefault(),q.val(""),$.settings.always_visible?(v=null,m=null,w=null,t("td.dp_selected",n).removeClass("dp_selected")):(v=null,m=null,w=null,b=null,y=null),$.hide(),$.settings.onClear&&"function"==typeof $.settings.onClear&&$.settings.onClear.call(q,q)}),$.settings.always_visible||(t(document).on("mousedown.Zebra_DatePicker_"+T+", touchstart.Zebra_DatePicker_"+T,function(e){if(n.hasClass("dp_visible")){if($.settings.show_icon&&t(e.target).get(0)===a.get(0))return!0;0===t(e.target).parents().filter(".Zebra_DatePicker").length&&$.hide()}}),t(document).on("keyup.Zebra_DatePicker_"+T,function(t){n.hasClass("dp_visible")&&27===t.which&&$.hide()})),at()};$.clear_date=function(){t(l).trigger("click")},$.destroy=function(){void 0!==$.icon&&$.icon.remove(),$.datepicker.remove(),$.settings.show_icon&&!$.settings.always_visible&&q.unwrap(),q.off("click.Zebra_DatePicker_"+T),q.off("blur.Zebra_DatePicker_"+T),t(document).off("keyup.Zebra_DatePicker_"+T),t(document).off("mousedown.Zebra_DatePicker_"+T),t(window).off("resize.Zebra_DatePicker_"+T),t(window).off("orientationchange.Zebra_DatePicker_"+T),q.removeData("Zebra_DatePicker"),q.attr("readonly",V.readonly),q.attr("style",V.style?V.style:"")},$.hide=function(){$.settings.always_visible||(et("hide"),n.removeClass("dp_visible").addClass("dp_hidden"),$.settings.onClose&&"function"==typeof $.settings.onClose&&$.settings.onClose.call(q,q))},$.set_date=function(t){var e;(e=R(t))&&!st(e.getFullYear(),e.getMonth(),e.getDate())&&(q.val(t),lt(e))},$.show=function(){i=$.settings.view;var e=R(q.val()||($.settings.start_date?$.settings.start_date:""));if(e?(m=e.getMonth(),b=e.getMonth(),w=e.getFullYear(),y=e.getFullYear(),v=e.getDate(),st(w,m,v)&&($.settings.strict&&q.val(""),b=u,y=f)):(b=u,y=f),at(),$.settings.always_visible)n.removeClass("dp_hidden").addClass("dp_visible");else{if($.settings.container.is("body")){var s=n.outerWidth(),r=n.outerHeight(),o=(void 0!==a?a.offset().left+a.outerWidth(!0):q.offset().left+q.outerWidth(!0))+$.settings.offset[0],d=(void 0!==a?a.offset().top:q.offset().top)-r+$.settings.offset[1],c=t(window).width(),l=t(window).height(),h=t(window).scrollTop(),_=t(window).scrollLeft();"below"===$.settings.default_position&&(d=(void 0!==a?a.offset().top:q.offset().top)+$.settings.offset[1]),o+s>_+c&&(o=_+c-s),o<_&&(o=_),d+r>h+l&&(d=h+l-r),d<h&&(d=h),n.css({left:o,top:d})}else n.css({left:0,top:0});n.removeClass("dp_hidden").addClass("dp_visible"),et()}$.settings.onOpen&&"function"==typeof $.settings.onOpen&&$.settings.onOpen.call(q,q)},$.update=function(e){$.original_direction&&($.original_direction=$.direction),$.settings=t.extend($.settings,e),E(!0)};var R=function(e){if(e+="",""!==t.trim(e)){for(var s=Q($.settings.format),i=["d","D","j","l","N","S","w","F","m","M","n","Y","y"],n=[],a=[],r=null,o=null,d=0;d<i.length;d++)(r=s.indexOf(i[d]))>-1&&n.push({character:i[d],position:r});if(n.sort(function(t,e){return t.position-e.position}),t.each(n,function(t,e){switch(e.character){case"d":a.push("0[1-9]|[12][0-9]|3[01]");break;case"D":case"M":a.push("[a-z]{3}");break;case"j":a.push("[1-9]|[12][0-9]|3[01]");break;case"l":case"F":a.push("[a-z]+");break;case"N":a.push("[1-7]");break;case"S":a.push("st|nd|rd|th");break;case"w":a.push("[0-6]");break;case"m":a.push("0[1-9]|1[012]+");break;case"n":a.push("[1-9]|1[012]");break;case"Y":a.push("[0-9]{4}");break;case"y":a.push("[0-9]{2}")}}),a.length&&(n.reverse(),t.each(n,function(t,e){s=s.replace(e.character,"("+a[a.length-t-1]+")")}),a=new RegExp("^"+s+"$","ig"),o=a.exec(e))){var c,l=new Date,h=1,_=l.getMonth()+1,g=l.getFullYear(),u=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],f=["January","February","March","April","May","June","July","August","September","October","November","December"],p=!0;if(n.reverse(),t.each(n,function(e,s){if(!p)return!0;switch(s.character){case"m":case"n":_=ct(o[e+1]);break;case"d":case"j":h=ct(o[e+1]);break;case"D":case"l":case"F":case"M":c="D"===s.character||"l"===s.character?$.settings.days:$.settings.months,p=!1,t.each(c,function(t,i){if(p)return!0;if(o[e+1].toLowerCase()===i.substring(0,"D"===s.character||"M"===s.character?3:i.length).toLowerCase()){switch(s.character){case"D":o[e+1]=u[t].substring(0,3);break;case"l":o[e+1]=u[t];break;case"F":o[e+1]=f[t],_=t+1;break;case"M":o[e+1]=f[t].substring(0,3),_=t+1}p=!0}});break;case"Y":g=ct(o[e+1]);break;case"y":g="19"+ct(o[e+1])}}),p){var b=new Date(g,(_||1)-1,h||1);if(b.getFullYear()===g&&b.getDate()===(h||1)&&b.getMonth()===(_||1)-1)return b}}return!1}},B=function(t){"firefox"===_t.name?t.css("MozUserSelect","none"):"explorer"===_t.name?t.on("selectstart",function(){return!1}):t.mousedown(function(){return!1})},Q=function(t){return t.replace(/([-.,*+?^${}()|[\]\/\\])/g,"\\$1")},U=function(e){var s,i,n="",a=e.getDate(),r=e.getDay(),o=$.settings.days[r],d=e.getMonth()+1,c=$.settings.months[d-1],l=e.getFullYear()+"";for(s=0;s<$.settings.format.length;s++)switch(i=$.settings.format.charAt(s)){case"y":l=l.substr(2);case"Y":n+=l;break;case"m":d=dt(d,2);case"n":n+=d;break;case"M":c=t.isArray($.settings.months_abbr)&&void 0!==$.settings.months_abbr[d-1]?$.settings.months_abbr[d-1]:$.settings.months[d-1].substr(0,3);case"F":n+=c;break;case"d":a=dt(a,2);case"j":n+=a;break;case"D":o=t.isArray($.settings.days_abbr)&&void 0!==$.settings.days_abbr[r]?$.settings.days_abbr[r]:$.settings.days[r].substr(0,3);case"l":n+=o;break;case"N":r++;case"w":n+=r;break;case"S":n+=a%10==1&&"11"!==a?"st":a%10==2&&"12"!==a?"nd":a%10==3&&"13"!==a?"rd":"th";break;default:n+=i}return n},X=function(){var e,s,i,n,a,r,d,c,l,u,f=new Date(y,b+1,0).getDate(),p=new Date(y,b,1).getDay(),k=new Date(y,b,0).getDate(),D=p-$.settings.first_day_of_week;for(D=D<0?7+D:D,nt($.settings.header_captions.days),s="<tr>",$.settings.show_week_number&&(s+="<th>"+$.settings.show_week_number+"</th>"),e=0;e<7;e++)s+="<th>"+(t.isArray($.settings.days_abbr)&&void 0!==$.settings.days_abbr[($.settings.first_day_of_week+e)%7]?$.settings.days_abbr[($.settings.first_day_of_week+e)%7]:$.settings.days[($.settings.first_day_of_week+e)%7].substr(0,2))+"</th>";for(s+="</tr><tr>",e=0;e<42;e++)e>0&&e%7==0&&(s+="</tr><tr>"),e%7==0&&$.settings.show_week_number&&(s+='<td class="dp_week_number">'+ht(new Date(y,b,e-D+1))+"</td>"),i=e-D+1,$.settings.select_other_months&&(e<D||i>f)&&(a=(n=new Date(y,b,i)).getFullYear(),r=n.getMonth(),d=n.getDate(),n=a+dt(r+1,2)+dt(d,2)),e<D?s+='<td class="'+($.settings.select_other_months&&!st(a,r,d)?"dp_not_in_month_selectable date_"+n:"dp_not_in_month")+'">'+($.settings.select_other_months||$.settings.show_other_months?dt(k-D+e+1,$.settings.zero_pad?2:0):"&nbsp;")+"</td>":i>f?s+='<td class="'+($.settings.select_other_months&&!st(a,r,d)?"dp_not_in_month_selectable date_"+n:"dp_not_in_month")+'">'+($.settings.select_other_months||$.settings.show_other_months?dt(i-f,$.settings.zero_pad?2:0):"&nbsp;")+"</td>":(c=($.settings.first_day_of_week+e)%7,l="",u=tt(y,b,i),st(y,b,i)?(t.inArray(c,$.settings.weekend_days)>-1?l="dp_weekend_disabled":l+=" dp_disabled",b===h&&y===_&&g===i&&(l+=" dp_disabled_current"),""!==u&&(l+=" "+u+"_disabled")):(t.inArray(c,$.settings.weekend_days)>-1&&(l="dp_weekend"),b===m&&y===w&&v===i&&(l+=" dp_selected"),b===h&&y===_&&g===i&&(l+=" dp_current"),""!==u&&(l+=" "+u)),s+="<td"+(""!==l?' class="'+t.trim(l)+'"':"")+">"+(($.settings.zero_pad?dt(i,2):i)||"&nbsp;")+"</td>");s+="</tr>",o.html(t(s)),$.settings.always_visible&&(S=t("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month, .dp_week_number)",o)),o.show()},tt=function(e,s,i){var n,a,r;for(a in void 0!==s&&(s+=1),L)if(n=L[a],r=!1,t.isArray(J[n])&&t.each(J[n],function(){if(!r){var a,o=this;if((t.inArray(e,o[2])>-1||t.inArray("*",o[2])>-1)&&(void 0!==s&&t.inArray(s,o[1])>-1||t.inArray("*",o[1])>-1)&&(void 0!==i&&t.inArray(i,o[0])>-1||t.inArray("*",o[0])>-1)){if("*"===o[3])return r=n;if(a=new Date(e,s-1,i).getDay(),t.inArray(a,o[3])>-1)return r=n}}}),r)return r;return r||""},et=function(e){var s,i;if("explorer"===_t.name&&6===_t.version)if("hide"===(A||(s=ct(n.css("zIndex"))-1,A=t("<iframe>",{src:'javascript:document.write("")',scrolling:"no",frameborder:0,css:{zIndex:s,position:"absolute",top:-1e3,left:-1e3,width:n.outerWidth(),height:n.outerHeight(),filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=0)",display:"none"}}),t("body").append(A)),e))A.hide();else i=n.offset(),A.css({top:i.top,left:i.left,display:"block"})},st=function(e,s,i){var n,a,r,o;if(!(void 0!==e&&!isNaN(e)||void 0!==s&&!isNaN(s)||void 0!==i&&!isNaN(i)))return!1;if(e<1e3)return!0;if(t.isArray($.settings.direction)||0!==ct($.settings.direction)){if(8===(a=((n=ct(ot(e,void 0!==s?dt(s,2):"",void 0!==i?dt(i,2):"")))+"").length)&&(void 0!==M&&n<ct(ot(f,dt(u,2),dt(p,2)))||void 0!==F&&n>ct(ot(Y,dt(P,2),dt(C,2)))))return!0;if(6===a&&(void 0!==M&&n<ct(ot(f,dt(u,2)))||void 0!==F&&n>ct(ot(Y,dt(P,2)))))return!0;if(4===a&&(void 0!==M&&n<f||void 0!==F&&n>Y))return!0}return void 0!==s&&(s+=1),r=!1,o=!1,t.isArray(D)&&D.length&&t.each(D,function(){if(!r){var n,a=this;if((t.inArray(e,a[2])>-1||t.inArray("*",a[2])>-1)&&(void 0!==s&&t.inArray(s,a[1])>-1||t.inArray("*",a[1])>-1)&&(void 0!==i&&t.inArray(i,a[0])>-1||t.inArray("*",a[0])>-1)){if("*"===a[3])return r=!0;if(n=new Date(e,s-1,i).getDay(),t.inArray(n,a[3])>-1)return r=!0}}}),k&&t.each(k,function(){if(!o){var n,a=this;if((t.inArray(e,a[2])>-1||t.inArray("*",a[2])>-1)&&(o=!0,void 0!==s))if(o=!0,t.inArray(s,a[1])>-1||t.inArray("*",a[1])>-1){if(void 0!==i)if(o=!0,t.inArray(i,a[0])>-1||t.inArray("*",a[0])>-1){if("*"===a[3])return o=!0;if(n=new Date(e,s-1,i).getDay(),t.inArray(n,a[3])>-1)return o=!0;o=!1}else o=!1}else o=!1}}),!(k&&o||!D||!r)},it=function(t){return(t+"").match(/^\-?[0-9]+$/)},nt=function(e){!isNaN(parseFloat(b))&&isFinite(b)&&(e=e.replace(/\bm\b|\bn\b|\bF\b|\bM\b/,function(e){switch(e){case"m":return dt(b+1,2);case"n":return b+1;case"F":return $.settings.months[b];case"M":return t.isArray($.settings.months_abbr)&&void 0!==$.settings.months_abbr[b]?$.settings.months_abbr[b]:$.settings.months[b].substr(0,3);default:return e}})),!isNaN(parseFloat(y))&&isFinite(y)&&(e=e.replace(/\bY\b/,y).replace(/\by\b/,(y+"").substr(2)).replace(/\bY1\b/i,y-7).replace(/\bY2\b/i,y+4)),t(".dp_caption",r).html(e)},at=function(){var e,s,a;""===o.text()||"days"===i?(""===o.text()?($.settings.always_visible||n.css("left",-1e3),n.css("visibility","visible"),X(),e=o.outerWidth(),s=o.outerHeight(),d.css({width:e,height:s}),c.css({width:e,height:s}),r.css("width",e),O.css("width",e),n.css("visibility","").addClass("dp_hidden")):X(),d.hide(),c.hide()):"months"===i?(function(){nt($.settings.header_captions.months);var e,s,i="<tr>";for(e=0;e<12;e++)e>0&&e%3==0&&(i+="</tr><tr>"),s="dp_month_"+e,st(y,e)?s+=" dp_disabled":!1!==m&&m===e&&y===w?s+=" dp_selected":h===e&&_===y&&(s+=" dp_current"),i+='<td class="'+t.trim(s)+'">'+(t.isArray($.settings.months_abbr)&&void 0!==$.settings.months_abbr[e]?$.settings.months_abbr[e]:$.settings.months[e].substr(0,3))+"</td>";i+="</tr>",d.html(t(i)),$.settings.always_visible&&(Z=t("td:not(.dp_disabled)",d)),d.show()}(),o.hide(),c.hide()):"years"===i&&(function(){nt($.settings.header_captions.years);var e,s,i="<tr>";for(e=0;e<12;e++)e>0&&e%3==0&&(i+="</tr><tr>"),s="",st(y-7+e)?s+=" dp_disabled":w&&w===y-7+e?s+=" dp_selected":_===y-7+e&&(s+=" dp_current"),i+="<td"+(""!==t.trim(s)?' class="'+t.trim(s)+'"':"")+">"+(y-7+e)+"</td>";i+="</tr>",c.html(t(i)),$.settings.always_visible&&(x=t("td:not(.dp_disabled)",c)),c.show()}(),o.hide(),d.hide()),$.settings.onChange&&"function"==typeof $.settings.onChange&&void 0!==i&&((a="days"===i?o.find("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month)"):"months"===i?d.find("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month)"):c.find("td:not(.dp_disabled, .dp_weekend_disabled, .dp_not_in_month)")).each(function(){var e;"days"===i?t(this).hasClass("dp_not_in_month_selectable")?(e=t(this).attr("class").match(/date\_([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])/),t(this).data("date",e[1]+"-"+e[2]+"-"+e[3])):t(this).data("date",y+"-"+dt(b+1,2)+"-"+dt(ct(t(this).text()),2)):"months"===i?(e=t(this).attr("class").match(/dp\_month\_([0-9]+)/),t(this).data("date",y+"-"+dt(ct(e[1])+1,2))):t(this).data("date",ct(t(this).text()))}),$.settings.onChange.call(q,i,a,q)),O.show(),!0===$.settings.show_clear_date||0===$.settings.show_clear_date&&""!==q.val()||$.settings.always_visible&&!1!==$.settings.show_clear_date?(l.show(),W?(N.css("width","50%"),l.css("width","50%")):(N.hide(),l.css("width","100%"))):(l.hide(),W?N.show().css("width","100%"):O.hide())},rt=function(t,e,s,i,n){var a=new Date(t,e,s,12,0,0),r="days"===i?S:"months"===i?Z:x,o=U(a);q.val(o),$.settings.always_visible&&(m=a.getMonth(),b=a.getMonth(),w=a.getFullYear(),y=a.getFullYear(),v=a.getDate(),r.removeClass("dp_selected"),n.addClass("dp_selected"),"days"===i&&n.hasClass("dp_not_in_month_selectable")&&$.show()),$.hide(),lt(a),$.settings.onSelect&&"function"==typeof $.settings.onSelect&&$.settings.onSelect.call(q,o,t+"-"+dt(e+1,2)+"-"+dt(s,2),a,q,ht(a)),q.focus()},ot=function(){var t,e="";for(t=0;t<arguments.length;t++)e+=arguments[t]+"";return e},dt=function(t,e){for(t+="";t.length<e;)t="0"+t;return t},ct=function(t){return parseInt(t,10)},lt=function(e){$.settings.pair&&t.each($.settings.pair,function(){var s,i=t(this);i.data&&i.data("Zebra_DatePicker")?((s=i.data("Zebra_DatePicker")).update({reference_date:e,direction:0===s.settings.direction?1:s.settings.direction}),s.settings.always_visible&&s.show()):i.data("zdp_reference_date",e)})},ht=function(t){var e,s,i,n,a,r,o,d=t.getFullYear(),c=t.getMonth()+1,l=t.getDate();return c<3?(i=(s=((e=d-1)/4|0)-(e/100|0)+(e/400|0))-(((e-1)/4|0)-((e-1)/100|0)+((e-1)/400|0)),n=0,a=l-1+31*(c-1)):(n=1+(i=(s=((e=d)/4|0)-(e/100|0)+(e/400|0))-(((e-1)/4|0)-((e-1)/100|0)+((e-1)/400|0))),a=l+((153*(c-3)+2)/5|0)+58+i),(o=a+3-(l=(a+(r=(e+s)%7)-n)%7))<0?53-((r-i)/5|0):o>364+i?1:1+(o/7|0)},_t={init:function(){this.name=this.searchString(this.dataBrowser)||"",this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||""},searchString:function(t){var e,s,i;for(e=0;e<t.length;e++)if(s=t[e].string,i=t[e].prop,this.versionSearchString=t[e].versionSearch||t[e].identity,s){if(-1!==s.indexOf(t[e].subString))return t[e].identity}else if(i)return t[e].identity},searchVersion:function(t){var e=t.indexOf(this.versionSearchString);if(-1!==e)return parseFloat(t.substring(e+this.versionSearchString.length+1))},dataBrowser:[{string:navigator.userAgent,subString:"Firefox",identity:"firefox"},{string:navigator.userAgent,subString:"MSIE",identity:"explorer",versionSearch:"MSIE"}]};_t.init(),E()},t.fn.Zebra_DatePicker=function(e){return this.each(function(){void 0!==t(this).data("Zebra_DatePicker")&&t(this).data("Zebra_DatePicker").destroy();var s=new t.Zebra_DatePicker(this,e);t(this).data("Zebra_DatePicker",s)})}}),function(e){"object"==typeof module&&"object"==typeof module.exports?e(require("jquery"),window,document):"undefined"!=typeof jQuery&&e(jQuery,window,document)}(function(e,t,i,n){!function(){function t(e,t,i){return new Array(i+1-e.length).join(t)+e}function n(){if(1===arguments.length){var t=arguments[0];return"string"==typeof t&&(t=e.fn.timepicker.parseTime(t)),new Date(0,0,0,t.getHours(),t.getMinutes(),t.getSeconds())}return 3===arguments.length?new Date(0,0,0,arguments[0],arguments[1],arguments[2]):2===arguments.length?new Date(0,0,0,arguments[0],arguments[1],0):new Date(0,0,0)}e.TimePicker=function(){var t=this;t.container=e(".ui-timepicker-container"),t.ui=t.container.find(".ui-timepicker"),0===t.container.length&&(t.container=e("<div></div>").addClass("ui-timepicker-container").addClass("ui-timepicker-hidden ui-helper-hidden").appendTo("body").hide(),t.ui=e("<div></div>").addClass("ui-timepicker").addClass("ui-widget ui-widget-content ui-menu").addClass("ui-corner-all").appendTo(t.container),t.viewport=e("<ul></ul>").addClass("ui-timepicker-viewport").appendTo(t.ui),e.fn.jquery>="1.4.2"&&t.ui.delegate("a","mouseenter.timepicker",function(){t.activate(!1,e(this).parent())}).delegate("a","mouseleave.timepicker",function(){t.deactivate(!1)}).delegate("a","click.timepicker",function(i){i.preventDefault(),t.select(!1,e(this).parent())}))},e.TimePicker.count=0,e.TimePicker.instance=function(){return e.TimePicker._instance||(e.TimePicker._instance=new e.TimePicker),e.TimePicker._instance},e.TimePicker.prototype={keyCode:{ALT:18,BLOQ_MAYUS:20,CTRL:17,DOWN:40,END:35,ENTER:13,HOME:36,LEFT:37,NUMPAD_ENTER:108,PAGE_DOWN:34,PAGE_UP:33,RIGHT:39,SHIFT:16,TAB:9,UP:38},_items:function(t,i){var r,a,s=e("<ul></ul>"),c=null;for(-1===t.options.timeFormat.indexOf("m")&&t.options.interval%60!=0&&(t.options.interval=60*Math.max(Math.round(t.options.interval/60),1)),r=i?n(i):t.options.startTime?n(t.options.startTime):n(t.options.startHour,t.options.startMinutes),a=new Date(r.getTime()+864e5);a>r;)this._isValidTime(t,r)&&(c=e("<li>").addClass("ui-menu-item").appendTo(s),e("<a>").addClass("ui-corner-all").text(e.fn.timepicker.formatTime(t.options.timeFormat,r)).appendTo(c),c.data("time-value",r)),r=new Date(r.getTime()+60*t.options.interval*1e3);return s.children()},_isValidTime:function(e,t){var i=null,r=null;return t=n(t),null!==e.options.minTime?i=n(e.options.minTime):null===e.options.minHour&&null===e.options.minMinutes||(i=n(e.options.minHour,e.options.minMinutes)),null!==e.options.maxTime?r=n(e.options.maxTime):null===e.options.maxHour&&null===e.options.maxMinutes||(r=n(e.options.maxHour,e.options.maxMinutes)),null!==i&&null!==r?t>=i&&r>=t:null!==i?t>=i:null===r||r>=t},_hasScroll:function(){var e=void 0!==this.ui.prop?"prop":"attr";return this.ui.height()<this.ui[e]("scrollHeight")},_move:function(e,t,i){var n=this;if(n.closed()&&n.open(e),n.active){var r=n.active[t+"All"](".ui-menu-item").eq(0);r.length?n.activate(e,r):n.activate(e,n.viewport.children(i))}else n.activate(e,n.viewport.children(i))},register:function(t,i){var n=this,r={};r.element=e(t),r.element.data("TimePicker")||(r.options=e.metadata?e.extend({},i,r.element.metadata()):e.extend({},i),r.widget=n,e.extend(r,{next:function(){return n.next(r)},previous:function(){return n.previous(r)},first:function(){return n.first(r)},last:function(){return n.last(r)},selected:function(){return n.selected(r)},open:function(){return n.open(r)},close:function(){return n.close(r)},closed:function(){return n.closed(r)},destroy:function(){return n.destroy(r)},parse:function(e){return n.parse(r,e)},format:function(e,t){return n.format(r,e,t)},getTime:function(){return n.getTime(r)},setTime:function(e,t){return n.setTime(r,e,t)},option:function(e,t){return n.option(r,e,t)}}),n._setDefaultTime(r),n._addInputEventsHandlers(r),r.element.data("TimePicker",r))},_setDefaultTime:function(t){"now"===t.options.defaultTime?t.setTime(n(new Date)):t.options.defaultTime&&t.options.defaultTime.getFullYear?t.setTime(n(t.options.defaultTime)):t.options.defaultTime&&t.setTime(e.fn.timepicker.parseTime(t.options.defaultTime))},_addInputEventsHandlers:function(t){var i=this;t.element.bind("keydown.timepicker",function(e){switch(e.which||e.keyCode){case i.keyCode.ENTER:case i.keyCode.NUMPAD_ENTER:e.preventDefault(),i.closed()?t.element.trigger("change.timepicker"):i.select(t,i.active);break;case i.keyCode.UP:t.previous();break;case i.keyCode.DOWN:t.next();break;default:i.closed()||t.close(!0)}}).bind("focus.timepicker",function(){t.open()}).bind("blur.timepicker",function(){setTimeout(function(){t.element.data("timepicker-user-clicked-outside")&&t.close()})}).bind("change.timepicker",function(){t.closed()&&t.setTime(e.fn.timepicker.parseTime(t.element.val()))})},select:function(t,i){var n=this,r=!1===t?n.instance:t;n.setTime(r,e.fn.timepicker.parseTime(i.children("a").text())),n.close(r,!0)},activate:function(e,t){var i=this;if((!1===e?i.instance:e)===i.instance){if(i.deactivate(),i._hasScroll()){var r=t.offset().top-i.ui.offset().top,a=i.ui.scrollTop(),o=i.ui.height();0>r?i.ui.scrollTop(a+r):r>=o&&i.ui.scrollTop(a+r-o+t.height())}i.active=t.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-item").end()}},deactivate:function(){var e=this;e.active&&(e.active.children("a").removeClass("ui-state-hover").removeAttr("id"),e.active=null)},next:function(e){return(this.closed()||this.instance===e)&&this._move(e,"next",".ui-menu-item:first"),e.element},previous:function(e){return(this.closed()||this.instance===e)&&this._move(e,"prev",".ui-menu-item:last"),e.element},first:function(e){return this.instance===e&&(this.active&&0===this.active.prevAll(".ui-menu-item").length)},last:function(e){return this.instance===e&&(this.active&&0===this.active.nextAll(".ui-menu-item").length)},selected:function(e){return this.instance===e&&this.active?this.active:null},open:function(t){var n=this,r=t.getTime(),a=t.options.dynamic&&r;if(!t.options.dropdown)return t.element;switch(t.element.data("timepicker-event-namespace",Math.random()),e(i).bind("click.timepicker-"+t.element.data("timepicker-event-namespace"),function(e){t.element.get(0)===e.target?t.element.data("timepicker-user-clicked-outside",!1):t.element.data("timepicker-user-clicked-outside",!0).blur()}),(t.rebuild||!t.items||a)&&(t.items=n._items(t,a?r:null)),(t.rebuild||n.instance!==t||a)&&(e.fn.jquery<"1.4.2"?(n.viewport.children().remove(),n.viewport.append(t.items),n.viewport.find("a").bind("mouseover.timepicker",function(){n.activate(t,e(this).parent())}).bind("mouseout.timepicker",function(){n.deactivate(t)}).bind("click.timepicker",function(i){i.preventDefault(),n.select(t,e(this).parent())})):(n.viewport.children().detach(),n.viewport.append(t.items))),t.rebuild=!1,n.container.removeClass("ui-helper-hidden ui-timepicker-hidden ui-timepicker-standard ui-timepicker-corners").show(),t.options.theme){case"standard":n.container.addClass("ui-timepicker-standard");break;case"standard-rounded-corners":n.container.addClass("ui-timepicker-standard ui-timepicker-corners")}n.container.hasClass("ui-timepicker-no-scrollbar")||t.options.scrollbar||(n.container.addClass("ui-timepicker-no-scrollbar"),n.viewport.css({paddingRight:40}));var o=n.container.outerHeight()-n.container.height(),s=t.options.zindex?t.options.zindex:t.element.offsetParent().css("z-index"),c=t.element.offset();n.container.css({top:c.top+t.element.outerHeight(),left:c.left}),n.container.show(),n.container.css({left:t.element.offset().left,height:n.ui.outerHeight()+o,width:t.element.outerWidth(),zIndex:s,cursor:"default"});var u=n.container.width()-(n.ui.outerWidth()-n.ui.width());return n.ui.css({width:u}),n.viewport.css({width:u}),t.items.css({width:u}),n.instance=t,r?t.items.each(function(){var a=e(this);return(e.fn.jquery<"1.4.2"?e.fn.timepicker.parseTime(a.find("a").text()):a.data("time-value")).getTime()!==r.getTime()||(n.activate(t,a),!1)}):n.deactivate(t),t.element},close:function(t){var n=this;return n.instance===t&&(n.container.addClass("ui-helper-hidden ui-timepicker-hidden").hide(),n.ui.scrollTop(0),n.ui.children().removeClass("ui-state-hover")),e(i).unbind("click.timepicker-"+t.element.data("timepicker-event-namespace")),t.element},closed:function(){return this.ui.is(":hidden")},destroy:function(e){return this.close(e,!0),e.element.unbind(".timepicker").data("TimePicker",null)},parse:function(t,i){return e.fn.timepicker.parseTime(i)},format:function(t,i,n){return n=n||t.options.timeFormat,e.fn.timepicker.formatTime(n,i)},getTime:function(t){var n=e.fn.timepicker.parseTime(t.element.val());return n instanceof Date&&!this._isValidTime(t,n)?null:n instanceof Date&&t.selectedTime?t.format(n)===t.format(t.selectedTime)?t.selectedTime:n:n instanceof Date?n:null},setTime:function(t,i,r){var o=t.selectedTime;if("string"==typeof i&&(i=t.parse(i)),i&&i.getMinutes&&this._isValidTime(t,i)){if(i=n(i),t.selectedTime=i,t.element.val(t.format(i,t.options.timeFormat)),r)return t}else t.selectedTime=null;return null===o&&null===t.selectedTime||(t.element.trigger("time-change",[i]),e.isFunction(t.options.change)&&t.options.change.apply(t.element,[i])),t.element},option:function(t,i,n){if(void 0===n)return t.options[i];var r,a,o=t.getTime();"string"==typeof i?(r={})[i]=n:r=i,a=["minHour","minMinutes","minTime","maxHour","maxMinutes","maxTime","startHour","startMinutes","startTime","timeFormat","interval","dropdown"],e.each(r,function(i){t.options[i]=r[i],t.rebuild=t.rebuild||e.inArray(i,a)>-1}),t.rebuild&&t.setTime(o)}},e.TimePicker.defaults={timeFormat:"hh:mm p",minHour:null,minMinutes:null,minTime:null,maxHour:null,maxMinutes:null,maxTime:null,startHour:null,startMinutes:null,startTime:null,interval:30,dynamic:!0,theme:"standard",zindex:null,dropdown:!0,scrollbar:!1,change:function(){}},e.TimePicker.methods={chainable:["next","previous","open","close","destroy","setTime"]},e.fn.timepicker=function(t){if("string"==typeof t){var i,n,r=Array.prototype.slice.call(arguments,1);return n=this[i="option"===t&&arguments.length>2||-1!==e.inArray(t,e.TimePicker.methods.chainable)?"each":"map"](function(){var n=e(this).data("TimePicker");return"object"==typeof n?n[t].apply(n,r):void 0}),"map"===i&&1===this.length?e.makeArray(n).shift():"map"===i?e.makeArray(n):n}if(1===this.length&&this.data("TimePicker"))return this.data("TimePicker");var a=e.extend({},e.TimePicker.defaults,t);return this.each(function(){e.TimePicker.instance().register(this,a)})},e.fn.timepicker.formatTime=function(e,i){var n=i.getHours(),r=n%12,a=i.getMinutes(),o=i.getSeconds(),s={hh:t((0===r?12:r).toString(),"0",2),HH:t(n.toString(),"0",2),mm:t(a.toString(),"0",2),ss:t(o.toString(),"0",2),h:0===r?12:r,H:n,m:a,s:o,p:n>11?"PM":"AM"},c=e,u="";for(u in s)s.hasOwnProperty(u)&&(c=c.replace(new RegExp(u,"g"),s[u]));return c.replace(new RegExp("a","g"),n>11?"pm":"am")},e.fn.timepicker.parseTime=function(){var t=[[/^(\d+)$/,"$1"],[/^:(\d)$/,"$10"],[/^:(\d+)/,"$1"],[/^(\d):([7-9])$/,"0$10$2"],[/^(\d):(\d\d)$/,"$1$2"],[/^(\d):(\d{1,})$/,"0$1$20"],[/^(\d\d):([7-9])$/,"$10$2"],[/^(\d\d):(\d)$/,"$1$20"],[/^(\d\d):(\d*)$/,"$1$2"],[/^(\d{3,}):(\d)$/,"$10$2"],[/^(\d{3,}):(\d{2,})/,"$1$2"],[/^(\d):(\d):(\d)$/,"0$10$20$3"],[/^(\d{1,2}):(\d):(\d\d)/,"$10$2$3"]],i=t.length;return function(r){var o,s,a=n(new Date),c=!1,u=!1,l=!1;if(void 0===r||!r.toLowerCase)return null;r=r.toLowerCase(),s=!(o=/a/.test(r))&&/p/.test(r),r=r.replace(/[^0-9:]/g,"").replace(/:+/g,":");for(var m=0;i>m;m+=1)if(t[m][0].test(r)){r=r.replace(t[m][0],t[m][1]);break}return 1===(r=r.replace(/:/g,"")).length||2===r.length?c=r:3===r.length||5===r.length?(c=r.substr(0,1),u=r.substr(1,2),l=r.substr(3,2)):(4===r.length||r.length>5)&&(c=r.substr(0,2),u=r.substr(2,2),l=r.substr(4,2)),r.length>0&&r.length<5&&(r.length<3&&(u=0),l=0),!1!==c&&!1!==u&&!1!==l&&(c=parseInt(c,10),u=parseInt(u,10),l=parseInt(l,10),o&&12===c?c=0:s&&12>c&&(c+=12),c>24?r.length>=6?e.fn.timepicker.parseTime(r.substr(0,5)):e.fn.timepicker.parseTime(r+"0"+(o?"a":"")+(s?"p":"")):(a.setHours(c,u,l),a))}}()}()});